blob: dab0619587860b960a0296ab2cd306ab08ddb8c1 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000035/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38 if (Context.typesAreCompatible(Context.getWideCharType(), T))
39 return true;
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
43 }
44 return false;
45}
46
47enum StringInitFailureKind {
48 SIF_None,
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
52 SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000061 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000062 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000063
Chris Lattnera9196812009-02-26 23:26:43 +000064 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000069 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000070
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000073 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000074 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000075
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000076 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000078
79 switch (SL->getKind()) {
80 case StringLiteral::Ascii:
81 case StringLiteral::UTF8:
82 // char array can be initialized with a narrow string.
83 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000084 if (ElemTy->isCharType())
85 return SIF_None;
86 if (IsWideCharCompatible(ElemTy, Context))
87 return SIF_NarrowStringIntoWideChar;
88 return SIF_Other;
89 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90 // "An array with element type compatible with a qualified or unqualified
91 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92 // string literal with the corresponding encoding prefix (L, u, or U,
93 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +000094 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000095 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96 return SIF_None;
97 if (ElemTy->isCharType())
98 return SIF_WideStringIntoChar;
99 if (IsWideCharCompatible(ElemTy, Context))
100 return SIF_IncompatWideStringIntoWideChar;
101 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000102 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000103 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104 return SIF_None;
105 if (ElemTy->isCharType())
106 return SIF_WideStringIntoChar;
107 if (IsWideCharCompatible(ElemTy, Context))
108 return SIF_IncompatWideStringIntoWideChar;
109 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000110 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000111 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112 return SIF_None;
113 if (ElemTy->isCharType())
114 return SIF_WideStringIntoChar;
115 if (IsWideCharCompatible(ElemTy, Context))
116 return SIF_IncompatWideStringIntoWideChar;
117 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregorfb65e592011-07-27 05:40:30 +0000120 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000121}
122
Hans Wennborg950f3182013-05-16 09:22:40 +0000123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000125 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000129}
130
Richard Smith430c23b2013-05-05 16:40:13 +0000131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000134 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000135 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000136 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137 break;
138 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139 E = PE->getSubExpr();
140 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141 E = UO->getSubExpr();
142 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143 E = GSE->getResultExpr();
144 else
145 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000146 }
Richard Smith430c23b2013-05-05 16:40:13 +0000147}
148
John McCall5decec92011-02-21 07:57:55 +0000149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000151 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000152 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000153 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000154 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner0cb78032009-02-24 22:27:37 +0000156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000158 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000159 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000160 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000164 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000165 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Eli Friedman893abe42009-05-29 18:22:49 +0000168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Eli Friedman554eba92011-04-11 00:23:45 +0000170 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000171 // the size may be smaller or larger than the string we are initializing.
172 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000173 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000175 // For Pascal strings it's OK to strip off the terminating null character,
176 // so the example below is valid:
177 //
178 // unsigned char a[2] = "\pa";
179 if (SL->isPascal())
180 StrLength--;
181 }
182
Eli Friedman554eba92011-04-11 00:23:45 +0000183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000185 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000186 diag::err_initializer_string_for_char_array_too_long)
187 << Str->getSourceRange();
188 } else {
189 // C99 6.7.8p14.
190 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 S.Diag(Str->getLocStart(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000192 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000193 << Str->getSourceRange();
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Eli Friedman893abe42009-05-29 18:22:49 +0000196 // Set the type to the actual size that we are initializing. If we have
197 // something like:
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000201}
202
Chris Lattner0cb78032009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000221/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000234namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000235class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000236 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000237 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000238 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Anders Carlsson6cabf312010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000248 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000249 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000250 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000251 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000252 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000257 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000258 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000259 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000262 void CheckComplexType(const InitializedEntity &Entity,
263 InitListExpr *IList, QualType DeclType,
264 unsigned &Index,
265 InitListExpr *StructuredList,
266 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000267 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000268 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000269 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000274 unsigned &Index,
275 InitListExpr *StructuredList,
276 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000277 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000278 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000282 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000283 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000284 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000286 unsigned &StructuredIndex,
287 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000288 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000289 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000290 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000294 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000295 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000296 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000297 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000303 bool FinishSubobjectInit,
304 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000305 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
306 QualType CurrentObjectType,
307 InitListExpr *StructuredList,
308 unsigned StructuredIndex,
309 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000310 void UpdateStructuredListElement(InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000312 Expr *expr);
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000315
Richard Smith454a7cd2014-06-03 08:26:00 +0000316 static ExprResult PerformEmptyInit(Sema &SemaRef,
317 SourceLocation Loc,
318 const InitializedEntity &Entity,
319 bool VerifyOnly);
320 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 const InitializedEntity &ParentEntity,
322 InitListExpr *ILE, bool &RequiresSecondPass);
Richard Smith454a7cd2014-06-03 08:26:00 +0000323 void FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000324 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000325 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
326 Expr *InitExpr, FieldDecl *Field,
327 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000328 void CheckEmptyInitializable(const InitializedEntity &Entity,
329 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000330
Douglas Gregor85df8d82009-01-29 00:45:39 +0000331public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000332 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000333 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000334 bool HadError() { return hadError; }
335
336 // @brief Retrieves the fully-structured initializer list used for
337 // semantic analysis and code generation.
338 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
339};
Chris Lattner9ececce2009-02-24 22:48:58 +0000340} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000341
Richard Smith454a7cd2014-06-03 08:26:00 +0000342ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
343 SourceLocation Loc,
344 const InitializedEntity &Entity,
345 bool VerifyOnly) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000346 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
347 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000348 MultiExprArg SubInit;
349 Expr *InitExpr;
350 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
351
352 // C++ [dcl.init.aggr]p7:
353 // If there are fewer initializer-clauses in the list than there are
354 // members in the aggregate, then each member not explicitly initialized
355 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000356 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
357 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
358 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000359 // C++1y / DR1070:
360 // shall be initialized [...] from an empty initializer list.
361 //
362 // We apply the resolution of this DR to C++11 but not C++98, since C++98
363 // does not have useful semantics for initialization from an init list.
364 // We treat this as copy-initialization, because aggregate initialization
365 // always performs copy-initialization on its elements.
366 //
367 // Only do this if we're initializing a class type, to avoid filling in
368 // the initializer list where possible.
369 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
370 InitListExpr(SemaRef.Context, Loc, None, Loc);
371 InitExpr->setType(SemaRef.Context.VoidTy);
372 SubInit = InitExpr;
373 Kind = InitializationKind::CreateCopy(Loc, Loc);
374 } else {
375 // C++03:
376 // shall be value-initialized.
377 }
378
379 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000380 // libstdc++4.6 marks the vector default constructor as explicit in
381 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
382 // stlport does so too. Look for std::__debug for libstdc++, and for
383 // std:: for stlport. This is effectively a compiler-side implementation of
384 // LWG2193.
385 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
386 InitializationSequence::FK_ExplicitConstructor) {
387 OverloadCandidateSet::iterator Best;
388 OverloadingResult O =
389 InitSeq.getFailedCandidateSet()
390 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
391 (void)O;
392 assert(O == OR_Success && "Inconsistent overload resolution");
393 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
394 CXXRecordDecl *R = CtorDecl->getParent();
395
396 if (CtorDecl->getMinRequiredArguments() == 0 &&
397 CtorDecl->isExplicit() && R->getDeclName() &&
398 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
399
400
401 bool IsInStd = false;
402 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000403 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000404 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
405 IsInStd = true;
406 }
407
408 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
409 .Cases("basic_string", "deque", "forward_list", true)
410 .Cases("list", "map", "multimap", "multiset", true)
411 .Cases("priority_queue", "queue", "set", "stack", true)
412 .Cases("unordered_map", "unordered_set", "vector", true)
413 .Default(false)) {
414 InitSeq.InitializeFrom(
415 SemaRef, Entity,
416 InitializationKind::CreateValue(Loc, Loc, Loc, true),
417 MultiExprArg(), /*TopLevelOfInitList=*/false);
418 // Emit a warning for this. System header warnings aren't shown
419 // by default, but people working on system headers should see it.
420 if (!VerifyOnly) {
421 SemaRef.Diag(CtorDecl->getLocation(),
422 diag::warn_invalid_initializer_from_system_header);
423 SemaRef.Diag(Entity.getDecl()->getLocation(),
424 diag::note_used_in_initialization_here);
425 }
426 }
427 }
428 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000429 if (!InitSeq) {
430 if (!VerifyOnly) {
431 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
432 if (Entity.getKind() == InitializedEntity::EK_Member)
433 SemaRef.Diag(Entity.getDecl()->getLocation(),
434 diag::note_in_omitted_aggregate_initializer)
435 << /*field*/1 << Entity.getDecl();
436 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
437 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
438 << /*array element*/0 << Entity.getElementIndex();
439 }
440 return ExprError();
441 }
442
443 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
444 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
445}
446
447void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
448 SourceLocation Loc) {
449 assert(VerifyOnly &&
450 "CheckEmptyInitializable is only inteded for verification mode.");
451 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000452 hadError = true;
453}
454
Richard Smith454a7cd2014-06-03 08:26:00 +0000455void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000456 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000457 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000458 bool &RequiresSecondPass) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000459 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000460 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000462 = InitializedEntity::InitializeMember(Field, &ParentEntity);
463 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000464 // C++1y [dcl.init.aggr]p7:
465 // If there are fewer initializer-clauses in the list than there are
466 // members in the aggregate, then each member not explicitly initialized
467 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000468 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000469 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
470 if (DIE.isInvalid()) {
471 hadError = true;
472 return;
473 }
Richard Smith852c9db2013-04-20 22:23:05 +0000474 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000475 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000476 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000477 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000478 RequiresSecondPass = true;
479 }
480 return;
481 }
482
Douglas Gregor2bb07652009-12-22 00:05:34 +0000483 if (Field->getType()->isReferenceType()) {
484 // C++ [dcl.init.aggr]p9:
485 // If an incomplete or empty initializer-list leaves a
486 // member of reference type uninitialized, the program is
487 // ill-formed.
488 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
489 << Field->getType()
490 << ILE->getSyntacticForm()->getSourceRange();
491 SemaRef.Diag(Field->getLocation(),
492 diag::note_uninit_reference_member);
493 hadError = true;
494 return;
495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000496
Richard Smith454a7cd2014-06-03 08:26:00 +0000497 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
498 /*VerifyOnly*/false);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000499 if (MemberInit.isInvalid()) {
500 hadError = true;
501 return;
502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Douglas Gregor2bb07652009-12-22 00:05:34 +0000504 if (hadError) {
505 // Do nothing
506 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000507 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000508 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
509 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000510 // extend the initializer list to include the constructor
511 // call and make a note that we'll need to take another pass
512 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000513 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000514 RequiresSecondPass = true;
515 }
516 } else if (InitListExpr *InnerILE
517 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000518 FillInEmptyInitializations(MemberEntity, InnerILE,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000520}
521
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522/// Recursively replaces NULL values within the given initializer list
523/// with expressions that perform value-initialization of the
524/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525void
Richard Smith454a7cd2014-06-03 08:26:00 +0000526InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000527 InitListExpr *ILE,
528 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000529 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000530 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000531
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000532 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000533 const RecordDecl *RDecl = RType->getDecl();
534 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000535 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Douglas Gregor2bb07652009-12-22 00:05:34 +0000536 Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000537 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
538 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000539 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000540 if (Field->hasInClassInitializer()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000541 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000542 break;
543 }
544 }
545 } else {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000546 unsigned Init = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000547 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000548 if (Field->isUnnamedBitfield())
549 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000550
Douglas Gregor2bb07652009-12-22 00:05:34 +0000551 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000552 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000553
Richard Smith454a7cd2014-06-03 08:26:00 +0000554 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000555 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000556 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000557
Douglas Gregor2bb07652009-12-22 00:05:34 +0000558 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000559
Douglas Gregor2bb07652009-12-22 00:05:34 +0000560 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000561 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000562 break;
563 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000564 }
565
566 return;
Mike Stump11289f42009-09-09 15:08:12 +0000567 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000568
569 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000570
Douglas Gregor723796a2009-12-16 06:35:08 +0000571 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000572 unsigned NumInits = ILE->getNumInits();
573 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000574 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000575 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000576 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
577 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000579 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000580 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000581 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000582 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000584 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000585 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000586 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000587
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000588 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000589 if (hadError)
590 return;
591
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000592 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
593 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000594 ElementEntity.setElementIndex(Init);
595
Craig Topperc3ec1492014-05-26 06:22:03 +0000596 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000597 if (!InitExpr && !ILE->hasArrayFiller()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000598 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
599 ElementEntity,
600 /*VerifyOnly*/false);
Douglas Gregor723796a2009-12-16 06:35:08 +0000601 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000602 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000603 return;
604 }
605
606 if (hadError) {
607 // Do nothing
608 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000609 // For arrays, just set the expression used for value-initialization
610 // of the "holes" in the array.
611 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000612 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000613 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000614 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000615 } else {
616 // For arrays, just set the expression used for value-initialization
617 // of the rest of elements and exit.
618 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000619 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000620 return;
621 }
622
Richard Smith454a7cd2014-06-03 08:26:00 +0000623 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
624 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000625 // extend the initializer list to include the constructor
626 // call and make a note that we'll need to take another pass
627 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000628 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000629 RequiresSecondPass = true;
630 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000631 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000632 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000633 = dyn_cast_or_null<InitListExpr>(InitExpr))
Richard Smith454a7cd2014-06-03 08:26:00 +0000634 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000635 }
636}
637
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000638
Douglas Gregor723796a2009-12-16 06:35:08 +0000639InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000640 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000641 bool VerifyOnly)
642 : SemaRef(S), VerifyOnly(VerifyOnly) {
Richard Smith520449d2015-02-05 06:15:50 +0000643 // FIXME: Check that IL isn't already the semantic form of some other
644 // InitListExpr. If it is, we'd create a broken AST.
645
Steve Narofff8ecff22008-05-01 22:18:59 +0000646 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000647
Richard Smith4e0d2e42013-09-20 20:10:22 +0000648 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000649 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000650 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000651 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000652
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000653 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000654 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000655 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000656 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000657 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000658 RequiresSecondPass);
659 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000660}
661
662int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000663 // FIXME: use a proper constant
664 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000665 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000666 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000667 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
668 }
669 return maxElements;
670}
671
672int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000673 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000674 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000675 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000676 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000677 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000678
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000679 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000680 return std::min(InitializableMembers, 1);
681 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000682}
683
Richard Smith4e0d2e42013-09-20 20:10:22 +0000684/// Check whether the range of the initializer \p ParentIList from element
685/// \p Index onwards can be used to initialize an object of type \p T. Update
686/// \p Index to indicate how many elements of the list were consumed.
687///
688/// This also fills in \p StructuredList, from element \p StructuredIndex
689/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000690void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000691 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 QualType T, unsigned &Index,
693 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000694 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000695 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000696
Steve Narofff8ecff22008-05-01 22:18:59 +0000697 if (T->isArrayType())
698 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000699 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000700 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000701 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000702 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000703 else
David Blaikie83d382b2011-09-23 05:06:16 +0000704 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000705
Eli Friedmane0f832b2008-05-25 13:49:22 +0000706 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
709 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000710 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000711 hadError = true;
712 return;
713 }
714
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000715 // Build a structured initializer list corresponding to this subobject.
716 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000717 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
718 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000719 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000720 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000721 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000722
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000723 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000724 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000726 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000727 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000728 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000729
Richard Smithde229232013-06-06 11:41:05 +0000730 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000731 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000732
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000733 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000734 // Update the structured sub-object initializer so that it's ending
735 // range corresponds with the end of the last initializer it used.
736 if (EndIndex < ParentIList->getNumInits()) {
737 SourceLocation EndLoc
738 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
739 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000742 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000743 if (T->isArrayType() || T->isRecordType()) {
744 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000745 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000746 << StructuredSubobjectInitList->getSourceRange()
747 << FixItHint::CreateInsertion(
748 StructuredSubobjectInitList->getLocStart(), "{")
749 << FixItHint::CreateInsertion(
750 SemaRef.getLocForEndOfToken(
751 StructuredSubobjectInitList->getLocEnd()),
752 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000753 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000754 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000755}
756
Richard Smith420fa122015-02-12 01:50:05 +0000757/// Warn that \p Entity was of scalar type and was initialized by a
758/// single-element braced initializer list.
759static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
760 SourceRange Braces) {
761 // Don't warn during template instantiation. If the initialization was
762 // non-dependent, we warned during the initial parse; otherwise, the
763 // type might not be scalar in some uses of the template.
764 if (!S.ActiveTemplateInstantiations.empty())
765 return;
766
767 unsigned DiagID = 0;
768
769 switch (Entity.getKind()) {
770 case InitializedEntity::EK_VectorElement:
771 case InitializedEntity::EK_ComplexElement:
772 case InitializedEntity::EK_ArrayElement:
773 case InitializedEntity::EK_Parameter:
774 case InitializedEntity::EK_Parameter_CF_Audited:
775 case InitializedEntity::EK_Result:
776 // Extra braces here are suspicious.
777 DiagID = diag::warn_braces_around_scalar_init;
778 break;
779
780 case InitializedEntity::EK_Member:
781 // Warn on aggregate initialization but not on ctor init list or
782 // default member initializer.
783 if (Entity.getParent())
784 DiagID = diag::warn_braces_around_scalar_init;
785 break;
786
787 case InitializedEntity::EK_Variable:
788 case InitializedEntity::EK_LambdaCapture:
789 // No warning, might be direct-list-initialization.
790 // FIXME: Should we warn for copy-list-initialization in these cases?
791 break;
792
793 case InitializedEntity::EK_New:
794 case InitializedEntity::EK_Temporary:
795 case InitializedEntity::EK_CompoundLiteralInit:
796 // No warning, braces are part of the syntax of the underlying construct.
797 break;
798
799 case InitializedEntity::EK_RelatedResult:
800 // No warning, we already warned when initializing the result.
801 break;
802
803 case InitializedEntity::EK_Exception:
804 case InitializedEntity::EK_Base:
805 case InitializedEntity::EK_Delegating:
806 case InitializedEntity::EK_BlockElement:
807 llvm_unreachable("unexpected braced scalar init");
808 }
809
810 if (DiagID) {
811 S.Diag(Braces.getBegin(), DiagID)
812 << Braces
813 << FixItHint::CreateRemoval(Braces.getBegin())
814 << FixItHint::CreateRemoval(Braces.getEnd());
815 }
816}
817
818
Richard Smith4e0d2e42013-09-20 20:10:22 +0000819/// Check whether the initializer \p IList (that was written with explicit
820/// braces) can be used to initialize an object of type \p T.
821///
822/// This also fills in \p StructuredList with the fully-braced, desugared
823/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000824void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000825 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000826 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000827 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000828 if (!VerifyOnly) {
829 SyntacticToSemantic[IList] = StructuredList;
830 StructuredList->setSyntacticForm(IList);
831 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000832
833 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000835 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000836 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000837 QualType ExprTy = T;
838 if (!ExprTy->isArrayType())
839 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000840 IList->setType(ExprTy);
841 StructuredList->setType(ExprTy);
842 }
Eli Friedman85f54972008-05-25 13:22:35 +0000843 if (hadError)
844 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000845
Eli Friedman85f54972008-05-25 13:22:35 +0000846 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000847 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000848 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000849 if (SemaRef.getLangOpts().CPlusPlus ||
850 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000851 IList->getType()->isVectorType())) {
852 hadError = true;
853 }
854 return;
855 }
856
Eli Friedmanbd327452009-05-29 20:20:05 +0000857 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000858 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
859 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000860 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000861 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000862 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000863 hadError = true;
864 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000865 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000866 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000867 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000868 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000869 // Don't complain for incomplete types, since we'll get an error
870 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000871 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000872 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000873 CurrentObjectType->isArrayType()? 0 :
874 CurrentObjectType->isVectorType()? 1 :
875 CurrentObjectType->isScalarType()? 2 :
876 CurrentObjectType->isUnionType()? 3 :
877 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000878
Richard Smith1b98ccc2014-07-19 01:39:17 +0000879 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000880 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000881 DK = diag::err_excess_initializers;
882 hadError = true;
883 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000884 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000885 DK = diag::err_excess_initializers;
886 hadError = true;
887 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000888
Chris Lattnerb0912a52009-02-24 22:50:46 +0000889 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000890 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000891 }
892 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000893
Richard Smith420fa122015-02-12 01:50:05 +0000894 if (!VerifyOnly && T->isScalarType() &&
895 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
896 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +0000897}
898
Anders Carlsson6cabf312010-01-23 23:23:01 +0000899void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000900 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000901 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000902 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 unsigned &Index,
904 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000905 unsigned &StructuredIndex,
906 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000907 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
908 // Explicitly braced initializer for complex type can be real+imaginary
909 // parts.
910 CheckComplexType(Entity, IList, DeclType, Index,
911 StructuredList, StructuredIndex);
912 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000913 CheckScalarType(Entity, IList, DeclType, Index,
914 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000915 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000917 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000918 } else if (DeclType->isRecordType()) {
919 assert(DeclType->isAggregateType() &&
920 "non-aggregate records should be handed in CheckSubElementType");
921 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
922 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
923 SubobjectIsDesignatorContext, Index,
924 StructuredList, StructuredIndex,
925 TopLevelObject);
926 } else if (DeclType->isArrayType()) {
927 llvm::APSInt Zero(
928 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
929 false);
930 CheckArrayType(Entity, IList, DeclType, Zero,
931 SubobjectIsDesignatorContext, Index,
932 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000933 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
934 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000935 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000936 if (!VerifyOnly)
937 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
938 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000939 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000940 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000941 CheckReferenceType(Entity, IList, DeclType, Index,
942 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000943 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000944 if (!VerifyOnly)
945 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
946 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000947 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000948 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000949 if (!VerifyOnly)
950 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
951 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000952 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000953 }
954}
955
Anders Carlsson6cabf312010-01-23 23:23:01 +0000956void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000957 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000958 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000959 unsigned &Index,
960 InitListExpr *StructuredList,
961 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000962 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000963
964 if (ElemType->isReferenceType())
965 return CheckReferenceType(Entity, IList, ElemType, Index,
966 StructuredList, StructuredIndex);
967
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000968 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smithe20c83d2012-07-07 08:35:56 +0000969 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000970 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000971 = getStructuredSubobjectInit(IList, Index, ElemType,
972 StructuredList, StructuredIndex,
973 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000974 CheckExplicitInitList(Entity, SubInitList, ElemType,
975 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000976 ++StructuredIndex;
977 ++Index;
978 return;
979 }
980 assert(SemaRef.getLangOpts().CPlusPlus &&
981 "non-aggregate records are only possible in C++");
982 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +0000983 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +0000984 // This happens during template instantiation when we see an InitListExpr
985 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +0000986 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +0000987 "found implicit initialization for the wrong type");
988 if (!VerifyOnly)
989 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
990 ++Index;
991 return;
Richard Smithe20c83d2012-07-07 08:35:56 +0000992 }
993
Eli Friedman4628cf72013-08-19 22:12:56 +0000994 // FIXME: Need to handle atomic aggregate types with implicit init lists.
995 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000996 return CheckScalarType(Entity, IList, ElemType, Index,
997 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000998
Eli Friedman4628cf72013-08-19 22:12:56 +0000999 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1000 ElemType->isArrayType()) && "Unexpected type");
1001
John McCall5decec92011-02-21 07:57:55 +00001002 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
1003 // arrayType can be incomplete if we're initializing a flexible
1004 // array member. There's nothing we can do with the completed
1005 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001007 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001008 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001009 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1010 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001011 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001012 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001013 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001014 }
John McCall5decec92011-02-21 07:57:55 +00001015
1016 // Fall through for subaggregate initialization.
1017
David Blaikiebbafb8a2012-03-11 07:00:24 +00001018 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +00001019 // C++ [dcl.init.aggr]p12:
1020 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +00001021 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +00001022 // an initializer-list. If the initializer can initialize a
1023 // member, the member is initialized. [...]
1024
1025 // FIXME: Better EqualLoc?
1026 InitializationKind Kind =
1027 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001028 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +00001029
1030 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001031 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +00001032 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001033 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +00001034 if (Result.isInvalid())
1035 hadError = true;
John McCall5decec92011-02-21 07:57:55 +00001036
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001037 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001038 Result.getAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001039 }
John McCall5decec92011-02-21 07:57:55 +00001040 ++Index;
1041 return;
1042 }
1043
1044 // Fall through for subaggregate initialization
1045 } else {
1046 // C99 6.7.8p13:
1047 //
1048 // The initializer for a structure or union object that has
1049 // automatic storage duration shall be either an initializer
1050 // list as described below, or a single expression that has
1051 // compatible structure or union type. In the latter case, the
1052 // initial value of the object, including unnamed members, is
1053 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001054 ExprResult ExprRes = expr;
John McCall5decec92011-02-21 07:57:55 +00001055 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001056 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
1057 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +00001058 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001059 if (ExprRes.isInvalid())
1060 hadError = true;
1061 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001062 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001063 if (ExprRes.isInvalid())
1064 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001065 }
1066 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001067 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001068 ++Index;
1069 return;
1070 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001071 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001072 // Fall through for subaggregate initialization
1073 }
1074
1075 // C++ [dcl.init.aggr]p12:
1076 //
1077 // [...] Otherwise, if the member is itself a non-empty
1078 // subaggregate, brace elision is assumed and the initializer is
1079 // considered for the initialization of the first member of
1080 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001081 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001082 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001083 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1084 StructuredIndex);
1085 ++StructuredIndex;
1086 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001087 if (!VerifyOnly) {
1088 // We cannot initialize this element, so let
1089 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001090 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001091 /*TopLevelOfInitList=*/true);
1092 }
John McCall5decec92011-02-21 07:57:55 +00001093 hadError = true;
1094 ++Index;
1095 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001096 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001097}
1098
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001099void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1100 InitListExpr *IList, QualType DeclType,
1101 unsigned &Index,
1102 InitListExpr *StructuredList,
1103 unsigned &StructuredIndex) {
1104 assert(Index == 0 && "Index in explicit init list must be zero");
1105
1106 // As an extension, clang supports complex initializers, which initialize
1107 // a complex number component-wise. When an explicit initializer list for
1108 // a complex number contains two two initializers, this extension kicks in:
1109 // it exepcts the initializer list to contain two elements convertible to
1110 // the element type of the complex type. The first element initializes
1111 // the real part, and the second element intitializes the imaginary part.
1112
1113 if (IList->getNumInits() != 2)
1114 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1115 StructuredIndex);
1116
1117 // This is an extension in C. (The builtin _Complex type does not exist
1118 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001119 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001120 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1121 << IList->getSourceRange();
1122
1123 // Initialize the complex number.
1124 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1125 InitializedEntity ElementEntity =
1126 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1127
1128 for (unsigned i = 0; i < 2; ++i) {
1129 ElementEntity.setElementIndex(Index);
1130 CheckSubElementType(ElementEntity, IList, elementType, Index,
1131 StructuredList, StructuredIndex);
1132 }
1133}
1134
1135
Anders Carlsson6cabf312010-01-23 23:23:01 +00001136void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001137 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001138 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001139 InitListExpr *StructuredList,
1140 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001141 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001142 if (!VerifyOnly)
1143 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001144 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001145 diag::warn_cxx98_compat_empty_scalar_initializer :
1146 diag::err_empty_scalar_initializer)
1147 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001148 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001149 ++Index;
1150 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001151 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001152 }
John McCall643169b2010-11-11 00:46:36 +00001153
1154 Expr *expr = IList->getInit(Index);
1155 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001156 // FIXME: This is invalid, and accepting it causes overload resolution
1157 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001158 if (!VerifyOnly)
1159 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001160 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001161 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001162
1163 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1164 StructuredIndex);
1165 return;
1166 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001167 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001168 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001169 diag::err_designator_for_scalar_init)
1170 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001171 hadError = true;
1172 ++Index;
1173 ++StructuredIndex;
1174 return;
1175 }
1176
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001177 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001178 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001179 hadError = true;
1180 ++Index;
1181 return;
1182 }
1183
John McCall643169b2010-11-11 00:46:36 +00001184 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001185 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001186 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001187
Craig Topperc3ec1492014-05-26 06:22:03 +00001188 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001189
1190 if (Result.isInvalid())
1191 hadError = true; // types weren't compatible.
1192 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001193 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194
John McCall643169b2010-11-11 00:46:36 +00001195 if (ResultExpr != expr) {
1196 // The type was promoted, update initializer list.
1197 IList->setInit(Index, ResultExpr);
1198 }
1199 }
1200 if (hadError)
1201 ++StructuredIndex;
1202 else
1203 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1204 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001205}
1206
Anders Carlsson6cabf312010-01-23 23:23:01 +00001207void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1208 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001209 unsigned &Index,
1210 InitListExpr *StructuredList,
1211 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001212 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001213 // FIXME: It would be wonderful if we could point at the actual member. In
1214 // general, it would be useful to pass location information down the stack,
1215 // so that we know the location (or decl) of the "current object" being
1216 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001217 if (!VerifyOnly)
1218 SemaRef.Diag(IList->getLocStart(),
1219 diag::err_init_reference_member_uninitialized)
1220 << DeclType
1221 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001222 hadError = true;
1223 ++Index;
1224 ++StructuredIndex;
1225 return;
1226 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001227
1228 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001229 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001230 if (!VerifyOnly)
1231 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1232 << DeclType << IList->getSourceRange();
1233 hadError = true;
1234 ++Index;
1235 ++StructuredIndex;
1236 return;
1237 }
1238
1239 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001240 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001241 hadError = true;
1242 ++Index;
1243 return;
1244 }
1245
1246 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001247 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1248 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001249
1250 if (Result.isInvalid())
1251 hadError = true;
1252
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001253 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001254 IList->setInit(Index, expr);
1255
1256 if (hadError)
1257 ++StructuredIndex;
1258 else
1259 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1260 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001261}
1262
Anders Carlsson6cabf312010-01-23 23:23:01 +00001263void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001264 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001265 unsigned &Index,
1266 InitListExpr *StructuredList,
1267 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001268 const VectorType *VT = DeclType->getAs<VectorType>();
1269 unsigned maxElements = VT->getNumElements();
1270 unsigned numEltsInit = 0;
1271 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001272
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001273 if (Index >= IList->getNumInits()) {
1274 // Make sure the element type can be value-initialized.
1275 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001276 CheckEmptyInitializable(
1277 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1278 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001279 return;
1280 }
1281
David Blaikiebbafb8a2012-03-11 07:00:24 +00001282 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001283 // If the initializing element is a vector, try to copy-initialize
1284 // instead of breaking it apart (which is doomed to failure anyway).
1285 Expr *Init = IList->getInit(Index);
1286 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001287 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001288 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001289 hadError = true;
1290 ++Index;
1291 return;
1292 }
1293
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001294 ExprResult Result =
1295 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1296 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001297
Craig Topperc3ec1492014-05-26 06:22:03 +00001298 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001299 if (Result.isInvalid())
1300 hadError = true; // types weren't compatible.
1301 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001302 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303
John McCall6a16b2f2010-10-30 00:11:39 +00001304 if (ResultExpr != Init) {
1305 // The type was promoted, update initializer list.
1306 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001307 }
1308 }
John McCall6a16b2f2010-10-30 00:11:39 +00001309 if (hadError)
1310 ++StructuredIndex;
1311 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001312 UpdateStructuredListElement(StructuredList, StructuredIndex,
1313 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001314 ++Index;
1315 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001316 }
Mike Stump11289f42009-09-09 15:08:12 +00001317
John McCall6a16b2f2010-10-30 00:11:39 +00001318 InitializedEntity ElementEntity =
1319 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320
John McCall6a16b2f2010-10-30 00:11:39 +00001321 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1322 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001323 if (Index >= IList->getNumInits()) {
1324 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001325 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001326 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
John McCall6a16b2f2010-10-30 00:11:39 +00001329 ElementEntity.setElementIndex(Index);
1330 CheckSubElementType(ElementEntity, IList, elementType, Index,
1331 StructuredList, StructuredIndex);
1332 }
James Molloy9eef2652014-06-20 14:35:13 +00001333
1334 if (VerifyOnly)
1335 return;
1336
1337 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1338 const VectorType *T = Entity.getType()->getAs<VectorType>();
1339 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1340 T->getVectorKind() == VectorType::NeonPolyVector)) {
1341 // The ability to use vector initializer lists is a GNU vector extension
1342 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1343 // endian machines it works fine, however on big endian machines it
1344 // exhibits surprising behaviour:
1345 //
1346 // uint32x2_t x = {42, 64};
1347 // return vget_lane_u32(x, 0); // Will return 64.
1348 //
1349 // Because of this, explicitly call out that it is non-portable.
1350 //
1351 SemaRef.Diag(IList->getLocStart(),
1352 diag::warn_neon_vector_initializer_non_portable);
1353
1354 const char *typeCode;
1355 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1356
1357 if (elementType->isFloatingType())
1358 typeCode = "f";
1359 else if (elementType->isSignedIntegerType())
1360 typeCode = "s";
1361 else if (elementType->isUnsignedIntegerType())
1362 typeCode = "u";
1363 else
1364 llvm_unreachable("Invalid element type!");
1365
1366 SemaRef.Diag(IList->getLocStart(),
1367 SemaRef.Context.getTypeSize(VT) > 64 ?
1368 diag::note_neon_vector_initializer_non_portable_q :
1369 diag::note_neon_vector_initializer_non_portable)
1370 << typeCode << typeSize;
1371 }
1372
John McCall6a16b2f2010-10-30 00:11:39 +00001373 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001374 }
John McCall6a16b2f2010-10-30 00:11:39 +00001375
1376 InitializedEntity ElementEntity =
1377 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001378
John McCall6a16b2f2010-10-30 00:11:39 +00001379 // OpenCL initializers allows vectors to be constructed from vectors.
1380 for (unsigned i = 0; i < maxElements; ++i) {
1381 // Don't attempt to go past the end of the init list
1382 if (Index >= IList->getNumInits())
1383 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384
John McCall6a16b2f2010-10-30 00:11:39 +00001385 ElementEntity.setElementIndex(Index);
1386
1387 QualType IType = IList->getInit(Index)->getType();
1388 if (!IType->isVectorType()) {
1389 CheckSubElementType(ElementEntity, IList, elementType, Index,
1390 StructuredList, StructuredIndex);
1391 ++numEltsInit;
1392 } else {
1393 QualType VecType;
1394 const VectorType *IVT = IType->getAs<VectorType>();
1395 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001396
John McCall6a16b2f2010-10-30 00:11:39 +00001397 if (IType->isExtVectorType())
1398 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1399 else
1400 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001401 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001402 CheckSubElementType(ElementEntity, IList, VecType, Index,
1403 StructuredList, StructuredIndex);
1404 numEltsInit += numIElts;
1405 }
1406 }
1407
1408 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001409 if (numEltsInit != maxElements) {
1410 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001411 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001412 diag::err_vector_incorrect_num_initializers)
1413 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1414 hadError = true;
1415 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001416}
1417
Anders Carlsson6cabf312010-01-23 23:23:01 +00001418void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001419 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001420 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001421 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001422 unsigned &Index,
1423 InitListExpr *StructuredList,
1424 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001425 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1426
Steve Narofff8ecff22008-05-01 22:18:59 +00001427 // Check for the special-case of initializing an array with a string.
1428 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001429 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1430 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001431 // We place the string literal directly into the resulting
1432 // initializer list. This is the only place where the structure
1433 // of the structured initializer list doesn't match exactly,
1434 // because doing so would involve allocating one character
1435 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001436 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001437 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1438 UpdateStructuredListElement(StructuredList, StructuredIndex,
1439 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001440 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1441 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001442 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001443 return;
1444 }
1445 }
John McCall66884dd2011-02-21 07:22:22 +00001446 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001447 // Check for VLAs; in standard C it would be possible to check this
1448 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1449 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001450 if (!VerifyOnly)
1451 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1452 diag::err_variable_object_no_init)
1453 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001454 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001455 ++Index;
1456 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001457 return;
1458 }
1459
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001460 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001461 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1462 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001463 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001464 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001465 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001466 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001467 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001468 maxElementsKnown = true;
1469 }
1470
John McCall66884dd2011-02-21 07:22:22 +00001471 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001472 while (Index < IList->getNumInits()) {
1473 Expr *Init = IList->getInit(Index);
1474 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001475 // If we're not the subobject that matches up with the '{' for
1476 // the designator, we shouldn't be handling the
1477 // designator. Return immediately.
1478 if (!SubobjectIsDesignatorContext)
1479 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001480
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001481 // Handle this designated initializer. elementIndex will be
1482 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001483 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001484 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001485 StructuredList, StructuredIndex, true,
1486 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001487 hadError = true;
1488 continue;
1489 }
1490
Douglas Gregor033d1252009-01-23 16:54:12 +00001491 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001492 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001493 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001494 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001495 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001496
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001497 // If the array is of incomplete type, keep track of the number of
1498 // elements in the initializer.
1499 if (!maxElementsKnown && elementIndex > maxElements)
1500 maxElements = elementIndex;
1501
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001502 continue;
1503 }
1504
1505 // If we know the maximum number of elements, and we've already
1506 // hit it, stop consuming elements in the initializer list.
1507 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001508 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001509
Anders Carlsson6cabf312010-01-23 23:23:01 +00001510 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001511 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001512 Entity);
1513 // Check this element.
1514 CheckSubElementType(ElementEntity, IList, elementType, Index,
1515 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001516 ++elementIndex;
1517
1518 // If the array is of incomplete type, keep track of the number of
1519 // elements in the initializer.
1520 if (!maxElementsKnown && elementIndex > maxElements)
1521 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001522 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001523 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001524 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001525 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001526 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001527 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001528 // Sizing an array implicitly to zero is not allowed by ISO C,
1529 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001530 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001531 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001532 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001533
Mike Stump11289f42009-09-09 15:08:12 +00001534 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001535 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001536 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001537 if (!hadError && VerifyOnly) {
1538 // Check if there are any members of the array that get value-initialized.
1539 // If so, check if doing that is possible.
1540 // FIXME: This needs to detect holes left by designated initializers too.
1541 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001542 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1543 SemaRef.Context, 0, Entity),
1544 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001545 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001546}
1547
Eli Friedman3fa64df2011-08-23 22:24:57 +00001548bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1549 Expr *InitExpr,
1550 FieldDecl *Field,
1551 bool TopLevelObject) {
1552 // Handle GNU flexible array initializers.
1553 unsigned FlexArrayDiag;
1554 if (isa<InitListExpr>(InitExpr) &&
1555 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1556 // Empty flexible array init always allowed as an extension
1557 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001558 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001559 // Disallow flexible array init in C++; it is not required for gcc
1560 // compatibility, and it needs work to IRGen correctly in general.
1561 FlexArrayDiag = diag::err_flexible_array_init;
1562 } else if (!TopLevelObject) {
1563 // Disallow flexible array init on non-top-level object
1564 FlexArrayDiag = diag::err_flexible_array_init;
1565 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1566 // Disallow flexible array init on anything which is not a variable.
1567 FlexArrayDiag = diag::err_flexible_array_init;
1568 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1569 // Disallow flexible array init on local variables.
1570 FlexArrayDiag = diag::err_flexible_array_init;
1571 } else {
1572 // Allow other cases.
1573 FlexArrayDiag = diag::ext_flexible_array_init;
1574 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001575
1576 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001577 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001578 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001579 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001580 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1581 << Field;
1582 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001583
1584 return FlexArrayDiag != diag::ext_flexible_array_init;
1585}
1586
Anders Carlsson6cabf312010-01-23 23:23:01 +00001587void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001588 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001589 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001590 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001591 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001592 unsigned &Index,
1593 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001594 unsigned &StructuredIndex,
1595 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001596 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001597
Eli Friedman23a9e312008-05-19 19:16:24 +00001598 // If the record is invalid, some of it's members are invalid. To avoid
1599 // confusion, we forgo checking the intializer for the entire record.
1600 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001601 // Assume it was supposed to consume a single initializer.
1602 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001603 hadError = true;
1604 return;
Mike Stump11289f42009-09-09 15:08:12 +00001605 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001606
1607 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001608 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001609
1610 // If there's a default initializer, use it.
1611 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1612 if (VerifyOnly)
1613 return;
1614 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1615 Field != FieldEnd; ++Field) {
1616 if (Field->hasInClassInitializer()) {
1617 StructuredList->setInitializedFieldInUnion(*Field);
1618 // FIXME: Actually build a CXXDefaultInitExpr?
1619 return;
1620 }
1621 }
1622 }
1623
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001624 // Value-initialize the first member of the union that isn't an unnamed
1625 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001626 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1627 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001628 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001629 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001630 CheckEmptyInitializable(
1631 InitializedEntity::InitializeMember(*Field, &Entity),
1632 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001633 else
David Blaikie40ed2972012-06-06 20:45:41 +00001634 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001635 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001636 }
1637 }
1638 return;
1639 }
1640
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001641 // If structDecl is a forward declaration, this loop won't do
1642 // anything except look at designated initializers; That's okay,
1643 // because an error should get printed out elsewhere. It might be
1644 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001645 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001646 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001647 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001648 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001649 while (Index < IList->getNumInits()) {
1650 Expr *Init = IList->getInit(Index);
1651
1652 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001653 // If we're not the subobject that matches up with the '{' for
1654 // the designator, we shouldn't be handling the
1655 // designator. Return immediately.
1656 if (!SubobjectIsDesignatorContext)
1657 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001658
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001659 // Handle this designated initializer. Field will be updated to
1660 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001661 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001662 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001663 StructuredList, StructuredIndex,
1664 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001665 hadError = true;
1666
Douglas Gregora9add4e2009-02-12 19:00:39 +00001667 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001668
1669 // Disable check for missing fields when designators are used.
1670 // This matches gcc behaviour.
1671 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001672 continue;
1673 }
1674
1675 if (Field == FieldEnd) {
1676 // We've run out of fields. We're done.
1677 break;
1678 }
1679
Douglas Gregora9add4e2009-02-12 19:00:39 +00001680 // We've already initialized a member of a union. We're done.
1681 if (InitializedSomething && DeclType->isUnionType())
1682 break;
1683
Douglas Gregor91f84212008-12-11 16:49:14 +00001684 // If we've hit the flexible array member at the end, we're done.
1685 if (Field->getType()->isIncompleteArrayType())
1686 break;
1687
Douglas Gregor51695702009-01-29 16:53:55 +00001688 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001689 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001690 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001691 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001692 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001693
Douglas Gregora82064c2011-06-29 21:51:31 +00001694 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001695 bool InvalidUse;
1696 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001697 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001698 else
David Blaikie40ed2972012-06-06 20:45:41 +00001699 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001700 IList->getInit(Index)->getLocStart());
1701 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001702 ++Index;
1703 ++Field;
1704 hadError = true;
1705 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001706 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001707
Anders Carlsson6cabf312010-01-23 23:23:01 +00001708 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001709 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001710 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1711 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001712 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001713
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001714 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001715 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001716 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001717 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001718
1719 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001720 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001721
John McCalle40b58e2010-03-11 19:32:38 +00001722 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001723 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1724 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1725 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001726 // It is possible we have one or more unnamed bitfields remaining.
1727 // Find first (if any) named field and emit warning.
1728 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1729 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001730 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001731 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001732 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001733 break;
1734 }
1735 }
1736 }
1737
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001738 // Check that any remaining fields can be value-initialized.
1739 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1740 !Field->getType()->isIncompleteArrayType()) {
1741 // FIXME: Should check for holes left by designated initializers too.
1742 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001743 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001744 CheckEmptyInitializable(
1745 InitializedEntity::InitializeMember(*Field, &Entity),
1746 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001747 }
1748 }
1749
Mike Stump11289f42009-09-09 15:08:12 +00001750 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001751 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001752 return;
1753
David Blaikie40ed2972012-06-06 20:45:41 +00001754 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001755 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001756 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001757 ++Index;
1758 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001759 }
1760
Anders Carlsson6cabf312010-01-23 23:23:01 +00001761 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001762 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001763
Anders Carlsson6cabf312010-01-23 23:23:01 +00001764 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001765 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001766 StructuredList, StructuredIndex);
1767 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001768 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001769 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001770}
Steve Narofff8ecff22008-05-01 22:18:59 +00001771
Douglas Gregord5846a12009-04-15 06:41:24 +00001772/// \brief Expand a field designator that refers to a member of an
1773/// anonymous struct or union into a series of field designators that
1774/// refers to the field within the appropriate subobject.
1775///
Douglas Gregord5846a12009-04-15 06:41:24 +00001776static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001777 DesignatedInitExpr *DIE,
1778 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001779 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001780 typedef DesignatedInitExpr::Designator Designator;
1781
Douglas Gregord5846a12009-04-15 06:41:24 +00001782 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001783 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001784 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1785 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1786 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001787 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001788 DIE->getDesignator(DesigIdx)->getDotLoc(),
1789 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1790 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001791 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1792 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001793 assert(isa<FieldDecl>(*PI));
1794 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001795 }
1796
1797 // Expand the current designator into the set of replacement
1798 // designators, so we have a full subobject path down to where the
1799 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001800 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001801 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001802}
Mike Stump11289f42009-09-09 15:08:12 +00001803
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001804static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1805 DesignatedInitExpr *DIE) {
1806 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1807 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1808 for (unsigned I = 0; I < NumIndexExprs; ++I)
1809 IndexExprs[I] = DIE->getSubExpr(I + 1);
1810 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001811 DIE->size(), IndexExprs,
1812 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001813 DIE->usesGNUSyntax(), DIE->getInit());
1814}
1815
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001816namespace {
1817
1818// Callback to only accept typo corrections that are for field members of
1819// the given struct or union.
1820class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1821 public:
1822 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1823 : Record(RD) {}
1824
Craig Toppere14c0f82014-03-12 04:55:44 +00001825 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001826 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1827 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1828 }
1829
1830 private:
1831 RecordDecl *Record;
1832};
1833
1834}
1835
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001836/// @brief Check the well-formedness of a C99 designated initializer.
1837///
1838/// Determines whether the designated initializer @p DIE, which
1839/// resides at the given @p Index within the initializer list @p
1840/// IList, is well-formed for a current object of type @p DeclType
1841/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001842/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001843/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001844///
1845/// @param IList The initializer list in which this designated
1846/// initializer occurs.
1847///
Douglas Gregora5324162009-04-15 04:56:10 +00001848/// @param DIE The designated initializer expression.
1849///
1850/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001851///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001852/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001853/// into which the designation in @p DIE should refer.
1854///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001855/// @param NextField If non-NULL and the first designator in @p DIE is
1856/// a field, this will be set to the field declaration corresponding
1857/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001858///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001859/// @param NextElementIndex If non-NULL and the first designator in @p
1860/// DIE is an array designator or GNU array-range designator, this
1861/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001862///
1863/// @param Index Index into @p IList where the designated initializer
1864/// @p DIE occurs.
1865///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001866/// @param StructuredList The initializer list expression that
1867/// describes all of the subobject initializers in the order they'll
1868/// actually be initialized.
1869///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001870/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001871bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001872InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001873 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001874 DesignatedInitExpr *DIE,
1875 unsigned DesigIdx,
1876 QualType &CurrentObjectType,
1877 RecordDecl::field_iterator *NextField,
1878 llvm::APSInt *NextElementIndex,
1879 unsigned &Index,
1880 InitListExpr *StructuredList,
1881 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001882 bool FinishSubobjectInit,
1883 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001884 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001885 // Check the actual initialization for the designated object type.
1886 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001887
1888 // Temporarily remove the designator expression from the
1889 // initializer list that the child calls see, so that we don't try
1890 // to re-process the designator.
1891 unsigned OldIndex = Index;
1892 IList->setInit(OldIndex, DIE->getInit());
1893
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001894 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001895 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001896
1897 // Restore the designated initializer expression in the syntactic
1898 // form of the initializer list.
1899 if (IList->getInit(OldIndex) != DIE->getInit())
1900 DIE->setInit(IList->getInit(OldIndex));
1901 IList->setInit(OldIndex, DIE);
1902
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001903 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001904 }
1905
Douglas Gregora5324162009-04-15 04:56:10 +00001906 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001907 bool IsFirstDesignator = (DesigIdx == 0);
1908 if (!VerifyOnly) {
1909 assert((IsFirstDesignator || StructuredList) &&
1910 "Need a non-designated initializer list to start from");
1911
1912 // Determine the structural initializer list that corresponds to the
1913 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001914 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001915 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1916 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001917 SourceRange(D->getLocStart(),
1918 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001919 assert(StructuredList && "Expected a structured initializer list");
1920 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001921
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001922 if (D->isFieldDesignator()) {
1923 // C99 6.7.8p7:
1924 //
1925 // If a designator has the form
1926 //
1927 // . identifier
1928 //
1929 // then the current object (defined below) shall have
1930 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001931 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001932 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001933 if (!RT) {
1934 SourceLocation Loc = D->getDotLoc();
1935 if (Loc.isInvalid())
1936 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001937 if (!VerifyOnly)
1938 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001939 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001940 ++Index;
1941 return true;
1942 }
1943
Douglas Gregord5846a12009-04-15 06:41:24 +00001944 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00001945 if (!KnownField) {
1946 IdentifierInfo *FieldName = D->getFieldName();
1947 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1948 for (NamedDecl *ND : Lookup) {
1949 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
1950 KnownField = FD;
1951 break;
1952 }
1953 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001954 // In verify mode, don't modify the original.
1955 if (VerifyOnly)
1956 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00001957 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001958 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00001959 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001960 break;
1961 }
1962 }
David Majnemer36ef8982014-08-11 18:33:59 +00001963 if (!KnownField) {
1964 if (VerifyOnly) {
1965 ++Index;
1966 return true; // No typo correction when just trying this out.
1967 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001968
David Majnemer36ef8982014-08-11 18:33:59 +00001969 // Name lookup found something, but it wasn't a field.
1970 if (!Lookup.empty()) {
1971 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1972 << FieldName;
1973 SemaRef.Diag(Lookup.front()->getLocation(),
1974 diag::note_field_designator_found);
1975 ++Index;
1976 return true;
1977 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001978
David Majnemer36ef8982014-08-11 18:33:59 +00001979 // Name lookup didn't find anything.
1980 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00001981 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1982 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00001983 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001984 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
1985 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001986 SemaRef.diagnoseTypo(
1987 Corrected,
1988 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00001989 << FieldName << CurrentObjectType);
1990 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001991 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001992 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00001993 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001994 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1995 << FieldName << CurrentObjectType;
1996 ++Index;
1997 return true;
1998 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001999 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002000 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002001
David Majnemer58e4ea92014-08-23 01:48:50 +00002002 unsigned FieldIndex = 0;
2003 for (auto *FI : RT->getDecl()->fields()) {
2004 if (FI->isUnnamedBitfield())
2005 continue;
2006 if (KnownField == FI)
2007 break;
2008 ++FieldIndex;
2009 }
2010
David Majnemer36ef8982014-08-11 18:33:59 +00002011 RecordDecl::field_iterator Field =
2012 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2013
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002014 // All of the fields of a union are located at the same place in
2015 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002016 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002017 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002018 if (!VerifyOnly) {
2019 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2020 if (CurrentField && CurrentField != *Field) {
2021 assert(StructuredList->getNumInits() == 1
2022 && "A union should never have more than one initializer!");
2023
2024 // we're about to throw away an initializer, emit warning
2025 SemaRef.Diag(D->getFieldLoc(),
2026 diag::warn_initializer_overrides)
2027 << D->getSourceRange();
2028 Expr *ExistingInit = StructuredList->getInit(0);
2029 SemaRef.Diag(ExistingInit->getLocStart(),
2030 diag::note_previous_initializer)
2031 << /*FIXME:has side effects=*/0
2032 << ExistingInit->getSourceRange();
2033
2034 // remove existing initializer
2035 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002036 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002037 }
2038
David Blaikie40ed2972012-06-06 20:45:41 +00002039 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002040 }
Douglas Gregor51695702009-01-29 16:53:55 +00002041 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002042
Douglas Gregora82064c2011-06-29 21:51:31 +00002043 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002044 bool InvalidUse;
2045 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00002046 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002047 else
David Blaikie40ed2972012-06-06 20:45:41 +00002048 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002049 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002050 ++Index;
2051 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002052 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002053
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002054 if (!VerifyOnly) {
2055 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002056 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002057
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002058 // Make sure that our non-designated initializer list has space
2059 // for a subobject corresponding to this field.
2060 if (FieldIndex >= StructuredList->getNumInits())
2061 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2062 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002063
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002064 // This designator names a flexible array member.
2065 if (Field->getType()->isIncompleteArrayType()) {
2066 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002067 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002068 // We can't designate an object within the flexible array
2069 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002070 if (!VerifyOnly) {
2071 DesignatedInitExpr::Designator *NextD
2072 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002073 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002074 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002075 << SourceRange(NextD->getLocStart(),
2076 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002077 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002078 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002079 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002080 Invalid = true;
2081 }
2082
Chris Lattner001b29c2010-10-10 17:49:49 +00002083 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2084 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002085 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002086 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002087 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002088 diag::err_flexible_array_init_needs_braces)
2089 << DIE->getInit()->getSourceRange();
2090 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002091 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002092 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002093 Invalid = true;
2094 }
2095
Eli Friedman3fa64df2011-08-23 22:24:57 +00002096 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002097 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002098 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002099 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002100
2101 if (Invalid) {
2102 ++Index;
2103 return true;
2104 }
2105
2106 // Initialize the array.
2107 bool prevHadError = hadError;
2108 unsigned newStructuredIndex = FieldIndex;
2109 unsigned OldIndex = Index;
2110 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002111
2112 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002113 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002114 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002115 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002116
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002117 IList->setInit(OldIndex, DIE);
2118 if (hadError && !prevHadError) {
2119 ++Field;
2120 ++FieldIndex;
2121 if (NextField)
2122 *NextField = Field;
2123 StructuredIndex = FieldIndex;
2124 return true;
2125 }
2126 } else {
2127 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002128 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002129 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002131 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002132 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002134 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002135 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002136 true, false))
2137 return true;
2138 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002139
2140 // Find the position of the next field to be initialized in this
2141 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002142 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002143 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002144
2145 // If this the first designator, our caller will continue checking
2146 // the rest of this struct/class/union subobject.
2147 if (IsFirstDesignator) {
2148 if (NextField)
2149 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002150 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002151 return false;
2152 }
2153
Douglas Gregor17bd0942009-01-28 23:36:17 +00002154 if (!FinishSubobjectInit)
2155 return false;
2156
Douglas Gregord5846a12009-04-15 06:41:24 +00002157 // We've already initialized something in the union; we're done.
2158 if (RT->getDecl()->isUnion())
2159 return hadError;
2160
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002161 // Check the remaining fields within this class/struct/union subobject.
2162 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163
Anders Carlsson6cabf312010-01-23 23:23:01 +00002164 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002165 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002166 return hadError && !prevHadError;
2167 }
2168
2169 // C99 6.7.8p6:
2170 //
2171 // If a designator has the form
2172 //
2173 // [ constant-expression ]
2174 //
2175 // then the current object (defined below) shall have array
2176 // type and the expression shall be an integer constant
2177 // expression. If the array is of unknown size, any
2178 // nonnegative value is valid.
2179 //
2180 // Additionally, cope with the GNU extension that permits
2181 // designators of the form
2182 //
2183 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002184 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002185 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002186 if (!VerifyOnly)
2187 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2188 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002189 ++Index;
2190 return true;
2191 }
2192
Craig Topperc3ec1492014-05-26 06:22:03 +00002193 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002194 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2195 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002196 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002197 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002198 DesignatedEndIndex = DesignatedStartIndex;
2199 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002200 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002201
Mike Stump11289f42009-09-09 15:08:12 +00002202 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002203 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002204 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002205 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002206 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002207
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002208 // Codegen can't handle evaluating array range designators that have side
2209 // effects, because we replicate the AST value for each initialized element.
2210 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2211 // elements with something that has a side effect, so codegen can emit an
2212 // "error unsupported" error instead of miscompiling the app.
2213 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002214 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002215 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002216 }
2217
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002218 if (isa<ConstantArrayType>(AT)) {
2219 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002220 DesignatedStartIndex
2221 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002222 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002223 DesignatedEndIndex
2224 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002225 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2226 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002227 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002228 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002229 diag::err_array_designator_too_large)
2230 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2231 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002232 ++Index;
2233 return true;
2234 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002235 } else {
2236 // Make sure the bit-widths and signedness match.
2237 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002238 DesignatedEndIndex
2239 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002240 else if (DesignatedStartIndex.getBitWidth() <
2241 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002242 DesignatedStartIndex
2243 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002244 DesignatedStartIndex.setIsUnsigned(true);
2245 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002246 }
Mike Stump11289f42009-09-09 15:08:12 +00002247
Eli Friedman1f16b742013-06-11 21:48:11 +00002248 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2249 // We're modifying a string literal init; we have to decompose the string
2250 // so we can modify the individual characters.
2251 ASTContext &Context = SemaRef.Context;
2252 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2253
2254 // Compute the character type
2255 QualType CharTy = AT->getElementType();
2256
2257 // Compute the type of the integer literals.
2258 QualType PromotedCharTy = CharTy;
2259 if (CharTy->isPromotableIntegerType())
2260 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2261 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2262
2263 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2264 // Get the length of the string.
2265 uint64_t StrLen = SL->getLength();
2266 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2267 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2268 StructuredList->resizeInits(Context, StrLen);
2269
2270 // Build a literal for each character in the string, and put them into
2271 // the init list.
2272 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2273 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2274 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002275 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002276 if (CharTy != PromotedCharTy)
2277 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002278 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002279 StructuredList->updateInit(Context, i, Init);
2280 }
2281 } else {
2282 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2283 std::string Str;
2284 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2285
2286 // Get the length of the string.
2287 uint64_t StrLen = Str.size();
2288 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2289 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2290 StructuredList->resizeInits(Context, StrLen);
2291
2292 // Build a literal for each character in the string, and put them into
2293 // the init list.
2294 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2295 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2296 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002297 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002298 if (CharTy != PromotedCharTy)
2299 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002300 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002301 StructuredList->updateInit(Context, i, Init);
2302 }
2303 }
2304 }
2305
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002306 // Make sure that our non-designated initializer list has space
2307 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002308 if (!VerifyOnly &&
2309 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002310 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002311 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002312
Douglas Gregor17bd0942009-01-28 23:36:17 +00002313 // Repeatedly perform subobject initializations in the range
2314 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002315
Douglas Gregor17bd0942009-01-28 23:36:17 +00002316 // Move to the next designator
2317 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2318 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002319
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002320 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002321 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002322
Douglas Gregor17bd0942009-01-28 23:36:17 +00002323 while (DesignatedStartIndex <= DesignatedEndIndex) {
2324 // Recurse to check later designated subobjects.
2325 QualType ElementType = AT->getElementType();
2326 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002327
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002328 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002330 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002331 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002332 (DesignatedStartIndex == DesignatedEndIndex),
2333 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002334 return true;
2335
2336 // Move to the next index in the array that we'll be initializing.
2337 ++DesignatedStartIndex;
2338 ElementIndex = DesignatedStartIndex.getZExtValue();
2339 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002340
2341 // If this the first designator, our caller will continue checking
2342 // the rest of this array subobject.
2343 if (IsFirstDesignator) {
2344 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002345 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002346 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002347 return false;
2348 }
Mike Stump11289f42009-09-09 15:08:12 +00002349
Douglas Gregor17bd0942009-01-28 23:36:17 +00002350 if (!FinishSubobjectInit)
2351 return false;
2352
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002353 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002354 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002355 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002356 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002357 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002358 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002359}
2360
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002361// Get the structured initializer list for a subobject of type
2362// @p CurrentObjectType.
2363InitListExpr *
2364InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2365 QualType CurrentObjectType,
2366 InitListExpr *StructuredList,
2367 unsigned StructuredIndex,
2368 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002369 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002370 return nullptr; // No structured list in verification-only mode.
2371 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002372 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002373 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002374 else if (StructuredIndex < StructuredList->getNumInits())
2375 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002376
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002377 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2378 return Result;
2379
2380 if (ExistingInit) {
2381 // We are creating an initializer list that initializes the
2382 // subobjects of the current object, but there was already an
2383 // initialization that completely initialized the current
2384 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002385 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002386 // struct X { int a, b; };
2387 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002388 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002389 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2390 // designated initializer re-initializes the whole
2391 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002392 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002393 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002394 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002395 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002396 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002397 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002398 << ExistingInit->getSourceRange();
2399 }
2400
Mike Stump11289f42009-09-09 15:08:12 +00002401 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002402 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002403 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002404 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002405
Eli Friedman91f5ae52012-02-23 02:25:10 +00002406 QualType ResultType = CurrentObjectType;
2407 if (!ResultType->isArrayType())
2408 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2409 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002410
Douglas Gregor6d00c992009-03-20 23:58:33 +00002411 // Pre-allocate storage for the structured initializer list.
2412 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002413 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002414 bool GotNumInits = false;
2415 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002416 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002417 GotNumInits = true;
2418 } else if (Index < IList->getNumInits()) {
2419 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002420 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002421 GotNumInits = true;
2422 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002423 }
2424
Mike Stump11289f42009-09-09 15:08:12 +00002425 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002426 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2427 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2428 NumElements = CAType->getSize().getZExtValue();
2429 // Simple heuristic so that we don't allocate a very large
2430 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002431 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002432 NumElements = 0;
2433 }
John McCall9dd450b2009-09-21 23:43:11 +00002434 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002435 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002436 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002437 RecordDecl *RDecl = RType->getDecl();
2438 if (RDecl->isUnion())
2439 NumElements = 1;
2440 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002441 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002442 }
2443
Ted Kremenekac034612010-04-13 23:39:13 +00002444 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002445
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002446 // Link this new initializer list into the structured initializer
2447 // lists.
2448 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002449 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002450 else {
2451 Result->setSyntacticForm(IList);
2452 SyntacticToSemantic[IList] = Result;
2453 }
2454
2455 return Result;
2456}
2457
2458/// Update the initializer at index @p StructuredIndex within the
2459/// structured initializer list to the value @p expr.
2460void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2461 unsigned &StructuredIndex,
2462 Expr *expr) {
2463 // No structured initializer list to update
2464 if (!StructuredList)
2465 return;
2466
Ted Kremenekac034612010-04-13 23:39:13 +00002467 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2468 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002469 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002470 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002471 diag::warn_initializer_overrides)
2472 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002473 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002474 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002475 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002476 << PrevInit->getSourceRange();
2477 }
Mike Stump11289f42009-09-09 15:08:12 +00002478
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002479 ++StructuredIndex;
2480}
2481
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002482/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002483/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002484/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002485/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002486/// failure. Returns the index expression, possibly with an implicit cast
2487/// added, on success. If everything went okay, Value will receive the
2488/// value of the constant expression.
2489static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002490CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002491 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002492
2493 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002494 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2495 if (Result.isInvalid())
2496 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002497
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002498 if (Value.isSigned() && Value.isNegative())
2499 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002500 << Value.toString(10) << Index->getSourceRange();
2501
Douglas Gregor51650d32009-01-23 21:04:18 +00002502 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002503 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002504}
2505
John McCalldadc5752010-08-24 06:29:42 +00002506ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002507 SourceLocation Loc,
2508 bool GNUSyntax,
2509 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002510 typedef DesignatedInitExpr::Designator ASTDesignator;
2511
2512 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002513 SmallVector<ASTDesignator, 32> Designators;
2514 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002515
2516 // Build designators and check array designator expressions.
2517 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2518 const Designator &D = Desig.getDesignator(Idx);
2519 switch (D.getKind()) {
2520 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002521 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002522 D.getFieldLoc()));
2523 break;
2524
2525 case Designator::ArrayDesignator: {
2526 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2527 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002528 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002529 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002530 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002531 Invalid = true;
2532 else {
2533 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002534 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002535 D.getRBracketLoc()));
2536 InitExpressions.push_back(Index);
2537 }
2538 break;
2539 }
2540
2541 case Designator::ArrayRangeDesignator: {
2542 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2543 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2544 llvm::APSInt StartValue;
2545 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002546 bool StartDependent = StartIndex->isTypeDependent() ||
2547 StartIndex->isValueDependent();
2548 bool EndDependent = EndIndex->isTypeDependent() ||
2549 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002550 if (!StartDependent)
2551 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002552 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002553 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002554 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002555
2556 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002557 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002558 else {
2559 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002560 if (StartDependent || EndDependent) {
2561 // Nothing to compute.
2562 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002563 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002564 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002565 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002566
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002567 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002568 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002569 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002570 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2571 Invalid = true;
2572 } else {
2573 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002574 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002575 D.getEllipsisLoc(),
2576 D.getRBracketLoc()));
2577 InitExpressions.push_back(StartIndex);
2578 InitExpressions.push_back(EndIndex);
2579 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002580 }
2581 break;
2582 }
2583 }
2584 }
2585
2586 if (Invalid || Init.isInvalid())
2587 return ExprError();
2588
2589 // Clear out the expressions within the designation.
2590 Desig.ClearExprs(*this);
2591
2592 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002593 = DesignatedInitExpr::Create(Context,
2594 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002595 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002596 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002597
David Blaikiebbafb8a2012-03-11 07:00:24 +00002598 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002599 Diag(DIE->getLocStart(), diag::ext_designated_init)
2600 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002601
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002602 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002603}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002604
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002605//===----------------------------------------------------------------------===//
2606// Initialization entity
2607//===----------------------------------------------------------------------===//
2608
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002609InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002610 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002611 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002612{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002613 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2614 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002615 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002616 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002617 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002618 Type = VT->getElementType();
2619 } else {
2620 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2621 assert(CT && "Unexpected type");
2622 Kind = EK_ComplexElement;
2623 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002624 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002625}
2626
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002627InitializedEntity
2628InitializedEntity::InitializeBase(ASTContext &Context,
2629 const CXXBaseSpecifier *Base,
2630 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002631 InitializedEntity Result;
2632 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002633 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002634 Result.Base = reinterpret_cast<uintptr_t>(Base);
2635 if (IsInheritedVirtualBase)
2636 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002637
Douglas Gregor1b303932009-12-22 15:35:07 +00002638 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002639 return Result;
2640}
2641
Douglas Gregor85dabae2009-12-16 01:38:02 +00002642DeclarationName InitializedEntity::getName() const {
2643 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002644 case EK_Parameter:
2645 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002646 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2647 return (D ? D->getDeclName() : DeclarationName());
2648 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002649
2650 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002651 case EK_Member:
2652 return VariableOrMember->getDeclName();
2653
Douglas Gregor19666fb2012-02-15 16:57:26 +00002654 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002655 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002656
Douglas Gregor85dabae2009-12-16 01:38:02 +00002657 case EK_Result:
2658 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002659 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002660 case EK_Temporary:
2661 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002662 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002663 case EK_ArrayElement:
2664 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002665 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002666 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002667 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002668 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002669 return DeclarationName();
2670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671
David Blaikie8a40f702012-01-17 06:56:22 +00002672 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002673}
2674
Douglas Gregora4b592a2009-12-19 03:01:41 +00002675DeclaratorDecl *InitializedEntity::getDecl() const {
2676 switch (getKind()) {
2677 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002678 case EK_Member:
2679 return VariableOrMember;
2680
John McCall31168b02011-06-15 23:02:42 +00002681 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002682 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002683 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2684
Douglas Gregora4b592a2009-12-19 03:01:41 +00002685 case EK_Result:
2686 case EK_Exception:
2687 case EK_New:
2688 case EK_Temporary:
2689 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002690 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002691 case EK_ArrayElement:
2692 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002693 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002694 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002695 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002696 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002697 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002698 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002700
David Blaikie8a40f702012-01-17 06:56:22 +00002701 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002702}
2703
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002704bool InitializedEntity::allowsNRVO() const {
2705 switch (getKind()) {
2706 case EK_Result:
2707 case EK_Exception:
2708 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002710 case EK_Variable:
2711 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002712 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002713 case EK_Member:
2714 case EK_New:
2715 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002716 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002717 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002718 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002719 case EK_ArrayElement:
2720 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002721 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002722 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002723 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002724 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002725 break;
2726 }
2727
2728 return false;
2729}
2730
Richard Smithe6c01442013-06-05 00:46:14 +00002731unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002732 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002733 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2734 for (unsigned I = 0; I != Depth; ++I)
2735 OS << "`-";
2736
2737 switch (getKind()) {
2738 case EK_Variable: OS << "Variable"; break;
2739 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002740 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2741 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002742 case EK_Result: OS << "Result"; break;
2743 case EK_Exception: OS << "Exception"; break;
2744 case EK_Member: OS << "Member"; break;
2745 case EK_New: OS << "New"; break;
2746 case EK_Temporary: OS << "Temporary"; break;
2747 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002748 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002749 case EK_Base: OS << "Base"; break;
2750 case EK_Delegating: OS << "Delegating"; break;
2751 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2752 case EK_VectorElement: OS << "VectorElement " << Index; break;
2753 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2754 case EK_BlockElement: OS << "Block"; break;
2755 case EK_LambdaCapture:
2756 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002757 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002758 break;
2759 }
2760
2761 if (Decl *D = getDecl()) {
2762 OS << " ";
2763 cast<NamedDecl>(D)->printQualifiedName(OS);
2764 }
2765
2766 OS << " '" << getType().getAsString() << "'\n";
2767
2768 return Depth + 1;
2769}
2770
2771void InitializedEntity::dump() const {
2772 dumpImpl(llvm::errs());
2773}
2774
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002775//===----------------------------------------------------------------------===//
2776// Initialization sequence
2777//===----------------------------------------------------------------------===//
2778
2779void InitializationSequence::Step::Destroy() {
2780 switch (Kind) {
2781 case SK_ResolveAddressOfOverloadedFunction:
2782 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002783 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002784 case SK_CastDerivedToBaseLValue:
2785 case SK_BindReference:
2786 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002787 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002788 case SK_UserConversion:
2789 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002790 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002791 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00002792 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00002793 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002794 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00002795 case SK_UnwrapInitList:
2796 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002797 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00002798 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002799 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002800 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002801 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002802 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002803 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002804 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002805 case SK_PassByIndirectCopyRestore:
2806 case SK_PassByIndirectRestore:
2807 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002808 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00002809 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00002810 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002811 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002812 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002814 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002815 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002816 delete ICS;
2817 }
2818}
2819
Douglas Gregor838fcc32010-03-26 20:14:36 +00002820bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002821 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002822}
2823
2824bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002825 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002826 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002827
Douglas Gregor838fcc32010-03-26 20:14:36 +00002828 switch (getFailureKind()) {
2829 case FK_TooManyInitsForReference:
2830 case FK_ArrayNeedsInitList:
2831 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002832 case FK_ArrayNeedsInitListOrWideStringLiteral:
2833 case FK_NarrowStringIntoWideCharArray:
2834 case FK_WideStringIntoCharArray:
2835 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002836 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2837 case FK_NonConstLValueReferenceBindingToTemporary:
2838 case FK_NonConstLValueReferenceBindingToUnrelated:
2839 case FK_RValueReferenceBindingToLValue:
2840 case FK_ReferenceInitDropsQualifiers:
2841 case FK_ReferenceInitFailed:
2842 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002843 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002844 case FK_TooManyInitsForScalar:
2845 case FK_ReferenceBindingToInitList:
2846 case FK_InitListBadDestinationType:
2847 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002848 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002849 case FK_ArrayTypeMismatch:
2850 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002851 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002852 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002853 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002854 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002855 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002856
Douglas Gregor838fcc32010-03-26 20:14:36 +00002857 case FK_ReferenceInitOverloadFailed:
2858 case FK_UserConversionOverloadFailed:
2859 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002860 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002861 return FailedOverloadResult == OR_Ambiguous;
2862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863
David Blaikie8a40f702012-01-17 06:56:22 +00002864 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002865}
2866
Douglas Gregorb33eed02010-04-16 22:09:46 +00002867bool InitializationSequence::isConstructorInitialization() const {
2868 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2869}
2870
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002871void
2872InitializationSequence
2873::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2874 DeclAccessPair Found,
2875 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002876 Step S;
2877 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2878 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002879 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002880 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002881 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002882 Steps.push_back(S);
2883}
2884
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002886 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002887 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002888 switch (VK) {
2889 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2890 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2891 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002892 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002893 S.Type = BaseType;
2894 Steps.push_back(S);
2895}
2896
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002897void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002898 bool BindingTemporary) {
2899 Step S;
2900 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2901 S.Type = T;
2902 Steps.push_back(S);
2903}
2904
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002905void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2906 Step S;
2907 S.Kind = SK_ExtraneousCopyToTemporary;
2908 S.Type = T;
2909 Steps.push_back(S);
2910}
2911
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002912void
2913InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2914 DeclAccessPair FoundDecl,
2915 QualType T,
2916 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002917 Step S;
2918 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002919 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002920 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002921 S.Function.Function = Function;
2922 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002923 Steps.push_back(S);
2924}
2925
2926void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002927 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002928 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002929 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002930 switch (VK) {
2931 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002932 S.Kind = SK_QualificationConversionRValue;
2933 break;
John McCall2536c6d2010-08-25 10:28:54 +00002934 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002935 S.Kind = SK_QualificationConversionXValue;
2936 break;
John McCall2536c6d2010-08-25 10:28:54 +00002937 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002938 S.Kind = SK_QualificationConversionLValue;
2939 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002940 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002941 S.Type = Ty;
2942 Steps.push_back(S);
2943}
2944
Richard Smith77be48a2014-07-31 06:31:19 +00002945void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
2946 Step S;
2947 S.Kind = SK_AtomicConversion;
2948 S.Type = Ty;
2949 Steps.push_back(S);
2950}
2951
Jordan Roseb1312a52013-04-11 00:58:58 +00002952void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2953 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2954
2955 Step S;
2956 S.Kind = SK_LValueToRValue;
2957 S.Type = Ty;
2958 Steps.push_back(S);
2959}
2960
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002961void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002962 const ImplicitConversionSequence &ICS, QualType T,
2963 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002964 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002965 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2966 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002967 S.Type = T;
2968 S.ICS = new ImplicitConversionSequence(ICS);
2969 Steps.push_back(S);
2970}
2971
Douglas Gregor51e77d52009-12-10 17:56:55 +00002972void InitializationSequence::AddListInitializationStep(QualType T) {
2973 Step S;
2974 S.Kind = SK_ListInitialization;
2975 S.Type = T;
2976 Steps.push_back(S);
2977}
2978
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002980InitializationSequence
2981::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2982 AccessSpecifier Access,
2983 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002984 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002985 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002986 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00002987 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00002988 : SK_ConstructorInitializationFromList
2989 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002990 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002991 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002992 S.Function.Function = Constructor;
2993 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002994 Steps.push_back(S);
2995}
2996
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002997void InitializationSequence::AddZeroInitializationStep(QualType T) {
2998 Step S;
2999 S.Kind = SK_ZeroInitialization;
3000 S.Type = T;
3001 Steps.push_back(S);
3002}
3003
Douglas Gregore1314a62009-12-18 05:02:21 +00003004void InitializationSequence::AddCAssignmentStep(QualType T) {
3005 Step S;
3006 S.Kind = SK_CAssignment;
3007 S.Type = T;
3008 Steps.push_back(S);
3009}
3010
Eli Friedman78275202009-12-19 08:11:05 +00003011void InitializationSequence::AddStringInitStep(QualType T) {
3012 Step S;
3013 S.Kind = SK_StringInit;
3014 S.Type = T;
3015 Steps.push_back(S);
3016}
3017
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003018void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3019 Step S;
3020 S.Kind = SK_ObjCObjectConversion;
3021 S.Type = T;
3022 Steps.push_back(S);
3023}
3024
Douglas Gregore2f943b2011-02-22 18:29:51 +00003025void InitializationSequence::AddArrayInitStep(QualType T) {
3026 Step S;
3027 S.Kind = SK_ArrayInit;
3028 S.Type = T;
3029 Steps.push_back(S);
3030}
3031
Richard Smithebeed412012-02-15 22:38:09 +00003032void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3033 Step S;
3034 S.Kind = SK_ParenthesizedArrayInit;
3035 S.Type = T;
3036 Steps.push_back(S);
3037}
3038
John McCall31168b02011-06-15 23:02:42 +00003039void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3040 bool shouldCopy) {
3041 Step s;
3042 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3043 : SK_PassByIndirectRestore);
3044 s.Type = type;
3045 Steps.push_back(s);
3046}
3047
3048void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3049 Step S;
3050 S.Kind = SK_ProduceObjCObject;
3051 S.Type = T;
3052 Steps.push_back(S);
3053}
3054
Sebastian Redlc1839b12012-01-17 22:49:42 +00003055void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3056 Step S;
3057 S.Kind = SK_StdInitializerList;
3058 S.Type = T;
3059 Steps.push_back(S);
3060}
3061
Guy Benyei61054192013-02-07 10:55:47 +00003062void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3063 Step S;
3064 S.Kind = SK_OCLSamplerInit;
3065 S.Type = T;
3066 Steps.push_back(S);
3067}
3068
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003069void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3070 Step S;
3071 S.Kind = SK_OCLZeroEvent;
3072 S.Type = T;
3073 Steps.push_back(S);
3074}
3075
Sebastian Redl29526f02011-11-27 16:50:07 +00003076void InitializationSequence::RewrapReferenceInitList(QualType T,
3077 InitListExpr *Syntactic) {
3078 assert(Syntactic->getNumInits() == 1 &&
3079 "Can only rewrap trivial init lists.");
3080 Step S;
3081 S.Kind = SK_UnwrapInitList;
3082 S.Type = Syntactic->getInit(0)->getType();
3083 Steps.insert(Steps.begin(), S);
3084
3085 S.Kind = SK_RewrapInitList;
3086 S.Type = T;
3087 S.WrappingSyntacticList = Syntactic;
3088 Steps.push_back(S);
3089}
3090
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003091void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003092 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003093 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003094 this->Failure = Failure;
3095 this->FailedOverloadResult = Result;
3096}
3097
3098//===----------------------------------------------------------------------===//
3099// Attempt initialization
3100//===----------------------------------------------------------------------===//
3101
John McCall31168b02011-06-15 23:02:42 +00003102static void MaybeProduceObjCObject(Sema &S,
3103 InitializationSequence &Sequence,
3104 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003105 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003106
3107 /// When initializing a parameter, produce the value if it's marked
3108 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003109 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003110 if (!Entity.isParameterConsumed())
3111 return;
3112
3113 assert(Entity.getType()->isObjCRetainableType() &&
3114 "consuming an object of unretainable type?");
3115 Sequence.AddProduceObjCObjectStep(Entity.getType());
3116
3117 /// When initializing a return value, if the return type is a
3118 /// retainable type, then returns need to immediately retain the
3119 /// object. If an autorelease is required, it will be done at the
3120 /// last instant.
3121 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3122 if (!Entity.getType()->isObjCRetainableType())
3123 return;
3124
3125 Sequence.AddProduceObjCObjectStep(Entity.getType());
3126 }
3127}
3128
Richard Smithcc1b96d2013-06-12 22:31:48 +00003129static void TryListInitialization(Sema &S,
3130 const InitializedEntity &Entity,
3131 const InitializationKind &Kind,
3132 InitListExpr *InitList,
3133 InitializationSequence &Sequence);
3134
Richard Smithd86812d2012-07-05 08:39:21 +00003135/// \brief When initializing from init list via constructor, handle
3136/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003137///
Richard Smithd86812d2012-07-05 08:39:21 +00003138/// \return true if we have handled initialization of an object of type
3139/// std::initializer_list<T>, false otherwise.
3140static bool TryInitializerListConstruction(Sema &S,
3141 InitListExpr *List,
3142 QualType DestType,
3143 InitializationSequence &Sequence) {
3144 QualType E;
3145 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003146 return false;
3147
Richard Smithcc1b96d2013-06-12 22:31:48 +00003148 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3149 Sequence.setIncompleteTypeFailure(E);
3150 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003151 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003152
3153 // Try initializing a temporary array from the init list.
3154 QualType ArrayType = S.Context.getConstantArrayType(
3155 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3156 List->getNumInits()),
3157 clang::ArrayType::Normal, 0);
3158 InitializedEntity HiddenArray =
3159 InitializedEntity::InitializeTemporary(ArrayType);
3160 InitializationKind Kind =
3161 InitializationKind::CreateDirectList(List->getExprLoc());
3162 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3163 if (Sequence)
3164 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003165 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003166}
3167
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003168static OverloadingResult
3169ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003170 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003171 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003172 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003173 OverloadCandidateSet::iterator &Best,
3174 bool CopyInitializing, bool AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003175 bool OnlyListConstructors, bool IsListInit) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003176 CandidateSet.clear();
3177
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003178 for (ArrayRef<NamedDecl *>::iterator
3179 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003180 NamedDecl *D = *Con;
3181 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3182 bool SuppressUserConversions = false;
3183
3184 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003185 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003186 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3187 if (ConstructorTmpl)
3188 Constructor = cast<CXXConstructorDecl>(
3189 ConstructorTmpl->getTemplatedDecl());
3190 else {
3191 Constructor = cast<CXXConstructorDecl>(D);
3192
Richard Smith6c6ddab2013-09-21 21:23:47 +00003193 // C++11 [over.best.ics]p4:
Larisse Voufo19d08672015-01-27 18:47:05 +00003194 // ... and the constructor or user-defined conversion function is a
3195 // candidate by
3196 // — 13.3.1.3, when the argument is the temporary in the second step
3197 // of a class copy-initialization, or
3198 // — 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
3199 // user-defined conversion sequences are not considered.
Larisse Voufobcf327a2015-02-10 02:20:14 +00003200 // FIXME: This breaks backward compatibility, e.g. PR12117. As a
3201 // temporary fix, let's re-instate the third bullet above until
3202 // there is a resolution in the standard, i.e.,
3203 // - 13.3.1.7 when the initializer list has exactly one element that is
3204 // itself an initializer list and a conversion to some class X or
3205 // reference to (possibly cv-qualified) X is considered for the first
3206 // parameter of a constructor of X.
3207 if ((CopyInitializing ||
3208 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3209 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003210 SuppressUserConversions = true;
3211 }
3212
3213 if (!Constructor->isInvalidDecl() &&
3214 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003215 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003216 if (ConstructorTmpl)
3217 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003218 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003219 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003220 else {
3221 // C++ [over.match.copy]p1:
3222 // - When initializing a temporary to be bound to the first parameter
3223 // of a constructor that takes a reference to possibly cv-qualified
3224 // T as its first argument, called with a single argument in the
3225 // context of direct-initialization, explicit conversion functions
3226 // are also considered.
3227 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003228 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003229 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003230 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003231 SuppressUserConversions,
3232 /*PartialOverloading=*/false,
3233 /*AllowExplicit=*/AllowExplicitConv);
3234 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003235 }
3236 }
3237
3238 // Perform overload resolution and return the result.
3239 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3240}
3241
Sebastian Redled2e5322011-12-22 14:44:04 +00003242/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3243/// enumerates the constructors of the initialized entity and performs overload
3244/// resolution to select the best.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003245/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003246/// \param IsInitListCopy Is this non-list-initialization resulting from a
3247/// list-initialization from {x} where x is the same
3248/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003249static void TryConstructorInitialization(Sema &S,
3250 const InitializedEntity &Entity,
3251 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003252 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003253 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003254 bool IsListInit = false,
3255 bool IsInitListCopy = false) {
3256 assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3257 "IsListInit must come with a single initializer list argument.");
Sebastian Redl88e4d492012-02-04 21:27:33 +00003258
Sebastian Redled2e5322011-12-22 14:44:04 +00003259 // The type we're constructing needs to be complete.
3260 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003261 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003262 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003263 }
3264
3265 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3266 assert(DestRecordType && "Constructor initialization requires record type");
3267 CXXRecordDecl *DestRecordDecl
3268 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3269
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003270 // Build the candidate set directly in the initialization sequence
3271 // structure, so that it will persist if we fail.
3272 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3273
3274 // Determine whether we are allowed to call explicit constructors or
3275 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003276 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003277 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003278
Sebastian Redled2e5322011-12-22 14:44:04 +00003279 // - Otherwise, if T is a class type, constructors are considered. The
3280 // applicable constructors are enumerated, and the best one is chosen
3281 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003282 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003283 // The container holding the constructors can under certain conditions
3284 // be changed while iterating (e.g. because of deserialization).
3285 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003286 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003287
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003288 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003289 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003290 bool AsInitializerList = false;
3291
Larisse Voufo19d08672015-01-27 18:47:05 +00003292 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003293 // When objects of non-aggregate type T are list-initialized, such that
3294 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3295 // according to the rules in this section, overload resolution selects
3296 // the constructor in two phases:
3297 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003298 // - Initially, the candidate functions are the initializer-list
3299 // constructors of the class T and the argument list consists of the
3300 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003301 if (IsListInit) {
Richard Smithd86812d2012-07-05 08:39:21 +00003302 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003303 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003304
3305 // If the initializer list has no elements and T has a default constructor,
3306 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003307 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003308 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003309 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003310 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003311 /*OnlyListConstructor=*/true,
3312 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003313
3314 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003315 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003316 }
3317
3318 // C++11 [over.match.list]p1:
3319 // - If no viable initializer-list constructor is found, overload resolution
3320 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003321 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003322 // elements of the initializer list.
3323 if (Result == OR_No_Viable_Function) {
3324 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003325 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003326 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003327 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003328 /*OnlyListConstructors=*/false,
3329 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003330 }
3331 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003332 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003333 InitializationSequence::FK_ListConstructorOverloadFailed :
3334 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003335 Result);
3336 return;
3337 }
3338
Richard Smithd86812d2012-07-05 08:39:21 +00003339 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003340 // If a program calls for the default initialization of an object
3341 // of a const-qualified type T, T shall be a class type with a
3342 // user-provided default constructor.
3343 if (Kind.getKind() == InitializationKind::IK_Default &&
3344 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003345 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003346 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3347 return;
3348 }
3349
Sebastian Redl048a6d72012-04-01 19:54:59 +00003350 // C++11 [over.match.list]p1:
3351 // In copy-list-initialization, if an explicit constructor is chosen, the
3352 // initializer is ill-formed.
3353 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smithed83ebd2015-02-05 07:02:11 +00003354 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003355 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3356 return;
3357 }
3358
Sebastian Redled2e5322011-12-22 14:44:04 +00003359 // Add the constructor initialization step. Any cv-qualification conversion is
3360 // subsumed by the initialization.
3361 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithed83ebd2015-02-05 07:02:11 +00003362 Sequence.AddConstructorInitializationStep(
3363 CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
3364 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003365}
3366
Sebastian Redl29526f02011-11-27 16:50:07 +00003367static bool
3368ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3369 Expr *Initializer,
3370 QualType &SourceType,
3371 QualType &UnqualifiedSourceType,
3372 QualType UnqualifiedTargetType,
3373 InitializationSequence &Sequence) {
3374 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3375 S.Context.OverloadTy) {
3376 DeclAccessPair Found;
3377 bool HadMultipleCandidates = false;
3378 if (FunctionDecl *Fn
3379 = S.ResolveAddressOfOverloadedFunction(Initializer,
3380 UnqualifiedTargetType,
3381 false, Found,
3382 &HadMultipleCandidates)) {
3383 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3384 HadMultipleCandidates);
3385 SourceType = Fn->getType();
3386 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3387 } else if (!UnqualifiedTargetType->isRecordType()) {
3388 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3389 return true;
3390 }
3391 }
3392 return false;
3393}
3394
3395static void TryReferenceInitializationCore(Sema &S,
3396 const InitializedEntity &Entity,
3397 const InitializationKind &Kind,
3398 Expr *Initializer,
3399 QualType cv1T1, QualType T1,
3400 Qualifiers T1Quals,
3401 QualType cv2T2, QualType T2,
3402 Qualifiers T2Quals,
3403 InitializationSequence &Sequence);
3404
Richard Smithd86812d2012-07-05 08:39:21 +00003405static void TryValueInitialization(Sema &S,
3406 const InitializedEntity &Entity,
3407 const InitializationKind &Kind,
3408 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003409 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003410
Sebastian Redl29526f02011-11-27 16:50:07 +00003411/// \brief Attempt list initialization of a reference.
3412static void TryReferenceListInitialization(Sema &S,
3413 const InitializedEntity &Entity,
3414 const InitializationKind &Kind,
3415 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003416 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003417 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003418 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003419 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3420 return;
3421 }
3422
3423 QualType DestType = Entity.getType();
3424 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3425 Qualifiers T1Quals;
3426 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3427
3428 // Reference initialization via an initializer list works thus:
3429 // If the initializer list consists of a single element that is
3430 // reference-related to the referenced type, bind directly to that element
3431 // (possibly creating temporaries).
3432 // Otherwise, initialize a temporary with the initializer list and
3433 // bind to that.
3434 if (InitList->getNumInits() == 1) {
3435 Expr *Initializer = InitList->getInit(0);
3436 QualType cv2T2 = Initializer->getType();
3437 Qualifiers T2Quals;
3438 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3439
3440 // If this fails, creating a temporary wouldn't work either.
3441 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3442 T1, Sequence))
3443 return;
3444
3445 SourceLocation DeclLoc = Initializer->getLocStart();
3446 bool dummy1, dummy2, dummy3;
3447 Sema::ReferenceCompareResult RefRelationship
3448 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3449 dummy2, dummy3);
3450 if (RefRelationship >= Sema::Ref_Related) {
3451 // Try to bind the reference here.
3452 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3453 T1Quals, cv2T2, T2, T2Quals, Sequence);
3454 if (Sequence)
3455 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3456 return;
3457 }
Richard Smith03d93932013-01-15 07:58:29 +00003458
3459 // Update the initializer if we've resolved an overloaded function.
3460 if (Sequence.step_begin() != Sequence.step_end())
3461 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003462 }
3463
3464 // Not reference-related. Create a temporary and bind to that.
3465 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3466
3467 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3468 if (Sequence) {
3469 if (DestType->isRValueReferenceType() ||
3470 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3471 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3472 else
3473 Sequence.SetFailed(
3474 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3475 }
3476}
3477
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003478/// \brief Attempt list initialization (C++0x [dcl.init.list])
3479static void TryListInitialization(Sema &S,
3480 const InitializedEntity &Entity,
3481 const InitializationKind &Kind,
3482 InitListExpr *InitList,
3483 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003484 QualType DestType = Entity.getType();
3485
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003486 // C++ doesn't allow scalar initialization with more than one argument.
3487 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003488 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003489 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3490 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3491 return;
3492 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003493 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003494 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003495 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003496 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003497
Larisse Voufod2010992015-01-24 23:09:54 +00003498 if (DestType->isRecordType() &&
3499 S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3500 Sequence.setIncompleteTypeFailure(DestType);
3501 return;
3502 }
Richard Smithd86812d2012-07-05 08:39:21 +00003503
Larisse Voufo19d08672015-01-27 18:47:05 +00003504 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003505 // - If T is a class type and the initializer list has a single element of
3506 // type cv U, where U is T or a class derived from T, the object is
3507 // initialized from that element (by copy-initialization for
3508 // copy-list-initialization, or by direct-initialization for
3509 // direct-list-initialization).
3510 // - Otherwise, if T is a character array and the initializer list has a
3511 // single element that is an appropriately-typed string literal
3512 // (8.5.2 [dcl.init.string]), initialization is performed as described
3513 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003514 // - Otherwise, if T is an aggregate, [...] (continue below).
3515 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003516 if (DestType->isRecordType()) {
3517 QualType InitType = InitList->getInit(0)->getType();
3518 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
3519 S.IsDerivedFrom(InitType, DestType)) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003520 Expr *InitAsExpr = InitList->getInit(0);
3521 TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
3522 Sequence, /*InitListSyntax*/ false,
3523 /*IsInitListCopy*/ true);
Larisse Voufod2010992015-01-24 23:09:54 +00003524 return;
3525 }
3526 }
3527 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3528 Expr *SubInit[1] = {InitList->getInit(0)};
3529 if (!isa<VariableArrayType>(DestAT) &&
3530 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3531 InitializationKind SubKind =
3532 Kind.getKind() == InitializationKind::IK_DirectList
3533 ? InitializationKind::CreateDirect(Kind.getLocation(),
3534 InitList->getLBraceLoc(),
3535 InitList->getRBraceLoc())
3536 : Kind;
3537 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3538 /*TopLevelOfInitList*/ true);
3539
3540 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3541 // the element is not an appropriately-typed string literal, in which
3542 // case we should proceed as in C++11 (below).
3543 if (Sequence) {
3544 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3545 return;
3546 }
3547 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003548 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003549 }
Larisse Voufod2010992015-01-24 23:09:54 +00003550
3551 // C++11 [dcl.init.list]p3:
3552 // - If T is an aggregate, aggregate initialization is performed.
3553 if (DestType->isRecordType() && !DestType->isAggregateType()) {
3554 if (S.getLangOpts().CPlusPlus11) {
3555 // - Otherwise, if the initializer list has no elements and T is a
3556 // class type with a default constructor, the object is
3557 // value-initialized.
3558 if (InitList->getNumInits() == 0) {
3559 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3560 if (RD->hasDefaultConstructor()) {
3561 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3562 return;
3563 }
3564 }
3565
3566 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3567 // an initializer_list object constructed [...]
3568 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3569 return;
3570
3571 // - Otherwise, if T is a class type, constructors are considered.
3572 Expr *InitListAsExpr = InitList;
3573 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3574 Sequence, /*InitListSyntax*/ true);
3575 } else
3576 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3577 return;
3578 }
3579
Richard Smith089c3162013-09-21 21:55:46 +00003580 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3581 InitList->getNumInits() == 1 &&
3582 InitList->getInit(0)->getType()->isRecordType()) {
3583 // - Otherwise, if the initializer list has a single element of type E
3584 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00003585 // initialized from that element (by copy-initialization for
3586 // copy-list-initialization, or by direct-initialization for
3587 // direct-list-initialization); if a narrowing conversion is required
3588 // to convert the element to T, the program is ill-formed.
3589 //
Richard Smith089c3162013-09-21 21:55:46 +00003590 // Per core-24034, this is direct-initialization if we were performing
3591 // direct-list-initialization and copy-initialization otherwise.
3592 // We can't use InitListChecker for this, because it always performs
3593 // copy-initialization. This only matters if we might use an 'explicit'
3594 // conversion operator, so we only need to handle the cases where the source
3595 // is of record type.
3596 InitializationKind SubKind =
3597 Kind.getKind() == InitializationKind::IK_DirectList
3598 ? InitializationKind::CreateDirect(Kind.getLocation(),
3599 InitList->getLBraceLoc(),
3600 InitList->getRBraceLoc())
3601 : Kind;
3602 Expr *SubInit[1] = { InitList->getInit(0) };
3603 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3604 /*TopLevelOfInitList*/true);
3605 if (Sequence)
3606 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3607 return;
3608 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003609
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003610 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003611 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003612 if (CheckInitList.HadError()) {
3613 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3614 return;
3615 }
3616
3617 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003618 Sequence.AddListInitializationStep(DestType);
3619}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003620
3621/// \brief Try a reference initialization that involves calling a conversion
3622/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003623static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3624 const InitializedEntity &Entity,
3625 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003626 Expr *Initializer,
3627 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003628 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003629 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003630 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3631 QualType T1 = cv1T1.getUnqualifiedType();
3632 QualType cv2T2 = Initializer->getType();
3633 QualType T2 = cv2T2.getUnqualifiedType();
3634
3635 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003636 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003637 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003639 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003640 ObjCConversion,
3641 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003642 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003643 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003644 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003645 (void)ObjCLifetimeConversion;
3646
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003647 // Build the candidate set directly in the initialization sequence
3648 // structure, so that it will persist if we fail.
3649 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3650 CandidateSet.clear();
3651
3652 // Determine whether we are allowed to call explicit constructors or
3653 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003654 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003655 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3656
Craig Topperc3ec1492014-05-26 06:22:03 +00003657 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003658 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3659 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003660 // The type we're converting to is a class type. Enumerate its constructors
3661 // to see if there is a suitable conversion.
3662 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003663
David Blaikieff7d47a2012-12-19 00:45:41 +00003664 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003665 // The container holding the constructors can under certain conditions
3666 // be changed while iterating (e.g. because of deserialization).
3667 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003668 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003669 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003670 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3671 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003672 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3673
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003674 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003675 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003676 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003677 if (ConstructorTmpl)
3678 Constructor = cast<CXXConstructorDecl>(
3679 ConstructorTmpl->getTemplatedDecl());
3680 else
John McCalla0296f72010-03-19 07:35:19 +00003681 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003683 if (!Constructor->isInvalidDecl() &&
3684 Constructor->isConvertingConstructor(AllowExplicit)) {
3685 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003686 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003687 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003688 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003689 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003690 else
John McCalla0296f72010-03-19 07:35:19 +00003691 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003692 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003693 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003695 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003696 }
John McCall3696dcb2010-08-17 07:23:57 +00003697 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3698 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003699
Craig Topperc3ec1492014-05-26 06:22:03 +00003700 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003701 if ((T2RecordType = T2->getAs<RecordType>()) &&
3702 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003703 // The type we're converting from is a class type, enumerate its conversion
3704 // functions.
3705 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3706
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003707 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
3708 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003709 NamedDecl *D = *I;
3710 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3711 if (isa<UsingShadowDecl>(D))
3712 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003714 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3715 CXXConversionDecl *Conv;
3716 if (ConvTemplate)
3717 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3718 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003719 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003720
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003721 // If the conversion function doesn't return a reference type,
3722 // it can't be considered for this conversion unless we're allowed to
3723 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724 // FIXME: Do we need to make sure that we only consider conversion
3725 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003726 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003727 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003728 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3729 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003730 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003731 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003732 DestType, CandidateSet,
3733 /*AllowObjCConversionOnExplicit=*/
3734 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003735 else
John McCalla0296f72010-03-19 07:35:19 +00003736 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003737 Initializer, DestType, CandidateSet,
3738 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003739 }
3740 }
3741 }
John McCall3696dcb2010-08-17 07:23:57 +00003742 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3743 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003745 SourceLocation DeclLoc = Initializer->getLocStart();
3746
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003748 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003750 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003751 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003752
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003753 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003754 // This is the overload that will be used for this initialization step if we
3755 // use this initialization. Mark it as referenced.
3756 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003757
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003758 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003759 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003760 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003761 else
3762 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003763
3764 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003765 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003766 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003767 T2.getNonLValueExprType(S.Context),
3768 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003769
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003771 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003772 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003773 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003774 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003775 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003776 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003777
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003778 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003779 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003780 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003781 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003782 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003783 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003784 NewDerivedToBase, NewObjCConversion,
3785 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003786 if (NewRefRelationship == Sema::Ref_Incompatible) {
3787 // If the type we've converted to is not reference-related to the
3788 // type we're looking for, then there is another conversion step
3789 // we need to perform to produce a temporary of the right type
3790 // that we'll be binding to.
3791 ImplicitConversionSequence ICS;
3792 ICS.setStandard();
3793 ICS.Standard = Best->FinalConversion;
3794 T2 = ICS.Standard.getToType(2);
3795 Sequence.AddConversionSequenceStep(ICS, T2);
3796 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003797 Sequence.AddDerivedToBaseCastStep(
3798 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003799 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003800 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003801 else if (NewObjCConversion)
3802 Sequence.AddObjCObjectConversionStep(
3803 S.Context.getQualifiedType(T1,
3804 T2.getNonReferenceType().getQualifiers()));
3805
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003806 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003807 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003809 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3810 return OR_Success;
3811}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812
Richard Smithc620f552011-10-19 16:55:56 +00003813static void CheckCXX98CompatAccessibleCopy(Sema &S,
3814 const InitializedEntity &Entity,
3815 Expr *CurInitExpr);
3816
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3818static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003819 const InitializedEntity &Entity,
3820 const InitializationKind &Kind,
3821 Expr *Initializer,
3822 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003823 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003824 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003825 Qualifiers T1Quals;
3826 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003827 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003828 Qualifiers T2Quals;
3829 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003830
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003831 // If the initializer is the address of an overloaded function, try
3832 // to resolve the overloaded function. If all goes well, T2 is the
3833 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003834 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3835 T1, Sequence))
3836 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003837
Sebastian Redl29526f02011-11-27 16:50:07 +00003838 // Delegate everything else to a subfunction.
3839 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3840 T1Quals, cv2T2, T2, T2Quals, Sequence);
3841}
3842
Jordan Roseb1312a52013-04-11 00:58:58 +00003843/// Converts the target of reference initialization so that it has the
3844/// appropriate qualifiers and value kind.
3845///
3846/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3847/// \code
3848/// int x;
3849/// const int &r = x;
3850/// \endcode
3851///
3852/// In this case the reference is binding to a bitfield lvalue, which isn't
3853/// valid. Perform a load to create a lifetime-extended temporary instead.
3854/// \code
3855/// const int &r = someStruct.bitfield;
3856/// \endcode
3857static ExprValueKind
3858convertQualifiersAndValueKindIfNecessary(Sema &S,
3859 InitializationSequence &Sequence,
3860 Expr *Initializer,
3861 QualType cv1T1,
3862 Qualifiers T1Quals,
3863 Qualifiers T2Quals,
3864 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003865 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003866 Initializer->refersToVectorElement();
3867
3868 if (IsNonAddressableType) {
3869 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3870 // lvalue reference to a non-volatile const type, or the reference shall be
3871 // an rvalue reference.
3872 //
3873 // If not, we can't make a temporary and bind to that. Give up and allow the
3874 // error to be diagnosed later.
3875 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3876 assert(Initializer->isGLValue());
3877 return Initializer->getValueKind();
3878 }
3879
3880 // Force a load so we can materialize a temporary.
3881 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3882 return VK_RValue;
3883 }
3884
3885 if (T1Quals != T2Quals) {
3886 Sequence.AddQualificationConversionStep(cv1T1,
3887 Initializer->getValueKind());
3888 }
3889
3890 return Initializer->getValueKind();
3891}
3892
3893
Sebastian Redl29526f02011-11-27 16:50:07 +00003894/// \brief Reference initialization without resolving overloaded functions.
3895static void TryReferenceInitializationCore(Sema &S,
3896 const InitializedEntity &Entity,
3897 const InitializationKind &Kind,
3898 Expr *Initializer,
3899 QualType cv1T1, QualType T1,
3900 Qualifiers T1Quals,
3901 QualType cv2T2, QualType T2,
3902 Qualifiers T2Quals,
3903 InitializationSequence &Sequence) {
3904 QualType DestType = Entity.getType();
3905 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003906 // Compute some basic properties of the types and the initializer.
3907 bool isLValueRef = DestType->isLValueReferenceType();
3908 bool isRValueRef = !isLValueRef;
3909 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003910 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003911 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003912 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003913 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003914 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003915 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003916
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003917 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003919 // "cv2 T2" as follows:
3920 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003922 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003923 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003924 // there are no function rvalues in C++, rvalue refs to functions are treated
3925 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003926 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003927 bool T1Function = T1->isFunctionType();
3928 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003930 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003932 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003933 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003934 // reference-compatible with "cv2 T2," or
3935 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003936 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003937 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003938 // can occur. However, we do pay attention to whether it is a bit-field
3939 // to decide whether we're actually binding to a temporary created from
3940 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003941 if (DerivedToBase)
3942 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003944 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003945 else if (ObjCConversion)
3946 Sequence.AddObjCObjectConversionStep(
3947 S.Context.getQualifiedType(T1, T2Quals));
3948
Jordan Roseb1312a52013-04-11 00:58:58 +00003949 ExprValueKind ValueKind =
3950 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3951 cv1T1, T1Quals, T2Quals,
3952 isLValueRef);
3953 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003954 return;
3955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956
3957 // - has a class type (i.e., T2 is a class type), where T1 is not
3958 // reference-related to T2, and can be implicitly converted to an
3959 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3960 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003961 // applicable conversion functions (13.3.1.6) and choosing the best
3962 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003963 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003964 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003965 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3966 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003967 ConvOvlResult = TryRefInitWithConversionFunction(
3968 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003969 if (ConvOvlResult == OR_Success)
3970 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003971 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003972 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003973 InitializationSequence::FK_ReferenceInitOverloadFailed,
3974 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003975 }
3976 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003977
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003978 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003979 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003980 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003981 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003982 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3983 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3984 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003985 Sequence.SetOverloadFailure(
3986 InitializationSequence::FK_ReferenceInitOverloadFailed,
3987 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003988 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003989 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003990 ? (RefRelationship == Sema::Ref_Related
3991 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3992 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3993 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003994
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003995 return;
3996 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003997
Douglas Gregor92e460e2011-01-20 16:44:54 +00003998 // - If the initializer expression
3999 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
4000 // "cv1 T1" is reference-compatible with "cv2 T2"
4001 // Note: functions are handled below.
4002 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00004003 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004005 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00004006 (InitCategory.isXValue() ||
4007 (InitCategory.isPRValue() && T2->isRecordType()) ||
4008 (InitCategory.isPRValue() && T2->isArrayType()))) {
4009 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
4010 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004011 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4012 // compiler the freedom to perform a copy here or bind to the
4013 // object, while C++0x requires that we bind directly to the
4014 // object. Hence, we always bind to the object without making an
4015 // extra copy. However, in C++03 requires that we check for the
4016 // presence of a suitable copy constructor:
4017 //
4018 // The constructor that would be used to make the copy shall
4019 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004020 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004021 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004022 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004023 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025
Douglas Gregor92e460e2011-01-20 16:44:54 +00004026 if (DerivedToBase)
4027 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
4028 ValueKind);
4029 else if (ObjCConversion)
4030 Sequence.AddObjCObjectConversionStep(
4031 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004032
Jordan Roseb1312a52013-04-11 00:58:58 +00004033 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
4034 Initializer, cv1T1,
4035 T1Quals, T2Quals,
4036 isLValueRef);
4037
4038 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004041
4042 // - has a class type (i.e., T2 is a class type), where T1 is not
4043 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004044 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4045 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004046 //
4047 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004048 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004049 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004050 ConvOvlResult = TryRefInitWithConversionFunction(
4051 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004052 if (ConvOvlResult)
4053 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004054 InitializationSequence::FK_ReferenceInitOverloadFailed,
4055 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057 return;
4058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004060 if ((RefRelationship == Sema::Ref_Compatible ||
4061 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
4062 isRValueRef && InitCategory.isLValue()) {
4063 Sequence.SetFailed(
4064 InitializationSequence::FK_RValueReferenceBindingToLValue);
4065 return;
4066 }
4067
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004068 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4069 return;
4070 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004071
4072 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004073 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004074 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004075 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004076
John McCallec6f4e92010-06-04 02:29:22 +00004077 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4078
Richard Smith2eabf782013-06-13 00:57:57 +00004079 // FIXME: Why do we use an implicit conversion here rather than trying
4080 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004081 ImplicitConversionSequence ICS
4082 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004083 /*SuppressUserConversions=*/false,
4084 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004085 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004086 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4087 /*AllowObjCWritebackConversion=*/false);
4088
4089 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004090 // FIXME: Use the conversion function set stored in ICS to turn
4091 // this into an overloading ambiguity diagnostic. However, we need
4092 // to keep that set as an OverloadCandidateSet rather than as some
4093 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004094 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4095 Sequence.SetOverloadFailure(
4096 InitializationSequence::FK_ReferenceInitOverloadFailed,
4097 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004098 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4099 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004100 else
4101 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004102 return;
John McCall31168b02011-06-15 23:02:42 +00004103 } else {
4104 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004105 }
4106
4107 // [...] If T1 is reference-related to T2, cv1 must be the
4108 // same cv-qualification as, or greater cv-qualification
4109 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004110 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4111 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004112 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004113 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004114 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4115 return;
4116 }
4117
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004118 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004119 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004120 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004121 InitCategory.isLValue()) {
4122 Sequence.SetFailed(
4123 InitializationSequence::FK_RValueReferenceBindingToLValue);
4124 return;
4125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004127 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4128 return;
4129}
4130
4131/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132/// (C++ [dcl.init.string], C99 6.7.8).
4133static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004134 const InitializedEntity &Entity,
4135 const InitializationKind &Kind,
4136 Expr *Initializer,
4137 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004138 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004139}
4140
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004141/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004143 const InitializedEntity &Entity,
4144 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004145 InitializationSequence &Sequence,
4146 InitListExpr *InitList) {
4147 assert((!InitList || InitList->getNumInits() == 0) &&
4148 "Shouldn't use value-init for non-empty init lists");
4149
Richard Smith1bfe0682012-02-14 21:14:13 +00004150 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004151 //
4152 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004153 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004155 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004156 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004157
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004158 if (const RecordType *RT = T->getAs<RecordType>()) {
4159 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004160 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004161 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004162 // C++98:
4163 // -- if T is a class type (clause 9) with a user-declared constructor
4164 // (12.1), then the default constructor for T is called (and the
4165 // initialization is ill-formed if T has no accessible default
4166 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004167 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004168 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004169 } else {
4170 // C++11:
4171 // -- if T is a class type (clause 9) with either no default constructor
4172 // (12.1 [class.ctor]) or a default constructor that is user-provided
4173 // or deleted, then the object is default-initialized;
4174 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4175 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004176 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178
Richard Smith1bfe0682012-02-14 21:14:13 +00004179 // -- if T is a (possibly cv-qualified) non-union class type without a
4180 // user-provided or deleted default constructor, then the object is
4181 // zero-initialized and, if T has a non-trivial default constructor,
4182 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004183 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4184 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004185 if (NeedZeroInitialization)
4186 Sequence.AddZeroInitializationStep(Entity.getType());
4187
Richard Smith593f9932012-12-08 02:01:17 +00004188 // C++03:
4189 // -- if T is a non-union class type without a user-declared constructor,
4190 // then every non-static data member and base class component of T is
4191 // value-initialized;
4192 // [...] A program that calls for [...] value-initialization of an
4193 // entity of reference type is ill-formed.
4194 //
4195 // C++11 doesn't need this handling, because value-initialization does not
4196 // occur recursively there, and the implicit default constructor is
4197 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004198 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004199 ClassDecl->hasUninitializedReferenceMember()) {
4200 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4201 return;
4202 }
4203
Richard Smithd86812d2012-07-05 08:39:21 +00004204 // If this is list-value-initialization, pass the empty init list on when
4205 // building the constructor call. This affects the semantics of a few
4206 // things (such as whether an explicit default constructor can be called).
4207 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004208 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004209 bool InitListSyntax = InitList;
4210
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004211 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4212 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004213 }
4214 }
4215
Douglas Gregor1b303932009-12-22 15:35:07 +00004216 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004217}
4218
Douglas Gregor85dabae2009-12-16 01:38:02 +00004219/// \brief Attempt default initialization (C++ [dcl.init]p6).
4220static void TryDefaultInitialization(Sema &S,
4221 const InitializedEntity &Entity,
4222 const InitializationKind &Kind,
4223 InitializationSequence &Sequence) {
4224 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225
Douglas Gregor85dabae2009-12-16 01:38:02 +00004226 // C++ [dcl.init]p6:
4227 // To default-initialize an object of type T means:
4228 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004229 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4230
Douglas Gregor85dabae2009-12-16 01:38:02 +00004231 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4232 // constructor for T is called (and the initialization is ill-formed if
4233 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004234 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004235 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004236 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004237 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238
Douglas Gregor85dabae2009-12-16 01:38:02 +00004239 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240
Douglas Gregor85dabae2009-12-16 01:38:02 +00004241 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004243 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004244 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004245 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004246 return;
4247 }
4248
4249 // If the destination type has a lifetime property, zero-initialize it.
4250 if (DestType.getQualifiers().hasObjCLifetime()) {
4251 Sequence.AddZeroInitializationStep(Entity.getType());
4252 return;
4253 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004254}
4255
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004256/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4257/// which enumerates all conversion functions and performs overload resolution
4258/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004260 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004261 const InitializationKind &Kind,
4262 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004263 InitializationSequence &Sequence,
4264 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004265 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4266 QualType SourceType = Initializer->getType();
4267 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4268 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269
Douglas Gregor540c3b02009-12-14 17:27:33 +00004270 // Build the candidate set directly in the initialization sequence
4271 // structure, so that it will persist if we fail.
4272 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4273 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004274
Douglas Gregor540c3b02009-12-14 17:27:33 +00004275 // Determine whether we are allowed to call explicit constructors or
4276 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004277 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Douglas Gregor540c3b02009-12-14 17:27:33 +00004279 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4280 // The type we're converting to is a class type. Enumerate its constructors
4281 // to see if there is a suitable conversion.
4282 CXXRecordDecl *DestRecordDecl
4283 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Douglas Gregord9848152010-04-26 14:36:57 +00004285 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004287 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004288 // The container holding the constructors can under certain conditions
4289 // be changed while iterating. To be safe we copy the lookup results
4290 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004291 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004292 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004293 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004294 Con != ConEnd; ++Con) {
4295 NamedDecl *D = *Con;
4296 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297
Douglas Gregord9848152010-04-26 14:36:57 +00004298 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004299 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004300 FunctionTemplateDecl *ConstructorTmpl
4301 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004302 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004303 Constructor = cast<CXXConstructorDecl>(
4304 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004305 else
Douglas Gregord9848152010-04-26 14:36:57 +00004306 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregord9848152010-04-26 14:36:57 +00004308 if (!Constructor->isInvalidDecl() &&
4309 Constructor->isConvertingConstructor(AllowExplicit)) {
4310 if (ConstructorTmpl)
4311 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004312 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004313 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004314 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004315 else
4316 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004317 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004318 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320 }
Douglas Gregord9848152010-04-26 14:36:57 +00004321 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004322 }
Eli Friedman78275202009-12-19 08:11:05 +00004323
4324 SourceLocation DeclLoc = Initializer->getLocStart();
4325
Douglas Gregor540c3b02009-12-14 17:27:33 +00004326 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4327 // The type we're converting from is a class type, enumerate its conversion
4328 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004329
Eli Friedman4afe9a32009-12-20 22:12:03 +00004330 // We can only enumerate the conversion functions for a complete type; if
4331 // the type isn't complete, simply skip this step.
4332 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4333 CXXRecordDecl *SourceRecordDecl
4334 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004336 const auto &Conversions =
4337 SourceRecordDecl->getVisibleConversionFunctions();
4338 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004339 NamedDecl *D = *I;
4340 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4341 if (isa<UsingShadowDecl>(D))
4342 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343
Eli Friedman4afe9a32009-12-20 22:12:03 +00004344 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4345 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004346 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004347 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004348 else
John McCallda4458e2010-03-31 01:36:47 +00004349 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350
Eli Friedman4afe9a32009-12-20 22:12:03 +00004351 if (AllowExplicit || !Conv->isExplicit()) {
4352 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004353 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004354 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004355 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004356 else
John McCalla0296f72010-03-19 07:35:19 +00004357 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004358 Initializer, DestType, CandidateSet,
4359 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004360 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004361 }
4362 }
4363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364
4365 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004366 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004367 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004368 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004369 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004371 Result);
4372 return;
4373 }
John McCall0d1da222010-01-12 00:44:57 +00004374
Douglas Gregor540c3b02009-12-14 17:27:33 +00004375 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004376 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004377 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378
Douglas Gregor540c3b02009-12-14 17:27:33 +00004379 if (isa<CXXConstructorDecl>(Function)) {
4380 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004381 // subsumed by the initialization. Per DR5, the created temporary is of the
4382 // cv-unqualified type of the destination.
4383 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4384 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004385 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004386 return;
4387 }
4388
4389 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004390 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004391 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004392 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004393 // the resulting temporary object (possible to create an object of
4394 // a base class type). That copy is not a separate conversion, so
4395 // we just make a note of the actual destination type (possibly a
4396 // base class of the type returned by the conversion function) and
4397 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004398 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4399 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004400 return;
4401 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004402
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004403 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4404 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405
Douglas Gregor5ab11652010-04-17 22:01:05 +00004406 // If the conversion following the call to the conversion function
4407 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004408 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4409 Best->FinalConversion.Third) {
4410 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004411 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004412 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004413 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004414 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004415}
4416
Richard Smithf032001b2013-06-20 02:18:31 +00004417/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4418/// a function with a pointer return type contains a 'return false;' statement.
4419/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4420/// code using that header.
4421///
4422/// Work around this by treating 'return false;' as zero-initializing the result
4423/// if it's used in a pointer-returning function in a system header.
4424static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4425 const InitializedEntity &Entity,
4426 const Expr *Init) {
4427 return S.getLangOpts().CPlusPlus11 &&
4428 Entity.getKind() == InitializedEntity::EK_Result &&
4429 Entity.getType()->isPointerType() &&
4430 isa<CXXBoolLiteralExpr>(Init) &&
4431 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4432 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4433}
4434
John McCall31168b02011-06-15 23:02:42 +00004435/// The non-zero enum values here are indexes into diagnostic alternatives.
4436enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4437
4438/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004439static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004440 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004441 // Skip parens.
4442 e = e->IgnoreParens();
4443
4444 // Skip address-of nodes.
4445 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4446 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004447 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4448 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004449
4450 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004451 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4452 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004453 case CK_Dependent:
4454 case CK_BitCast:
4455 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004456 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004457 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004458
4459 case CK_ArrayToPointerDecay:
4460 return IIK_nonscalar;
4461
4462 case CK_NullToPointer:
4463 return IIK_okay;
4464
4465 default:
4466 break;
4467 }
4468
4469 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004470 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004471 // set isWeakAccess to true, to mean that there will be an implicit
4472 // load which requires a cleanup.
4473 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4474 isWeakAccess = true;
4475
John McCall63f84442011-06-27 23:59:58 +00004476 if (!isAddressOf) return IIK_nonlocal;
4477
John McCall113bee02012-03-10 09:33:50 +00004478 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4479 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004480
4481 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004482
4483 // If we have a conditional operator, check both sides.
4484 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004485 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4486 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004487 return iik;
4488
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004489 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004490
4491 // These are never scalar.
4492 } else if (isa<ArraySubscriptExpr>(e)) {
4493 return IIK_nonscalar;
4494
4495 // Otherwise, it needs to be a null pointer constant.
4496 } else {
4497 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4498 ? IIK_okay : IIK_nonlocal);
4499 }
4500
4501 return IIK_nonlocal;
4502}
4503
4504/// Check whether the given expression is a valid operand for an
4505/// indirect copy/restore.
4506static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4507 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004508 bool isWeakAccess = false;
4509 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4510 // If isWeakAccess to true, there will be an implicit
4511 // load which requires a cleanup.
4512 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4513 S.ExprNeedsCleanups = true;
4514
John McCall31168b02011-06-15 23:02:42 +00004515 if (iik == IIK_okay) return;
4516
4517 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4518 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4519 << src->getSourceRange();
4520}
4521
Douglas Gregore2f943b2011-02-22 18:29:51 +00004522/// \brief Determine whether we have compatible array types for the
4523/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00004524static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00004525 const ArrayType *Source) {
4526 // If the source and destination array types are equivalent, we're
4527 // done.
4528 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4529 return true;
4530
4531 // Make sure that the element types are the same.
4532 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4533 return false;
4534
4535 // The only mismatch we allow is when the destination is an
4536 // incomplete array type and the source is a constant array type.
4537 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4538}
4539
John McCall31168b02011-06-15 23:02:42 +00004540static bool tryObjCWritebackConversion(Sema &S,
4541 InitializationSequence &Sequence,
4542 const InitializedEntity &Entity,
4543 Expr *Initializer) {
4544 bool ArrayDecay = false;
4545 QualType ArgType = Initializer->getType();
4546 QualType ArgPointee;
4547 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4548 ArrayDecay = true;
4549 ArgPointee = ArgArrayType->getElementType();
4550 ArgType = S.Context.getPointerType(ArgPointee);
4551 }
4552
4553 // Handle write-back conversion.
4554 QualType ConvertedArgType;
4555 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4556 ConvertedArgType))
4557 return false;
4558
4559 // We should copy unless we're passing to an argument explicitly
4560 // marked 'out'.
4561 bool ShouldCopy = true;
4562 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4563 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4564
4565 // Do we need an lvalue conversion?
4566 if (ArrayDecay || Initializer->isGLValue()) {
4567 ImplicitConversionSequence ICS;
4568 ICS.setStandard();
4569 ICS.Standard.setAsIdentityConversion();
4570
4571 QualType ResultType;
4572 if (ArrayDecay) {
4573 ICS.Standard.First = ICK_Array_To_Pointer;
4574 ResultType = S.Context.getPointerType(ArgPointee);
4575 } else {
4576 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4577 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4578 }
4579
4580 Sequence.AddConversionSequenceStep(ICS, ResultType);
4581 }
4582
4583 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4584 return true;
4585}
4586
Guy Benyei61054192013-02-07 10:55:47 +00004587static bool TryOCLSamplerInitialization(Sema &S,
4588 InitializationSequence &Sequence,
4589 QualType DestType,
4590 Expr *Initializer) {
4591 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4592 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4593 return false;
4594
4595 Sequence.AddOCLSamplerInitStep(DestType);
4596 return true;
4597}
4598
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004599//
4600// OpenCL 1.2 spec, s6.12.10
4601//
4602// The event argument can also be used to associate the
4603// async_work_group_copy with a previous async copy allowing
4604// an event to be shared by multiple async copies; otherwise
4605// event should be zero.
4606//
4607static bool TryOCLZeroEventInitialization(Sema &S,
4608 InitializationSequence &Sequence,
4609 QualType DestType,
4610 Expr *Initializer) {
4611 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4612 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4613 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4614 return false;
4615
4616 Sequence.AddOCLZeroEventStep(DestType);
4617 return true;
4618}
4619
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004620InitializationSequence::InitializationSequence(Sema &S,
4621 const InitializedEntity &Entity,
4622 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004623 MultiExprArg Args,
4624 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004625 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004626 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4627}
4628
4629void InitializationSequence::InitializeFrom(Sema &S,
4630 const InitializedEntity &Entity,
4631 const InitializationKind &Kind,
4632 MultiExprArg Args,
4633 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004634 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
John McCall5e77d762013-04-16 07:28:30 +00004636 // Eliminate non-overload placeholder types in the arguments. We
4637 // need to do this before checking whether types are dependent
4638 // because lowering a pseudo-object expression might well give us
4639 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004640 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004641 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4642 // FIXME: should we be doing this here?
4643 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4644 if (result.isInvalid()) {
4645 SetFailed(FK_PlaceholderType);
4646 return;
4647 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004648 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004649 }
4650
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004651 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004652 // The semantics of initializers are as follows. The destination type is
4653 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004654 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004656 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004657 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004658
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004659 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004660 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004661 SequenceKind = DependentSequence;
4662 return;
4663 }
4664
Sebastian Redld201edf2011-06-05 13:59:11 +00004665 // Almost everything is a normal sequence.
4666 setSequenceKind(NormalSequence);
4667
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004668 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004669 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004670 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004671 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004672 if (S.getLangOpts().ObjC1) {
4673 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4674 DestType, Initializer->getType(),
4675 Initializer) ||
4676 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4677 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004678 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004679 if (!isa<InitListExpr>(Initializer))
4680 SourceType = Initializer->getType();
4681 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004682
Sebastian Redl0501c632012-02-12 16:37:36 +00004683 // - If the initializer is a (non-parenthesized) braced-init-list, the
4684 // object is list-initialized (8.5.4).
4685 if (Kind.getKind() != InitializationKind::IK_Direct) {
4686 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4687 TryListInitialization(S, Entity, Kind, InitList, *this);
4688 return;
4689 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004692 // - If the destination type is a reference type, see 8.5.3.
4693 if (DestType->isReferenceType()) {
4694 // C++0x [dcl.init.ref]p1:
4695 // A variable declared to be a T& or T&&, that is, "reference to type T"
4696 // (8.3.2), shall be initialized by an object, or function, of type T or
4697 // by an object that can be converted into a T.
4698 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004699 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004700 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004701 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004702 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004703 return;
4704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004706 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004707 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004708 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004709 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004710 return;
4711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004712
Douglas Gregor85dabae2009-12-16 01:38:02 +00004713 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004714 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004715 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004716 return;
4717 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004718
John McCall66884dd2011-02-21 07:22:22 +00004719 // - If the destination type is an array of characters, an array of
4720 // char16_t, an array of char32_t, or an array of wchar_t, and the
4721 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004723 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004724 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004725 if (Initializer && isa<VariableArrayType>(DestAT)) {
4726 SetFailed(FK_VariableLengthArrayHasInitializer);
4727 return;
4728 }
4729
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004730 if (Initializer) {
4731 switch (IsStringInit(Initializer, DestAT, Context)) {
4732 case SIF_None:
4733 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4734 return;
4735 case SIF_NarrowStringIntoWideChar:
4736 SetFailed(FK_NarrowStringIntoWideCharArray);
4737 return;
4738 case SIF_WideStringIntoChar:
4739 SetFailed(FK_WideStringIntoCharArray);
4740 return;
4741 case SIF_IncompatWideStringIntoWideChar:
4742 SetFailed(FK_IncompatWideStringIntoWideChar);
4743 return;
4744 case SIF_Other:
4745 break;
4746 }
John McCall66884dd2011-02-21 07:22:22 +00004747 }
4748
Douglas Gregore2f943b2011-02-22 18:29:51 +00004749 // Note: as an GNU C extension, we allow initialization of an
4750 // array from a compound literal that creates an array of the same
4751 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004752 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004753 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4754 Initializer->getType()->isArrayType()) {
4755 const ArrayType *SourceAT
4756 = Context.getAsArrayType(Initializer->getType());
4757 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004758 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004759 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004760 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004761 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004762 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004763 }
Richard Smithebeed412012-02-15 22:38:09 +00004764 }
Richard Smithd86812d2012-07-05 08:39:21 +00004765 // Note: as a GNU C++ extension, we allow list-initialization of a
4766 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004767 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004768 Entity.getKind() == InitializedEntity::EK_Member &&
4769 Initializer && isa<InitListExpr>(Initializer)) {
4770 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4771 *this);
4772 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004773 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004774 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004775 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4776 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004777 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004778 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004779
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004780 return;
4781 }
Eli Friedman78275202009-12-19 08:11:05 +00004782
Larisse Voufod2010992015-01-24 23:09:54 +00004783 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00004784 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004785 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004786 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004787
4788 // We're at the end of the line for C: it's either a write-back conversion
4789 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004790 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004791 // If allowed, check whether this is an Objective-C writeback conversion.
4792 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004793 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004794 return;
4795 }
Guy Benyei61054192013-02-07 10:55:47 +00004796
4797 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4798 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004799
4800 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4801 return;
4802
John McCall31168b02011-06-15 23:02:42 +00004803 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004804 AddCAssignmentStep(DestType);
4805 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004806 return;
4807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808
David Blaikiebbafb8a2012-03-11 07:00:24 +00004809 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004810
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004811 // - If the destination type is a (possibly cv-qualified) class type:
4812 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813 // - If the initialization is direct-initialization, or if it is
4814 // copy-initialization where the cv-unqualified version of the
4815 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004816 // class of the destination, constructors are considered. [...]
4817 if (Kind.getKind() == InitializationKind::IK_Direct ||
4818 (Kind.getKind() == InitializationKind::IK_Copy &&
4819 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4820 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004821 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith77be48a2014-07-31 06:31:19 +00004822 DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004823 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004824 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004826 // used) to a derived class thereof are enumerated as described in
4827 // 13.3.1.4, and the best one is chosen through overload resolution
4828 // (13.3).
4829 else
Richard Smith77be48a2014-07-31 06:31:19 +00004830 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004831 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004832 return;
4833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004835 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004836 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004837 return;
4838 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004839 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004840
4841 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004842 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004843 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00004844 // For a conversion to _Atomic(T) from either T or a class type derived
4845 // from T, initialize the T object then convert to _Atomic type.
4846 bool NeedAtomicConversion = false;
4847 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4848 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4849 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4850 DestType = Atomic->getValueType();
4851 NeedAtomicConversion = true;
4852 }
4853 }
4854
4855 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004856 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004857 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00004858 if (!Failed() && NeedAtomicConversion)
4859 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004860 return;
4861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004863 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004864 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004865 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004867 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00004868
John McCall31168b02011-06-15 23:02:42 +00004869 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00004870 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00004871 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004872 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004873 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004874 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4875 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00004876
4877 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00004878 ICS.Standard.Second == ICK_Writeback_Conversion) {
4879 // Objective-C ARC writeback conversion.
4880
4881 // We should copy unless we're passing to an argument explicitly
4882 // marked 'out'.
4883 bool ShouldCopy = true;
4884 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4885 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4886
4887 // If there was an lvalue adjustment, add it as a separate conversion.
4888 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4889 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4890 ImplicitConversionSequence LvalueICS;
4891 LvalueICS.setStandard();
4892 LvalueICS.Standard.setAsIdentityConversion();
4893 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4894 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004895 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004896 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004897
Richard Smith77be48a2014-07-31 06:31:19 +00004898 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004899 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004900 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004901 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4902 AddZeroInitializationStep(Entity.getType());
4903 } else if (Initializer->getType() == Context.OverloadTy &&
4904 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4905 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004906 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004907 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004908 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004909 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00004910 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004911
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004912 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004913 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004914}
4915
4916InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004917 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004918 StepEnd = Steps.end();
4919 Step != StepEnd; ++Step)
4920 Step->Destroy();
4921}
4922
4923//===----------------------------------------------------------------------===//
4924// Perform initialization
4925//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004926static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004927getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004928 switch(Entity.getKind()) {
4929 case InitializedEntity::EK_Variable:
4930 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004931 case InitializedEntity::EK_Exception:
4932 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004933 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004934 return Sema::AA_Initializing;
4935
4936 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004937 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004938 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4939 return Sema::AA_Sending;
4940
Douglas Gregore1314a62009-12-18 05:02:21 +00004941 return Sema::AA_Passing;
4942
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004943 case InitializedEntity::EK_Parameter_CF_Audited:
4944 if (Entity.getDecl() &&
4945 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4946 return Sema::AA_Sending;
4947
4948 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4949
Douglas Gregore1314a62009-12-18 05:02:21 +00004950 case InitializedEntity::EK_Result:
4951 return Sema::AA_Returning;
4952
Douglas Gregore1314a62009-12-18 05:02:21 +00004953 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004954 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004955 // FIXME: Can we tell apart casting vs. converting?
4956 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004957
Douglas Gregore1314a62009-12-18 05:02:21 +00004958 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004959 case InitializedEntity::EK_ArrayElement:
4960 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004961 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004962 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004963 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004964 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004965 return Sema::AA_Initializing;
4966 }
4967
David Blaikie8a40f702012-01-17 06:56:22 +00004968 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004969}
4970
Richard Smith27874d62013-01-08 00:08:23 +00004971/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004972/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004973static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004974 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004975 case InitializedEntity::EK_ArrayElement:
4976 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004977 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004978 case InitializedEntity::EK_New:
4979 case InitializedEntity::EK_Variable:
4980 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004981 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004982 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004983 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004984 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004985 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004986 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004987 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004988 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004989
Douglas Gregore1314a62009-12-18 05:02:21 +00004990 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004991 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004992 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004993 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004994 return true;
4995 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996
Douglas Gregore1314a62009-12-18 05:02:21 +00004997 llvm_unreachable("missed an InitializedEntity kind?");
4998}
4999
Douglas Gregor95562572010-04-24 23:45:46 +00005000/// \brief Whether the given entity, when initialized with an object
5001/// created for that initialization, requires destruction.
5002static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
5003 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005004 case InitializedEntity::EK_Result:
5005 case InitializedEntity::EK_New:
5006 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005007 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005008 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005009 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005010 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005011 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005012 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005013
Richard Smith27874d62013-01-08 00:08:23 +00005014 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00005015 case InitializedEntity::EK_Variable:
5016 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005017 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005018 case InitializedEntity::EK_Temporary:
5019 case InitializedEntity::EK_ArrayElement:
5020 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005021 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005022 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005023 return true;
5024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025
5026 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005027}
5028
Richard Smithc620f552011-10-19 16:55:56 +00005029/// \brief Look for copy and move constructors and constructor templates, for
5030/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
5031static void LookupCopyAndMoveConstructors(Sema &S,
5032 OverloadCandidateSet &CandidateSet,
5033 CXXRecordDecl *Class,
5034 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00005035 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005036 // The container holding the constructors can under certain conditions
5037 // be changed while iterating (e.g. because of deserialization).
5038 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00005039 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00005040 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005041 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
5042 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00005043 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00005044
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005045 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00005046 // Handle copy/moveconstructors, only.
5047 if (!Constructor || Constructor->isInvalidDecl() ||
5048 !Constructor->isCopyOrMoveConstructor() ||
5049 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5050 continue;
5051
5052 DeclAccessPair FoundDecl
5053 = DeclAccessPair::make(Constructor, Constructor->getAccess());
5054 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005055 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00005056 continue;
5057 }
5058
5059 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005060 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00005061 if (ConstructorTmpl->isInvalidDecl())
5062 continue;
5063
5064 Constructor = cast<CXXConstructorDecl>(
5065 ConstructorTmpl->getTemplatedDecl());
5066 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5067 continue;
5068
5069 // FIXME: Do we need to limit this to copy-constructor-like
5070 // candidates?
5071 DeclAccessPair FoundDecl
5072 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00005073 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005074 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00005075 }
5076}
5077
5078/// \brief Get the location at which initialization diagnostics should appear.
5079static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5080 Expr *Initializer) {
5081 switch (Entity.getKind()) {
5082 case InitializedEntity::EK_Result:
5083 return Entity.getReturnLoc();
5084
5085 case InitializedEntity::EK_Exception:
5086 return Entity.getThrowLoc();
5087
5088 case InitializedEntity::EK_Variable:
5089 return Entity.getDecl()->getLocation();
5090
Douglas Gregor19666fb2012-02-15 16:57:26 +00005091 case InitializedEntity::EK_LambdaCapture:
5092 return Entity.getCaptureLoc();
5093
Richard Smithc620f552011-10-19 16:55:56 +00005094 case InitializedEntity::EK_ArrayElement:
5095 case InitializedEntity::EK_Member:
5096 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005097 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005098 case InitializedEntity::EK_Temporary:
5099 case InitializedEntity::EK_New:
5100 case InitializedEntity::EK_Base:
5101 case InitializedEntity::EK_Delegating:
5102 case InitializedEntity::EK_VectorElement:
5103 case InitializedEntity::EK_ComplexElement:
5104 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005105 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005106 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005107 return Initializer->getLocStart();
5108 }
5109 llvm_unreachable("missed an InitializedEntity kind?");
5110}
5111
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005112/// \brief Make a (potentially elidable) temporary copy of the object
5113/// provided by the given initializer by calling the appropriate copy
5114/// constructor.
5115///
5116/// \param S The Sema object used for type-checking.
5117///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005118/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005119/// the type of the initializer expression or a superclass thereof.
5120///
James Dennett634962f2012-06-14 21:40:34 +00005121/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005122///
5123/// \param CurInit The initializer expression.
5124///
5125/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5126/// is permitted in C++03 (but not C++0x) when binding a reference to
5127/// an rvalue.
5128///
5129/// \returns An expression that copies the initializer expression into
5130/// a temporary object, or an error expression if a copy could not be
5131/// created.
John McCalldadc5752010-08-24 06:29:42 +00005132static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005133 QualType T,
5134 const InitializedEntity &Entity,
5135 ExprResult CurInit,
5136 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005137 if (CurInit.isInvalid())
5138 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005139 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005140 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005141 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005142 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005143 Class = cast<CXXRecordDecl>(Record->getDecl());
5144 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005145 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005146
Douglas Gregor5d369002011-01-21 18:05:27 +00005147 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005148 // When certain criteria are met, an implementation is allowed to
5149 // omit the copy/move construction of a class object, even if the
5150 // copy/move constructor and/or destructor for the object have
5151 // side effects. [...]
5152 // - when a temporary class object that has not been bound to a
5153 // reference (12.2) would be copied/moved to a class object
5154 // with the same cv-unqualified type, the copy/move operation
5155 // can be omitted by constructing the temporary object
5156 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005158 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005159 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005160 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005161 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005162 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005163 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005164
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005165 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005166 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005167 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005168
Douglas Gregorf282a762011-01-21 19:38:21 +00005169 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005170 // Only consider constructors and constructor templates. Per
5171 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5172 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005173 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005174 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005175
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005176 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5177
Douglas Gregore1314a62009-12-18 05:02:21 +00005178 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005179 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005180 case OR_Success:
5181 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005182
Douglas Gregore1314a62009-12-18 05:02:21 +00005183 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005184 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5185 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5186 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005187 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005188 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005189 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005190 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005191 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005192 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005193
Douglas Gregore1314a62009-12-18 05:02:21 +00005194 case OR_Ambiguous:
5195 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005196 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005197 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005198 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005199 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200
Douglas Gregore1314a62009-12-18 05:02:21 +00005201 case OR_Deleted:
5202 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005203 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005204 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005205 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005206 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005207 }
5208
Douglas Gregor5ab11652010-04-17 22:01:05 +00005209 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005210 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005211 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005212
Anders Carlssona01874b2010-04-21 18:47:17 +00005213 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005214 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005215
5216 if (IsExtraneousCopy) {
5217 // If this is a totally extraneous copy for C++03 reference
5218 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005219 // expression. We don't generate an (elided) copy operation here
5220 // because doing so would require us to pass down a flag to avoid
5221 // infinite recursion, where each step adds another extraneous,
5222 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005223
Douglas Gregor30b52772010-04-18 07:57:34 +00005224 // Instantiate the default arguments of any extra parameters in
5225 // the selected copy constructor, as if we were going to create a
5226 // proper call to the copy constructor.
5227 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5228 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5229 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005230 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005231 break;
5232
5233 // Build the default argument expression; we don't actually care
5234 // if this succeeds or not, because this routine will complain
5235 // if there was a problem.
5236 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5237 }
5238
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005239 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005241
Douglas Gregor5ab11652010-04-17 22:01:05 +00005242 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005243 // constructor call (we might have derived-to-base conversions, or
5244 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005245 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005246 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005247
Douglas Gregord0ace022010-04-25 00:55:24 +00005248 // Actually perform the constructor call.
5249 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005250 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005251 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005252 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005253 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005254 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005255 CXXConstructExpr::CK_Complete,
5256 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005257
Douglas Gregord0ace022010-04-25 00:55:24 +00005258 // If we're supposed to bind temporaries, do so.
5259 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005260 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005261 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005262}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005263
Richard Smithc620f552011-10-19 16:55:56 +00005264/// \brief Check whether elidable copy construction for binding a reference to
5265/// a temporary would have succeeded if we were building in C++98 mode, for
5266/// -Wc++98-compat.
5267static void CheckCXX98CompatAccessibleCopy(Sema &S,
5268 const InitializedEntity &Entity,
5269 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005270 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005271
5272 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5273 if (!Record)
5274 return;
5275
5276 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005277 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005278 return;
5279
5280 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005281 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005282 LookupCopyAndMoveConstructors(
5283 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5284
5285 // Perform overload resolution.
5286 OverloadCandidateSet::iterator Best;
5287 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5288
5289 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5290 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5291 << CurInitExpr->getSourceRange();
5292
5293 switch (OR) {
5294 case OR_Success:
5295 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005296 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005297 // FIXME: Check default arguments as far as that's possible.
5298 break;
5299
5300 case OR_No_Viable_Function:
5301 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005302 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005303 break;
5304
5305 case OR_Ambiguous:
5306 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005307 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005308 break;
5309
5310 case OR_Deleted:
5311 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005312 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005313 break;
5314 }
5315}
5316
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005317void InitializationSequence::PrintInitLocationNote(Sema &S,
5318 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005319 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005320 if (Entity.getDecl()->getLocation().isInvalid())
5321 return;
5322
5323 if (Entity.getDecl()->getDeclName())
5324 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5325 << Entity.getDecl()->getDeclName();
5326 else
5327 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5328 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005329 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5330 Entity.getMethodDecl())
5331 S.Diag(Entity.getMethodDecl()->getLocation(),
5332 diag::note_method_return_type_change)
5333 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005334}
5335
Sebastian Redl112aa822011-07-14 19:07:55 +00005336static bool isReferenceBinding(const InitializationSequence::Step &s) {
5337 return s.Kind == InitializationSequence::SK_BindReference ||
5338 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5339}
5340
Jordan Rose6c0505e2013-05-06 16:48:12 +00005341/// Returns true if the parameters describe a constructor initialization of
5342/// an explicit temporary object, e.g. "Point(x, y)".
5343static bool isExplicitTemporary(const InitializedEntity &Entity,
5344 const InitializationKind &Kind,
5345 unsigned NumArgs) {
5346 switch (Entity.getKind()) {
5347 case InitializedEntity::EK_Temporary:
5348 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005349 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005350 break;
5351 default:
5352 return false;
5353 }
5354
5355 switch (Kind.getKind()) {
5356 case InitializationKind::IK_DirectList:
5357 return true;
5358 // FIXME: Hack to work around cast weirdness.
5359 case InitializationKind::IK_Direct:
5360 case InitializationKind::IK_Value:
5361 return NumArgs != 1;
5362 default:
5363 return false;
5364 }
5365}
5366
Sebastian Redled2e5322011-12-22 14:44:04 +00005367static ExprResult
5368PerformConstructorInitialization(Sema &S,
5369 const InitializedEntity &Entity,
5370 const InitializationKind &Kind,
5371 MultiExprArg Args,
5372 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005373 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005374 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005375 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005376 SourceLocation LBraceLoc,
5377 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005378 unsigned NumArgs = Args.size();
5379 CXXConstructorDecl *Constructor
5380 = cast<CXXConstructorDecl>(Step.Function.Function);
5381 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5382
5383 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005384 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005385 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5386 ? Kind.getEqualLoc()
5387 : Kind.getLocation();
5388
5389 if (Kind.getKind() == InitializationKind::IK_Default) {
5390 // Force even a trivial, implicit default constructor to be
5391 // semantically checked. We do this explicitly because we don't build
5392 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005393 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005394 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005395 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005396 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5397 }
5398
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005399 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005400
Douglas Gregor6073dca2012-02-24 23:56:31 +00005401 // C++ [over.match.copy]p1:
5402 // - When initializing a temporary to be bound to the first parameter
5403 // of a constructor that takes a reference to possibly cv-qualified
5404 // T as its first argument, called with a single argument in the
5405 // context of direct-initialization, explicit conversion functions
5406 // are also considered.
5407 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5408 Args.size() == 1 &&
5409 Constructor->isCopyOrMoveConstructor();
5410
Sebastian Redled2e5322011-12-22 14:44:04 +00005411 // Determine the arguments required to actually perform the constructor
5412 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005413 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005414 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005415 AllowExplicitConv,
5416 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005417 return ExprError();
5418
5419
Jordan Rose6c0505e2013-05-06 16:48:12 +00005420 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005421 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005422 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005423 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5424 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005425
5426 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5427 if (!TSInfo)
5428 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005429 SourceRange ParenOrBraceRange =
5430 (Kind.getKind() == InitializationKind::IK_DirectList)
5431 ? SourceRange(LBraceLoc, RBraceLoc)
5432 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005433
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005434 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5435 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5436 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005437 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005438 } else {
5439 CXXConstructExpr::ConstructionKind ConstructKind =
5440 CXXConstructExpr::CK_Complete;
5441
5442 if (Entity.getKind() == InitializedEntity::EK_Base) {
5443 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5444 CXXConstructExpr::CK_VirtualBase :
5445 CXXConstructExpr::CK_NonVirtualBase;
5446 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5447 ConstructKind = CXXConstructExpr::CK_Delegating;
5448 }
5449
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005450 // Only get the parenthesis or brace range if it is a list initialization or
5451 // direct construction.
5452 SourceRange ParenOrBraceRange;
5453 if (IsListInitialization)
5454 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5455 else if (Kind.getKind() == InitializationKind::IK_Direct)
5456 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005457
5458 // If the entity allows NRVO, mark the construction as elidable
5459 // unconditionally.
5460 if (Entity.allowsNRVO())
5461 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5462 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005463 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005464 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005465 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005466 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005467 ConstructorInitRequiresZeroInit,
5468 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005469 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005470 else
5471 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5472 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005473 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005474 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005475 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005476 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005477 ConstructorInitRequiresZeroInit,
5478 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005479 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005480 }
5481 if (CurInit.isInvalid())
5482 return ExprError();
5483
5484 // Only check access if all of that succeeded.
5485 S.CheckConstructorAccess(Loc, Constructor, Entity,
5486 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005487 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5488 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005489
5490 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005491 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005492
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005493 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005494}
5495
Richard Smitheb3cad52012-06-04 22:27:30 +00005496/// Determine whether the specified InitializedEntity definitely has a lifetime
5497/// longer than the current full-expression. Conservatively returns false if
5498/// it's unclear.
5499static bool
5500InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5501 const InitializedEntity *Top = &Entity;
5502 while (Top->getParent())
5503 Top = Top->getParent();
5504
5505 switch (Top->getKind()) {
5506 case InitializedEntity::EK_Variable:
5507 case InitializedEntity::EK_Result:
5508 case InitializedEntity::EK_Exception:
5509 case InitializedEntity::EK_Member:
5510 case InitializedEntity::EK_New:
5511 case InitializedEntity::EK_Base:
5512 case InitializedEntity::EK_Delegating:
5513 return true;
5514
5515 case InitializedEntity::EK_ArrayElement:
5516 case InitializedEntity::EK_VectorElement:
5517 case InitializedEntity::EK_BlockElement:
5518 case InitializedEntity::EK_ComplexElement:
5519 // Could not determine what the full initialization is. Assume it might not
5520 // outlive the full-expression.
5521 return false;
5522
5523 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005524 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005525 case InitializedEntity::EK_Temporary:
5526 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005527 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005528 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005529 // The entity being initialized might not outlive the full-expression.
5530 return false;
5531 }
5532
5533 llvm_unreachable("unknown entity kind");
5534}
5535
Richard Smithe6c01442013-06-05 00:46:14 +00005536/// Determine the declaration which an initialized entity ultimately refers to,
5537/// for the purpose of lifetime-extending a temporary bound to a reference in
5538/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005539static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5540 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005541 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005542 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005543 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005544 case InitializedEntity::EK_Variable:
5545 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005546 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005547
5548 case InitializedEntity::EK_Member:
5549 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005550 if (Entity->getParent())
5551 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5552 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005553
5554 // except:
5555 // -- A temporary bound to a reference member in a constructor's
5556 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005557 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005558
5559 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005560 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005561 // -- A temporary bound to a reference parameter in a function call
5562 // persists until the completion of the full-expression containing
5563 // the call.
5564 case InitializedEntity::EK_Result:
5565 // -- The lifetime of a temporary bound to the returned value in a
5566 // function return statement is not extended; the temporary is
5567 // destroyed at the end of the full-expression in the return statement.
5568 case InitializedEntity::EK_New:
5569 // -- A temporary bound to a reference in a new-initializer persists
5570 // until the completion of the full-expression containing the
5571 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005572 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005573
5574 case InitializedEntity::EK_Temporary:
5575 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005576 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005577 // We don't yet know the storage duration of the surrounding temporary.
5578 // Assume it's got full-expression duration for now, it will patch up our
5579 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005580 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005581
5582 case InitializedEntity::EK_ArrayElement:
5583 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005584 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5585 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005586
5587 case InitializedEntity::EK_Base:
5588 case InitializedEntity::EK_Delegating:
5589 // We can reach this case for aggregate initialization in a constructor:
5590 // struct A { int &&r; };
5591 // struct B : A { B() : A{0} {} };
5592 // In this case, use the innermost field decl as the context.
5593 return FallbackDecl;
5594
5595 case InitializedEntity::EK_BlockElement:
5596 case InitializedEntity::EK_LambdaCapture:
5597 case InitializedEntity::EK_Exception:
5598 case InitializedEntity::EK_VectorElement:
5599 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005600 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005601 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005602 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005603}
5604
David Majnemerdaff3702014-05-01 17:50:17 +00005605static void performLifetimeExtension(Expr *Init,
5606 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005607
5608/// Update a glvalue expression that is used as the initializer of a reference
5609/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005610/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005611static bool
5612performReferenceExtension(Expr *Init,
5613 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005614 // Walk past any constructs which we can lifetime-extend across.
5615 Expr *Old;
5616 do {
5617 Old = Init;
5618
Richard Smithdbc82492015-01-10 01:28:13 +00005619 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5620 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5621 // This is just redundant braces around an initializer. Step over it.
5622 Init = ILE->getInit(0);
5623 }
5624 }
5625
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005626 // Step over any subobject adjustments; we may have a materialized
5627 // temporary inside them.
5628 SmallVector<const Expr *, 2> CommaLHSs;
5629 SmallVector<SubobjectAdjustment, 2> Adjustments;
5630 Init = const_cast<Expr *>(
5631 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5632
5633 // Per current approach for DR1376, look through casts to reference type
5634 // when performing lifetime extension.
5635 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5636 if (CE->getSubExpr()->isGLValue())
5637 Init = CE->getSubExpr();
5638
5639 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5640 // It's unclear if binding a reference to that xvalue extends the array
5641 // temporary.
5642 } while (Init != Old);
5643
Richard Smithe6c01442013-06-05 00:46:14 +00005644 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5645 // Update the storage duration of the materialized temporary.
5646 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005647 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5648 ExtendingEntity->allocateManglingNumber());
5649 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005650 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005651 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005652
5653 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005654}
5655
5656/// Update a prvalue expression that is going to be materialized as a
5657/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005658static void performLifetimeExtension(Expr *Init,
5659 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005660 // Dig out the expression which constructs the extended temporary.
5661 SmallVector<const Expr *, 2> CommaLHSs;
5662 SmallVector<SubobjectAdjustment, 2> Adjustments;
5663 Init = const_cast<Expr *>(
5664 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5665
Richard Smith736a9472013-06-12 20:42:33 +00005666 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5667 Init = BTE->getSubExpr();
5668
Richard Smithcc1b96d2013-06-12 22:31:48 +00005669 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005670 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005671 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005672 return;
5673 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005674
Richard Smithe6c01442013-06-05 00:46:14 +00005675 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005676 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005677 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005678 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005679 return;
5680 }
5681
Richard Smithcc1b96d2013-06-12 22:31:48 +00005682 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005683 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5684
5685 // If we lifetime-extend a braced initializer which is initializing an
5686 // aggregate, and that aggregate contains reference members which are
5687 // bound to temporaries, those temporaries are also lifetime-extended.
5688 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5689 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005690 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005691 else {
5692 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005693 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005694 if (Index >= ILE->getNumInits())
5695 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005696 if (I->isUnnamedBitfield())
5697 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005698 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005699 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005700 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005701 else if (isa<InitListExpr>(SubInit) ||
5702 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005703 // This may be either aggregate-initialization of a member or
5704 // initialization of a std::initializer_list object. Either way,
5705 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005706 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005707 ++Index;
5708 }
5709 }
5710 }
5711 }
5712}
5713
Richard Smithcc1b96d2013-06-12 22:31:48 +00005714static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5715 const Expr *Init, bool IsInitializerList,
5716 const ValueDecl *ExtendingDecl) {
5717 // Warn if a field lifetime-extends a temporary.
5718 if (isa<FieldDecl>(ExtendingDecl)) {
5719 if (IsInitializerList) {
5720 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5721 << /*at end of constructor*/true;
5722 return;
5723 }
5724
5725 bool IsSubobjectMember = false;
5726 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5727 Ent = Ent->getParent()) {
5728 if (Ent->getKind() != InitializedEntity::EK_Base) {
5729 IsSubobjectMember = true;
5730 break;
5731 }
5732 }
5733 S.Diag(Init->getExprLoc(),
5734 diag::warn_bind_ref_member_to_temporary)
5735 << ExtendingDecl << Init->getSourceRange()
5736 << IsSubobjectMember << IsInitializerList;
5737 if (IsSubobjectMember)
5738 S.Diag(ExtendingDecl->getLocation(),
5739 diag::note_ref_subobject_of_member_declared_here);
5740 else
5741 S.Diag(ExtendingDecl->getLocation(),
5742 diag::note_ref_or_ptr_member_declared_here)
5743 << /*is pointer*/false;
5744 }
5745}
5746
Richard Smithaaa0ec42013-09-21 21:19:19 +00005747static void DiagnoseNarrowingInInitList(Sema &S,
5748 const ImplicitConversionSequence &ICS,
5749 QualType PreNarrowingType,
5750 QualType EntityType,
5751 const Expr *PostInit);
5752
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005754InitializationSequence::Perform(Sema &S,
5755 const InitializedEntity &Entity,
5756 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005757 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005758 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005759 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005760 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005761 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005762 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005763
Sebastian Redld201edf2011-06-05 13:59:11 +00005764 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005765 // If the declaration is a non-dependent, incomplete array type
5766 // that has an initializer, then its type will be completed once
5767 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005768 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005769 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005770 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005771 if (const IncompleteArrayType *ArrayT
5772 = S.Context.getAsIncompleteArrayType(DeclType)) {
5773 // FIXME: We don't currently have the ability to accurately
5774 // compute the length of an initializer list without
5775 // performing full type-checking of the initializer list
5776 // (since we have to determine where braces are implicitly
5777 // introduced and such). So, we fall back to making the array
5778 // type a dependently-sized array type with no specified
5779 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005780 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005781 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005782
Douglas Gregor51e77d52009-12-10 17:56:55 +00005783 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005784 if (DeclaratorDecl *DD = Entity.getDecl()) {
5785 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5786 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005787 if (IncompleteArrayTypeLoc ArrayLoc =
5788 TL.getAs<IncompleteArrayTypeLoc>())
5789 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005790 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005791 }
5792
5793 *ResultType
5794 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005795 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005796 ArrayT->getSizeModifier(),
5797 ArrayT->getIndexTypeCVRQualifiers(),
5798 Brackets);
5799 }
5800
5801 }
5802 }
Sebastian Redla9351792012-02-11 23:51:47 +00005803 if (Kind.getKind() == InitializationKind::IK_Direct &&
5804 !Kind.isExplicitCast()) {
5805 // Rebuild the ParenListExpr.
5806 SourceRange ParenRange = Kind.getParenRange();
5807 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005808 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005809 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005810 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005811 Kind.isExplicitCast() ||
5812 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005813 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005814 }
5815
Sebastian Redld201edf2011-06-05 13:59:11 +00005816 // No steps means no initialization.
5817 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005818 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005819
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005820 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005821 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005822 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005823 // Produce a C++98 compatibility warning if we are initializing a reference
5824 // from an initializer list. For parameters, we produce a better warning
5825 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005826 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005827 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5828 << Init->getSourceRange();
5829 }
5830
Richard Smitheb3cad52012-06-04 22:27:30 +00005831 // Diagnose cases where we initialize a pointer to an array temporary, and the
5832 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005833 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005834 Entity.getType()->isPointerType() &&
5835 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005836 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005837 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5838 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5839 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5840 << Init->getSourceRange();
5841 }
5842
Douglas Gregor1b303932009-12-22 15:35:07 +00005843 QualType DestType = Entity.getType().getNonReferenceType();
5844 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005845 // the same as Entity.getDecl()->getType() in cases involving type merging,
5846 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005847 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005848 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005849 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005850
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005851 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005852
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005853 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005854 // grab the only argument out the Args and place it into the "current"
5855 // initializer.
5856 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005857 case SK_ResolveAddressOfOverloadedFunction:
5858 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005859 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005860 case SK_CastDerivedToBaseLValue:
5861 case SK_BindReference:
5862 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005863 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005864 case SK_UserConversion:
5865 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005866 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005867 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00005868 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00005869 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005870 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005871 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005872 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005873 case SK_UnwrapInitList:
5874 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005875 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005876 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005877 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005878 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005879 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005880 case SK_PassByIndirectCopyRestore:
5881 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005882 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005883 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005884 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005885 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005886 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005887 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005888 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005889 break;
John McCall34376a62010-12-04 03:47:34 +00005890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005891
Douglas Gregore1314a62009-12-18 05:02:21 +00005892 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00005893 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00005894 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005895 case SK_ZeroInitialization:
5896 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005898
5899 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005900 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005901 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005902 for (step_iterator Step = step_begin(), StepEnd = step_end();
5903 Step != StepEnd; ++Step) {
5904 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005905 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005906
John Wiegley01296292011-04-08 18:41:53 +00005907 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005909 switch (Step->Kind) {
5910 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005911 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005912 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005913 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005914 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5915 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005916 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005917 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005918 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005919 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005920
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005921 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005922 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005923 case SK_CastDerivedToBaseLValue: {
5924 // We have a derived-to-base cast that produces either an rvalue or an
5925 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005926
John McCallcf142162010-08-07 06:22:56 +00005927 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005928
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005929 // Casts to inaccessible base classes are allowed with C-style casts.
5930 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5931 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005932 CurInit.get()->getLocStart(),
5933 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005934 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005935 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005936
John McCall2536c6d2010-08-25 10:28:54 +00005937 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005938 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005939 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005940 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005941 VK_XValue :
5942 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005943 CurInit =
5944 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5945 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005946 break;
5947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005948
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005949 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005950 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5951 if (CurInit.get()->refersToBitField()) {
5952 // We don't necessarily have an unambiguous source bit-field.
5953 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005954 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005955 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005956 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005957 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005958 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005959 if (BitField)
5960 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5961
John McCallfaf5fb42010-08-26 23:41:50 +00005962 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005963 }
Anders Carlssona91be642010-01-29 02:47:33 +00005964
John Wiegley01296292011-04-08 18:41:53 +00005965 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005966 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005967 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5968 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005969 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005970 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005971 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005972 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005973
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005974 // Reference binding does not have any corresponding ASTs.
5975
5976 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005977 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005978 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005979
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005980 // Even though we didn't materialize a temporary, the binding may still
5981 // extend the lifetime of a temporary. This happens if we bind a reference
5982 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005983 if (const InitializedEntity *ExtendingEntity =
5984 getEntityForTemporaryLifetimeExtension(&Entity))
5985 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5986 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5987 /*IsInitializerList=*/false,
5988 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005989
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005990 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005991
Richard Smithe6c01442013-06-05 00:46:14 +00005992 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005993 // Make sure the "temporary" is actually an rvalue.
5994 assert(CurInit.get()->isRValue() && "not a temporary");
5995
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005996 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005997 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005998 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005999
Douglas Gregorfe314812011-06-21 17:03:29 +00006000 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00006001 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00006002 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006003 Entity.getType()->isLValueReferenceType());
6004
6005 // Maybe lifetime-extend the temporary's subobjects to match the
6006 // entity's lifetime.
6007 if (const InitializedEntity *ExtendingEntity =
6008 getEntityForTemporaryLifetimeExtension(&Entity))
6009 if (performReferenceExtension(MTE, ExtendingEntity))
6010 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
6011 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006012
6013 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00006014 // need cleanups. Likewise if we're extending this temporary to automatic
6015 // storage duration -- we need to register its cleanup during the
6016 // full-expression's cleanups.
6017 if ((S.getLangOpts().ObjCAutoRefCount &&
6018 MTE->getType()->isObjCLifetimeType()) ||
6019 (MTE->getStorageDuration() == SD_Automatic &&
6020 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00006021 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00006022
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006023 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006024 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006025 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006026
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006027 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006028 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006029 /*IsExtraneousCopy=*/true);
6030 break;
6031
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006032 case SK_UserConversion: {
6033 // We have a user-defined conversion that invokes either a constructor
6034 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006035 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00006036 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00006037 FunctionDecl *Fn = Step->Function.Function;
6038 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006039 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006040 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006041 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006042 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006043 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006044 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006045 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00006046
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006047 // Determine the arguments required to actually perform the constructor
6048 // call.
John Wiegley01296292011-04-08 18:41:53 +00006049 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006050 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006051 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006052 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006053 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006054
Richard Smithb24f0672012-02-11 19:22:50 +00006055 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006057 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006058 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006059 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006060 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006061 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006062 CXXConstructExpr::CK_Complete,
6063 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006064 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006065 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006066
Anders Carlssona01874b2010-04-21 18:47:17 +00006067 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00006068 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00006069 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6070 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006071
John McCalle3027922010-08-25 11:45:40 +00006072 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00006073 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6074 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6075 S.IsDerivedFrom(SourceType, Class))
6076 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006077
Douglas Gregor95562572010-04-24 23:45:46 +00006078 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006079 } else {
6080 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006081 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006082 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006083 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006084 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6085 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006086
6087 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006088 // derived-to-base conversion? I believe the answer is "no", because
6089 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006090 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006091 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006092 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006093 FoundFn, Conversion);
6094 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006095 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006096 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006097
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006098 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006099 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6100 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006101 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006102 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006103
John McCalle3027922010-08-25 11:45:40 +00006104 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006105
Alp Toker314cc812014-01-25 16:55:45 +00006106 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006108
Sebastian Redl112aa822011-07-14 19:07:55 +00006109 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006110 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6111
6112 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006113 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006114 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006115 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006116 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006117 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006118 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006119 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006120 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6121 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006122 }
6123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006124
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006125 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6126 CastKind, CurInit.get(), nullptr,
6127 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006128 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006129 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006130 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006131 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006132 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006133 break;
6134 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006135
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006136 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006137 case SK_QualificationConversionXValue:
6138 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006139 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006140 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006141 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006142 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006143 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006144 VK_XValue :
6145 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006146 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006147 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006148 }
6149
Richard Smith77be48a2014-07-31 06:31:19 +00006150 case SK_AtomicConversion: {
6151 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6152 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6153 CK_NonAtomicToAtomic, VK_RValue);
6154 break;
6155 }
6156
Jordan Roseb1312a52013-04-11 00:58:58 +00006157 case SK_LValueToRValue: {
6158 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006159 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6160 CK_LValueToRValue, CurInit.get(),
6161 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006162 break;
6163 }
6164
Richard Smithaaa0ec42013-09-21 21:19:19 +00006165 case SK_ConversionSequence:
6166 case SK_ConversionSequenceNoNarrowing: {
6167 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006168 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6169 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006170 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006171 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006172 ExprResult CurInitExprRes =
6173 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006174 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006175 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006176 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006177 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006178
6179 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6180 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6181 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6182 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006183 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006185
Douglas Gregor51e77d52009-12-10 17:56:55 +00006186 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006187 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006188 // If we're not initializing the top-level entity, we need to create an
6189 // InitializeTemporary entity for our target type.
6190 QualType Ty = Step->Type;
6191 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006192 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006193 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6194 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006195 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006196 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006197 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006198
Richard Smithcc1b96d2013-06-12 22:31:48 +00006199 // Hack: We must update *ResultType if available in order to set the
6200 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6201 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6202 if (ResultType &&
6203 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006204 if ((*ResultType)->isRValueReferenceType())
6205 Ty = S.Context.getRValueReferenceType(Ty);
6206 else if ((*ResultType)->isLValueReferenceType())
6207 Ty = S.Context.getLValueReferenceType(Ty,
6208 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6209 *ResultType = Ty;
6210 }
6211
6212 InitListExpr *StructuredInitList =
6213 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006214 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006215 CurInit = shouldBindAsTemporary(InitEntity)
6216 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006217 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006218 break;
6219 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006220
Richard Smith53324112014-07-16 21:33:43 +00006221 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006222 // When an initializer list is passed for a parameter of type "reference
6223 // to object", we don't get an EK_Temporary entity, but instead an
6224 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006225 // FIXME: This is a hack. What we really should do is create a user
6226 // conversion step for this case, but this makes it considerably more
6227 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006228 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6229 Entity.getType().getNonReferenceType());
6230 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006231 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006232 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006233 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6234 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006235 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006236 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6237 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006238 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006239 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006240 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006241 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006242 InitList->getLBraceLoc(),
6243 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006244 break;
6245 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006246
Sebastian Redl29526f02011-11-27 16:50:07 +00006247 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006248 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006249 break;
6250
6251 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006252 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006253 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6254 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006255 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006256 ILE->setSyntacticForm(Syntactic);
6257 ILE->setType(E->getType());
6258 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006259 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006260 break;
6261 }
6262
Richard Smith53324112014-07-16 21:33:43 +00006263 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006264 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006265 // When an initializer list is passed for a parameter of type "reference
6266 // to object", we don't get an EK_Temporary entity, but instead an
6267 // EK_Parameter entity with reference type.
6268 // FIXME: This is a hack. What we really should do is create a user
6269 // conversion step for this case, but this makes it considerably more
6270 // complicated. For now, this will do.
6271 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6272 Entity.getType().getNonReferenceType());
6273 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006274 bool IsStdInitListInit =
6275 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006276 CurInit = PerformConstructorInitialization(
6277 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6278 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006279 /*IsListInitialization*/IsStdInitListInit,
6280 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006281 /*LBraceLoc*/SourceLocation(),
6282 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006283 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006285
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006286 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006287 step_iterator NextStep = Step;
6288 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006289 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006290 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006291 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006292 // The need for zero-initialization is recorded directly into
6293 // the call to the object's constructor within the next step.
6294 ConstructorInitRequiresZeroInit = true;
6295 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006296 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006297 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006298 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6299 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006300 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006301 Kind.getRange().getBegin());
6302
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006303 CurInit = new (S.Context) CXXScalarValueInitExpr(
6304 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6305 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006306 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006307 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006308 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006309 break;
6310 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006311
6312 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006313 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006314 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006315 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006316 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6317 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006318 if (Result.isInvalid())
6319 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006320 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006321
6322 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006323 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006324 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006325 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006326 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006327 == Sema::Compatible)
6328 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006329 if (CurInitExprRes.isInvalid())
6330 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006331 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006332
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006333 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006334 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6335 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006336 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006337 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006338 &Complained)) {
6339 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006340 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006341 } else if (Complained)
6342 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006343 break;
6344 }
Eli Friedman78275202009-12-19 08:11:05 +00006345
6346 case SK_StringInit: {
6347 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006348 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006349 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006350 break;
6351 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006352
6353 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006354 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006355 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006356 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006357 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006358
6359 case SK_ArrayInit:
6360 // Okay: we checked everything before creating this step. Note that
6361 // this is a GNU extension.
6362 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006363 << Step->Type << CurInit.get()->getType()
6364 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006365
6366 // If the destination type is an incomplete array type, update the
6367 // type accordingly.
6368 if (ResultType) {
6369 if (const IncompleteArrayType *IncompleteDest
6370 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6371 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006372 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006373 *ResultType = S.Context.getConstantArrayType(
6374 IncompleteDest->getElementType(),
6375 ConstantSource->getSize(),
6376 ArrayType::Normal, 0);
6377 }
6378 }
6379 }
John McCall31168b02011-06-15 23:02:42 +00006380 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006381
Richard Smithebeed412012-02-15 22:38:09 +00006382 case SK_ParenthesizedArrayInit:
6383 // Okay: we checked everything before creating this step. Note that
6384 // this is a GNU extension.
6385 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6386 << CurInit.get()->getSourceRange();
6387 break;
6388
John McCall31168b02011-06-15 23:02:42 +00006389 case SK_PassByIndirectCopyRestore:
6390 case SK_PassByIndirectRestore:
6391 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006392 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6393 CurInit.get(), Step->Type,
6394 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006395 break;
6396
6397 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006398 CurInit =
6399 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6400 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006401 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006402
6403 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006404 S.Diag(CurInit.get()->getExprLoc(),
6405 diag::warn_cxx98_compat_initializer_list_init)
6406 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006407
Richard Smithcc1b96d2013-06-12 22:31:48 +00006408 // Materialize the temporary into memory.
6409 MaterializeTemporaryExpr *MTE = new (S.Context)
6410 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006411 /*BoundToLvalueReference=*/false);
6412
6413 // Maybe lifetime-extend the array temporary's subobjects to match the
6414 // entity's lifetime.
6415 if (const InitializedEntity *ExtendingEntity =
6416 getEntityForTemporaryLifetimeExtension(&Entity))
6417 if (performReferenceExtension(MTE, ExtendingEntity))
6418 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6419 /*IsInitializerList=*/true,
6420 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006421
6422 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006423 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006424
6425 // Bind the result, in case the library has given initializer_list a
6426 // non-trivial destructor.
6427 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006428 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006429 break;
6430 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006431
Guy Benyei61054192013-02-07 10:55:47 +00006432 case SK_OCLSamplerInit: {
6433 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006434 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006435
6436 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006437
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006438 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006439 if (!SourceType->isSamplerT())
6440 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6441 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006442 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006443 llvm_unreachable("Invalid EntityKind!");
6444 }
6445
6446 break;
6447 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006448 case SK_OCLZeroEvent: {
6449 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006450 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006451
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006452 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006453 CK_ZeroToOCLEvent,
6454 CurInit.get()->getValueKind());
6455 break;
6456 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006457 }
6458 }
John McCall1f425642010-11-11 03:21:53 +00006459
6460 // Diagnose non-fatal problems with the completed initialization.
6461 if (Entity.getKind() == InitializedEntity::EK_Member &&
6462 cast<FieldDecl>(Entity.getDecl())->isBitField())
6463 S.CheckBitFieldInitialization(Kind.getLocation(),
6464 cast<FieldDecl>(Entity.getDecl()),
6465 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006466
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006467 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006468}
6469
Richard Smith593f9932012-12-08 02:01:17 +00006470/// Somewhere within T there is an uninitialized reference subobject.
6471/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006472static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6473 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006474 if (T->isReferenceType()) {
6475 S.Diag(Loc, diag::err_reference_without_init)
6476 << T.getNonReferenceType();
6477 return true;
6478 }
6479
6480 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6481 if (!RD || !RD->hasUninitializedReferenceMember())
6482 return false;
6483
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006484 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006485 if (FI->isUnnamedBitfield())
6486 continue;
6487
6488 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6489 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6490 return true;
6491 }
6492 }
6493
Aaron Ballman574705e2014-03-13 15:41:46 +00006494 for (const auto &BI : RD->bases()) {
6495 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006496 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6497 return true;
6498 }
6499 }
6500
6501 return false;
6502}
6503
6504
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006505//===----------------------------------------------------------------------===//
6506// Diagnose initialization failures
6507//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006508
6509/// Emit notes associated with an initialization that failed due to a
6510/// "simple" conversion failure.
6511static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6512 Expr *op) {
6513 QualType destType = entity.getType();
6514 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6515 op->getType()->isObjCObjectPointerType()) {
6516
6517 // Emit a possible note about the conversion failing because the
6518 // operand is a message send with a related result type.
6519 S.EmitRelatedResultTypeNote(op);
6520
6521 // Emit a possible note about a return failing because we're
6522 // expecting a related result type.
6523 if (entity.getKind() == InitializedEntity::EK_Result)
6524 S.EmitRelatedResultTypeNoteForReturn(destType);
6525 }
6526}
6527
Richard Smith0449aaf2013-11-21 23:30:57 +00006528static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6529 InitListExpr *InitList) {
6530 QualType DestType = Entity.getType();
6531
6532 QualType E;
6533 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6534 QualType ArrayType = S.Context.getConstantArrayType(
6535 E.withConst(),
6536 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6537 InitList->getNumInits()),
6538 clang::ArrayType::Normal, 0);
6539 InitializedEntity HiddenArray =
6540 InitializedEntity::InitializeTemporary(ArrayType);
6541 return diagnoseListInit(S, HiddenArray, InitList);
6542 }
6543
Richard Smith8d082d12014-09-04 22:13:39 +00006544 if (DestType->isReferenceType()) {
6545 // A list-initialization failure for a reference means that we tried to
6546 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
6547 // inner initialization failed.
6548 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
6549 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
6550 SourceLocation Loc = InitList->getLocStart();
6551 if (auto *D = Entity.getDecl())
6552 Loc = D->getLocation();
6553 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
6554 return;
6555 }
6556
Richard Smith0449aaf2013-11-21 23:30:57 +00006557 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6558 /*VerifyOnly=*/false);
6559 assert(DiagnoseInitList.HadError() &&
6560 "Inconsistent init list check result.");
6561}
6562
Nico Weber9386c822014-07-23 05:16:10 +00006563/// Prints a fixit for adding a null initializer for |Entity|. Call this only
6564/// right after emitting a diagnostic.
6565static void maybeEmitZeroInitializationFixit(Sema &S,
6566 InitializationSequence &Sequence,
6567 const InitializedEntity &Entity) {
6568 if (Entity.getKind() != InitializedEntity::EK_Variable)
6569 return;
6570
6571 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
6572 if (VD->getInit() || VD->getLocEnd().isMacroID())
6573 return;
6574
6575 QualType VariableTy = VD->getType().getCanonicalType();
6576 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
6577 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
6578
6579 S.Diag(Loc, diag::note_add_initializer)
6580 << VD << FixItHint::CreateInsertion(Loc, Init);
6581}
6582
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006583bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006584 const InitializedEntity &Entity,
6585 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006586 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006587 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006588 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006589
Douglas Gregor1b303932009-12-22 15:35:07 +00006590 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006591 switch (Failure) {
6592 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006593 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006594 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006595 // Dig out the reference subobject which is uninitialized and diagnose it.
6596 // If this is value-initialization, this could be nested some way within
6597 // the target type.
6598 assert(Kind.getKind() == InitializationKind::IK_Value ||
6599 DestType->isReferenceType());
6600 bool Diagnosed =
6601 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6602 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6603 (void)Diagnosed;
6604 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006605 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006606 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006608
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006609 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006610 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006611 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006612 case FK_ArrayNeedsInitListOrStringLiteral:
6613 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6614 break;
6615 case FK_ArrayNeedsInitListOrWideStringLiteral:
6616 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6617 break;
6618 case FK_NarrowStringIntoWideCharArray:
6619 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6620 break;
6621 case FK_WideStringIntoCharArray:
6622 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6623 break;
6624 case FK_IncompatWideStringIntoWideChar:
6625 S.Diag(Kind.getLocation(),
6626 diag::err_array_init_incompat_wide_string_into_wchar);
6627 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006628 case FK_ArrayTypeMismatch:
6629 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006630 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006631 (Failure == FK_ArrayTypeMismatch
6632 ? diag::err_array_init_different_type
6633 : diag::err_array_init_non_constant_array))
6634 << DestType.getNonReferenceType()
6635 << Args[0]->getType()
6636 << Args[0]->getSourceRange();
6637 break;
6638
John McCalla59dc2f2012-01-05 00:13:19 +00006639 case FK_VariableLengthArrayHasInitializer:
6640 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6641 << Args[0]->getSourceRange();
6642 break;
6643
John McCall16df1e52010-03-30 21:47:33 +00006644 case FK_AddressOfOverloadFailed: {
6645 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006647 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006648 true,
6649 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006650 break;
John McCall16df1e52010-03-30 21:47:33 +00006651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006652
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006653 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006654 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006655 switch (FailedOverloadResult) {
6656 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006657 if (Failure == FK_UserConversionOverloadFailed)
6658 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6659 << Args[0]->getType() << DestType
6660 << Args[0]->getSourceRange();
6661 else
6662 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6663 << DestType << Args[0]->getType()
6664 << Args[0]->getSourceRange();
6665
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006666 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006667 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006668
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006669 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006670 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006671 DestType.getNonReferenceType(),
6672 diag::err_typecheck_nonviable_condition_incomplete,
6673 Args[0]->getType(), Args[0]->getSourceRange()))
6674 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6675 << Args[0]->getType() << Args[0]->getSourceRange()
6676 << DestType.getNonReferenceType();
6677
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006678 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006679 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006680
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006681 case OR_Deleted: {
6682 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6683 << Args[0]->getType() << DestType.getNonReferenceType()
6684 << Args[0]->getSourceRange();
6685 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006686 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006687 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6688 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006689 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006690 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006691 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006692 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006693 }
6694 break;
6695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006697 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006698 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006699 }
6700 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006702 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006703 if (isa<InitListExpr>(Args[0])) {
6704 S.Diag(Kind.getLocation(),
6705 diag::err_lvalue_reference_bind_to_initlist)
6706 << DestType.getNonReferenceType().isVolatileQualified()
6707 << DestType.getNonReferenceType()
6708 << Args[0]->getSourceRange();
6709 break;
6710 }
6711 // Intentional fallthrough
6712
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006713 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006714 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006715 Failure == FK_NonConstLValueReferenceBindingToTemporary
6716 ? diag::err_lvalue_reference_bind_to_temporary
6717 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006718 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006719 << DestType.getNonReferenceType()
6720 << Args[0]->getType()
6721 << Args[0]->getSourceRange();
6722 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006723
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006724 case FK_RValueReferenceBindingToLValue:
6725 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006726 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006727 << Args[0]->getSourceRange();
6728 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006729
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006730 case FK_ReferenceInitDropsQualifiers:
6731 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6732 << DestType.getNonReferenceType()
6733 << Args[0]->getType()
6734 << Args[0]->getSourceRange();
6735 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006736
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006737 case FK_ReferenceInitFailed:
6738 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6739 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006740 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006741 << Args[0]->getType()
6742 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006743 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006744 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745
Douglas Gregorb491ed32011-02-19 21:32:49 +00006746 case FK_ConversionFailed: {
6747 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006748 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006749 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006750 << DestType
John McCall086a4642010-11-24 05:12:34 +00006751 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006752 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006753 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006754 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6755 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006756 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006757 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006758 }
John Wiegley01296292011-04-08 18:41:53 +00006759
6760 case FK_ConversionFromPropertyFailed:
6761 // No-op. This error has already been reported.
6762 break;
6763
Douglas Gregor51e77d52009-12-10 17:56:55 +00006764 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006765 SourceRange R;
6766
6767 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006768 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006769 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006771 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006772
Alp Tokerb6cc5922014-05-03 03:45:55 +00006773 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006774 if (Kind.isCStyleOrFunctionalCast())
6775 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6776 << R;
6777 else
6778 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6779 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006780 break;
6781 }
6782
6783 case FK_ReferenceBindingToInitList:
6784 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6785 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6786 break;
6787
6788 case FK_InitListBadDestinationType:
6789 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6790 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6791 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006793 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006794 case FK_ConstructorOverloadFailed: {
6795 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006796 if (Args.size())
6797 ArgsRange = SourceRange(Args.front()->getLocStart(),
6798 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006799
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006800 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00006801 assert(Args.size() == 1 &&
6802 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006803 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006804 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006805 }
6806
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006807 // FIXME: Using "DestType" for the entity we're printing is probably
6808 // bad.
6809 switch (FailedOverloadResult) {
6810 case OR_Ambiguous:
6811 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6812 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006813 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006814 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006815
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006816 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006817 if (Kind.getKind() == InitializationKind::IK_Default &&
6818 (Entity.getKind() == InitializedEntity::EK_Base ||
6819 Entity.getKind() == InitializedEntity::EK_Member) &&
6820 isa<CXXConstructorDecl>(S.CurContext)) {
6821 // This is implicit default initialization of a member or
6822 // base within a constructor. If no viable function was
6823 // found, notify the user that she needs to explicitly
6824 // initialize this base/member.
6825 CXXConstructorDecl *Constructor
6826 = cast<CXXConstructorDecl>(S.CurContext);
6827 if (Entity.getKind() == InitializedEntity::EK_Base) {
6828 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006829 << (Constructor->getInheritedConstructor() ? 2 :
6830 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006831 << S.Context.getTypeDeclType(Constructor->getParent())
6832 << /*base=*/0
6833 << Entity.getType();
6834
6835 RecordDecl *BaseDecl
6836 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6837 ->getDecl();
6838 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6839 << S.Context.getTagDeclType(BaseDecl);
6840 } else {
6841 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006842 << (Constructor->getInheritedConstructor() ? 2 :
6843 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006844 << S.Context.getTypeDeclType(Constructor->getParent())
6845 << /*member=*/1
6846 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006847 S.Diag(Entity.getDecl()->getLocation(),
6848 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006849
6850 if (const RecordType *Record
6851 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006852 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006853 diag::note_previous_decl)
6854 << S.Context.getTagDeclType(Record->getDecl());
6855 }
6856 break;
6857 }
6858
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006859 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6860 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006861 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006862 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006863
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006864 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006865 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006866 OverloadingResult Ovl
6867 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006868 if (Ovl != OR_Deleted) {
6869 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6870 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006871 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006872 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006873 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006874
6875 // If this is a defaulted or implicitly-declared function, then
6876 // it was implicitly deleted. Make it clear that the deletion was
6877 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006878 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006879 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006880 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006881 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006882 else
6883 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6884 << true << DestType << ArgsRange;
6885
6886 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006887 break;
6888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006890 case OR_Success:
6891 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006892 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006893 }
David Blaikie60deeee2012-01-17 08:24:58 +00006894 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006895
Douglas Gregor85dabae2009-12-16 01:38:02 +00006896 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006897 if (Entity.getKind() == InitializedEntity::EK_Member &&
6898 isa<CXXConstructorDecl>(S.CurContext)) {
6899 // This is implicit default-initialization of a const member in
6900 // a constructor. Complain that it needs to be explicitly
6901 // initialized.
6902 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6903 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006904 << (Constructor->getInheritedConstructor() ? 2 :
6905 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006906 << S.Context.getTypeDeclType(Constructor->getParent())
6907 << /*const=*/1
6908 << Entity.getName();
6909 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6910 << Entity.getName();
6911 } else {
6912 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00006913 << DestType << (bool)DestType->getAs<RecordType>();
6914 maybeEmitZeroInitializationFixit(S, *this, Entity);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006915 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006916 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006917
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006918 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006919 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006920 diag::err_init_incomplete_type);
6921 break;
6922
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006923 case FK_ListInitializationFailed: {
6924 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006925 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6926 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006927 break;
6928 }
John McCall4124c492011-10-17 18:40:02 +00006929
6930 case FK_PlaceholderType: {
6931 // FIXME: Already diagnosed!
6932 break;
6933 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006934
Sebastian Redl048a6d72012-04-01 19:54:59 +00006935 case FK_ExplicitConstructor: {
6936 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6937 << Args[0]->getSourceRange();
6938 OverloadCandidateSet::iterator Best;
6939 OverloadingResult Ovl
6940 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006941 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006942 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6943 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6944 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6945 break;
6946 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006948
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006949 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006950 return true;
6951}
Douglas Gregore1314a62009-12-18 05:02:21 +00006952
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006953void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006954 switch (SequenceKind) {
6955 case FailedSequence: {
6956 OS << "Failed sequence: ";
6957 switch (Failure) {
6958 case FK_TooManyInitsForReference:
6959 OS << "too many initializers for reference";
6960 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006961
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006962 case FK_ArrayNeedsInitList:
6963 OS << "array requires initializer list";
6964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006966 case FK_ArrayNeedsInitListOrStringLiteral:
6967 OS << "array requires initializer list or string literal";
6968 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006969
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006970 case FK_ArrayNeedsInitListOrWideStringLiteral:
6971 OS << "array requires initializer list or wide string literal";
6972 break;
6973
6974 case FK_NarrowStringIntoWideCharArray:
6975 OS << "narrow string into wide char array";
6976 break;
6977
6978 case FK_WideStringIntoCharArray:
6979 OS << "wide string into char array";
6980 break;
6981
6982 case FK_IncompatWideStringIntoWideChar:
6983 OS << "incompatible wide string into wide char array";
6984 break;
6985
Douglas Gregore2f943b2011-02-22 18:29:51 +00006986 case FK_ArrayTypeMismatch:
6987 OS << "array type mismatch";
6988 break;
6989
6990 case FK_NonConstantArrayInit:
6991 OS << "non-constant array initializer";
6992 break;
6993
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006994 case FK_AddressOfOverloadFailed:
6995 OS << "address of overloaded function failed";
6996 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006998 case FK_ReferenceInitOverloadFailed:
6999 OS << "overload resolution for reference initialization failed";
7000 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007001
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007002 case FK_NonConstLValueReferenceBindingToTemporary:
7003 OS << "non-const lvalue reference bound to temporary";
7004 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007005
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007006 case FK_NonConstLValueReferenceBindingToUnrelated:
7007 OS << "non-const lvalue reference bound to unrelated type";
7008 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007009
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007010 case FK_RValueReferenceBindingToLValue:
7011 OS << "rvalue reference bound to an lvalue";
7012 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007014 case FK_ReferenceInitDropsQualifiers:
7015 OS << "reference initialization drops qualifiers";
7016 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007018 case FK_ReferenceInitFailed:
7019 OS << "reference initialization failed";
7020 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007021
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007022 case FK_ConversionFailed:
7023 OS << "conversion failed";
7024 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007025
John Wiegley01296292011-04-08 18:41:53 +00007026 case FK_ConversionFromPropertyFailed:
7027 OS << "conversion from property failed";
7028 break;
7029
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007030 case FK_TooManyInitsForScalar:
7031 OS << "too many initializers for scalar";
7032 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007033
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007034 case FK_ReferenceBindingToInitList:
7035 OS << "referencing binding to initializer list";
7036 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007038 case FK_InitListBadDestinationType:
7039 OS << "initializer list for non-aggregate, non-scalar type";
7040 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007041
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007042 case FK_UserConversionOverloadFailed:
7043 OS << "overloading failed for user-defined conversion";
7044 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007045
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007046 case FK_ConstructorOverloadFailed:
7047 OS << "constructor overloading failed";
7048 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007049
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007050 case FK_DefaultInitOfConst:
7051 OS << "default initialization of a const variable";
7052 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00007054 case FK_Incomplete:
7055 OS << "initialization of incomplete type";
7056 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007057
7058 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007059 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00007060 break;
7061
John McCalla59dc2f2012-01-05 00:13:19 +00007062 case FK_VariableLengthArrayHasInitializer:
7063 OS << "variable length array has an initializer";
7064 break;
7065
John McCall4124c492011-10-17 18:40:02 +00007066 case FK_PlaceholderType:
7067 OS << "initializer expression isn't contextually valid";
7068 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00007069
7070 case FK_ListConstructorOverloadFailed:
7071 OS << "list constructor overloading failed";
7072 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007073
Sebastian Redl048a6d72012-04-01 19:54:59 +00007074 case FK_ExplicitConstructor:
7075 OS << "list copy initialization chose explicit constructor";
7076 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007077 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007078 OS << '\n';
7079 return;
7080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007081
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007082 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007083 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007084 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007085
Sebastian Redld201edf2011-06-05 13:59:11 +00007086 case NormalSequence:
7087 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007088 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007090
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007091 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7092 if (S != step_begin()) {
7093 OS << " -> ";
7094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007095
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007096 switch (S->Kind) {
7097 case SK_ResolveAddressOfOverloadedFunction:
7098 OS << "resolve address of overloaded function";
7099 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007101 case SK_CastDerivedToBaseRValue:
7102 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7103 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007105 case SK_CastDerivedToBaseXValue:
7106 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007108
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007109 case SK_CastDerivedToBaseLValue:
7110 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7111 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007113 case SK_BindReference:
7114 OS << "bind reference to lvalue";
7115 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007117 case SK_BindReferenceToTemporary:
7118 OS << "bind reference to a temporary";
7119 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007120
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007121 case SK_ExtraneousCopyToTemporary:
7122 OS << "extraneous C++03 copy to temporary";
7123 break;
7124
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007125 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007126 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007127 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007128
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007129 case SK_QualificationConversionRValue:
7130 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007131 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007132
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007133 case SK_QualificationConversionXValue:
7134 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007135 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007136
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007137 case SK_QualificationConversionLValue:
7138 OS << "qualification conversion (lvalue)";
7139 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007140
Richard Smith77be48a2014-07-31 06:31:19 +00007141 case SK_AtomicConversion:
7142 OS << "non-atomic-to-atomic conversion";
7143 break;
7144
Jordan Roseb1312a52013-04-11 00:58:58 +00007145 case SK_LValueToRValue:
7146 OS << "load (lvalue to rvalue)";
7147 break;
7148
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007149 case SK_ConversionSequence:
7150 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007151 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007152 OS << ")";
7153 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007154
Richard Smithaaa0ec42013-09-21 21:19:19 +00007155 case SK_ConversionSequenceNoNarrowing:
7156 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007157 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007158 OS << ")";
7159 break;
7160
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007161 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007162 OS << "list aggregate initialization";
7163 break;
7164
Sebastian Redl29526f02011-11-27 16:50:07 +00007165 case SK_UnwrapInitList:
7166 OS << "unwrap reference initializer list";
7167 break;
7168
7169 case SK_RewrapInitList:
7170 OS << "rewrap reference initializer list";
7171 break;
7172
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007173 case SK_ConstructorInitialization:
7174 OS << "constructor initialization";
7175 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007176
Richard Smith53324112014-07-16 21:33:43 +00007177 case SK_ConstructorInitializationFromList:
7178 OS << "list initialization via constructor";
7179 break;
7180
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007181 case SK_ZeroInitialization:
7182 OS << "zero initialization";
7183 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007184
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007185 case SK_CAssignment:
7186 OS << "C assignment";
7187 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007188
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007189 case SK_StringInit:
7190 OS << "string initialization";
7191 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007192
7193 case SK_ObjCObjectConversion:
7194 OS << "Objective-C object conversion";
7195 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007196
7197 case SK_ArrayInit:
7198 OS << "array initialization";
7199 break;
John McCall31168b02011-06-15 23:02:42 +00007200
Richard Smithebeed412012-02-15 22:38:09 +00007201 case SK_ParenthesizedArrayInit:
7202 OS << "parenthesized array initialization";
7203 break;
7204
John McCall31168b02011-06-15 23:02:42 +00007205 case SK_PassByIndirectCopyRestore:
7206 OS << "pass by indirect copy and restore";
7207 break;
7208
7209 case SK_PassByIndirectRestore:
7210 OS << "pass by indirect restore";
7211 break;
7212
7213 case SK_ProduceObjCObject:
7214 OS << "Objective-C object retension";
7215 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007216
7217 case SK_StdInitializerList:
7218 OS << "std::initializer_list from initializer list";
7219 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007220
Richard Smithf8adcdc2014-07-17 05:12:35 +00007221 case SK_StdInitializerListConstructorCall:
7222 OS << "list initialization from std::initializer_list";
7223 break;
7224
Guy Benyei61054192013-02-07 10:55:47 +00007225 case SK_OCLSamplerInit:
7226 OS << "OpenCL sampler_t from integer constant";
7227 break;
7228
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007229 case SK_OCLZeroEvent:
7230 OS << "OpenCL event_t from zero";
7231 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007232 }
Richard Smith6b216962013-02-05 05:52:24 +00007233
7234 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007235 }
Richard Smith6b216962013-02-05 05:52:24 +00007236
7237 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007238}
7239
7240void InitializationSequence::dump() const {
7241 dump(llvm::errs());
7242}
7243
Richard Smithaaa0ec42013-09-21 21:19:19 +00007244static void DiagnoseNarrowingInInitList(Sema &S,
7245 const ImplicitConversionSequence &ICS,
7246 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007247 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007248 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007249 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007250 switch (ICS.getKind()) {
7251 case ImplicitConversionSequence::StandardConversion:
7252 SCS = &ICS.Standard;
7253 break;
7254 case ImplicitConversionSequence::UserDefinedConversion:
7255 SCS = &ICS.UserDefined.After;
7256 break;
7257 case ImplicitConversionSequence::AmbiguousConversion:
7258 case ImplicitConversionSequence::EllipsisConversion:
7259 case ImplicitConversionSequence::BadConversion:
7260 return;
7261 }
7262
Richard Smith66e05fe2012-01-18 05:21:49 +00007263 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7264 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007265 QualType ConstantType;
7266 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7267 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007268 case NK_Not_Narrowing:
7269 // No narrowing occurred.
7270 return;
7271
7272 case NK_Type_Narrowing:
7273 // This was a floating-to-integer conversion, which is always considered a
7274 // narrowing conversion even if the value is a constant and can be
7275 // represented exactly as an integer.
7276 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007277 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7278 ? diag::warn_init_list_type_narrowing
7279 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007280 << PostInit->getSourceRange()
7281 << PreNarrowingType.getLocalUnqualifiedType()
7282 << EntityType.getLocalUnqualifiedType();
7283 break;
7284
7285 case NK_Constant_Narrowing:
7286 // A constant value was narrowed.
7287 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007288 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7289 ? diag::warn_init_list_constant_narrowing
7290 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007291 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007292 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007293 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007294 break;
7295
7296 case NK_Variable_Narrowing:
7297 // A variable's value may have been narrowed.
7298 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007299 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7300 ? diag::warn_init_list_variable_narrowing
7301 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007302 << PostInit->getSourceRange()
7303 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007304 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007305 break;
7306 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007307
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007308 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007309 llvm::raw_svector_ostream OS(StaticCast);
7310 OS << "static_cast<";
7311 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7312 // It's important to use the typedef's name if there is one so that the
7313 // fixit doesn't break code using types like int64_t.
7314 //
7315 // FIXME: This will break if the typedef requires qualification. But
7316 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007317 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007318 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007319 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007320 else {
7321 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7322 // with a broken cast.
7323 return;
7324 }
7325 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007326 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007327 << PostInit->getSourceRange()
7328 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7329 << FixItHint::CreateInsertion(
7330 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007331}
7332
Douglas Gregore1314a62009-12-18 05:02:21 +00007333//===----------------------------------------------------------------------===//
7334// Initialization helper functions
7335//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007336bool
7337Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7338 ExprResult Init) {
7339 if (Init.isInvalid())
7340 return false;
7341
7342 Expr *InitE = Init.get();
7343 assert(InitE && "No initialization expression");
7344
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007345 InitializationKind Kind
7346 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007347 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007348 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007349}
7350
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007351ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007352Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7353 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007354 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007355 bool TopLevelOfInitList,
7356 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007357 if (Init.isInvalid())
7358 return ExprError();
7359
John McCall1f425642010-11-11 03:21:53 +00007360 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007361 assert(InitE && "No initialization expression?");
7362
7363 if (EqualLoc.isInvalid())
7364 EqualLoc = InitE->getLocStart();
7365
7366 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007367 EqualLoc,
7368 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007369 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007370 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007371
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007372 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007373
Richard Smith66e05fe2012-01-18 05:21:49 +00007374 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007375}