blob: 80431a63b83edb0185e2ca1506c53df424c6373d [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
Steve Narofff8ecff22008-05-01 22:18:59 +000014#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000016#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000017#include "clang/AST/ExprObjC.h"
Richard Smithafe48f92018-07-23 21:21:22 +000018#include "clang/AST/ExprOpenMP.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"
Mehdi Amini9670f842016-07-18 19:02:11 +000022#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Lookup.h"
24#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000025#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000026#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000028#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000029
Douglas Gregore4a0bb72009-01-22 00:58:24 +000030using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000031
Chris Lattner0cb78032009-02-24 22:27:37 +000032//===----------------------------------------------------------------------===//
33// Sema Initialization Checking
34//===----------------------------------------------------------------------===//
35
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000036/// Check whether T is compatible with a wide character type (wchar_t,
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000037/// char16_t or char32_t).
38static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
39 if (Context.typesAreCompatible(Context.getWideCharType(), T))
40 return true;
41 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
42 return Context.typesAreCompatible(Context.Char16Ty, T) ||
43 Context.typesAreCompatible(Context.Char32Ty, T);
44 }
45 return false;
46}
47
48enum StringInitFailureKind {
49 SIF_None,
50 SIF_NarrowStringIntoWideChar,
51 SIF_WideStringIntoChar,
52 SIF_IncompatWideStringIntoWideChar,
Richard Smith3a8244d2018-05-01 05:02:45 +000053 SIF_UTF8StringIntoPlainChar,
54 SIF_PlainStringIntoUTF8Char,
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000055 SIF_Other
56};
57
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058/// Check whether the array of type AT can be initialized by the Init
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000059/// expression by means of string initialization. Returns SIF_None if so,
60/// otherwise returns a StringInitFailureKind that describes why the
61/// initialization would not work.
62static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
63 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000064 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000065 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // See if this is a string literal or @encode.
68 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattnera9196812009-02-26 23:26:43 +000070 // Handle @encode, which is a narrow string.
71 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000072 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000073
74 // Otherwise we can only handle string literals.
75 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000076 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000077 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000078
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000079 const QualType ElemTy =
80 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000081
82 switch (SL->getKind()) {
Douglas Gregorfb65e592011-07-27 05:40:30 +000083 case StringLiteral::UTF8:
Richard Smith3a8244d2018-05-01 05:02:45 +000084 // char8_t array can be initialized with a UTF-8 string.
85 if (ElemTy->isChar8Type())
86 return SIF_None;
87 LLVM_FALLTHROUGH;
88 case StringLiteral::Ascii:
Douglas Gregorfb65e592011-07-27 05:40:30 +000089 // char array can be initialized with a narrow string.
90 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000091 if (ElemTy->isCharType())
Richard Smith3a8244d2018-05-01 05:02:45 +000092 return (SL->getKind() == StringLiteral::UTF8 &&
93 Context.getLangOpts().Char8)
94 ? SIF_UTF8StringIntoPlainChar
95 : SIF_None;
96 if (ElemTy->isChar8Type())
97 return SIF_PlainStringIntoUTF8Char;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000098 if (IsWideCharCompatible(ElemTy, Context))
99 return SIF_NarrowStringIntoWideChar;
100 return SIF_Other;
101 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
102 // "An array with element type compatible with a qualified or unqualified
103 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
104 // string literal with the corresponding encoding prefix (L, u, or U,
105 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +0000106 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000107 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
108 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000109 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000110 return SIF_WideStringIntoChar;
111 if (IsWideCharCompatible(ElemTy, Context))
112 return SIF_IncompatWideStringIntoWideChar;
113 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000114 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000115 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
116 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000117 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000118 return SIF_WideStringIntoChar;
119 if (IsWideCharCompatible(ElemTy, Context))
120 return SIF_IncompatWideStringIntoWideChar;
121 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000122 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000123 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
124 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000125 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 return SIF_WideStringIntoChar;
127 if (IsWideCharCompatible(ElemTy, Context))
128 return SIF_IncompatWideStringIntoWideChar;
129 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Douglas Gregorfb65e592011-07-27 05:40:30 +0000132 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000133}
134
Hans Wennborg950f3182013-05-16 09:22:40 +0000135static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
136 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000137 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000138 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000139 return SIF_Other;
140 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000141}
142
Richard Smith430c23b2013-05-05 16:40:13 +0000143/// Update the type of a string literal, including any surrounding parentheses,
144/// to match the type of the object which it is initializing.
145static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000146 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000147 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000148 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
149 break;
150 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
151 E = PE->getSubExpr();
152 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
153 E = UO->getSubExpr();
154 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
155 E = GSE->getResultExpr();
156 else
157 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000158 }
Richard Smith430c23b2013-05-05 16:40:13 +0000159}
160
John McCall5decec92011-02-21 07:57:55 +0000161static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
162 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000163 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000164 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000165 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000166 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattner0cb78032009-02-24 22:27:37 +0000168 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000169 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000170 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000171 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000172 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000173 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
174 ConstVal,
175 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000176 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000177 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000178 }
Mike Stump11289f42009-09-09 15:08:12 +0000179
Eli Friedman893abe42009-05-29 18:22:49 +0000180 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Eli Friedman554eba92011-04-11 00:23:45 +0000182 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000183 // the size may be smaller or larger than the string we are initializing.
184 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000185 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000186 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000187 // For Pascal strings it's OK to strip off the terminating null character,
188 // so the example below is valid:
189 //
190 // unsigned char a[2] = "\pa";
191 if (SL->isPascal())
192 StrLength--;
193 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000194
Eli Friedman554eba92011-04-11 00:23:45 +0000195 // [dcl.init.string]p2
196 if (StrLength > CAT->getSize().getZExtValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000197 S.Diag(Str->getBeginLoc(),
Eli Friedman554eba92011-04-11 00:23:45 +0000198 diag::err_initializer_string_for_char_array_too_long)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000199 << Str->getSourceRange();
Eli Friedman554eba92011-04-11 00:23:45 +0000200 } else {
201 // C99 6.7.8p14.
202 if (StrLength-1 > CAT->getSize().getZExtValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000203 S.Diag(Str->getBeginLoc(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000204 diag::ext_initializer_string_for_char_array_too_long)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000205 << Str->getSourceRange();
Eli Friedman554eba92011-04-11 00:23:45 +0000206 }
Mike Stump11289f42009-09-09 15:08:12 +0000207
Eli Friedman893abe42009-05-29 18:22:49 +0000208 // Set the type to the actual size that we are initializing. If we have
209 // something like:
210 // char x[1] = "foo";
211 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000212 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000213}
214
Chris Lattner0cb78032009-02-24 22:27:37 +0000215//===----------------------------------------------------------------------===//
216// Semantic checking for initializer lists.
217//===----------------------------------------------------------------------===//
218
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000219namespace {
220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// Semantic checking for initializer lists.
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222///
223/// The InitListChecker class contains a set of routines that each
224/// handle the initialization of a certain kind of entity, e.g.,
225/// arrays, vectors, struct/union types, scalars, etc. The
226/// InitListChecker itself performs a recursive walk of the subobject
227/// structure of the type to be initialized, while stepping through
228/// the initializer list one element at a time. The IList and Index
229/// parameters to each of the Check* routines contain the active
230/// (syntactic) initializer list and the index into that initializer
231/// list that represents the current initializer. Each routine is
232/// responsible for moving that Index forward as it consumes elements.
233///
234/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000235/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000236/// initializer list and the index into that initializer list where we
237/// are copying initializers as we map them over to the semantic
238/// list. Once we have completed our recursive walk of the subobject
239/// structure, we will have constructed a full semantic initializer
240/// list.
241///
242/// C99 designators cause changes in the initializer list traversal,
243/// because they make the initialization "jump" into a specific
244/// subobject and then continue the initialization from that
245/// point. CheckDesignatedInitializer() recursively steps into the
246/// designated subobject and manages backing out the recursion to
247/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000248class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000249 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000251 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000252 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000253 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000254 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000255
Anders Carlsson6cabf312010-01-23 23:23:01 +0000256 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000257 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000258 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000259 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000260 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000261 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000262 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000263 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000264 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000265 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000266 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000267 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000268 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000269 unsigned &StructuredIndex,
270 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000271 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000272 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000273 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000274 InitListExpr *StructuredList,
275 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000276 void CheckComplexType(const InitializedEntity &Entity,
277 InitListExpr *IList, QualType DeclType,
278 unsigned &Index,
279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000282 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000283 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000284 InitListExpr *StructuredList,
285 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000286 void CheckReferenceType(const InitializedEntity &Entity,
287 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000288 unsigned &Index,
289 InitListExpr *StructuredList,
290 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000291 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000292 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000293 InitListExpr *StructuredList,
294 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000295 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000296 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000297 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000298 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000299 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000300 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000301 unsigned &StructuredIndex,
302 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000303 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000304 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000305 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000306 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000309 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000310 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000311 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000312 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000313 RecordDecl::field_iterator *NextField,
314 llvm::APSInt *NextElementIndex,
315 unsigned &Index,
316 InitListExpr *StructuredList,
317 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000318 bool FinishSubobjectInit,
319 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000320 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
321 QualType CurrentObjectType,
322 InitListExpr *StructuredList,
323 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000324 SourceRange InitRange,
325 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000326 void UpdateStructuredListElement(InitListExpr *StructuredList,
327 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000328 Expr *expr);
329 int numArrayElements(QualType DeclType);
330 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000331
Richard Smith454a7cd2014-06-03 08:26:00 +0000332 static ExprResult PerformEmptyInit(Sema &SemaRef,
333 SourceLocation Loc,
334 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000335 bool VerifyOnly,
336 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000337
338 // Explanation on the "FillWithNoInit" mode:
339 //
340 // Assume we have the following definitions (Case#1):
341 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
342 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
343 //
344 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
345 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
346 //
347 // But if we have (Case#2):
348 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
349 //
350 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
351 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
352 //
353 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
354 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
355 // initializers but with special "NoInitExpr" place holders, which tells the
356 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000357 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
358 const InitializedEntity &ParentEntity,
359 InitListExpr *ILE, bool &RequiresSecondPass,
360 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000361 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000362 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000363 InitListExpr *ILE, bool &RequiresSecondPass,
364 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000365 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000366 InitListExpr *ILE, bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000367 InitListExpr *OuterILE, unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000368 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000369 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
370 Expr *InitExpr, FieldDecl *Field,
371 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000372 void CheckEmptyInitializable(const InitializedEntity &Entity,
373 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000374
Douglas Gregor85df8d82009-01-29 00:45:39 +0000375public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000376 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000377 InitListExpr *IL, QualType &T, bool VerifyOnly,
378 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000379 bool HadError() { return hadError; }
380
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000381 // Retrieves the fully-structured initializer list used for
Douglas Gregor85df8d82009-01-29 00:45:39 +0000382 // semantic analysis and code generation.
383 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
384};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000385
Chris Lattner9ececce2009-02-24 22:48:58 +0000386} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000387
Richard Smith454a7cd2014-06-03 08:26:00 +0000388ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
389 SourceLocation Loc,
390 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000391 bool VerifyOnly,
392 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000393 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
394 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000395 MultiExprArg SubInit;
396 Expr *InitExpr;
397 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
398
399 // C++ [dcl.init.aggr]p7:
400 // If there are fewer initializer-clauses in the list than there are
401 // members in the aggregate, then each member not explicitly initialized
402 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000403 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
404 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
405 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000406 // C++1y / DR1070:
407 // shall be initialized [...] from an empty initializer list.
408 //
409 // We apply the resolution of this DR to C++11 but not C++98, since C++98
410 // does not have useful semantics for initialization from an init list.
411 // We treat this as copy-initialization, because aggregate initialization
412 // always performs copy-initialization on its elements.
413 //
414 // Only do this if we're initializing a class type, to avoid filling in
415 // the initializer list where possible.
416 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
417 InitListExpr(SemaRef.Context, Loc, None, Loc);
418 InitExpr->setType(SemaRef.Context.VoidTy);
419 SubInit = InitExpr;
420 Kind = InitializationKind::CreateCopy(Loc, Loc);
421 } else {
422 // C++03:
423 // shall be value-initialized.
424 }
425
426 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000427 // libstdc++4.6 marks the vector default constructor as explicit in
428 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
429 // stlport does so too. Look for std::__debug for libstdc++, and for
430 // std:: for stlport. This is effectively a compiler-side implementation of
431 // LWG2193.
432 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
433 InitializationSequence::FK_ExplicitConstructor) {
434 OverloadCandidateSet::iterator Best;
435 OverloadingResult O =
436 InitSeq.getFailedCandidateSet()
437 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
438 (void)O;
439 assert(O == OR_Success && "Inconsistent overload resolution");
440 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
441 CXXRecordDecl *R = CtorDecl->getParent();
442
443 if (CtorDecl->getMinRequiredArguments() == 0 &&
444 CtorDecl->isExplicit() && R->getDeclName() &&
445 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000446 bool IsInStd = false;
447 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000448 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000449 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
450 IsInStd = true;
451 }
452
Fangrui Song6907ce22018-07-30 19:24:48 +0000453 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
Nico Weberbcb70ee2014-07-02 23:51:09 +0000454 .Cases("basic_string", "deque", "forward_list", true)
455 .Cases("list", "map", "multimap", "multiset", true)
456 .Cases("priority_queue", "queue", "set", "stack", true)
457 .Cases("unordered_map", "unordered_set", "vector", true)
458 .Default(false)) {
459 InitSeq.InitializeFrom(
460 SemaRef, Entity,
461 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000462 MultiExprArg(), /*TopLevelOfInitList=*/false,
463 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000464 // Emit a warning for this. System header warnings aren't shown
465 // by default, but people working on system headers should see it.
466 if (!VerifyOnly) {
467 SemaRef.Diag(CtorDecl->getLocation(),
468 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000469 if (Entity.getKind() == InitializedEntity::EK_Member)
470 SemaRef.Diag(Entity.getDecl()->getLocation(),
471 diag::note_used_in_initialization_here);
472 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
473 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000474 }
475 }
476 }
477 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000478 if (!InitSeq) {
479 if (!VerifyOnly) {
480 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
481 if (Entity.getKind() == InitializedEntity::EK_Member)
482 SemaRef.Diag(Entity.getDecl()->getLocation(),
483 diag::note_in_omitted_aggregate_initializer)
484 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000485 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
486 bool IsTrailingArrayNewMember =
487 Entity.getParent() &&
488 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000489 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000490 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
491 << Entity.getElementIndex();
492 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000493 }
494 return ExprError();
495 }
496
497 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
498 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
499}
500
501void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
502 SourceLocation Loc) {
503 assert(VerifyOnly &&
504 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000505 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
506 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000507 hadError = true;
508}
509
Richard Smith872307e2016-03-08 22:17:41 +0000510void InitListChecker::FillInEmptyInitForBase(
511 unsigned Init, const CXXBaseSpecifier &Base,
512 const InitializedEntity &ParentEntity, InitListExpr *ILE,
513 bool &RequiresSecondPass, bool FillWithNoInit) {
514 assert(Init < ILE->getNumInits() && "should have been expanded");
515
516 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
517 SemaRef.Context, &Base, false, &ParentEntity);
518
519 if (!ILE->getInit(Init)) {
520 ExprResult BaseInit =
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000521 FillWithNoInit
522 ? new (SemaRef.Context) NoInitExpr(Base.getType())
523 : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
524 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000525 if (BaseInit.isInvalid()) {
526 hadError = true;
527 return;
528 }
529
530 ILE->setInit(Init, BaseInit.getAs<Expr>());
531 } else if (InitListExpr *InnerILE =
532 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
Richard Smithf3b4ca82018-02-07 22:25:16 +0000533 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
534 ILE, Init, FillWithNoInit);
Richard Smith872307e2016-03-08 22:17:41 +0000535 } else if (DesignatedInitUpdateExpr *InnerDIUE =
536 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
537 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000538 RequiresSecondPass, ILE, Init,
539 /*FillWithNoInit =*/true);
Richard Smith872307e2016-03-08 22:17:41 +0000540 }
541}
542
Richard Smith454a7cd2014-06-03 08:26:00 +0000543void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000544 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000545 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000546 bool &RequiresSecondPass,
547 bool FillWithNoInit) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000548 SourceLocation Loc = ILE->getEndLoc();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000549 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000551 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000552
553 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
554 if (!RType->getDecl()->isUnion())
555 assert(Init < NumInits && "This ILE should have been expanded");
556
Douglas Gregor2bb07652009-12-22 00:05:34 +0000557 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000558 if (FillWithNoInit) {
559 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
560 if (Init < NumInits)
561 ILE->setInit(Init, Filler);
562 else
563 ILE->updateInit(SemaRef.Context, Init, Filler);
564 return;
565 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000566 // C++1y [dcl.init.aggr]p7:
567 // If there are fewer initializer-clauses in the list than there are
568 // members in the aggregate, then each member not explicitly initialized
569 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000570 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000571 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
572 if (DIE.isInvalid()) {
573 hadError = true;
574 return;
575 }
Richard Smithd87aab92018-07-17 22:24:09 +0000576 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000577 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000578 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000579 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000580 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000581 RequiresSecondPass = true;
582 }
583 return;
584 }
585
Douglas Gregor2bb07652009-12-22 00:05:34 +0000586 if (Field->getType()->isReferenceType()) {
587 // C++ [dcl.init.aggr]p9:
588 // If an incomplete or empty initializer-list leaves a
589 // member of reference type uninitialized, the program is
590 // ill-formed.
591 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
592 << Field->getType()
593 << ILE->getSyntacticForm()->getSourceRange();
594 SemaRef.Diag(Field->getLocation(),
595 diag::note_uninit_reference_member);
596 hadError = true;
597 return;
598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
Richard Smith454a7cd2014-06-03 08:26:00 +0000600 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000601 /*VerifyOnly*/false,
602 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000603 if (MemberInit.isInvalid()) {
604 hadError = true;
605 return;
606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor2bb07652009-12-22 00:05:34 +0000608 if (hadError) {
609 // Do nothing
610 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000611 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000612 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
613 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000614 // extend the initializer list to include the constructor
615 // call and make a note that we'll need to take another pass
616 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000617 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000618 RequiresSecondPass = true;
619 }
620 } else if (InitListExpr *InnerILE
621 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000622 FillInEmptyInitializations(MemberEntity, InnerILE,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000623 RequiresSecondPass, ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000624 else if (DesignatedInitUpdateExpr *InnerDIUE
625 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
626 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000627 RequiresSecondPass, ILE, Init,
628 /*FillWithNoInit =*/true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000629}
630
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000631/// Recursively replaces NULL values within the given initializer list
632/// with expressions that perform value-initialization of the
Richard Smithf3b4ca82018-02-07 22:25:16 +0000633/// appropriate type, and finish off the InitListExpr formation.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634void
Richard Smith454a7cd2014-06-03 08:26:00 +0000635InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000636 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000637 bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000638 InitListExpr *OuterILE,
639 unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000640 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000641 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000642 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000643
Richard Smithf3b4ca82018-02-07 22:25:16 +0000644 // If this is a nested initializer list, we might have changed its contents
645 // (and therefore some of its properties, such as instantiation-dependence)
646 // while filling it in. Inform the outer initializer list so that its state
647 // can be updated to match.
648 // FIXME: We should fully build the inner initializers before constructing
649 // the outer InitListExpr instead of mutating AST nodes after they have
650 // been used as subexpressions of other nodes.
651 struct UpdateOuterILEWithUpdatedInit {
652 InitListExpr *Outer;
653 unsigned OuterIndex;
654 ~UpdateOuterILEWithUpdatedInit() {
655 if (Outer)
656 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
657 }
658 } UpdateOuterRAII = {OuterILE, OuterIndex};
659
Richard Smith382bc512017-02-23 22:41:47 +0000660 // A transparent ILE is not performing aggregate initialization and should
661 // not be filled in.
662 if (ILE->isTransparent())
663 return;
664
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000665 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000666 const RecordDecl *RDecl = RType->getDecl();
667 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000668 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000669 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000670 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
671 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000672 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000673 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000674 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
675 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000676 break;
677 }
678 }
679 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000680 // The fields beyond ILE->getNumInits() are default initialized, so in
681 // order to leave them uninitialized, the ILE is expanded and the extra
682 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000683 unsigned NumElems = numStructUnionElements(ILE->getType());
684 if (RDecl->hasFlexibleArrayMember())
685 ++NumElems;
686 if (ILE->getNumInits() < NumElems)
687 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000688
Douglas Gregor2bb07652009-12-22 00:05:34 +0000689 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000690
691 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
692 for (auto &Base : CXXRD->bases()) {
693 if (hadError)
694 return;
695
696 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
697 FillWithNoInit);
698 ++Init;
699 }
700 }
701
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000702 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000703 if (Field->isUnnamedBitfield())
704 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000705
Douglas Gregor2bb07652009-12-22 00:05:34 +0000706 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000707 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000708
Yunzhong Gaocb779302015-06-10 00:27:52 +0000709 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
710 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000711 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000712 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000713
Douglas Gregor2bb07652009-12-22 00:05:34 +0000714 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000715
Douglas Gregor2bb07652009-12-22 00:05:34 +0000716 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000717 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000718 break;
719 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000720 }
721
722 return;
Mike Stump11289f42009-09-09 15:08:12 +0000723 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000724
725 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000726
Douglas Gregor723796a2009-12-16 06:35:08 +0000727 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000728 unsigned NumInits = ILE->getNumInits();
729 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000730 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000731 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000732 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000733 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000734 // For an array new with an unknown bound, ask for one additional element
735 // in order to populate the array filler.
736 if (Entity.isVariableLengthArrayNew())
737 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000739 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000740 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000741 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000742 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000743 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000744 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000745 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000746 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000747
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000748 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000749 if (hadError)
750 return;
751
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000752 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
753 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000754 ElementEntity.setElementIndex(Init);
755
Richard Smith3e268632018-05-23 23:41:38 +0000756 if (Init >= NumInits && ILE->hasArrayFiller())
757 return;
758
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000760 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
761 ILE->setInit(Init, ILE->getArrayFiller());
762 else if (!InitExpr && !ILE->hasArrayFiller()) {
763 Expr *Filler = nullptr;
764
765 if (FillWithNoInit)
766 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
767 else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000768 ExprResult ElementInit =
769 PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
770 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000771 if (ElementInit.isInvalid()) {
772 hadError = true;
773 return;
774 }
775
776 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000777 }
778
779 if (hadError) {
780 // Do nothing
781 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000782 // For arrays, just set the expression used for value-initialization
783 // of the "holes" in the array.
784 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000785 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000786 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000787 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000788 } else {
789 // For arrays, just set the expression used for value-initialization
790 // of the rest of elements and exit.
791 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000792 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000793 return;
794 }
795
Yunzhong Gaocb779302015-06-10 00:27:52 +0000796 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000797 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000798 // extend the initializer list to include the constructor
799 // call and make a note that we'll need to take another pass
800 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000801 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000802 RequiresSecondPass = true;
803 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000804 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000805 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000806 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000807 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000808 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000809 else if (DesignatedInitUpdateExpr *InnerDIUE
810 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
811 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000812 RequiresSecondPass, ILE, Init,
813 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000814 }
815}
816
Douglas Gregor723796a2009-12-16 06:35:08 +0000817InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000818 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000819 bool VerifyOnly,
820 bool TreatUnavailableAsInvalid)
821 : SemaRef(S), VerifyOnly(VerifyOnly),
822 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000823 // FIXME: Check that IL isn't already the semantic form of some other
824 // InitListExpr. If it is, we'd create a broken AST.
825
Steve Narofff8ecff22008-05-01 22:18:59 +0000826 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000827
Richard Smith4e0d2e42013-09-20 20:10:22 +0000828 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000829 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000830 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000831 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000832
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000833 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000834 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000835 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
836 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000837 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000838 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000839 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000840 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000841}
842
843int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000844 // FIXME: use a proper constant
845 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000846 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000847 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000848 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
849 }
850 return maxElements;
851}
852
853int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000854 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000855 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000856 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
857 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000858 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000859 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000860 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000861
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000862 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000863 return std::min(InitializableMembers, 1);
864 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000865}
866
Richard Smith283e2072017-10-03 20:36:00 +0000867/// Determine whether Entity is an entity for which it is idiomatic to elide
868/// the braces in aggregate initialization.
869static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
870 // Recursive initialization of the one and only field within an aggregate
871 // class is considered idiomatic. This case arises in particular for
872 // initialization of std::array, where the C++ standard suggests the idiom of
873 //
874 // std::array<T, N> arr = {1, 2, 3};
875 //
876 // (where std::array is an aggregate struct containing a single array field.
877
878 // FIXME: Should aggregate initialization of a struct with a single
879 // base class and no members also suppress the warning?
880 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
881 return false;
882
883 auto *ParentRD =
884 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
885 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
886 if (CXXRD->getNumBases())
887 return false;
888
889 auto FieldIt = ParentRD->field_begin();
890 assert(FieldIt != ParentRD->field_end() &&
891 "no fields but have initializer for member?");
892 return ++FieldIt == ParentRD->field_end();
893}
894
Richard Smith4e0d2e42013-09-20 20:10:22 +0000895/// Check whether the range of the initializer \p ParentIList from element
896/// \p Index onwards can be used to initialize an object of type \p T. Update
897/// \p Index to indicate how many elements of the list were consumed.
898///
899/// This also fills in \p StructuredList, from element \p StructuredIndex
900/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000901void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000902 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 QualType T, unsigned &Index,
904 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000905 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000906 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Steve Narofff8ecff22008-05-01 22:18:59 +0000908 if (T->isArrayType())
909 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000910 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000911 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000912 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000913 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000914 else
David Blaikie83d382b2011-09-23 05:06:16 +0000915 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000916
Eli Friedmane0f832b2008-05-25 13:49:22 +0000917 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000918 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000919 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000920 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000921 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000922 hadError = true;
923 return;
924 }
925
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000926 // Build a structured initializer list corresponding to this subobject.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000927 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
928 ParentIList, Index, T, StructuredList, StructuredIndex,
929 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
930 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000931 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000932
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000933 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000934 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000936 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000937 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000938 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000939
Richard Smithde229232013-06-06 11:41:05 +0000940 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000942
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000943 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000944 // Update the structured sub-object initializer so that it's ending
945 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000946 if (EndIndex < ParentIList->getNumInits() &&
947 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000948 SourceLocation EndLoc
949 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
950 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000953 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000954 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000955 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
956 !isIdiomaticBraceElisionEntity(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000957 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
Richard Smithde229232013-06-06 11:41:05 +0000958 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000959 << StructuredSubobjectInitList->getSourceRange()
960 << FixItHint::CreateInsertion(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000961 StructuredSubobjectInitList->getBeginLoc(), "{")
Alp Tokerb6cc5922014-05-03 03:45:55 +0000962 << FixItHint::CreateInsertion(
963 SemaRef.getLocForEndOfToken(
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000964 StructuredSubobjectInitList->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +0000965 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000966 }
Richard Smith79c88c32018-09-26 19:00:16 +0000967
968 // Warn if this type won't be an aggregate in future versions of C++.
969 auto *CXXRD = T->getAsCXXRecordDecl();
970 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
971 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
972 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
973 << StructuredSubobjectInitList->getSourceRange() << T;
974 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000975 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000976}
977
Richard Smith420fa122015-02-12 01:50:05 +0000978/// Warn that \p Entity was of scalar type and was initialized by a
979/// single-element braced initializer list.
980static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
981 SourceRange Braces) {
982 // Don't warn during template instantiation. If the initialization was
983 // non-dependent, we warned during the initial parse; otherwise, the
984 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000985 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000986 return;
987
988 unsigned DiagID = 0;
989
990 switch (Entity.getKind()) {
991 case InitializedEntity::EK_VectorElement:
992 case InitializedEntity::EK_ComplexElement:
993 case InitializedEntity::EK_ArrayElement:
994 case InitializedEntity::EK_Parameter:
995 case InitializedEntity::EK_Parameter_CF_Audited:
996 case InitializedEntity::EK_Result:
997 // Extra braces here are suspicious.
998 DiagID = diag::warn_braces_around_scalar_init;
999 break;
1000
1001 case InitializedEntity::EK_Member:
1002 // Warn on aggregate initialization but not on ctor init list or
1003 // default member initializer.
1004 if (Entity.getParent())
1005 DiagID = diag::warn_braces_around_scalar_init;
1006 break;
1007
1008 case InitializedEntity::EK_Variable:
1009 case InitializedEntity::EK_LambdaCapture:
1010 // No warning, might be direct-list-initialization.
1011 // FIXME: Should we warn for copy-list-initialization in these cases?
1012 break;
1013
1014 case InitializedEntity::EK_New:
1015 case InitializedEntity::EK_Temporary:
1016 case InitializedEntity::EK_CompoundLiteralInit:
1017 // No warning, braces are part of the syntax of the underlying construct.
1018 break;
1019
1020 case InitializedEntity::EK_RelatedResult:
1021 // No warning, we already warned when initializing the result.
1022 break;
1023
1024 case InitializedEntity::EK_Exception:
1025 case InitializedEntity::EK_Base:
1026 case InitializedEntity::EK_Delegating:
1027 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001028 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001029 case InitializedEntity::EK_Binding:
Richard Smith67af95b2018-07-23 19:19:08 +00001030 case InitializedEntity::EK_StmtExprResult:
Richard Smith420fa122015-02-12 01:50:05 +00001031 llvm_unreachable("unexpected braced scalar init");
1032 }
1033
1034 if (DiagID) {
1035 S.Diag(Braces.getBegin(), DiagID)
1036 << Braces
1037 << FixItHint::CreateRemoval(Braces.getBegin())
1038 << FixItHint::CreateRemoval(Braces.getEnd());
1039 }
1040}
1041
Richard Smith4e0d2e42013-09-20 20:10:22 +00001042/// Check whether the initializer \p IList (that was written with explicit
1043/// braces) can be used to initialize an object of type \p T.
1044///
1045/// This also fills in \p StructuredList with the fully-braced, desugared
1046/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001047void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001048 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001049 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001050 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001051 if (!VerifyOnly) {
1052 SyntacticToSemantic[IList] = StructuredList;
1053 StructuredList->setSyntacticForm(IList);
1054 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001055
1056 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001057 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001058 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001059 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001060 QualType ExprTy = T;
1061 if (!ExprTy->isArrayType())
1062 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001063 IList->setType(ExprTy);
1064 StructuredList->setType(ExprTy);
1065 }
Eli Friedman85f54972008-05-25 13:22:35 +00001066 if (hadError)
1067 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001068
Eli Friedman85f54972008-05-25 13:22:35 +00001069 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001070 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001071 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001072 if (SemaRef.getLangOpts().CPlusPlus ||
1073 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001074 IList->getType()->isVectorType())) {
1075 hadError = true;
1076 }
1077 return;
1078 }
1079
Eli Friedmanbd327452009-05-29 20:20:05 +00001080 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001081 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1082 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001083 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001084 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001085 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001086 hadError = true;
1087 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001088 // Special-case
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001089 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1090 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001091 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001092 // Don't complain for incomplete types, since we'll get an error
1093 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001094 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001095 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001096 CurrentObjectType->isArrayType()? 0 :
1097 CurrentObjectType->isVectorType()? 1 :
1098 CurrentObjectType->isScalarType()? 2 :
1099 CurrentObjectType->isUnionType()? 3 :
1100 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001101
Richard Smith1b98ccc2014-07-19 01:39:17 +00001102 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001103 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001104 DK = diag::err_excess_initializers;
1105 hadError = true;
1106 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001107 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001108 DK = diag::err_excess_initializers;
1109 hadError = true;
1110 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001111
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001112 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1113 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001114 }
1115 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001116
Richard Smith79c88c32018-09-26 19:00:16 +00001117 if (!VerifyOnly) {
1118 if (T->isScalarType() && IList->getNumInits() == 1 &&
1119 !isa<InitListExpr>(IList->getInit(0)))
1120 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1121
1122 // Warn if this is a class type that won't be an aggregate in future
1123 // versions of C++.
1124 auto *CXXRD = T->getAsCXXRecordDecl();
1125 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1126 // Don't warn if there's an equivalent default constructor that would be
1127 // used instead.
1128 bool HasEquivCtor = false;
1129 if (IList->getNumInits() == 0) {
1130 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1131 HasEquivCtor = CD && !CD->isDeleted();
1132 }
1133
1134 if (!HasEquivCtor) {
1135 SemaRef.Diag(IList->getBeginLoc(),
1136 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1137 << IList->getSourceRange() << T;
1138 }
1139 }
1140 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001141}
1142
Anders Carlsson6cabf312010-01-23 23:23:01 +00001143void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001144 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001145 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001147 unsigned &Index,
1148 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001149 unsigned &StructuredIndex,
1150 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001151 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1152 // Explicitly braced initializer for complex type can be real+imaginary
1153 // parts.
1154 CheckComplexType(Entity, IList, DeclType, Index,
1155 StructuredList, StructuredIndex);
1156 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001157 CheckScalarType(Entity, IList, DeclType, Index,
1158 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001159 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001160 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001161 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001162 } else if (DeclType->isRecordType()) {
1163 assert(DeclType->isAggregateType() &&
1164 "non-aggregate records should be handed in CheckSubElementType");
1165 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001166 auto Bases =
1167 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1168 CXXRecordDecl::base_class_iterator());
1169 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1170 Bases = CXXRD->bases();
1171 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1172 SubobjectIsDesignatorContext, Index, StructuredList,
1173 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001174 } else if (DeclType->isArrayType()) {
1175 llvm::APSInt Zero(
1176 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1177 false);
1178 CheckArrayType(Entity, IList, DeclType, Zero,
1179 SubobjectIsDesignatorContext, Index,
1180 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001181 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1182 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001183 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001184 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001185 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1186 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001187 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001188 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001189 CheckReferenceType(Entity, IList, DeclType, Index,
1190 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001191 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001192 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001193 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001194 hadError = true;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001195 } else if (DeclType->isOCLIntelSubgroupAVCType()) {
1196 // Checks for scalar type are sufficient for these types too.
1197 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1198 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001199 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001200 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001201 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1202 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001203 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001204 }
1205}
1206
Anders Carlsson6cabf312010-01-23 23:23:01 +00001207void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001208 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001209 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001210 unsigned &Index,
1211 InitListExpr *StructuredList,
1212 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001213 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001214
1215 if (ElemType->isReferenceType())
1216 return CheckReferenceType(Entity, IList, ElemType, Index,
1217 StructuredList, StructuredIndex);
1218
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001219 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001220 if (SubInitList->getNumInits() == 1 &&
1221 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1222 SIF_None) {
1223 expr = SubInitList->getInit(0);
1224 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001225 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001226 = getStructuredSubobjectInit(IList, Index, ElemType,
1227 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001228 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001229 CheckExplicitInitList(Entity, SubInitList, ElemType,
1230 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001231
1232 if (!hadError && !VerifyOnly) {
1233 bool RequiresSecondPass = false;
1234 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001235 RequiresSecondPass, StructuredList,
1236 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001237 if (RequiresSecondPass && !hadError)
1238 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001239 RequiresSecondPass, StructuredList,
1240 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001241 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001242 ++StructuredIndex;
1243 ++Index;
1244 return;
1245 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001246 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001247 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001248 // This happens during template instantiation when we see an InitListExpr
1249 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001250 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001251 "found implicit initialization for the wrong type");
1252 if (!VerifyOnly)
1253 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1254 ++Index;
1255 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001256 }
1257
Richard Smith3c567fc2015-02-12 01:55:09 +00001258 if (SemaRef.getLangOpts().CPlusPlus) {
1259 // C++ [dcl.init.aggr]p2:
1260 // Each member is copy-initialized from the corresponding
1261 // initializer-clause.
1262
1263 // FIXME: Better EqualLoc?
1264 InitializationKind Kind =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001265 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
Richard Smith3c567fc2015-02-12 01:55:09 +00001266 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1267 /*TopLevelOfInitList*/ true);
1268
1269 // C++14 [dcl.init.aggr]p13:
1270 // If the assignment-expression can initialize a member, the member is
1271 // initialized. Otherwise [...] brace elision is assumed
1272 //
1273 // Brace elision is never performed if the element is not an
1274 // assignment-expression.
1275 if (Seq || isa<InitListExpr>(expr)) {
1276 if (!VerifyOnly) {
1277 ExprResult Result =
1278 Seq.Perform(SemaRef, Entity, Kind, expr);
1279 if (Result.isInvalid())
1280 hadError = true;
1281
1282 UpdateStructuredListElement(StructuredList, StructuredIndex,
1283 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001284 } else if (!Seq)
1285 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001286 ++Index;
1287 return;
1288 }
1289
1290 // Fall through for subaggregate initialization
1291 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1292 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001293 return CheckScalarType(Entity, IList, ElemType, Index,
1294 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001295 } else if (const ArrayType *arrayType =
1296 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001297 // arrayType can be incomplete if we're initializing a flexible
1298 // array member. There's nothing we can do with the completed
1299 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001300
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001301 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001302 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001303 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1304 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001305 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001306 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001307 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001308 }
John McCall5decec92011-02-21 07:57:55 +00001309
1310 // Fall through for subaggregate initialization.
1311
John McCall5decec92011-02-21 07:57:55 +00001312 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001313 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001314 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001315
John McCall5decec92011-02-21 07:57:55 +00001316 // C99 6.7.8p13:
1317 //
1318 // The initializer for a structure or union object that has
1319 // automatic storage duration shall be either an initializer
1320 // list as described below, or a single expression that has
1321 // compatible structure or union type. In the latter case, the
1322 // initial value of the object, including unnamed members, is
1323 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001324 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001325 if (SemaRef.CheckSingleAssignmentConstraints(
1326 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001327 if (ExprRes.isInvalid())
1328 hadError = true;
1329 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001330 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001331 if (ExprRes.isInvalid())
1332 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001333 }
1334 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001335 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001336 ++Index;
1337 return;
1338 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001339 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001340 // Fall through for subaggregate initialization
1341 }
1342
1343 // C++ [dcl.init.aggr]p12:
1344 //
1345 // [...] Otherwise, if the member is itself a non-empty
1346 // subaggregate, brace elision is assumed and the initializer is
1347 // considered for the initialization of the first member of
1348 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001349 // OpenCL vector initializer is handled elsewhere.
1350 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1351 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001352 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1353 StructuredIndex);
1354 ++StructuredIndex;
1355 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001356 if (!VerifyOnly) {
1357 // We cannot initialize this element, so let
1358 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001359 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001360 /*TopLevelOfInitList=*/true);
1361 }
John McCall5decec92011-02-21 07:57:55 +00001362 hadError = true;
1363 ++Index;
1364 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001365 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001366}
1367
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001368void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1369 InitListExpr *IList, QualType DeclType,
1370 unsigned &Index,
1371 InitListExpr *StructuredList,
1372 unsigned &StructuredIndex) {
1373 assert(Index == 0 && "Index in explicit init list must be zero");
1374
1375 // As an extension, clang supports complex initializers, which initialize
1376 // a complex number component-wise. When an explicit initializer list for
1377 // a complex number contains two two initializers, this extension kicks in:
1378 // it exepcts the initializer list to contain two elements convertible to
1379 // the element type of the complex type. The first element initializes
1380 // the real part, and the second element intitializes the imaginary part.
1381
1382 if (IList->getNumInits() != 2)
1383 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1384 StructuredIndex);
1385
1386 // This is an extension in C. (The builtin _Complex type does not exist
1387 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001388 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001389 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1390 << IList->getSourceRange();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001391
1392 // Initialize the complex number.
1393 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1394 InitializedEntity ElementEntity =
1395 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1396
1397 for (unsigned i = 0; i < 2; ++i) {
1398 ElementEntity.setElementIndex(Index);
1399 CheckSubElementType(ElementEntity, IList, elementType, Index,
1400 StructuredList, StructuredIndex);
1401 }
1402}
1403
Anders Carlsson6cabf312010-01-23 23:23:01 +00001404void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001405 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001406 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001407 InitListExpr *StructuredList,
1408 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001409 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001410 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001411 SemaRef.Diag(IList->getBeginLoc(),
1412 SemaRef.getLangOpts().CPlusPlus11
1413 ? diag::warn_cxx98_compat_empty_scalar_initializer
1414 : diag::err_empty_scalar_initializer)
1415 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001416 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001417 ++Index;
1418 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001419 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001420 }
John McCall643169b2010-11-11 00:46:36 +00001421
1422 Expr *expr = IList->getInit(Index);
1423 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001424 // FIXME: This is invalid, and accepting it causes overload resolution
1425 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001426 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001427 SemaRef.Diag(SubIList->getBeginLoc(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001428 diag::ext_many_braces_around_scalar_init)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001429 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001430
1431 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1432 StructuredIndex);
1433 return;
1434 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001435 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001436 SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
1437 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001438 hadError = true;
1439 ++Index;
1440 ++StructuredIndex;
1441 return;
1442 }
1443
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001444 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001445 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001446 hadError = true;
1447 ++Index;
1448 return;
1449 }
1450
John McCall643169b2010-11-11 00:46:36 +00001451 ExprResult Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001452 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1453 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001454
Craig Topperc3ec1492014-05-26 06:22:03 +00001455 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001456
1457 if (Result.isInvalid())
1458 hadError = true; // types weren't compatible.
1459 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001460 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001461
John McCall643169b2010-11-11 00:46:36 +00001462 if (ResultExpr != expr) {
1463 // The type was promoted, update initializer list.
1464 IList->setInit(Index, ResultExpr);
1465 }
1466 }
1467 if (hadError)
1468 ++StructuredIndex;
1469 else
1470 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1471 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001472}
1473
Anders Carlsson6cabf312010-01-23 23:23:01 +00001474void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1475 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001476 unsigned &Index,
1477 InitListExpr *StructuredList,
1478 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001479 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001480 // FIXME: It would be wonderful if we could point at the actual member. In
1481 // general, it would be useful to pass location information down the stack,
1482 // so that we know the location (or decl) of the "current object" being
1483 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001484 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001485 SemaRef.Diag(IList->getBeginLoc(),
1486 diag::err_init_reference_member_uninitialized)
1487 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001488 hadError = true;
1489 ++Index;
1490 ++StructuredIndex;
1491 return;
1492 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001493
1494 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001495 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001496 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001497 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1498 << DeclType << IList->getSourceRange();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001499 hadError = true;
1500 ++Index;
1501 ++StructuredIndex;
1502 return;
1503 }
1504
1505 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001506 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001507 hadError = true;
1508 ++Index;
1509 return;
1510 }
1511
1512 ExprResult Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001513 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001514 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001515
1516 if (Result.isInvalid())
1517 hadError = true;
1518
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001519 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001520 IList->setInit(Index, expr);
1521
1522 if (hadError)
1523 ++StructuredIndex;
1524 else
1525 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1526 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001527}
1528
Anders Carlsson6cabf312010-01-23 23:23:01 +00001529void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001530 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001531 unsigned &Index,
1532 InitListExpr *StructuredList,
1533 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001534 const VectorType *VT = DeclType->getAs<VectorType>();
1535 unsigned maxElements = VT->getNumElements();
1536 unsigned numEltsInit = 0;
1537 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001538
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001539 if (Index >= IList->getNumInits()) {
1540 // Make sure the element type can be value-initialized.
1541 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001542 CheckEmptyInitializable(
1543 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001544 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001545 return;
1546 }
1547
David Blaikiebbafb8a2012-03-11 07:00:24 +00001548 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001549 // If the initializing element is a vector, try to copy-initialize
1550 // instead of breaking it apart (which is doomed to failure anyway).
1551 Expr *Init = IList->getInit(Index);
1552 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001553 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001554 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001555 hadError = true;
1556 ++Index;
1557 return;
1558 }
1559
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001560 ExprResult Result =
1561 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1562 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001563
Craig Topperc3ec1492014-05-26 06:22:03 +00001564 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001565 if (Result.isInvalid())
1566 hadError = true; // types weren't compatible.
1567 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001568 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001569
John McCall6a16b2f2010-10-30 00:11:39 +00001570 if (ResultExpr != Init) {
1571 // The type was promoted, update initializer list.
1572 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001573 }
1574 }
John McCall6a16b2f2010-10-30 00:11:39 +00001575 if (hadError)
1576 ++StructuredIndex;
1577 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001578 UpdateStructuredListElement(StructuredList, StructuredIndex,
1579 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001580 ++Index;
1581 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001582 }
Mike Stump11289f42009-09-09 15:08:12 +00001583
John McCall6a16b2f2010-10-30 00:11:39 +00001584 InitializedEntity ElementEntity =
1585 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001586
John McCall6a16b2f2010-10-30 00:11:39 +00001587 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1588 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001589 if (Index >= IList->getNumInits()) {
1590 if (VerifyOnly)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001591 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
John McCall6a16b2f2010-10-30 00:11:39 +00001592 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594
John McCall6a16b2f2010-10-30 00:11:39 +00001595 ElementEntity.setElementIndex(Index);
1596 CheckSubElementType(ElementEntity, IList, elementType, Index,
1597 StructuredList, StructuredIndex);
1598 }
James Molloy9eef2652014-06-20 14:35:13 +00001599
1600 if (VerifyOnly)
1601 return;
1602
1603 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1604 const VectorType *T = Entity.getType()->getAs<VectorType>();
1605 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1606 T->getVectorKind() == VectorType::NeonPolyVector)) {
1607 // The ability to use vector initializer lists is a GNU vector extension
1608 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
Fangrui Song6907ce22018-07-30 19:24:48 +00001609 // endian machines it works fine, however on big endian machines it
James Molloy9eef2652014-06-20 14:35:13 +00001610 // exhibits surprising behaviour:
1611 //
1612 // uint32x2_t x = {42, 64};
1613 // return vget_lane_u32(x, 0); // Will return 64.
1614 //
1615 // Because of this, explicitly call out that it is non-portable.
1616 //
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001617 SemaRef.Diag(IList->getBeginLoc(),
James Molloy9eef2652014-06-20 14:35:13 +00001618 diag::warn_neon_vector_initializer_non_portable);
1619
1620 const char *typeCode;
1621 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1622
1623 if (elementType->isFloatingType())
1624 typeCode = "f";
1625 else if (elementType->isSignedIntegerType())
1626 typeCode = "s";
1627 else if (elementType->isUnsignedIntegerType())
1628 typeCode = "u";
1629 else
1630 llvm_unreachable("Invalid element type!");
1631
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001632 SemaRef.Diag(IList->getBeginLoc(),
1633 SemaRef.Context.getTypeSize(VT) > 64
1634 ? diag::note_neon_vector_initializer_non_portable_q
1635 : diag::note_neon_vector_initializer_non_portable)
1636 << typeCode << typeSize;
James Molloy9eef2652014-06-20 14:35:13 +00001637 }
1638
John McCall6a16b2f2010-10-30 00:11:39 +00001639 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001640 }
John McCall6a16b2f2010-10-30 00:11:39 +00001641
1642 InitializedEntity ElementEntity =
1643 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001644
John McCall6a16b2f2010-10-30 00:11:39 +00001645 // OpenCL initializers allows vectors to be constructed from vectors.
1646 for (unsigned i = 0; i < maxElements; ++i) {
1647 // Don't attempt to go past the end of the init list
1648 if (Index >= IList->getNumInits())
1649 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650
John McCall6a16b2f2010-10-30 00:11:39 +00001651 ElementEntity.setElementIndex(Index);
1652
1653 QualType IType = IList->getInit(Index)->getType();
1654 if (!IType->isVectorType()) {
1655 CheckSubElementType(ElementEntity, IList, elementType, Index,
1656 StructuredList, StructuredIndex);
1657 ++numEltsInit;
1658 } else {
1659 QualType VecType;
1660 const VectorType *IVT = IType->getAs<VectorType>();
1661 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001662
John McCall6a16b2f2010-10-30 00:11:39 +00001663 if (IType->isExtVectorType())
1664 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1665 else
1666 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001667 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001668 CheckSubElementType(ElementEntity, IList, VecType, Index,
1669 StructuredList, StructuredIndex);
1670 numEltsInit += numIElts;
1671 }
1672 }
1673
1674 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001675 if (numEltsInit != maxElements) {
1676 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001677 SemaRef.Diag(IList->getBeginLoc(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001678 diag::err_vector_incorrect_num_initializers)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001679 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001680 hadError = true;
1681 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001682}
1683
Anders Carlsson6cabf312010-01-23 23:23:01 +00001684void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001685 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001686 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001687 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001688 unsigned &Index,
1689 InitListExpr *StructuredList,
1690 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001691 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1692
Steve Narofff8ecff22008-05-01 22:18:59 +00001693 // Check for the special-case of initializing an array with a string.
1694 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001695 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1696 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001697 // We place the string literal directly into the resulting
1698 // initializer list. This is the only place where the structure
1699 // of the structured initializer list doesn't match exactly,
1700 // because doing so would involve allocating one character
1701 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001702 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001703 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1704 UpdateStructuredListElement(StructuredList, StructuredIndex,
1705 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001706 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1707 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001708 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001709 return;
1710 }
1711 }
John McCall66884dd2011-02-21 07:22:22 +00001712 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001713 // Check for VLAs; in standard C it would be possible to check this
1714 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1715 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001716 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001717 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1718 diag::err_variable_object_no_init)
1719 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001720 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001721 ++Index;
1722 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001723 return;
1724 }
1725
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001726 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001727 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1728 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001729 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001730 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001731 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001732 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001733 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001734 maxElementsKnown = true;
1735 }
1736
John McCall66884dd2011-02-21 07:22:22 +00001737 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001738 while (Index < IList->getNumInits()) {
1739 Expr *Init = IList->getInit(Index);
1740 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001741 // If we're not the subobject that matches up with the '{' for
1742 // the designator, we shouldn't be handling the
1743 // designator. Return immediately.
1744 if (!SubobjectIsDesignatorContext)
1745 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001746
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001747 // Handle this designated initializer. elementIndex will be
1748 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001749 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001750 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001751 StructuredList, StructuredIndex, true,
1752 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001753 hadError = true;
1754 continue;
1755 }
1756
Douglas Gregor033d1252009-01-23 16:54:12 +00001757 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001758 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001759 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001760 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001761 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001762
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001763 // If the array is of incomplete type, keep track of the number of
1764 // elements in the initializer.
1765 if (!maxElementsKnown && elementIndex > maxElements)
1766 maxElements = elementIndex;
1767
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001768 continue;
1769 }
1770
1771 // If we know the maximum number of elements, and we've already
1772 // hit it, stop consuming elements in the initializer list.
1773 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001774 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001775
Anders Carlsson6cabf312010-01-23 23:23:01 +00001776 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001777 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001778 Entity);
1779 // Check this element.
1780 CheckSubElementType(ElementEntity, IList, elementType, Index,
1781 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001782 ++elementIndex;
1783
1784 // If the array is of incomplete type, keep track of the number of
1785 // elements in the initializer.
1786 if (!maxElementsKnown && elementIndex > maxElements)
1787 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001788 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001789 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001790 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001791 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001792 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001793 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001794 // Sizing an array implicitly to zero is not allowed by ISO C,
1795 // but is supported by GNU.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001796 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001797 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001798
Mike Stump11289f42009-09-09 15:08:12 +00001799 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001800 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001801 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001802 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001803 // If there are any members of the array that get value-initialized, check
1804 // that is possible. That happens if we know the bound and don't have
1805 // enough elements, or if we're performing an array new with an unknown
1806 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001807 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001808 if ((maxElementsKnown && elementIndex < maxElements) ||
1809 Entity.isVariableLengthArrayNew())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001810 CheckEmptyInitializable(
1811 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1812 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001813 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001814}
1815
Eli Friedman3fa64df2011-08-23 22:24:57 +00001816bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1817 Expr *InitExpr,
1818 FieldDecl *Field,
1819 bool TopLevelObject) {
1820 // Handle GNU flexible array initializers.
1821 unsigned FlexArrayDiag;
1822 if (isa<InitListExpr>(InitExpr) &&
1823 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1824 // Empty flexible array init always allowed as an extension
1825 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001826 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001827 // Disallow flexible array init in C++; it is not required for gcc
1828 // compatibility, and it needs work to IRGen correctly in general.
1829 FlexArrayDiag = diag::err_flexible_array_init;
1830 } else if (!TopLevelObject) {
1831 // Disallow flexible array init on non-top-level object
1832 FlexArrayDiag = diag::err_flexible_array_init;
1833 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1834 // Disallow flexible array init on anything which is not a variable.
1835 FlexArrayDiag = diag::err_flexible_array_init;
1836 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1837 // Disallow flexible array init on local variables.
1838 FlexArrayDiag = diag::err_flexible_array_init;
1839 } else {
1840 // Allow other cases.
1841 FlexArrayDiag = diag::ext_flexible_array_init;
1842 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001843
1844 if (!VerifyOnly) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001845 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
1846 << InitExpr->getBeginLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001847 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1848 << Field;
1849 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001850
1851 return FlexArrayDiag != diag::ext_flexible_array_init;
1852}
1853
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001854/// Check if the type of a class element has an accessible destructor.
1855///
1856/// Aggregate initialization requires a class element's destructor be
1857/// accessible per 11.6.1 [dcl.init.aggr]:
1858///
1859/// The destructor for each element of class type is potentially invoked
1860/// (15.4 [class.dtor]) from the context where the aggregate initialization
1861/// occurs.
1862static bool hasAccessibleDestructor(QualType ElementType, SourceLocation Loc,
1863 Sema &SemaRef) {
1864 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1865 if (!CXXRD)
1866 return false;
1867
1868 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1869 SemaRef.CheckDestructorAccess(Loc, Destructor,
1870 SemaRef.PDiag(diag::err_access_dtor_temp)
1871 << ElementType);
1872 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1873 if (SemaRef.DiagnoseUseOfDecl(Destructor, Loc))
1874 return true;
1875 return false;
1876}
1877
Richard Smith872307e2016-03-08 22:17:41 +00001878void InitListChecker::CheckStructUnionTypes(
1879 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1880 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1881 bool SubobjectIsDesignatorContext, unsigned &Index,
1882 InitListExpr *StructuredList, unsigned &StructuredIndex,
1883 bool TopLevelObject) {
1884 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001885
Eli Friedman23a9e312008-05-19 19:16:24 +00001886 // If the record is invalid, some of it's members are invalid. To avoid
1887 // confusion, we forgo checking the intializer for the entire record.
1888 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001889 // Assume it was supposed to consume a single initializer.
1890 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001891 hadError = true;
1892 return;
Mike Stump11289f42009-09-09 15:08:12 +00001893 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001894
1895 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001896 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001897
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001898 if (!VerifyOnly)
1899 for (FieldDecl *FD : RD->fields()) {
1900 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
1901 if (hasAccessibleDestructor(ET, IList->getEndLoc(), SemaRef)) {
1902 hadError = true;
1903 return;
1904 }
1905 }
1906
Richard Smith852c9db2013-04-20 22:23:05 +00001907 // If there's a default initializer, use it.
1908 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1909 if (VerifyOnly)
1910 return;
1911 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1912 Field != FieldEnd; ++Field) {
1913 if (Field->hasInClassInitializer()) {
1914 StructuredList->setInitializedFieldInUnion(*Field);
1915 // FIXME: Actually build a CXXDefaultInitExpr?
1916 return;
1917 }
1918 }
1919 }
1920
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001921 // Value-initialize the first member of the union that isn't an unnamed
1922 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001923 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1924 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001925 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001926 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001927 CheckEmptyInitializable(
1928 InitializedEntity::InitializeMember(*Field, &Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001929 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001930 else
David Blaikie40ed2972012-06-06 20:45:41 +00001931 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001932 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001933 }
1934 }
1935 return;
1936 }
1937
Richard Smith872307e2016-03-08 22:17:41 +00001938 bool InitializedSomething = false;
1939
1940 // If we have any base classes, they are initialized prior to the fields.
1941 for (auto &Base : Bases) {
1942 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
Richard Smith872307e2016-03-08 22:17:41 +00001943
1944 // Designated inits always initialize fields, so if we see one, all
1945 // remaining base classes have no explicit initializer.
1946 if (Init && isa<DesignatedInitExpr>(Init))
1947 Init = nullptr;
1948
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001949 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
Richard Smith872307e2016-03-08 22:17:41 +00001950 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1951 SemaRef.Context, &Base, false, &Entity);
1952 if (Init) {
1953 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1954 StructuredList, StructuredIndex);
1955 InitializedSomething = true;
1956 } else if (VerifyOnly) {
1957 CheckEmptyInitializable(BaseEntity, InitLoc);
1958 }
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001959
1960 if (!VerifyOnly)
1961 if (hasAccessibleDestructor(Base.getType(), InitLoc, SemaRef)) {
1962 hadError = true;
1963 return;
1964 }
Richard Smith872307e2016-03-08 22:17:41 +00001965 }
1966
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001967 // If structDecl is a forward declaration, this loop won't do
1968 // anything except look at designated initializers; That's okay,
1969 // because an error should get printed out elsewhere. It might be
1970 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001971 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001972 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001973 bool CheckForMissingFields =
1974 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001975 bool HasDesignatedInit = false;
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001976
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001977 while (Index < IList->getNumInits()) {
1978 Expr *Init = IList->getInit(Index);
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001979 SourceLocation InitLoc = Init->getBeginLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001980
1981 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001982 // If we're not the subobject that matches up with the '{' for
1983 // the designator, we shouldn't be handling the
1984 // designator. Return immediately.
1985 if (!SubobjectIsDesignatorContext)
1986 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001987
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001988 HasDesignatedInit = true;
1989
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001990 // Handle this designated initializer. Field will be updated to
1991 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001992 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001993 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001994 StructuredList, StructuredIndex,
1995 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001996 hadError = true;
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001997 else if (!VerifyOnly) {
1998 // Find the field named by the designated initializer.
1999 RecordDecl::field_iterator F = RD->field_begin();
2000 while (std::next(F) != Field)
2001 ++F;
2002 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2003 if (hasAccessibleDestructor(ET, InitLoc, SemaRef)) {
2004 hadError = true;
2005 return;
2006 }
2007 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002008
Douglas Gregora9add4e2009-02-12 19:00:39 +00002009 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00002010
2011 // Disable check for missing fields when designators are used.
2012 // This matches gcc behaviour.
2013 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002014 continue;
2015 }
2016
2017 if (Field == FieldEnd) {
2018 // We've run out of fields. We're done.
2019 break;
2020 }
2021
Douglas Gregora9add4e2009-02-12 19:00:39 +00002022 // We've already initialized a member of a union. We're done.
2023 if (InitializedSomething && DeclType->isUnionType())
2024 break;
2025
Douglas Gregor91f84212008-12-11 16:49:14 +00002026 // If we've hit the flexible array member at the end, we're done.
2027 if (Field->getType()->isIncompleteArrayType())
2028 break;
2029
Douglas Gregor51695702009-01-29 16:53:55 +00002030 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002031 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002032 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00002033 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00002034 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002035
Douglas Gregora82064c2011-06-29 21:51:31 +00002036 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002037 bool InvalidUse;
2038 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002039 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002040 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002041 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2042 *Field, IList->getInit(Index)->getBeginLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002043 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002044 ++Index;
2045 ++Field;
2046 hadError = true;
2047 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002048 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002049
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002050 if (!VerifyOnly) {
2051 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2052 if (hasAccessibleDestructor(ET, InitLoc, SemaRef)) {
2053 hadError = true;
2054 return;
2055 }
2056 }
2057
Anders Carlsson6cabf312010-01-23 23:23:01 +00002058 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002059 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002060 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2061 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00002062 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00002063
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002064 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00002065 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00002066 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00002067 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002068
2069 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00002070 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002071
John McCalle40b58e2010-03-11 19:32:38 +00002072 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002073 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2074 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2075 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00002076 // It is possible we have one or more unnamed bitfields remaining.
2077 // Find first (if any) named field and emit warning.
2078 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2079 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00002080 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00002081 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00002082 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00002083 break;
2084 }
2085 }
2086 }
2087
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002088 // Check that any remaining fields can be value-initialized.
2089 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2090 !Field->getType()->isIncompleteArrayType()) {
2091 // FIXME: Should check for holes left by designated initializers too.
2092 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00002093 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00002094 CheckEmptyInitializable(
2095 InitializedEntity::InitializeMember(*Field, &Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002096 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002097 }
2098 }
2099
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002100 // Check that the types of the remaining fields have accessible destructors.
2101 if (!VerifyOnly) {
2102 // If the initializer expression has a designated initializer, check the
2103 // elements for which a designated initializer is not provided too.
2104 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2105 : Field;
2106 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2107 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2108 if (hasAccessibleDestructor(ET, IList->getEndLoc(), SemaRef)) {
2109 hadError = true;
2110 return;
2111 }
2112 }
2113 }
2114
Mike Stump11289f42009-09-09 15:08:12 +00002115 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002116 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002117 return;
2118
David Blaikie40ed2972012-06-06 20:45:41 +00002119 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002120 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002121 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002122 ++Index;
2123 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002124 }
2125
Anders Carlsson6cabf312010-01-23 23:23:01 +00002126 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002127 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Anders Carlsson6cabf312010-01-23 23:23:01 +00002129 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002131 StructuredList, StructuredIndex);
2132 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002134 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002135}
Steve Narofff8ecff22008-05-01 22:18:59 +00002136
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002137/// Expand a field designator that refers to a member of an
Douglas Gregord5846a12009-04-15 06:41:24 +00002138/// anonymous struct or union into a series of field designators that
2139/// refers to the field within the appropriate subobject.
2140///
Douglas Gregord5846a12009-04-15 06:41:24 +00002141static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002142 DesignatedInitExpr *DIE,
2143 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002144 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002145 typedef DesignatedInitExpr::Designator Designator;
2146
Douglas Gregord5846a12009-04-15 06:41:24 +00002147 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002148 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002149 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2150 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2151 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002152 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002153 DIE->getDesignator(DesigIdx)->getDotLoc(),
2154 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2155 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002156 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2157 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002158 assert(isa<FieldDecl>(*PI));
2159 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002160 }
2161
2162 // Expand the current designator into the set of replacement
2163 // designators, so we have a full subobject path down to where the
2164 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002165 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002166 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002167}
Mike Stump11289f42009-09-09 15:08:12 +00002168
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002169static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2170 DesignatedInitExpr *DIE) {
2171 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2172 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2173 for (unsigned I = 0; I < NumIndexExprs; ++I)
2174 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002175 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2176 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002177 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002178 DIE->usesGNUSyntax(), DIE->getInit());
2179}
2180
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002181namespace {
2182
2183// Callback to only accept typo corrections that are for field members of
2184// the given struct or union.
2185class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2186 public:
2187 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2188 : Record(RD) {}
2189
Craig Toppere14c0f82014-03-12 04:55:44 +00002190 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002191 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2192 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2193 }
2194
2195 private:
2196 RecordDecl *Record;
2197};
2198
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002199} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002200
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002201/// Check the well-formedness of a C99 designated initializer.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002202///
2203/// Determines whether the designated initializer @p DIE, which
2204/// resides at the given @p Index within the initializer list @p
2205/// IList, is well-formed for a current object of type @p DeclType
2206/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002207/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002208/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002209///
2210/// @param IList The initializer list in which this designated
2211/// initializer occurs.
2212///
Douglas Gregora5324162009-04-15 04:56:10 +00002213/// @param DIE The designated initializer expression.
2214///
2215/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002216///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002217/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002218/// into which the designation in @p DIE should refer.
2219///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002220/// @param NextField If non-NULL and the first designator in @p DIE is
2221/// a field, this will be set to the field declaration corresponding
2222/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002223///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002224/// @param NextElementIndex If non-NULL and the first designator in @p
2225/// DIE is an array designator or GNU array-range designator, this
2226/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002227///
2228/// @param Index Index into @p IList where the designated initializer
2229/// @p DIE occurs.
2230///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002231/// @param StructuredList The initializer list expression that
2232/// describes all of the subobject initializers in the order they'll
2233/// actually be initialized.
2234///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002235/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002236bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002237InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002238 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002239 DesignatedInitExpr *DIE,
2240 unsigned DesigIdx,
2241 QualType &CurrentObjectType,
2242 RecordDecl::field_iterator *NextField,
2243 llvm::APSInt *NextElementIndex,
2244 unsigned &Index,
2245 InitListExpr *StructuredList,
2246 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002247 bool FinishSubobjectInit,
2248 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002249 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002250 // Check the actual initialization for the designated object type.
2251 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002252
2253 // Temporarily remove the designator expression from the
2254 // initializer list that the child calls see, so that we don't try
2255 // to re-process the designator.
2256 unsigned OldIndex = Index;
2257 IList->setInit(OldIndex, DIE->getInit());
2258
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002259 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002260 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002261
2262 // Restore the designated initializer expression in the syntactic
2263 // form of the initializer list.
2264 if (IList->getInit(OldIndex) != DIE->getInit())
2265 DIE->setInit(IList->getInit(OldIndex));
2266 IList->setInit(OldIndex, DIE);
2267
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002268 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002269 }
2270
Douglas Gregora5324162009-04-15 04:56:10 +00002271 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002272 bool IsFirstDesignator = (DesigIdx == 0);
2273 if (!VerifyOnly) {
2274 assert((IsFirstDesignator || StructuredList) &&
2275 "Need a non-designated initializer list to start from");
2276
2277 // Determine the structural initializer list that corresponds to the
2278 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002279 if (IsFirstDesignator)
2280 StructuredList = SyntacticToSemantic.lookup(IList);
2281 else {
2282 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2283 StructuredList->getInit(StructuredIndex) : nullptr;
2284 if (!ExistingInit && StructuredList->hasArrayFiller())
2285 ExistingInit = StructuredList->getArrayFiller();
2286
2287 if (!ExistingInit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002288 StructuredList = getStructuredSubobjectInit(
2289 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002290 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
Yunzhong Gaocb779302015-06-10 00:27:52 +00002291 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2292 StructuredList = Result;
2293 else {
2294 if (DesignatedInitUpdateExpr *E =
2295 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2296 StructuredList = E->getUpdater();
2297 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002298 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2299 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002300 ExistingInit, DIE->getEndLoc());
Yunzhong Gaocb779302015-06-10 00:27:52 +00002301 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2302 StructuredList = DIUE->getUpdater();
2303 }
2304
2305 // We need to check on source range validity because the previous
2306 // initializer does not have to be an explicit initializer. e.g.,
2307 //
2308 // struct P { int a, b; };
2309 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2310 //
2311 // There is an overwrite taking place because the first braced initializer
2312 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2313 if (ExistingInit->getSourceRange().isValid()) {
2314 // We are creating an initializer list that initializes the
2315 // subobjects of the current object, but there was already an
2316 // initialization that completely initialized the current
2317 // subobject, e.g., by a compound literal:
2318 //
2319 // struct X { int a, b; };
2320 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2321 //
2322 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2323 // designated initializer re-initializes the whole
2324 // subobject [0], overwriting previous initializers.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002325 SemaRef.Diag(D->getBeginLoc(),
Yunzhong Gaocb779302015-06-10 00:27:52 +00002326 diag::warn_subobject_initializer_overrides)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002327 << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00002328
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002329 SemaRef.Diag(ExistingInit->getBeginLoc(),
Yunzhong Gaocb779302015-06-10 00:27:52 +00002330 diag::note_previous_initializer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002331 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002332 }
2333 }
2334 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002335 assert(StructuredList && "Expected a structured initializer list");
2336 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002337
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002338 if (D->isFieldDesignator()) {
2339 // C99 6.7.8p7:
2340 //
2341 // If a designator has the form
2342 //
2343 // . identifier
2344 //
2345 // then the current object (defined below) shall have
2346 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002347 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002348 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002349 if (!RT) {
2350 SourceLocation Loc = D->getDotLoc();
2351 if (Loc.isInvalid())
2352 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002353 if (!VerifyOnly)
2354 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002355 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002356 ++Index;
2357 return true;
2358 }
2359
Douglas Gregord5846a12009-04-15 06:41:24 +00002360 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002361 if (!KnownField) {
2362 IdentifierInfo *FieldName = D->getFieldName();
2363 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2364 for (NamedDecl *ND : Lookup) {
2365 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2366 KnownField = FD;
2367 break;
2368 }
2369 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002370 // In verify mode, don't modify the original.
2371 if (VerifyOnly)
2372 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002373 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002374 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002375 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002376 break;
2377 }
2378 }
David Majnemer36ef8982014-08-11 18:33:59 +00002379 if (!KnownField) {
2380 if (VerifyOnly) {
2381 ++Index;
2382 return true; // No typo correction when just trying this out.
2383 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002384
David Majnemer36ef8982014-08-11 18:33:59 +00002385 // Name lookup found something, but it wasn't a field.
2386 if (!Lookup.empty()) {
2387 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2388 << FieldName;
2389 SemaRef.Diag(Lookup.front()->getLocation(),
2390 diag::note_field_designator_found);
2391 ++Index;
2392 return true;
2393 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002394
David Majnemer36ef8982014-08-11 18:33:59 +00002395 // Name lookup didn't find anything.
2396 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002397 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2398 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002399 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002400 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2401 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002402 SemaRef.diagnoseTypo(
2403 Corrected,
2404 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002405 << FieldName << CurrentObjectType);
2406 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002407 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002408 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002409 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002410 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2411 << FieldName << CurrentObjectType;
2412 ++Index;
2413 return true;
2414 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002415 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002416 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002417
David Majnemer58e4ea92014-08-23 01:48:50 +00002418 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002419
2420 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2421 FieldIndex = CXXRD->getNumBases();
2422
David Majnemer58e4ea92014-08-23 01:48:50 +00002423 for (auto *FI : RT->getDecl()->fields()) {
2424 if (FI->isUnnamedBitfield())
2425 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002426 if (declaresSameEntity(KnownField, FI)) {
2427 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002428 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002429 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002430 ++FieldIndex;
2431 }
2432
David Majnemer36ef8982014-08-11 18:33:59 +00002433 RecordDecl::field_iterator Field =
2434 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2435
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002436 // All of the fields of a union are located at the same place in
2437 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002438 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002439 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002440 if (!VerifyOnly) {
2441 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002442 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002443 assert(StructuredList->getNumInits() == 1
2444 && "A union should never have more than one initializer!");
2445
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002446 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002447 if (ExistingInit) {
2448 // We're about to throw away an initializer, emit warning.
2449 SemaRef.Diag(D->getFieldLoc(),
2450 diag::warn_initializer_overrides)
2451 << D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002452 SemaRef.Diag(ExistingInit->getBeginLoc(),
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002453 diag::note_previous_initializer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002454 << /*FIXME:has side effects=*/0
2455 << ExistingInit->getSourceRange();
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002456 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002457
2458 // remove existing initializer
2459 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002460 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002461 }
2462
David Blaikie40ed2972012-06-06 20:45:41 +00002463 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002464 }
Douglas Gregor51695702009-01-29 16:53:55 +00002465 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002466
Douglas Gregora82064c2011-06-29 21:51:31 +00002467 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002468 bool InvalidUse;
2469 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002470 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002471 else
David Blaikie40ed2972012-06-06 20:45:41 +00002472 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002473 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002474 ++Index;
2475 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002476 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002477
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002478 if (!VerifyOnly) {
2479 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002480 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002481
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002482 // Make sure that our non-designated initializer list has space
2483 // for a subobject corresponding to this field.
2484 if (FieldIndex >= StructuredList->getNumInits())
2485 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2486 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002487
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002488 // This designator names a flexible array member.
2489 if (Field->getType()->isIncompleteArrayType()) {
2490 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002491 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002492 // We can't designate an object within the flexible array
2493 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002494 if (!VerifyOnly) {
2495 DesignatedInitExpr::Designator *NextD
2496 = DIE->getDesignator(DesigIdx + 1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002497 SemaRef.Diag(NextD->getBeginLoc(),
2498 diag::err_designator_into_flexible_array_member)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002499 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002500 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002501 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002502 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002503 Invalid = true;
2504 }
2505
Chris Lattner001b29c2010-10-10 17:49:49 +00002506 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2507 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002508 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002509 if (!VerifyOnly) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002510 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2511 diag::err_flexible_array_init_needs_braces)
2512 << DIE->getInit()->getSourceRange();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002513 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002514 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002515 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002516 Invalid = true;
2517 }
2518
Eli Friedman3fa64df2011-08-23 22:24:57 +00002519 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002520 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002521 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002522 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002523
2524 if (Invalid) {
2525 ++Index;
2526 return true;
2527 }
2528
2529 // Initialize the array.
2530 bool prevHadError = hadError;
2531 unsigned newStructuredIndex = FieldIndex;
2532 unsigned OldIndex = Index;
2533 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002534
2535 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002536 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002537 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002538 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002539
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002540 IList->setInit(OldIndex, DIE);
2541 if (hadError && !prevHadError) {
2542 ++Field;
2543 ++FieldIndex;
2544 if (NextField)
2545 *NextField = Field;
2546 StructuredIndex = FieldIndex;
2547 return true;
2548 }
2549 } else {
2550 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002551 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002552 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002553
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002554 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002555 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002557 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002558 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002559 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002560 return true;
2561 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002562
2563 // Find the position of the next field to be initialized in this
2564 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002565 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002566 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002567
2568 // If this the first designator, our caller will continue checking
2569 // the rest of this struct/class/union subobject.
2570 if (IsFirstDesignator) {
2571 if (NextField)
2572 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002573 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002574 return false;
2575 }
2576
Douglas Gregor17bd0942009-01-28 23:36:17 +00002577 if (!FinishSubobjectInit)
2578 return false;
2579
Douglas Gregord5846a12009-04-15 06:41:24 +00002580 // We've already initialized something in the union; we're done.
2581 if (RT->getDecl()->isUnion())
2582 return hadError;
2583
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002584 // Check the remaining fields within this class/struct/union subobject.
2585 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002586
Richard Smith872307e2016-03-08 22:17:41 +00002587 auto NoBases =
2588 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2589 CXXRecordDecl::base_class_iterator());
2590 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2591 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002592 return hadError && !prevHadError;
2593 }
2594
2595 // C99 6.7.8p6:
2596 //
2597 // If a designator has the form
2598 //
2599 // [ constant-expression ]
2600 //
2601 // then the current object (defined below) shall have array
2602 // type and the expression shall be an integer constant
2603 // expression. If the array is of unknown size, any
2604 // nonnegative value is valid.
2605 //
2606 // Additionally, cope with the GNU extension that permits
2607 // designators of the form
2608 //
2609 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002610 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002611 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002612 if (!VerifyOnly)
2613 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2614 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002615 ++Index;
2616 return true;
2617 }
2618
Craig Topperc3ec1492014-05-26 06:22:03 +00002619 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002620 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2621 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002622 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002623 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002624 DesignatedEndIndex = DesignatedStartIndex;
2625 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002626 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002627
Mike Stump11289f42009-09-09 15:08:12 +00002628 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002629 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002630 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002631 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002632 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002633
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002634 // Codegen can't handle evaluating array range designators that have side
2635 // effects, because we replicate the AST value for each initialized element.
2636 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2637 // elements with something that has a side effect, so codegen can emit an
2638 // "error unsupported" error instead of miscompiling the app.
2639 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002640 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002641 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002642 }
2643
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002644 if (isa<ConstantArrayType>(AT)) {
2645 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002646 DesignatedStartIndex
2647 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002648 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002649 DesignatedEndIndex
2650 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002651 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2652 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002653 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002654 SemaRef.Diag(IndexExpr->getBeginLoc(),
2655 diag::err_array_designator_too_large)
2656 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2657 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002658 ++Index;
2659 return true;
2660 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002661 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002662 unsigned DesignatedIndexBitWidth =
2663 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2664 DesignatedStartIndex =
2665 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2666 DesignatedEndIndex =
2667 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002668 DesignatedStartIndex.setIsUnsigned(true);
2669 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002670 }
Mike Stump11289f42009-09-09 15:08:12 +00002671
Eli Friedman1f16b742013-06-11 21:48:11 +00002672 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2673 // We're modifying a string literal init; we have to decompose the string
2674 // so we can modify the individual characters.
2675 ASTContext &Context = SemaRef.Context;
2676 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2677
2678 // Compute the character type
2679 QualType CharTy = AT->getElementType();
2680
2681 // Compute the type of the integer literals.
2682 QualType PromotedCharTy = CharTy;
2683 if (CharTy->isPromotableIntegerType())
2684 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2685 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2686
2687 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2688 // Get the length of the string.
2689 uint64_t StrLen = SL->getLength();
2690 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2691 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2692 StructuredList->resizeInits(Context, StrLen);
2693
2694 // Build a literal for each character in the string, and put them into
2695 // the init list.
2696 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2697 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2698 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002699 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002700 if (CharTy != PromotedCharTy)
2701 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002702 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002703 StructuredList->updateInit(Context, i, Init);
2704 }
2705 } else {
2706 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2707 std::string Str;
2708 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2709
2710 // Get the length of the string.
2711 uint64_t StrLen = Str.size();
2712 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2713 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2714 StructuredList->resizeInits(Context, StrLen);
2715
2716 // Build a literal for each character in the string, and put them into
2717 // the init list.
2718 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2719 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2720 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002721 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002722 if (CharTy != PromotedCharTy)
2723 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002724 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002725 StructuredList->updateInit(Context, i, Init);
2726 }
2727 }
2728 }
2729
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002730 // Make sure that our non-designated initializer list has space
2731 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002732 if (!VerifyOnly &&
2733 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002734 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002735 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002736
Douglas Gregor17bd0942009-01-28 23:36:17 +00002737 // Repeatedly perform subobject initializations in the range
2738 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002739
Douglas Gregor17bd0942009-01-28 23:36:17 +00002740 // Move to the next designator
2741 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2742 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002743
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002744 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002745 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002746
Douglas Gregor17bd0942009-01-28 23:36:17 +00002747 while (DesignatedStartIndex <= DesignatedEndIndex) {
2748 // Recurse to check later designated subobjects.
2749 QualType ElementType = AT->getElementType();
2750 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002751
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002752 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002753 if (CheckDesignatedInitializer(
2754 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2755 nullptr, Index, StructuredList, ElementIndex,
2756 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2757 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002758 return true;
2759
2760 // Move to the next index in the array that we'll be initializing.
2761 ++DesignatedStartIndex;
2762 ElementIndex = DesignatedStartIndex.getZExtValue();
2763 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002764
2765 // If this the first designator, our caller will continue checking
2766 // the rest of this array subobject.
2767 if (IsFirstDesignator) {
2768 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002769 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002770 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002771 return false;
2772 }
Mike Stump11289f42009-09-09 15:08:12 +00002773
Douglas Gregor17bd0942009-01-28 23:36:17 +00002774 if (!FinishSubobjectInit)
2775 return false;
2776
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002777 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002778 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002779 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002780 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002781 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002782 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002783}
2784
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002785// Get the structured initializer list for a subobject of type
2786// @p CurrentObjectType.
2787InitListExpr *
2788InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2789 QualType CurrentObjectType,
2790 InitListExpr *StructuredList,
2791 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002792 SourceRange InitRange,
2793 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002794 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002795 return nullptr; // No structured list in verification-only mode.
2796 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002797 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002798 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002799 else if (StructuredIndex < StructuredList->getNumInits())
2800 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002801
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002802 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002803 // There might have already been initializers for subobjects of the current
2804 // object, but a subsequent initializer list will overwrite the entirety
2805 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2806 //
2807 // struct P { char x[6]; };
2808 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2809 //
2810 // The first designated initializer is ignored, and l.x is just "f".
2811 if (!IsFullyOverwritten)
2812 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002813
2814 if (ExistingInit) {
2815 // We are creating an initializer list that initializes the
2816 // subobjects of the current object, but there was already an
2817 // initialization that completely initialized the current
2818 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002819 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002820 // struct X { int a, b; };
2821 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002822 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002823 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2824 // designated initializer re-initializes the whole
2825 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002826 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002827 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002828 << InitRange;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002829 SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
2830 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002831 }
2832
Mike Stump11289f42009-09-09 15:08:12 +00002833 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002834 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002835 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002836 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002837
Eli Friedman91f5ae52012-02-23 02:25:10 +00002838 QualType ResultType = CurrentObjectType;
2839 if (!ResultType->isArrayType())
2840 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2841 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002842
Douglas Gregor6d00c992009-03-20 23:58:33 +00002843 // Pre-allocate storage for the structured initializer list.
2844 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002845 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002846 bool GotNumInits = false;
2847 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002848 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002849 GotNumInits = true;
2850 } else if (Index < IList->getNumInits()) {
2851 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002852 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002853 GotNumInits = true;
2854 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002855 }
2856
Mike Stump11289f42009-09-09 15:08:12 +00002857 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002858 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2859 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2860 NumElements = CAType->getSize().getZExtValue();
2861 // Simple heuristic so that we don't allocate a very large
2862 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002863 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002864 NumElements = 0;
2865 }
John McCall9dd450b2009-09-21 23:43:11 +00002866 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002867 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002868 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002869 RecordDecl *RDecl = RType->getDecl();
2870 if (RDecl->isUnion())
2871 NumElements = 1;
2872 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002873 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002874 }
2875
Ted Kremenekac034612010-04-13 23:39:13 +00002876 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002877
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002878 // Link this new initializer list into the structured initializer
2879 // lists.
2880 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002881 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002882 else {
2883 Result->setSyntacticForm(IList);
2884 SyntacticToSemantic[IList] = Result;
2885 }
2886
2887 return Result;
2888}
2889
2890/// Update the initializer at index @p StructuredIndex within the
2891/// structured initializer list to the value @p expr.
2892void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2893 unsigned &StructuredIndex,
2894 Expr *expr) {
2895 // No structured initializer list to update
2896 if (!StructuredList)
2897 return;
2898
Ted Kremenekac034612010-04-13 23:39:13 +00002899 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2900 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002901 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002902 // We need to check on source range validity because the previous
2903 // initializer does not have to be an explicit initializer.
2904 // struct P { int a, b; };
2905 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2906 // There is an overwrite taking place because the first braced initializer
2907 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2908 if (PrevInit->getSourceRange().isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002909 SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
2910 << expr->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002911
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002912 SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
2913 << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002914 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002915 }
Mike Stump11289f42009-09-09 15:08:12 +00002916
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002917 ++StructuredIndex;
2918}
2919
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002920/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002921/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002922/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002923/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002924/// failure. Returns the index expression, possibly with an implicit cast
2925/// added, on success. If everything went okay, Value will receive the
2926/// value of the constant expression.
2927static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002928CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002929 SourceLocation Loc = Index->getBeginLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002930
2931 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002932 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2933 if (Result.isInvalid())
2934 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002935
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002936 if (Value.isSigned() && Value.isNegative())
2937 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002938 << Value.toString(10) << Index->getSourceRange();
2939
Douglas Gregor51650d32009-01-23 21:04:18 +00002940 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002941 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002942}
2943
John McCalldadc5752010-08-24 06:29:42 +00002944ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002945 SourceLocation Loc,
2946 bool GNUSyntax,
2947 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002948 typedef DesignatedInitExpr::Designator ASTDesignator;
2949
2950 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002951 SmallVector<ASTDesignator, 32> Designators;
2952 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002953
2954 // Build designators and check array designator expressions.
2955 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2956 const Designator &D = Desig.getDesignator(Idx);
2957 switch (D.getKind()) {
2958 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002959 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002960 D.getFieldLoc()));
2961 break;
2962
2963 case Designator::ArrayDesignator: {
2964 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2965 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002966 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002967 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002968 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002969 Invalid = true;
2970 else {
2971 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002972 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002973 D.getRBracketLoc()));
2974 InitExpressions.push_back(Index);
2975 }
2976 break;
2977 }
2978
2979 case Designator::ArrayRangeDesignator: {
2980 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2981 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2982 llvm::APSInt StartValue;
2983 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002984 bool StartDependent = StartIndex->isTypeDependent() ||
2985 StartIndex->isValueDependent();
2986 bool EndDependent = EndIndex->isTypeDependent() ||
2987 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002988 if (!StartDependent)
2989 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002990 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002991 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002992 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002993
2994 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002995 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002996 else {
2997 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002998 if (StartDependent || EndDependent) {
2999 // Nothing to compute.
3000 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00003001 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00003002 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00003003 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00003004
Douglas Gregor0f9d4002009-05-21 23:30:39 +00003005 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00003006 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00003007 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00003008 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3009 Invalid = true;
3010 } else {
3011 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00003012 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00003013 D.getEllipsisLoc(),
3014 D.getRBracketLoc()));
3015 InitExpressions.push_back(StartIndex);
3016 InitExpressions.push_back(EndIndex);
3017 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003018 }
3019 break;
3020 }
3021 }
3022 }
3023
3024 if (Invalid || Init.isInvalid())
3025 return ExprError();
3026
3027 // Clear out the expressions within the designation.
3028 Desig.ClearExprs(*this);
3029
3030 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00003031 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00003032 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003033 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003034 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003035
David Blaikiebbafb8a2012-03-11 07:00:24 +00003036 if (!getLangOpts().C99)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003037 Diag(DIE->getBeginLoc(), diag::ext_designated_init)
3038 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003039
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003040 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003041}
Douglas Gregor85df8d82009-01-29 00:45:39 +00003042
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003043//===----------------------------------------------------------------------===//
3044// Initialization entity
3045//===----------------------------------------------------------------------===//
3046
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003047InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00003048 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00003050{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003051 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3052 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00003053 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003054 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003055 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003056 Type = VT->getElementType();
3057 } else {
3058 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3059 assert(CT && "Unexpected type");
3060 Kind = EK_ComplexElement;
3061 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003062 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003063}
3064
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003065InitializedEntity
3066InitializedEntity::InitializeBase(ASTContext &Context,
3067 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00003068 bool IsInheritedVirtualBase,
3069 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003070 InitializedEntity Result;
3071 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00003072 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00003073 Result.Base = reinterpret_cast<uintptr_t>(Base);
3074 if (IsInheritedVirtualBase)
3075 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076
Douglas Gregor1b303932009-12-22 15:35:07 +00003077 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003078 return Result;
3079}
3080
Douglas Gregor85dabae2009-12-16 01:38:02 +00003081DeclarationName InitializedEntity::getName() const {
3082 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003083 case EK_Parameter:
3084 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00003085 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3086 return (D ? D->getDeclName() : DeclarationName());
3087 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003088
3089 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003090 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003091 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003092 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003093
Douglas Gregor19666fb2012-02-15 16:57:26 +00003094 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003095 return DeclarationName(Capture.VarID);
Fangrui Song6907ce22018-07-30 19:24:48 +00003096
Douglas Gregor85dabae2009-12-16 01:38:02 +00003097 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003098 case EK_StmtExprResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003099 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003100 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003101 case EK_Temporary:
3102 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003103 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003104 case EK_ArrayElement:
3105 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003106 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003107 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003108 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003109 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003110 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003111 return DeclarationName();
3112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003113
David Blaikie8a40f702012-01-17 06:56:22 +00003114 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003115}
3116
Richard Smith7873de02016-08-11 22:25:46 +00003117ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003118 switch (getKind()) {
3119 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003120 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003121 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003122 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003123
John McCall31168b02011-06-15 23:02:42 +00003124 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003125 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003126 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3127
Douglas Gregora4b592a2009-12-19 03:01:41 +00003128 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003129 case EK_StmtExprResult:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003130 case EK_Exception:
3131 case EK_New:
3132 case EK_Temporary:
3133 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003134 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003135 case EK_ArrayElement:
3136 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003137 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003138 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003139 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003140 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003141 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003142 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003143 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145
David Blaikie8a40f702012-01-17 06:56:22 +00003146 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003147}
3148
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003149bool InitializedEntity::allowsNRVO() const {
3150 switch (getKind()) {
3151 case EK_Result:
3152 case EK_Exception:
3153 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154
Richard Smith67af95b2018-07-23 19:19:08 +00003155 case EK_StmtExprResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003156 case EK_Variable:
3157 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003158 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003159 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003160 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003161 case EK_New:
3162 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003163 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003164 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003165 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003166 case EK_ArrayElement:
3167 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003168 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003169 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003170 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003171 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003172 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003173 break;
3174 }
3175
3176 return false;
3177}
3178
Richard Smithe6c01442013-06-05 00:46:14 +00003179unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003180 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003181 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3182 for (unsigned I = 0; I != Depth; ++I)
3183 OS << "`-";
3184
3185 switch (getKind()) {
3186 case EK_Variable: OS << "Variable"; break;
3187 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003188 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3189 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003190 case EK_Result: OS << "Result"; break;
Richard Smith67af95b2018-07-23 19:19:08 +00003191 case EK_StmtExprResult: OS << "StmtExprResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003192 case EK_Exception: OS << "Exception"; break;
3193 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003194 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003195 case EK_New: OS << "New"; break;
3196 case EK_Temporary: OS << "Temporary"; break;
3197 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003198 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003199 case EK_Base: OS << "Base"; break;
3200 case EK_Delegating: OS << "Delegating"; break;
3201 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3202 case EK_VectorElement: OS << "VectorElement " << Index; break;
3203 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3204 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003205 case EK_LambdaToBlockConversionBlockElement:
3206 OS << "Block (lambda)";
3207 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003208 case EK_LambdaCapture:
3209 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003210 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003211 break;
3212 }
3213
Richard Smith7873de02016-08-11 22:25:46 +00003214 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003215 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003216 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003217 }
3218
3219 OS << " '" << getType().getAsString() << "'\n";
3220
3221 return Depth + 1;
3222}
3223
Yaron Kerencdae9412016-01-29 19:38:18 +00003224LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003225 dumpImpl(llvm::errs());
3226}
3227
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003228//===----------------------------------------------------------------------===//
3229// Initialization sequence
3230//===----------------------------------------------------------------------===//
3231
3232void InitializationSequence::Step::Destroy() {
3233 switch (Kind) {
3234 case SK_ResolveAddressOfOverloadedFunction:
3235 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003236 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003237 case SK_CastDerivedToBaseLValue:
3238 case SK_BindReference:
3239 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003240 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003241 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003242 case SK_UserConversion:
3243 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003244 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003245 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003246 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003247 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003248 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003249 case SK_UnwrapInitList:
3250 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003251 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003252 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003253 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003254 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003255 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003256 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003257 case SK_ArrayLoopIndex:
3258 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003259 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003260 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003261 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003262 case SK_PassByIndirectCopyRestore:
3263 case SK_PassByIndirectRestore:
3264 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003265 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003266 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003267 case SK_OCLSamplerInit:
Andrew Savonichevb555b762018-10-23 15:19:20 +00003268 case SK_OCLZeroOpaqueType:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003269 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003270
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003271 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003272 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003273 delete ICS;
3274 }
3275}
3276
Douglas Gregor838fcc32010-03-26 20:14:36 +00003277bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003278 // There can be some lvalue adjustments after the SK_BindReference step.
3279 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3280 if (I->Kind == SK_BindReference)
3281 return true;
3282 if (I->Kind == SK_BindReferenceToTemporary)
3283 return false;
3284 }
3285 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003286}
3287
3288bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003289 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003290 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003291
Douglas Gregor838fcc32010-03-26 20:14:36 +00003292 switch (getFailureKind()) {
3293 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003294 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003295 case FK_ArrayNeedsInitList:
3296 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003297 case FK_ArrayNeedsInitListOrWideStringLiteral:
3298 case FK_NarrowStringIntoWideCharArray:
3299 case FK_WideStringIntoCharArray:
3300 case FK_IncompatWideStringIntoWideChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00003301 case FK_PlainStringIntoUTF8Char:
3302 case FK_UTF8StringIntoPlainChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003303 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3304 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003305 case FK_NonConstLValueReferenceBindingToBitfield:
3306 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003307 case FK_NonConstLValueReferenceBindingToUnrelated:
3308 case FK_RValueReferenceBindingToLValue:
3309 case FK_ReferenceInitDropsQualifiers:
3310 case FK_ReferenceInitFailed:
3311 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003312 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003313 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003314 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003315 case FK_ReferenceBindingToInitList:
3316 case FK_InitListBadDestinationType:
3317 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003318 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003319 case FK_ArrayTypeMismatch:
3320 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003321 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003322 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003323 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003324 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003325 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003326 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327
Douglas Gregor838fcc32010-03-26 20:14:36 +00003328 case FK_ReferenceInitOverloadFailed:
3329 case FK_UserConversionOverloadFailed:
3330 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003331 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003332 return FailedOverloadResult == OR_Ambiguous;
3333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334
David Blaikie8a40f702012-01-17 06:56:22 +00003335 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003336}
3337
Douglas Gregorb33eed02010-04-16 22:09:46 +00003338bool InitializationSequence::isConstructorInitialization() const {
3339 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3340}
3341
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003342void
3343InitializationSequence
3344::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3345 DeclAccessPair Found,
3346 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003347 Step S;
3348 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3349 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003350 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003351 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003352 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003353 Steps.push_back(S);
3354}
3355
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003357 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003358 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003359 switch (VK) {
3360 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3361 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3362 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003363 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003364 S.Type = BaseType;
3365 Steps.push_back(S);
3366}
3367
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003369 bool BindingTemporary) {
3370 Step S;
3371 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3372 S.Type = T;
3373 Steps.push_back(S);
3374}
3375
Richard Smithb8c0f552016-12-09 18:49:13 +00003376void InitializationSequence::AddFinalCopy(QualType T) {
3377 Step S;
3378 S.Kind = SK_FinalCopy;
3379 S.Type = T;
3380 Steps.push_back(S);
3381}
3382
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003383void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3384 Step S;
3385 S.Kind = SK_ExtraneousCopyToTemporary;
3386 S.Type = T;
3387 Steps.push_back(S);
3388}
3389
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003390void
3391InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3392 DeclAccessPair FoundDecl,
3393 QualType T,
3394 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003395 Step S;
3396 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003397 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003398 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003399 S.Function.Function = Function;
3400 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003401 Steps.push_back(S);
3402}
3403
3404void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003405 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003406 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003407 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003408 switch (VK) {
3409 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003410 S.Kind = SK_QualificationConversionRValue;
3411 break;
John McCall2536c6d2010-08-25 10:28:54 +00003412 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003413 S.Kind = SK_QualificationConversionXValue;
3414 break;
John McCall2536c6d2010-08-25 10:28:54 +00003415 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003416 S.Kind = SK_QualificationConversionLValue;
3417 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003418 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003419 S.Type = Ty;
3420 Steps.push_back(S);
3421}
3422
Richard Smith77be48a2014-07-31 06:31:19 +00003423void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3424 Step S;
3425 S.Kind = SK_AtomicConversion;
3426 S.Type = Ty;
3427 Steps.push_back(S);
3428}
3429
Jordan Roseb1312a52013-04-11 00:58:58 +00003430void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3431 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3432
3433 Step S;
3434 S.Kind = SK_LValueToRValue;
3435 S.Type = Ty;
3436 Steps.push_back(S);
3437}
3438
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003439void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003440 const ImplicitConversionSequence &ICS, QualType T,
3441 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003442 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003443 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3444 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003445 S.Type = T;
3446 S.ICS = new ImplicitConversionSequence(ICS);
3447 Steps.push_back(S);
3448}
3449
Douglas Gregor51e77d52009-12-10 17:56:55 +00003450void InitializationSequence::AddListInitializationStep(QualType T) {
3451 Step S;
3452 S.Kind = SK_ListInitialization;
3453 S.Type = T;
3454 Steps.push_back(S);
3455}
3456
Richard Smith55c28882016-05-12 23:45:49 +00003457void InitializationSequence::AddConstructorInitializationStep(
3458 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3459 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003460 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003461 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003462 : SK_ConstructorInitializationFromList
3463 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003464 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003465 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003466 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003467 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003468 Steps.push_back(S);
3469}
3470
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003471void InitializationSequence::AddZeroInitializationStep(QualType T) {
3472 Step S;
3473 S.Kind = SK_ZeroInitialization;
3474 S.Type = T;
3475 Steps.push_back(S);
3476}
3477
Douglas Gregore1314a62009-12-18 05:02:21 +00003478void InitializationSequence::AddCAssignmentStep(QualType T) {
3479 Step S;
3480 S.Kind = SK_CAssignment;
3481 S.Type = T;
3482 Steps.push_back(S);
3483}
3484
Eli Friedman78275202009-12-19 08:11:05 +00003485void InitializationSequence::AddStringInitStep(QualType T) {
3486 Step S;
3487 S.Kind = SK_StringInit;
3488 S.Type = T;
3489 Steps.push_back(S);
3490}
3491
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003492void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3493 Step S;
3494 S.Kind = SK_ObjCObjectConversion;
3495 S.Type = T;
3496 Steps.push_back(S);
3497}
3498
Richard Smith378b8c82016-12-14 03:22:16 +00003499void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003500 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003501 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003502 S.Type = T;
3503 Steps.push_back(S);
3504}
3505
Richard Smith410306b2016-12-12 02:53:20 +00003506void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3507 Step S;
3508 S.Kind = SK_ArrayLoopIndex;
3509 S.Type = EltT;
3510 Steps.insert(Steps.begin(), S);
3511
3512 S.Kind = SK_ArrayLoopInit;
3513 S.Type = T;
3514 Steps.push_back(S);
3515}
3516
Richard Smithebeed412012-02-15 22:38:09 +00003517void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3518 Step S;
3519 S.Kind = SK_ParenthesizedArrayInit;
3520 S.Type = T;
3521 Steps.push_back(S);
3522}
3523
John McCall31168b02011-06-15 23:02:42 +00003524void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3525 bool shouldCopy) {
3526 Step s;
3527 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3528 : SK_PassByIndirectRestore);
3529 s.Type = type;
3530 Steps.push_back(s);
3531}
3532
3533void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3534 Step S;
3535 S.Kind = SK_ProduceObjCObject;
3536 S.Type = T;
3537 Steps.push_back(S);
3538}
3539
Sebastian Redlc1839b12012-01-17 22:49:42 +00003540void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3541 Step S;
3542 S.Kind = SK_StdInitializerList;
3543 S.Type = T;
3544 Steps.push_back(S);
3545}
3546
Guy Benyei61054192013-02-07 10:55:47 +00003547void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3548 Step S;
3549 S.Kind = SK_OCLSamplerInit;
3550 S.Type = T;
3551 Steps.push_back(S);
3552}
3553
Andrew Savonichevb555b762018-10-23 15:19:20 +00003554void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003555 Step S;
Andrew Savonichevb555b762018-10-23 15:19:20 +00003556 S.Kind = SK_OCLZeroOpaqueType;
Egor Churaev89831422016-12-23 14:55:49 +00003557 S.Type = T;
3558 Steps.push_back(S);
3559}
3560
Sebastian Redl29526f02011-11-27 16:50:07 +00003561void InitializationSequence::RewrapReferenceInitList(QualType T,
3562 InitListExpr *Syntactic) {
3563 assert(Syntactic->getNumInits() == 1 &&
3564 "Can only rewrap trivial init lists.");
3565 Step S;
3566 S.Kind = SK_UnwrapInitList;
3567 S.Type = Syntactic->getInit(0)->getType();
3568 Steps.insert(Steps.begin(), S);
3569
3570 S.Kind = SK_RewrapInitList;
3571 S.Type = T;
3572 S.WrappingSyntacticList = Syntactic;
3573 Steps.push_back(S);
3574}
3575
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003576void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003577 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003578 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003579 this->Failure = Failure;
3580 this->FailedOverloadResult = Result;
3581}
3582
3583//===----------------------------------------------------------------------===//
3584// Attempt initialization
3585//===----------------------------------------------------------------------===//
3586
Nico Weber337d5aa2015-04-17 08:32:38 +00003587/// Tries to add a zero initializer. Returns true if that worked.
3588static bool
3589maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3590 const InitializedEntity &Entity) {
3591 if (Entity.getKind() != InitializedEntity::EK_Variable)
3592 return false;
3593
3594 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003595 if (VD->getInit() || VD->getEndLoc().isMacroID())
Nico Weber337d5aa2015-04-17 08:32:38 +00003596 return false;
3597
3598 QualType VariableTy = VD->getType().getCanonicalType();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003599 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
Nico Weber337d5aa2015-04-17 08:32:38 +00003600 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3601 if (!Init.empty()) {
3602 Sequence.AddZeroInitializationStep(Entity.getType());
3603 Sequence.SetZeroInitializationFixit(Init, Loc);
3604 return true;
3605 }
3606 return false;
3607}
3608
John McCall31168b02011-06-15 23:02:42 +00003609static void MaybeProduceObjCObject(Sema &S,
3610 InitializationSequence &Sequence,
3611 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003612 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003613
3614 /// When initializing a parameter, produce the value if it's marked
3615 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003616 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003617 if (!Entity.isParameterConsumed())
3618 return;
3619
3620 assert(Entity.getType()->isObjCRetainableType() &&
3621 "consuming an object of unretainable type?");
3622 Sequence.AddProduceObjCObjectStep(Entity.getType());
3623
3624 /// When initializing a return value, if the return type is a
3625 /// retainable type, then returns need to immediately retain the
3626 /// object. If an autorelease is required, it will be done at the
3627 /// last instant.
Richard Smith67af95b2018-07-23 19:19:08 +00003628 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3629 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
John McCall31168b02011-06-15 23:02:42 +00003630 if (!Entity.getType()->isObjCRetainableType())
3631 return;
3632
3633 Sequence.AddProduceObjCObjectStep(Entity.getType());
3634 }
3635}
3636
Richard Smithcc1b96d2013-06-12 22:31:48 +00003637static void TryListInitialization(Sema &S,
3638 const InitializedEntity &Entity,
3639 const InitializationKind &Kind,
3640 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003641 InitializationSequence &Sequence,
3642 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003643
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003644/// When initializing from init list via constructor, handle
Richard Smithd86812d2012-07-05 08:39:21 +00003645/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003646///
Richard Smithd86812d2012-07-05 08:39:21 +00003647/// \return true if we have handled initialization of an object of type
3648/// std::initializer_list<T>, false otherwise.
3649static bool TryInitializerListConstruction(Sema &S,
3650 InitListExpr *List,
3651 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003652 InitializationSequence &Sequence,
3653 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003654 QualType E;
3655 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003656 return false;
3657
Richard Smithdb0ac552015-12-18 22:40:25 +00003658 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003659 Sequence.setIncompleteTypeFailure(E);
3660 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003661 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003662
3663 // Try initializing a temporary array from the init list.
3664 QualType ArrayType = S.Context.getConstantArrayType(
3665 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3666 List->getNumInits()),
3667 clang::ArrayType::Normal, 0);
3668 InitializedEntity HiddenArray =
3669 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003670 InitializationKind Kind = InitializationKind::CreateDirectList(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003671 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
Manman Ren073db022016-03-10 18:53:19 +00003672 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3673 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003674 if (Sequence)
3675 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003676 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003677}
3678
Richard Smith7c2bcc92016-09-07 02:14:33 +00003679/// Determine if the constructor has the signature of a copy or move
3680/// constructor for the type T of the class in which it was found. That is,
3681/// determine if its first parameter is of type T or reference to (possibly
3682/// cv-qualified) T.
3683static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3684 const ConstructorInfo &Info) {
3685 if (Info.Constructor->getNumParams() == 0)
3686 return false;
3687
3688 QualType ParmT =
3689 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3690 QualType ClassT =
3691 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3692
3693 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3694}
3695
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003696static OverloadingResult
3697ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003698 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003699 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003700 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003701 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003702 OverloadCandidateSet::iterator &Best,
3703 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003704 bool OnlyListConstructors, bool IsListInit,
3705 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003706 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003707
Richard Smith40c78062015-02-21 02:31:57 +00003708 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003709 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003710 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003711 continue;
3712
Richard Smith7c2bcc92016-09-07 02:14:33 +00003713 if (!AllowExplicit && Info.Constructor->isExplicit())
3714 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003715
Richard Smith7c2bcc92016-09-07 02:14:33 +00003716 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3717 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003718
Richard Smith7c2bcc92016-09-07 02:14:33 +00003719 // C++11 [over.best.ics]p4:
3720 // ... and the constructor or user-defined conversion function is a
3721 // candidate by
3722 // - 13.3.1.3, when the argument is the temporary in the second step
3723 // of a class copy-initialization, or
3724 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3725 // - the second phase of 13.3.1.7 when the initializer list has exactly
3726 // one element that is itself an initializer list, and the target is
3727 // the first parameter of a constructor of class X, and the conversion
3728 // is to X or reference to (possibly cv-qualified X),
3729 // user-defined conversion sequences are not considered.
3730 bool SuppressUserConversions =
3731 SecondStepOfCopyInit ||
3732 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3733 hasCopyOrMoveCtorParam(S.Context, Info));
3734
3735 if (Info.ConstructorTmpl)
3736 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3737 /*ExplicitArgs*/ nullptr, Args,
3738 CandidateSet, SuppressUserConversions);
3739 else {
3740 // C++ [over.match.copy]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00003741 // - When initializing a temporary to be bound to the first parameter
Richard Smith7c2bcc92016-09-07 02:14:33 +00003742 // of a constructor [for type T] that takes a reference to possibly
3743 // cv-qualified T as its first argument, called with a single
3744 // argument in the context of direct-initialization, explicit
3745 // conversion functions are also considered.
3746 // FIXME: What if a constructor template instantiates to such a signature?
Fangrui Song6907ce22018-07-30 19:24:48 +00003747 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Richard Smith7c2bcc92016-09-07 02:14:33 +00003748 Args.size() == 1 &&
3749 hasCopyOrMoveCtorParam(S.Context, Info);
3750 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3751 CandidateSet, SuppressUserConversions,
3752 /*PartialOverloading=*/false,
3753 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003754 }
3755 }
3756
Richard Smith67ef14f2017-09-26 18:37:55 +00003757 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3758 //
3759 // When initializing an object of class type T by constructor
3760 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3761 // from a single expression of class type U, conversion functions of
3762 // U that convert to the non-reference type cv T are candidates.
3763 // Explicit conversion functions are only candidates during
3764 // direct-initialization.
3765 //
3766 // Note: SecondStepOfCopyInit is only ever true in this case when
3767 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003768 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003769 !SecondStepOfCopyInit) {
3770 Expr *Initializer = Args[0];
3771 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3772 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3773 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3774 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3775 NamedDecl *D = *I;
3776 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3777 D = D->getUnderlyingDecl();
3778
3779 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3780 CXXConversionDecl *Conv;
3781 if (ConvTemplate)
3782 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3783 else
3784 Conv = cast<CXXConversionDecl>(D);
3785
3786 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3787 if (ConvTemplate)
3788 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3789 ActingDC, Initializer, DestType,
3790 CandidateSet, AllowExplicit,
3791 /*AllowResultConversion*/false);
3792 else
3793 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3794 DestType, CandidateSet, AllowExplicit,
3795 /*AllowResultConversion*/false);
3796 }
3797 }
3798 }
3799 }
3800
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003801 // Perform overload resolution and return the result.
3802 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3803}
3804
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003805/// Attempt initialization by constructor (C++ [dcl.init]), which
Sebastian Redled2e5322011-12-22 14:44:04 +00003806/// enumerates the constructors of the initialized entity and performs overload
3807/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003808/// \param DestType The destination class type.
3809/// \param DestArrayType The destination type, which is either DestType or
3810/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003811/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003812/// \param IsInitListCopy Is this non-list-initialization resulting from a
3813/// list-initialization from {x} where x is the same
3814/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003815static void TryConstructorInitialization(Sema &S,
3816 const InitializedEntity &Entity,
3817 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003818 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003819 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003820 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003821 bool IsListInit = false,
3822 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003823 assert(((!IsListInit && !IsInitListCopy) ||
3824 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3825 "IsListInit/IsInitListCopy must come with a single initializer list "
3826 "argument.");
3827 InitListExpr *ILE =
3828 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3829 MultiExprArg UnwrappedArgs =
3830 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003831
Sebastian Redled2e5322011-12-22 14:44:04 +00003832 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003833 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003834 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003835 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003836 }
3837
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003838 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003839 // - If the initializer expression is a prvalue and the cv-unqualified
3840 // version of the source type is the same class as the class of the
3841 // destination, the initializer expression is used to initialize the
3842 // destination object.
3843 // Per DR (no number yet), this does not apply when initializing a base
3844 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003845 // ObjC++: Lambda captured by the block in the lambda to block conversion
3846 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003847 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003848 Entity.getKind() != InitializedEntity::EK_Base &&
3849 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003850 Entity.getKind() !=
3851 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003852 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3853 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3854 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003855 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003856 if (ILE)
3857 Sequence.RewrapReferenceInitList(DestType, ILE);
3858 return;
3859 }
3860
Sebastian Redled2e5322011-12-22 14:44:04 +00003861 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3862 assert(DestRecordType && "Constructor initialization requires record type");
3863 CXXRecordDecl *DestRecordDecl
3864 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3865
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003866 // Build the candidate set directly in the initialization sequence
3867 // structure, so that it will persist if we fail.
3868 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3869
3870 // Determine whether we are allowed to call explicit constructors or
3871 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003872 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003873 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003874
Sebastian Redled2e5322011-12-22 14:44:04 +00003875 // - Otherwise, if T is a class type, constructors are considered. The
3876 // applicable constructors are enumerated, and the best one is chosen
3877 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003878 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003879
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003880 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003881 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003882 bool AsInitializerList = false;
3883
Larisse Voufo19d08672015-01-27 18:47:05 +00003884 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003885 // When objects of non-aggregate type T are list-initialized, such that
3886 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3887 // according to the rules in this section, overload resolution selects
3888 // the constructor in two phases:
3889 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003890 // - Initially, the candidate functions are the initializer-list
3891 // constructors of the class T and the argument list consists of the
3892 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003893 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003894 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003895
3896 // If the initializer list has no elements and T has a default constructor,
3897 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003898 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003899 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003900 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003901 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003902 /*OnlyListConstructor=*/true,
3903 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003904 }
3905
3906 // C++11 [over.match.list]p1:
3907 // - If no viable initializer-list constructor is found, overload resolution
3908 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003909 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003910 // elements of the initializer list.
3911 if (Result == OR_No_Viable_Function) {
3912 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003913 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003914 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003915 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003916 /*OnlyListConstructors=*/false,
3917 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003918 }
3919 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003920 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003921 InitializationSequence::FK_ListConstructorOverloadFailed :
3922 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003923 Result);
3924 return;
3925 }
3926
Richard Smith67ef14f2017-09-26 18:37:55 +00003927 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3928
3929 // In C++17, ResolveConstructorOverload can select a conversion function
3930 // instead of a constructor.
3931 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3932 // Add the user-defined conversion step that calls the conversion function.
3933 QualType ConvType = CD->getConversionType();
3934 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3935 "should not have selected this conversion function");
3936 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3937 HadMultipleCandidates);
3938 if (!S.Context.hasSameType(ConvType, DestType))
3939 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3940 if (IsListInit)
3941 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3942 return;
3943 }
3944
Richard Smithd86812d2012-07-05 08:39:21 +00003945 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003946 // If a program calls for the default initialization of an object
3947 // of a const-qualified type T, T shall be a class type with a
3948 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003949 // C++ core issue 253 proposal:
3950 // If the implicit default constructor initializes all subobjects, no
3951 // initializer should be required.
3952 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3953 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003954 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003955 Entity.getType().isConstQualified()) {
3956 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3957 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3958 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3959 return;
3960 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003961 }
3962
Sebastian Redl048a6d72012-04-01 19:54:59 +00003963 // C++11 [over.match.list]p1:
3964 // In copy-list-initialization, if an explicit constructor is chosen, the
3965 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003966 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003967 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3968 return;
3969 }
3970
Sebastian Redled2e5322011-12-22 14:44:04 +00003971 // Add the constructor initialization step. Any cv-qualification conversion is
3972 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00003973 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003974 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003975 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003976}
3977
Sebastian Redl29526f02011-11-27 16:50:07 +00003978static bool
3979ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3980 Expr *Initializer,
3981 QualType &SourceType,
3982 QualType &UnqualifiedSourceType,
3983 QualType UnqualifiedTargetType,
3984 InitializationSequence &Sequence) {
3985 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3986 S.Context.OverloadTy) {
3987 DeclAccessPair Found;
3988 bool HadMultipleCandidates = false;
3989 if (FunctionDecl *Fn
3990 = S.ResolveAddressOfOverloadedFunction(Initializer,
3991 UnqualifiedTargetType,
3992 false, Found,
3993 &HadMultipleCandidates)) {
3994 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3995 HadMultipleCandidates);
3996 SourceType = Fn->getType();
3997 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3998 } else if (!UnqualifiedTargetType->isRecordType()) {
3999 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4000 return true;
4001 }
4002 }
4003 return false;
4004}
4005
4006static void TryReferenceInitializationCore(Sema &S,
4007 const InitializedEntity &Entity,
4008 const InitializationKind &Kind,
4009 Expr *Initializer,
4010 QualType cv1T1, QualType T1,
4011 Qualifiers T1Quals,
4012 QualType cv2T2, QualType T2,
4013 Qualifiers T2Quals,
4014 InitializationSequence &Sequence);
4015
Richard Smithd86812d2012-07-05 08:39:21 +00004016static void TryValueInitialization(Sema &S,
4017 const InitializedEntity &Entity,
4018 const InitializationKind &Kind,
4019 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00004020 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00004021
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004022/// Attempt list initialization of a reference.
Sebastian Redl29526f02011-11-27 16:50:07 +00004023static void TryReferenceListInitialization(Sema &S,
4024 const InitializedEntity &Entity,
4025 const InitializationKind &Kind,
4026 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004027 InitializationSequence &Sequence,
4028 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00004029 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004030 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00004031 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4032 return;
4033 }
David Majnemer9370dc22015-04-26 07:35:03 +00004034 // Can't reference initialize a compound literal.
4035 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4036 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4037 return;
4038 }
Sebastian Redl29526f02011-11-27 16:50:07 +00004039
4040 QualType DestType = Entity.getType();
4041 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4042 Qualifiers T1Quals;
4043 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4044
4045 // Reference initialization via an initializer list works thus:
4046 // If the initializer list consists of a single element that is
4047 // reference-related to the referenced type, bind directly to that element
4048 // (possibly creating temporaries).
4049 // Otherwise, initialize a temporary with the initializer list and
4050 // bind to that.
4051 if (InitList->getNumInits() == 1) {
4052 Expr *Initializer = InitList->getInit(0);
4053 QualType cv2T2 = Initializer->getType();
4054 Qualifiers T2Quals;
4055 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4056
4057 // If this fails, creating a temporary wouldn't work either.
4058 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4059 T1, Sequence))
4060 return;
4061
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004062 SourceLocation DeclLoc = Initializer->getBeginLoc();
Sebastian Redl29526f02011-11-27 16:50:07 +00004063 bool dummy1, dummy2, dummy3;
4064 Sema::ReferenceCompareResult RefRelationship
4065 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
4066 dummy2, dummy3);
4067 if (RefRelationship >= Sema::Ref_Related) {
4068 // Try to bind the reference here.
4069 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4070 T1Quals, cv2T2, T2, T2Quals, Sequence);
4071 if (Sequence)
4072 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4073 return;
4074 }
Richard Smith03d93932013-01-15 07:58:29 +00004075
4076 // Update the initializer if we've resolved an overloaded function.
4077 if (Sequence.step_begin() != Sequence.step_end())
4078 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00004079 }
4080
4081 // Not reference-related. Create a temporary and bind to that.
4082 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4083
Manman Ren073db022016-03-10 18:53:19 +00004084 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4085 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00004086 if (Sequence) {
4087 if (DestType->isRValueReferenceType() ||
4088 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
4089 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4090 else
4091 Sequence.SetFailed(
4092 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4093 }
4094}
4095
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004096/// Attempt list initialization (C++0x [dcl.init.list])
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004097static void TryListInitialization(Sema &S,
4098 const InitializedEntity &Entity,
4099 const InitializationKind &Kind,
4100 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004101 InitializationSequence &Sequence,
4102 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004103 QualType DestType = Entity.getType();
4104
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004105 // C++ doesn't allow scalar initialization with more than one argument.
4106 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004107 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004108 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4109 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4110 return;
4111 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004112 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004113 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4114 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004115 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004116 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004117
Larisse Voufod2010992015-01-24 23:09:54 +00004118 if (DestType->isRecordType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004119 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004120 Sequence.setIncompleteTypeFailure(DestType);
4121 return;
4122 }
Richard Smithd86812d2012-07-05 08:39:21 +00004123
Larisse Voufo19d08672015-01-27 18:47:05 +00004124 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004125 // - If T is a class type and the initializer list has a single element of
4126 // type cv U, where U is T or a class derived from T, the object is
4127 // initialized from that element (by copy-initialization for
4128 // copy-list-initialization, or by direct-initialization for
4129 // direct-list-initialization).
4130 // - Otherwise, if T is a character array and the initializer list has a
4131 // single element that is an appropriately-typed string literal
4132 // (8.5.2 [dcl.init.string]), initialization is performed as described
4133 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004134 // - Otherwise, if T is an aggregate, [...] (continue below).
4135 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004136 if (DestType->isRecordType()) {
4137 QualType InitType = InitList->getInit(0)->getType();
4138 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004139 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004140 Expr *InitListAsExpr = InitList;
4141 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004142 DestType, Sequence,
4143 /*InitListSyntax*/false,
4144 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004145 return;
4146 }
4147 }
4148 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4149 Expr *SubInit[1] = {InitList->getInit(0)};
4150 if (!isa<VariableArrayType>(DestAT) &&
4151 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4152 InitializationKind SubKind =
4153 Kind.getKind() == InitializationKind::IK_DirectList
4154 ? InitializationKind::CreateDirect(Kind.getLocation(),
4155 InitList->getLBraceLoc(),
4156 InitList->getRBraceLoc())
4157 : Kind;
4158 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004159 /*TopLevelOfInitList*/ true,
4160 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004161
4162 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4163 // the element is not an appropriately-typed string literal, in which
4164 // case we should proceed as in C++11 (below).
4165 if (Sequence) {
4166 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4167 return;
4168 }
4169 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004170 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004171 }
Larisse Voufod2010992015-01-24 23:09:54 +00004172
4173 // C++11 [dcl.init.list]p3:
4174 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004175 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4176 (S.getLangOpts().CPlusPlus11 &&
4177 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004178 if (S.getLangOpts().CPlusPlus11) {
4179 // - Otherwise, if the initializer list has no elements and T is a
4180 // class type with a default constructor, the object is
4181 // value-initialized.
4182 if (InitList->getNumInits() == 0) {
4183 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4184 if (RD->hasDefaultConstructor()) {
4185 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4186 return;
4187 }
4188 }
4189
4190 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4191 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004192 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4193 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004194 return;
4195
4196 // - Otherwise, if T is a class type, constructors are considered.
4197 Expr *InitListAsExpr = InitList;
4198 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004199 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004200 } else
4201 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4202 return;
4203 }
4204
Richard Smith089c3162013-09-21 21:55:46 +00004205 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004206 InitList->getNumInits() == 1) {
4207 Expr *E = InitList->getInit(0);
4208
4209 // - Otherwise, if T is an enumeration with a fixed underlying type,
4210 // the initializer-list has a single element v, and the initialization
4211 // is direct-list-initialization, the object is initialized with the
4212 // value T(v); if a narrowing conversion is required to convert v to
4213 // the underlying type of T, the program is ill-formed.
4214 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004215 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004216 Kind.getKind() == InitializationKind::IK_DirectList &&
4217 ET && ET->getDecl()->isFixed() &&
4218 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4219 (E->getType()->isIntegralOrEnumerationType() ||
4220 E->getType()->isFloatingType())) {
4221 // There are two ways that T(v) can work when T is an enumeration type.
4222 // If there is either an implicit conversion sequence from v to T or
4223 // a conversion function that can convert from v to T, then we use that.
4224 // Otherwise, if v is of integral, enumeration, or floating-point type,
4225 // it is converted to the enumeration type via its underlying type.
4226 // There is no overlap possible between these two cases (except when the
4227 // source value is already of the destination type), and the first
4228 // case is handled by the general case for single-element lists below.
4229 ImplicitConversionSequence ICS;
4230 ICS.setStandard();
4231 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004232 if (!E->isRValue())
4233 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004234 // If E is of a floating-point type, then the conversion is ill-formed
4235 // due to narrowing, but go through the motions in order to produce the
4236 // right diagnostic.
4237 ICS.Standard.Second = E->getType()->isFloatingType()
4238 ? ICK_Floating_Integral
4239 : ICK_Integral_Conversion;
4240 ICS.Standard.setFromType(E->getType());
4241 ICS.Standard.setToType(0, E->getType());
4242 ICS.Standard.setToType(1, DestType);
4243 ICS.Standard.setToType(2, DestType);
4244 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4245 /*TopLevelOfInitList*/true);
4246 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4247 return;
4248 }
4249
Richard Smith089c3162013-09-21 21:55:46 +00004250 // - Otherwise, if the initializer list has a single element of type E
4251 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004252 // initialized from that element (by copy-initialization for
4253 // copy-list-initialization, or by direct-initialization for
4254 // direct-list-initialization); if a narrowing conversion is required
4255 // to convert the element to T, the program is ill-formed.
4256 //
Richard Smith089c3162013-09-21 21:55:46 +00004257 // Per core-24034, this is direct-initialization if we were performing
4258 // direct-list-initialization and copy-initialization otherwise.
4259 // We can't use InitListChecker for this, because it always performs
4260 // copy-initialization. This only matters if we might use an 'explicit'
4261 // conversion operator, so we only need to handle the cases where the source
4262 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004263 if (InitList->getInit(0)->getType()->isRecordType()) {
4264 InitializationKind SubKind =
4265 Kind.getKind() == InitializationKind::IK_DirectList
4266 ? InitializationKind::CreateDirect(Kind.getLocation(),
4267 InitList->getLBraceLoc(),
4268 InitList->getRBraceLoc())
4269 : Kind;
4270 Expr *SubInit[1] = { InitList->getInit(0) };
4271 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4272 /*TopLevelOfInitList*/true,
4273 TreatUnavailableAsInvalid);
4274 if (Sequence)
4275 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4276 return;
4277 }
Richard Smith089c3162013-09-21 21:55:46 +00004278 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004279
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004280 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004281 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004282 if (CheckInitList.HadError()) {
4283 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4284 return;
4285 }
4286
4287 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004288 Sequence.AddListInitializationStep(DestType);
4289}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004290
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004291/// Try a reference initialization that involves calling a conversion
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004292/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004293static OverloadingResult TryRefInitWithConversionFunction(
4294 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4295 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4296 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004297 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4299 QualType T1 = cv1T1.getUnqualifiedType();
4300 QualType cv2T2 = Initializer->getType();
4301 QualType T2 = cv2T2.getUnqualifiedType();
4302
4303 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004304 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004305 bool ObjCLifetimeConversion;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004306 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
4307 DerivedToBase, ObjCConversion,
John McCall31168b02011-06-15 23:02:42 +00004308 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004309 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004310 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004311 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004312 (void)ObjCLifetimeConversion;
Fangrui Song6907ce22018-07-30 19:24:48 +00004313
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004314 // Build the candidate set directly in the initialization sequence
4315 // structure, so that it will persist if we fail.
4316 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004317 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004318
Richard Smithb368ea82018-07-02 23:25:22 +00004319 // Determine whether we are allowed to call explicit conversion operators.
4320 // Note that none of [over.match.copy], [over.match.conv], nor
4321 // [over.match.ref] permit an explicit constructor to be chosen when
4322 // initializing a reference, not even for direct-initialization.
4323 bool AllowExplicitCtors = false;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004324 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4325
Craig Topperc3ec1492014-05-26 06:22:03 +00004326 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004327 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004328 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004329 // The type we're converting to is a class type. Enumerate its constructors
4330 // to see if there is a suitable conversion.
4331 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004332
Richard Smith40c78062015-02-21 02:31:57 +00004333 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004334 auto Info = getConstructorInfo(D);
4335 if (!Info.Constructor)
4336 continue;
John McCalla0296f72010-03-19 07:35:19 +00004337
Richard Smithc2bebe92016-05-11 20:37:46 +00004338 if (!Info.Constructor->isInvalidDecl() &&
Richard Smithb368ea82018-07-02 23:25:22 +00004339 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004340 if (Info.ConstructorTmpl)
4341 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004342 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004343 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004344 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004345 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004346 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004347 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004348 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004349 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004351 }
John McCall3696dcb2010-08-17 07:23:57 +00004352 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4353 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354
Craig Topperc3ec1492014-05-26 06:22:03 +00004355 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004356 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004357 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004358 // The type we're converting from is a class type, enumerate its conversion
4359 // functions.
4360 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4361
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004362 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4363 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004364 NamedDecl *D = *I;
4365 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4366 if (isa<UsingShadowDecl>(D))
4367 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004369 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4370 CXXConversionDecl *Conv;
4371 if (ConvTemplate)
4372 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4373 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004374 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004376 // If the conversion function doesn't return a reference type,
4377 // it can't be considered for this conversion unless we're allowed to
4378 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379 // FIXME: Do we need to make sure that we only consider conversion
4380 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004381 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004382 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004383 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4384 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004385 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004386 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004387 DestType, CandidateSet,
4388 /*AllowObjCConversionOnExplicit=*/
4389 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004390 else
John McCalla0296f72010-03-19 07:35:19 +00004391 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004392 Initializer, DestType, CandidateSet,
4393 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004394 }
4395 }
4396 }
John McCall3696dcb2010-08-17 07:23:57 +00004397 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4398 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004400 SourceLocation DeclLoc = Initializer->getBeginLoc();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004401
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004403 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004405 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004406 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004407
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004408 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004409 // This is the overload that will be used for this initialization step if we
4410 // use this initialization. Mark it as referenced.
4411 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004412
Richard Smithb8c0f552016-12-09 18:49:13 +00004413 // Compute the returned type and value kind of the conversion.
4414 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004415 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004416 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004417 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004418 cv3T3 = T1;
4419
4420 ExprValueKind VK = VK_RValue;
4421 if (cv3T3->isLValueReferenceType())
4422 VK = VK_LValue;
4423 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4424 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4425 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004426
4427 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004428 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004429 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004430 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004431
Richard Smithb8c0f552016-12-09 18:49:13 +00004432 // Determine whether we'll need to perform derived-to-base adjustments or
4433 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004434 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004435 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004436 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004437 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004438 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004439 NewDerivedToBase, NewObjCConversion,
4440 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004441
4442 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004443 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004444 assert(!isa<CXXConstructorDecl>(Function) &&
4445 "should not have conversion after constructor");
4446
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004447 ImplicitConversionSequence ICS;
4448 ICS.setStandard();
4449 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004450 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4451
4452 // Every implicit conversion results in a prvalue, except for a glvalue
4453 // derived-to-base conversion, which we handle below.
4454 cv3T3 = ICS.Standard.getToType(2);
4455 VK = VK_RValue;
4456 }
4457
4458 // If the converted initializer is a prvalue, its type T4 is adjusted to
4459 // type "cv1 T4" and the temporary materialization conversion is applied.
4460 //
4461 // We adjust the cv-qualifications to match the reference regardless of
4462 // whether we have a prvalue so that the AST records the change. In this
4463 // case, T4 is "cv3 T3".
4464 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4465 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4466 Sequence.AddQualificationConversionStep(cv1T4, VK);
4467 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4468 VK = IsLValueRef ? VK_LValue : VK_XValue;
4469
4470 if (NewDerivedToBase)
4471 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004472 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004473 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004474
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004475 return OR_Success;
4476}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477
Richard Smithc620f552011-10-19 16:55:56 +00004478static void CheckCXX98CompatAccessibleCopy(Sema &S,
4479 const InitializedEntity &Entity,
4480 Expr *CurInitExpr);
4481
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004482/// Attempt reference initialization (C++0x [dcl.init.ref])
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004483static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004484 const InitializedEntity &Entity,
4485 const InitializationKind &Kind,
4486 Expr *Initializer,
4487 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004488 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004489 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004490 Qualifiers T1Quals;
4491 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004492 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004493 Qualifiers T2Quals;
4494 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004495
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004496 // If the initializer is the address of an overloaded function, try
4497 // to resolve the overloaded function. If all goes well, T2 is the
4498 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004499 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4500 T1, Sequence))
4501 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004502
Sebastian Redl29526f02011-11-27 16:50:07 +00004503 // Delegate everything else to a subfunction.
4504 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4505 T1Quals, cv2T2, T2, T2Quals, Sequence);
4506}
4507
Richard Smithb8c0f552016-12-09 18:49:13 +00004508/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004509/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004510/// such a glvalue will always create a temporary.
4511static bool isNonReferenceableGLValue(Expr *E) {
4512 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004513}
4514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004515/// Reference initialization without resolving overloaded functions.
Sebastian Redl29526f02011-11-27 16:50:07 +00004516static void TryReferenceInitializationCore(Sema &S,
4517 const InitializedEntity &Entity,
4518 const InitializationKind &Kind,
4519 Expr *Initializer,
4520 QualType cv1T1, QualType T1,
4521 Qualifiers T1Quals,
4522 QualType cv2T2, QualType T2,
4523 Qualifiers T2Quals,
4524 InitializationSequence &Sequence) {
4525 QualType DestType = Entity.getType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004526 SourceLocation DeclLoc = Initializer->getBeginLoc();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004527 // Compute some basic properties of the types and the initializer.
4528 bool isLValueRef = DestType->isLValueReferenceType();
4529 bool isRValueRef = !isLValueRef;
4530 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004531 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004532 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004533 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004534 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004535 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004536 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004537
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004538 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004540 // "cv2 T2" as follows:
4541 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004543 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004544 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004545 // there are no function rvalues in C++, rvalue refs to functions are treated
4546 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004547 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004548 bool T1Function = T1->isFunctionType();
4549 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004550 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004551 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004553 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004555 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004556 if (T1Quals != T2Quals)
4557 // Convert to cv1 T2. This should only add qualifiers unless this is a
4558 // c-style cast. The removal of qualifiers in that case notionally
4559 // happens after the reference binding, but that doesn't matter.
4560 Sequence.AddQualificationConversionStep(
4561 S.Context.getQualifiedType(T2, T1Quals),
4562 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004563 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004564 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004565 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004566 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004567
Richard Smithb8c0f552016-12-09 18:49:13 +00004568 // We only create a temporary here when binding a reference to a
4569 // bit-field or vector element. Those cases are't supposed to be
4570 // handled by this bullet, but the outcome is the same either way.
4571 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004572 return;
4573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574
4575 // - has a class type (i.e., T2 is a class type), where T1 is not
4576 // reference-related to T2, and can be implicitly converted to an
4577 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4578 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004579 // applicable conversion functions (13.3.1.6) and choosing the best
4580 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004581 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004582 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004583 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4584 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004585 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004586 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4587 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004588 if (ConvOvlResult == OR_Success)
4589 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004590 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004591 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004592 InitializationSequence::FK_ReferenceInitOverloadFailed,
4593 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004594 }
4595 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004596
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004598 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004599 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004600 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004601 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4602 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4603 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004604 Sequence.SetOverloadFailure(
4605 InitializationSequence::FK_ReferenceInitOverloadFailed,
4606 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004607 else if (!InitCategory.isLValue())
4608 Sequence.SetFailed(
4609 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4610 else {
4611 InitializationSequence::FailureKind FK;
4612 switch (RefRelationship) {
4613 case Sema::Ref_Compatible:
4614 if (Initializer->refersToBitField())
4615 FK = InitializationSequence::
4616 FK_NonConstLValueReferenceBindingToBitfield;
4617 else if (Initializer->refersToVectorElement())
4618 FK = InitializationSequence::
4619 FK_NonConstLValueReferenceBindingToVectorElement;
4620 else
4621 llvm_unreachable("unexpected kind of compatible initializer");
4622 break;
4623 case Sema::Ref_Related:
4624 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4625 break;
4626 case Sema::Ref_Incompatible:
4627 FK = InitializationSequence::
4628 FK_NonConstLValueReferenceBindingToUnrelated;
4629 break;
4630 }
4631 Sequence.SetFailed(FK);
4632 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004633 return;
4634 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004635
Douglas Gregor92e460e2011-01-20 16:44:54 +00004636 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004637 // - is an
4638 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4639 // [1z] rvalue (but not a bit-field) or
4640 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4641 //
4642 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004643 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004644 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004646 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004647 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004648 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004649 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004650 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004651 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004652 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004653 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4654 // compiler the freedom to perform a copy here or bind to the
4655 // object, while C++0x requires that we bind directly to the
4656 // object. Hence, we always bind to the object without making an
4657 // extra copy. However, in C++03 requires that we check for the
4658 // presence of a suitable copy constructor:
4659 //
4660 // The constructor that would be used to make the copy shall
4661 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004662 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004663 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004664 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004665 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667
Richard Smithb8c0f552016-12-09 18:49:13 +00004668 // C++1z [dcl.init.ref]/5.2.1.2:
4669 // If the converted initializer is a prvalue, its type T4 is adjusted
4670 // to type "cv1 T4" and the temporary materialization conversion is
4671 // applied.
4672 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4673 if (T1Quals != T2Quals)
4674 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4675 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4676 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4677
4678 // In any case, the reference is bound to the resulting glvalue (or to
4679 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004680 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004681 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004682 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004683 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686
4687 // - has a class type (i.e., T2 is a class type), where T1 is not
4688 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004689 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4690 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004691 //
4692 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004693 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004694 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004695 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004696 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4697 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004698 if (ConvOvlResult)
4699 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004700 InitializationSequence::FK_ReferenceInitOverloadFailed,
4701 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004703 return;
4704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705
Richard Smithce766292016-10-21 23:01:55 +00004706 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004707 isRValueRef && InitCategory.isLValue()) {
4708 Sequence.SetFailed(
4709 InitializationSequence::FK_RValueReferenceBindingToLValue);
4710 return;
4711 }
4712
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004713 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4714 return;
4715 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004716
4717 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004718 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004719 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004720 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004721
John McCallec6f4e92010-06-04 02:29:22 +00004722 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4723
Richard Smith2eabf782013-06-13 00:57:57 +00004724 // FIXME: Why do we use an implicit conversion here rather than trying
4725 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004726 ImplicitConversionSequence ICS
4727 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004728 /*SuppressUserConversions=*/false,
4729 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004730 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004731 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4732 /*AllowObjCWritebackConversion=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00004733
John McCall31168b02011-06-15 23:02:42 +00004734 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004735 // FIXME: Use the conversion function set stored in ICS to turn
4736 // this into an overloading ambiguity diagnostic. However, we need
4737 // to keep that set as an OverloadCandidateSet rather than as some
4738 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004739 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4740 Sequence.SetOverloadFailure(
4741 InitializationSequence::FK_ReferenceInitOverloadFailed,
4742 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004743 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4744 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004745 else
4746 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004747 return;
John McCall31168b02011-06-15 23:02:42 +00004748 } else {
4749 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004750 }
4751
4752 // [...] If T1 is reference-related to T2, cv1 must be the
4753 // same cv-qualification as, or greater cv-qualification
4754 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004755 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4756 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004758 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004759 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4760 return;
4761 }
4762
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004764 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004766 InitCategory.isLValue()) {
4767 Sequence.SetFailed(
4768 InitializationSequence::FK_RValueReferenceBindingToLValue);
4769 return;
4770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004772 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004773}
4774
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004775/// Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776/// (C++ [dcl.init.string], C99 6.7.8).
4777static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004778 const InitializedEntity &Entity,
4779 const InitializationKind &Kind,
4780 Expr *Initializer,
4781 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004782 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004783}
4784
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004785/// Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004786static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004787 const InitializedEntity &Entity,
4788 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004789 InitializationSequence &Sequence,
4790 InitListExpr *InitList) {
4791 assert((!InitList || InitList->getNumInits() == 0) &&
4792 "Shouldn't use value-init for non-empty init lists");
4793
Richard Smith1bfe0682012-02-14 21:14:13 +00004794 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004795 //
4796 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004797 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004799 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004800 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004802 if (const RecordType *RT = T->getAs<RecordType>()) {
4803 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004804 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004805 // C++98:
4806 // -- if T is a class type (clause 9) with a user-declared constructor
4807 // (12.1), then the default constructor for T is called (and the
4808 // initialization is ill-formed if T has no accessible default
4809 // constructor);
4810 // C++11:
4811 // -- if T is a class type (clause 9) with either no default constructor
4812 // (12.1 [class.ctor]) or a default constructor that is user-provided
4813 // or deleted, then the object is default-initialized;
4814 //
4815 // Note that the C++11 rule is the same as the C++98 rule if there are no
4816 // defaulted or deleted constructors, so we just use it unconditionally.
4817 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4818 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4819 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Richard Smith1bfe0682012-02-14 21:14:13 +00004821 // -- if T is a (possibly cv-qualified) non-union class type without a
4822 // user-provided or deleted default constructor, then the object is
4823 // zero-initialized and, if T has a non-trivial default constructor,
4824 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004825 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4826 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004827 if (NeedZeroInitialization)
4828 Sequence.AddZeroInitializationStep(Entity.getType());
4829
Richard Smith593f9932012-12-08 02:01:17 +00004830 // C++03:
4831 // -- if T is a non-union class type without a user-declared constructor,
4832 // then every non-static data member and base class component of T is
4833 // value-initialized;
4834 // [...] A program that calls for [...] value-initialization of an
4835 // entity of reference type is ill-formed.
4836 //
4837 // C++11 doesn't need this handling, because value-initialization does not
4838 // occur recursively there, and the implicit default constructor is
4839 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004840 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004841 ClassDecl->hasUninitializedReferenceMember()) {
4842 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4843 return;
4844 }
4845
Richard Smithd86812d2012-07-05 08:39:21 +00004846 // If this is list-value-initialization, pass the empty init list on when
4847 // building the constructor call. This affects the semantics of a few
4848 // things (such as whether an explicit default constructor can be called).
4849 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004850 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004851 bool InitListSyntax = InitList;
4852
Richard Smith81f5ade2016-12-15 02:28:18 +00004853 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004854 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4855 return TryConstructorInitialization(
4856 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004857 }
4858 }
4859
Douglas Gregor1b303932009-12-22 15:35:07 +00004860 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004861}
4862
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004863/// Attempt default initialization (C++ [dcl.init]p6).
Douglas Gregor85dabae2009-12-16 01:38:02 +00004864static void TryDefaultInitialization(Sema &S,
4865 const InitializedEntity &Entity,
4866 const InitializationKind &Kind,
4867 InitializationSequence &Sequence) {
4868 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869
Douglas Gregor85dabae2009-12-16 01:38:02 +00004870 // C++ [dcl.init]p6:
4871 // To default-initialize an object of type T means:
4872 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004873 QualType DestType = S.Context.getBaseElementType(Entity.getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00004874
Douglas Gregor85dabae2009-12-16 01:38:02 +00004875 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4876 // constructor for T is called (and the initialization is ill-formed if
4877 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004878 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004879 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4880 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004881 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883
Douglas Gregor85dabae2009-12-16 01:38:02 +00004884 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregor85dabae2009-12-16 01:38:02 +00004886 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004888 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004889 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004890 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4891 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004892 return;
4893 }
4894
4895 // If the destination type has a lifetime property, zero-initialize it.
4896 if (DestType.getQualifiers().hasObjCLifetime()) {
4897 Sequence.AddZeroInitializationStep(Entity.getType());
4898 return;
4899 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004900}
4901
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004902/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004903/// which enumerates all conversion functions and performs overload resolution
4904/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004905static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004906 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004907 const InitializationKind &Kind,
4908 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004909 InitializationSequence &Sequence,
4910 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004911 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4912 QualType SourceType = Initializer->getType();
4913 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4914 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915
Douglas Gregor540c3b02009-12-14 17:27:33 +00004916 // Build the candidate set directly in the initialization sequence
4917 // structure, so that it will persist if we fail.
4918 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004919 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920
Douglas Gregor540c3b02009-12-14 17:27:33 +00004921 // Determine whether we are allowed to call explicit constructors or
4922 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004923 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Douglas Gregor540c3b02009-12-14 17:27:33 +00004925 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4926 // The type we're converting to is a class type. Enumerate its constructors
4927 // to see if there is a suitable conversion.
4928 CXXRecordDecl *DestRecordDecl
4929 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930
Douglas Gregord9848152010-04-26 14:36:57 +00004931 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004932 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004933 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004934 auto Info = getConstructorInfo(D);
4935 if (!Info.Constructor)
4936 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004937
Richard Smithc2bebe92016-05-11 20:37:46 +00004938 if (!Info.Constructor->isInvalidDecl() &&
4939 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4940 if (Info.ConstructorTmpl)
4941 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004942 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004943 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004944 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004945 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004946 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004947 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004948 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004950 }
Douglas Gregord9848152010-04-26 14:36:57 +00004951 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004952 }
Eli Friedman78275202009-12-19 08:11:05 +00004953
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004954 SourceLocation DeclLoc = Initializer->getBeginLoc();
Eli Friedman78275202009-12-19 08:11:05 +00004955
Douglas Gregor540c3b02009-12-14 17:27:33 +00004956 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4957 // The type we're converting from is a class type, enumerate its conversion
4958 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004959
Eli Friedman4afe9a32009-12-20 22:12:03 +00004960 // We can only enumerate the conversion functions for a complete type; if
4961 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004962 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004963 CXXRecordDecl *SourceRecordDecl
4964 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004966 const auto &Conversions =
4967 SourceRecordDecl->getVisibleConversionFunctions();
4968 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004969 NamedDecl *D = *I;
4970 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4971 if (isa<UsingShadowDecl>(D))
4972 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973
Eli Friedman4afe9a32009-12-20 22:12:03 +00004974 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4975 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004976 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004977 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004978 else
John McCallda4458e2010-03-31 01:36:47 +00004979 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Eli Friedman4afe9a32009-12-20 22:12:03 +00004981 if (AllowExplicit || !Conv->isExplicit()) {
4982 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004983 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004984 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004985 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004986 else
John McCalla0296f72010-03-19 07:35:19 +00004987 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004988 Initializer, DestType, CandidateSet,
4989 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004990 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004991 }
4992 }
4993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004994
4995 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004996 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004997 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004998 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004999 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00005001 Result);
5002 return;
5003 }
John McCall0d1da222010-01-12 00:44:57 +00005004
Douglas Gregor540c3b02009-12-14 17:27:33 +00005005 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00005006 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005007 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008
Douglas Gregor540c3b02009-12-14 17:27:33 +00005009 if (isa<CXXConstructorDecl>(Function)) {
5010 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00005011 // subsumed by the initialization. Per DR5, the created temporary is of the
5012 // cv-unqualified type of the destination.
5013 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5014 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005015 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00005016
5017 // C++14 and before:
5018 // - if the function is a constructor, the call initializes a temporary
5019 // of the cv-unqualified version of the destination type. The [...]
5020 // temporary [...] is then used to direct-initialize, according to the
5021 // rules above, the object that is the destination of the
5022 // copy-initialization.
5023 // Note that this just performs a simple object copy from the temporary.
5024 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005025 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00005026 // - if the function is a constructor, the call is a prvalue of the
5027 // cv-unqualified version of the destination type whose return object
5028 // is initialized by the constructor. The call is used to
5029 // direct-initialize, according to the rules above, the object that
5030 // is the destination of the copy-initialization.
5031 // Therefore we need to do nothing further.
5032 //
5033 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005034 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00005035 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00005036 else if (DestType.hasQualifiers())
5037 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00005038 return;
5039 }
5040
5041 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005042 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005043 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5044 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045
Richard Smithb8c0f552016-12-09 18:49:13 +00005046 if (ConvType->getAs<RecordType>()) {
5047 // The call is used to direct-initialize [...] the object that is the
5048 // destination of the copy-initialization.
5049 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005050 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00005051 // - If the initializer expression is a prvalue and the cv-unqualified
5052 // version of the source type is the same as the class of the
5053 // destination [... do not make an extra copy]
5054 //
5055 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005056 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00005057 Function->getReturnType()->isReferenceType() ||
5058 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5059 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00005060 else if (!S.Context.hasSameType(ConvType, DestType))
5061 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00005062 return;
5063 }
5064
Douglas Gregor5ab11652010-04-17 22:01:05 +00005065 // If the conversion following the call to the conversion function
5066 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00005067 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5068 Best->FinalConversion.Third) {
5069 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00005070 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00005071 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005072 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00005073 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005074}
5075
Richard Smithf032001b2013-06-20 02:18:31 +00005076/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5077/// a function with a pointer return type contains a 'return false;' statement.
5078/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5079/// code using that header.
5080///
5081/// Work around this by treating 'return false;' as zero-initializing the result
5082/// if it's used in a pointer-returning function in a system header.
5083static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5084 const InitializedEntity &Entity,
5085 const Expr *Init) {
5086 return S.getLangOpts().CPlusPlus11 &&
5087 Entity.getKind() == InitializedEntity::EK_Result &&
5088 Entity.getType()->isPointerType() &&
5089 isa<CXXBoolLiteralExpr>(Init) &&
5090 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5091 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5092}
5093
John McCall31168b02011-06-15 23:02:42 +00005094/// The non-zero enum values here are indexes into diagnostic alternatives.
5095enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5096
5097/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00005098static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005099 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00005100 // Skip parens.
5101 e = e->IgnoreParens();
5102
5103 // Skip address-of nodes.
5104 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5105 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005106 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5107 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005108
5109 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005110 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5111 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005112 case CK_Dependent:
5113 case CK_BitCast:
5114 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005115 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005116 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005117
5118 case CK_ArrayToPointerDecay:
5119 return IIK_nonscalar;
5120
5121 case CK_NullToPointer:
5122 return IIK_okay;
5123
5124 default:
5125 break;
5126 }
5127
5128 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005129 } else if (isa<DeclRefExpr>(e)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005130 // set isWeakAccess to true, to mean that there will be an implicit
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005131 // load which requires a cleanup.
5132 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5133 isWeakAccess = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00005134
John McCall63f84442011-06-27 23:59:58 +00005135 if (!isAddressOf) return IIK_nonlocal;
5136
John McCall113bee02012-03-10 09:33:50 +00005137 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5138 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005139
5140 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005141
5142 // If we have a conditional operator, check both sides.
5143 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005144 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5145 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005146 return iik;
5147
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005148 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005149
5150 // These are never scalar.
5151 } else if (isa<ArraySubscriptExpr>(e)) {
5152 return IIK_nonscalar;
5153
5154 // Otherwise, it needs to be a null pointer constant.
5155 } else {
5156 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5157 ? IIK_okay : IIK_nonlocal);
5158 }
5159
5160 return IIK_nonlocal;
5161}
5162
5163/// Check whether the given expression is a valid operand for an
5164/// indirect copy/restore.
5165static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5166 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005167 bool isWeakAccess = false;
5168 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
Fangrui Song6907ce22018-07-30 19:24:48 +00005169 // If isWeakAccess to true, there will be an implicit
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005170 // load which requires a cleanup.
5171 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005172 S.Cleanup.setExprNeedsCleanups(true);
5173
John McCall31168b02011-06-15 23:02:42 +00005174 if (iik == IIK_okay) return;
5175
5176 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5177 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5178 << src->getSourceRange();
5179}
5180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005181/// Determine whether we have compatible array types for the
Douglas Gregore2f943b2011-02-22 18:29:51 +00005182/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005183static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005184 const ArrayType *Source) {
5185 // If the source and destination array types are equivalent, we're
5186 // done.
5187 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5188 return true;
5189
5190 // Make sure that the element types are the same.
5191 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5192 return false;
5193
5194 // The only mismatch we allow is when the destination is an
5195 // incomplete array type and the source is a constant array type.
5196 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5197}
5198
John McCall31168b02011-06-15 23:02:42 +00005199static bool tryObjCWritebackConversion(Sema &S,
5200 InitializationSequence &Sequence,
5201 const InitializedEntity &Entity,
5202 Expr *Initializer) {
5203 bool ArrayDecay = false;
5204 QualType ArgType = Initializer->getType();
5205 QualType ArgPointee;
5206 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5207 ArrayDecay = true;
5208 ArgPointee = ArgArrayType->getElementType();
5209 ArgType = S.Context.getPointerType(ArgPointee);
5210 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005211
John McCall31168b02011-06-15 23:02:42 +00005212 // Handle write-back conversion.
5213 QualType ConvertedArgType;
5214 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5215 ConvertedArgType))
5216 return false;
5217
5218 // We should copy unless we're passing to an argument explicitly
5219 // marked 'out'.
5220 bool ShouldCopy = true;
5221 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5222 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5223
5224 // Do we need an lvalue conversion?
5225 if (ArrayDecay || Initializer->isGLValue()) {
5226 ImplicitConversionSequence ICS;
5227 ICS.setStandard();
5228 ICS.Standard.setAsIdentityConversion();
5229
5230 QualType ResultType;
5231 if (ArrayDecay) {
5232 ICS.Standard.First = ICK_Array_To_Pointer;
5233 ResultType = S.Context.getPointerType(ArgPointee);
5234 } else {
5235 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5236 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5237 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005238
John McCall31168b02011-06-15 23:02:42 +00005239 Sequence.AddConversionSequenceStep(ICS, ResultType);
5240 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005241
John McCall31168b02011-06-15 23:02:42 +00005242 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5243 return true;
5244}
5245
Guy Benyei61054192013-02-07 10:55:47 +00005246static bool TryOCLSamplerInitialization(Sema &S,
5247 InitializationSequence &Sequence,
5248 QualType DestType,
5249 Expr *Initializer) {
5250 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005251 (!Initializer->isIntegerConstantExpr(S.Context) &&
5252 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005253 return false;
5254
5255 Sequence.AddOCLSamplerInitStep(DestType);
5256 return true;
5257}
5258
Andrew Savonichev3fee3512018-11-08 11:25:41 +00005259static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5260 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5261 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5262}
5263
Andrew Savonichevb555b762018-10-23 15:19:20 +00005264static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5265 InitializationSequence &Sequence,
5266 QualType DestType,
5267 Expr *Initializer) {
5268 if (!S.getLangOpts().OpenCL)
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005269 return false;
5270
Andrew Savonichevb555b762018-10-23 15:19:20 +00005271 //
5272 // OpenCL 1.2 spec, s6.12.10
5273 //
5274 // The event argument can also be used to associate the
5275 // async_work_group_copy with a previous async copy allowing
5276 // an event to be shared by multiple async copies; otherwise
5277 // event should be zero.
5278 //
5279 if (DestType->isEventT() || DestType->isQueueT()) {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00005280 if (!IsZeroInitializer(Initializer, S))
5281 return false;
5282
5283 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5284 return true;
5285 }
5286
5287 // We should allow zero initialization for all types defined in the
5288 // cl_intel_device_side_avc_motion_estimation extension, except
5289 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5290 if (S.getOpenCLOptions().isEnabled(
5291 "cl_intel_device_side_avc_motion_estimation") &&
5292 DestType->isOCLIntelSubgroupAVCType()) {
5293 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5294 DestType->isOCLIntelSubgroupAVCMceResultType())
5295 return false;
5296 if (!IsZeroInitializer(Initializer, S))
Andrew Savonichevb555b762018-10-23 15:19:20 +00005297 return false;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005298
Andrew Savonichevb555b762018-10-23 15:19:20 +00005299 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5300 return true;
5301 }
Egor Churaev89831422016-12-23 14:55:49 +00005302
Andrew Savonichevb555b762018-10-23 15:19:20 +00005303 return false;
Egor Churaev89831422016-12-23 14:55:49 +00005304}
5305
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005306InitializationSequence::InitializationSequence(Sema &S,
5307 const InitializedEntity &Entity,
5308 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005309 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005310 bool TopLevelOfInitList,
5311 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005312 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005313 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5314 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005315}
5316
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005317/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5318/// address of that function, this returns true. Otherwise, it returns false.
5319static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5320 auto *DRE = dyn_cast<DeclRefExpr>(E);
5321 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5322 return false;
5323
5324 return !S.checkAddressOfFunctionIsAvailable(
5325 cast<FunctionDecl>(DRE->getDecl()));
5326}
5327
Richard Smith410306b2016-12-12 02:53:20 +00005328/// Determine whether we can perform an elementwise array copy for this kind
5329/// of entity.
5330static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5331 switch (Entity.getKind()) {
5332 case InitializedEntity::EK_LambdaCapture:
5333 // C++ [expr.prim.lambda]p24:
5334 // For array members, the array elements are direct-initialized in
5335 // increasing subscript order.
5336 return true;
5337
5338 case InitializedEntity::EK_Variable:
5339 // C++ [dcl.decomp]p1:
5340 // [...] each element is copy-initialized or direct-initialized from the
5341 // corresponding element of the assignment-expression [...]
5342 return isa<DecompositionDecl>(Entity.getDecl());
5343
5344 case InitializedEntity::EK_Member:
5345 // C++ [class.copy.ctor]p14:
5346 // - if the member is an array, each element is direct-initialized with
5347 // the corresponding subobject of x
5348 return Entity.isImplicitMemberInitializer();
5349
5350 case InitializedEntity::EK_ArrayElement:
5351 // All the above cases are intended to apply recursively, even though none
5352 // of them actually say that.
5353 if (auto *E = Entity.getParent())
5354 return canPerformArrayCopy(*E);
5355 break;
5356
5357 default:
5358 break;
5359 }
5360
5361 return false;
5362}
5363
Richard Smith089c3162013-09-21 21:55:46 +00005364void InitializationSequence::InitializeFrom(Sema &S,
5365 const InitializedEntity &Entity,
5366 const InitializationKind &Kind,
5367 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005368 bool TopLevelOfInitList,
5369 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005370 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005371
John McCall5e77d762013-04-16 07:28:30 +00005372 // Eliminate non-overload placeholder types in the arguments. We
5373 // need to do this before checking whether types are dependent
5374 // because lowering a pseudo-object expression might well give us
5375 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005376 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005377 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5378 // FIXME: should we be doing this here?
5379 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5380 if (result.isInvalid()) {
5381 SetFailed(FK_PlaceholderType);
5382 return;
5383 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005384 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005385 }
5386
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005387 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005388 // The semantics of initializers are as follows. The destination type is
5389 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005390 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005392 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005393 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005394
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005395 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005396 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005397 SequenceKind = DependentSequence;
5398 return;
5399 }
5400
Sebastian Redld201edf2011-06-05 13:59:11 +00005401 // Almost everything is a normal sequence.
5402 setSequenceKind(NormalSequence);
5403
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005404 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005405 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005406 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005407 Initializer = Args[0];
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005408 if (S.getLangOpts().ObjC) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005409 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005410 DestType, Initializer->getType(),
5411 Initializer) ||
5412 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5413 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005414 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005415 if (!isa<InitListExpr>(Initializer))
5416 SourceType = Initializer->getType();
5417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005418
Sebastian Redl0501c632012-02-12 16:37:36 +00005419 // - If the initializer is a (non-parenthesized) braced-init-list, the
5420 // object is list-initialized (8.5.4).
5421 if (Kind.getKind() != InitializationKind::IK_Direct) {
5422 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005423 TryListInitialization(S, Entity, Kind, InitList, *this,
5424 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005425 return;
5426 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005428
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005429 // - If the destination type is a reference type, see 8.5.3.
5430 if (DestType->isReferenceType()) {
5431 // C++0x [dcl.init.ref]p1:
5432 // A variable declared to be a T& or T&&, that is, "reference to type T"
5433 // (8.3.2), shall be initialized by an object, or function, of type T or
5434 // by an object that can be converted into a T.
5435 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005436 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005437 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005438 // C++17 [dcl.init.ref]p5:
5439 // A reference [...] is initialized by an expression [...] as follows:
5440 // If the initializer is not an expression, presumably we should reject,
5441 // but the standard fails to actually say so.
5442 else if (isa<InitListExpr>(Args[0]))
5443 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005444 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005445 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005446 return;
5447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005448
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005449 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005450 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005451 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005452 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005453 return;
5454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005455
Douglas Gregor85dabae2009-12-16 01:38:02 +00005456 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005457 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005458 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005459 return;
5460 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005461
John McCall66884dd2011-02-21 07:22:22 +00005462 // - If the destination type is an array of characters, an array of
5463 // char16_t, an array of char32_t, or an array of wchar_t, and the
5464 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005465 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005466 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005467 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005468 if (Initializer && isa<VariableArrayType>(DestAT)) {
5469 SetFailed(FK_VariableLengthArrayHasInitializer);
5470 return;
5471 }
5472
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005473 if (Initializer) {
5474 switch (IsStringInit(Initializer, DestAT, Context)) {
5475 case SIF_None:
5476 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5477 return;
5478 case SIF_NarrowStringIntoWideChar:
5479 SetFailed(FK_NarrowStringIntoWideCharArray);
5480 return;
5481 case SIF_WideStringIntoChar:
5482 SetFailed(FK_WideStringIntoCharArray);
5483 return;
5484 case SIF_IncompatWideStringIntoWideChar:
5485 SetFailed(FK_IncompatWideStringIntoWideChar);
5486 return;
Richard Smith3a8244d2018-05-01 05:02:45 +00005487 case SIF_PlainStringIntoUTF8Char:
5488 SetFailed(FK_PlainStringIntoUTF8Char);
5489 return;
5490 case SIF_UTF8StringIntoPlainChar:
5491 SetFailed(FK_UTF8StringIntoPlainChar);
5492 return;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005493 case SIF_Other:
5494 break;
5495 }
John McCall66884dd2011-02-21 07:22:22 +00005496 }
5497
Richard Smith410306b2016-12-12 02:53:20 +00005498 // Some kinds of initialization permit an array to be initialized from
5499 // another array of the same type, and perform elementwise initialization.
5500 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5501 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5502 Entity.getType()) &&
5503 canPerformArrayCopy(Entity)) {
5504 // If source is a prvalue, use it directly.
5505 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005506 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005507 return;
5508 }
5509
5510 // Emit element-at-a-time copy loop.
5511 InitializedEntity Element =
5512 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5513 QualType InitEltT =
5514 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005515 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5516 Initializer->getValueKind(),
5517 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005518 Expr *OVEAsExpr = &OVE;
5519 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5520 TreatUnavailableAsInvalid);
5521 if (!Failed())
5522 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5523 return;
5524 }
5525
Douglas Gregore2f943b2011-02-22 18:29:51 +00005526 // Note: as an GNU C extension, we allow initialization of an
5527 // array from a compound literal that creates an array of the same
5528 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005529 if (!S.getLangOpts().CPlusPlus && Initializer &&
Bill Wendling8003edc2018-11-09 00:41:36 +00005530 (isa<ConstantExpr>(Initializer->IgnoreParens()) ||
5531 isa<CompoundLiteralExpr>(Initializer->IgnoreParens())) &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005532 Initializer->getType()->isArrayType()) {
5533 const ArrayType *SourceAT
5534 = Context.getAsArrayType(Initializer->getType());
5535 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005536 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005537 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005538 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005539 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005540 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005541 }
Richard Smithebeed412012-02-15 22:38:09 +00005542 }
Richard Smithd86812d2012-07-05 08:39:21 +00005543 // Note: as a GNU C++ extension, we allow list-initialization of a
5544 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005545 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005546 Entity.getKind() == InitializedEntity::EK_Member &&
5547 Initializer && isa<InitListExpr>(Initializer)) {
5548 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005549 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005550 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005551 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005552 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005553 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5554 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005555 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005556 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005557
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005558 return;
5559 }
Eli Friedman78275202009-12-19 08:11:05 +00005560
Larisse Voufod2010992015-01-24 23:09:54 +00005561 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005562 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005563 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005564 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005565
5566 // We're at the end of the line for C: it's either a write-back conversion
5567 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005568 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005569 // If allowed, check whether this is an Objective-C writeback conversion.
5570 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005571 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005572 return;
5573 }
Guy Benyei61054192013-02-07 10:55:47 +00005574
5575 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5576 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005577
Andrew Savonichevb555b762018-10-23 15:19:20 +00005578 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005579 return;
5580
John McCall31168b02011-06-15 23:02:42 +00005581 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005582 AddCAssignmentStep(DestType);
5583 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005584 return;
5585 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005586
David Blaikiebbafb8a2012-03-11 07:00:24 +00005587 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005588
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005589 // - If the destination type is a (possibly cv-qualified) class type:
5590 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005591 // - If the initialization is direct-initialization, or if it is
5592 // copy-initialization where the cv-unqualified version of the
5593 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005594 // class of the destination, constructors are considered. [...]
5595 if (Kind.getKind() == InitializationKind::IK_Direct ||
5596 (Kind.getKind() == InitializationKind::IK_Copy &&
5597 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005598 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005599 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005600 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005602 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005603 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005604 // used) to a derived class thereof are enumerated as described in
5605 // 13.3.1.4, and the best one is chosen through overload resolution
5606 // (13.3).
5607 else
Richard Smith77be48a2014-07-31 06:31:19 +00005608 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005609 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005610 return;
5611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612
Richard Smith49a6b6e2017-03-24 01:14:25 +00005613 assert(Args.size() >= 1 && "Zero-argument case handled above");
5614
5615 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005616 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005617 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005618 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005619 } else if (isa<InitListExpr>(Args[0])) {
5620 SetFailed(FK_ParenthesizedListInitForScalar);
5621 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623
5624 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005625 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005626 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005627 // For a conversion to _Atomic(T) from either T or a class type derived
5628 // from T, initialize the T object then convert to _Atomic type.
5629 bool NeedAtomicConversion = false;
5630 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5631 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005632 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
Richard Smith0f59cb32015-12-18 21:45:41 +00005633 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005634 DestType = Atomic->getValueType();
5635 NeedAtomicConversion = true;
5636 }
5637 }
5638
5639 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005640 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005641 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005642 if (!Failed() && NeedAtomicConversion)
5643 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005644 return;
5645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005647 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005648 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005649 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005650 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005651 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005652
John McCall31168b02011-06-15 23:02:42 +00005653 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005654 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005655 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005656 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005657 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005658 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5659 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005660
5661 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005662 ICS.Standard.Second == ICK_Writeback_Conversion) {
5663 // Objective-C ARC writeback conversion.
Fangrui Song6907ce22018-07-30 19:24:48 +00005664
John McCall31168b02011-06-15 23:02:42 +00005665 // We should copy unless we're passing to an argument explicitly
5666 // marked 'out'.
5667 bool ShouldCopy = true;
5668 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5669 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
Fangrui Song6907ce22018-07-30 19:24:48 +00005670
John McCall31168b02011-06-15 23:02:42 +00005671 // If there was an lvalue adjustment, add it as a separate conversion.
5672 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5673 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5674 ImplicitConversionSequence LvalueICS;
5675 LvalueICS.setStandard();
5676 LvalueICS.Standard.setAsIdentityConversion();
5677 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5678 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005679 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005680 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005681
Richard Smith77be48a2014-07-31 06:31:19 +00005682 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005683 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005684 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005685 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5686 AddZeroInitializationStep(Entity.getType());
5687 } else if (Initializer->getType() == Context.OverloadTy &&
5688 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5689 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005690 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005691 else if (Initializer->getType()->isFunctionType() &&
5692 isExprAnUnaddressableFunction(S, Initializer))
5693 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005694 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005695 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005696 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005697 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005698
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005699 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005700 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005701}
5702
5703InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005704 for (auto &S : Steps)
5705 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005706}
5707
5708//===----------------------------------------------------------------------===//
5709// Perform initialization
5710//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005712getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005713 switch(Entity.getKind()) {
5714 case InitializedEntity::EK_Variable:
5715 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005716 case InitializedEntity::EK_Exception:
5717 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005718 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005719 return Sema::AA_Initializing;
5720
5721 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005722 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005723 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5724 return Sema::AA_Sending;
5725
Douglas Gregore1314a62009-12-18 05:02:21 +00005726 return Sema::AA_Passing;
5727
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005728 case InitializedEntity::EK_Parameter_CF_Audited:
5729 if (Entity.getDecl() &&
5730 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5731 return Sema::AA_Sending;
Fangrui Song6907ce22018-07-30 19:24:48 +00005732
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005733 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
Fangrui Song6907ce22018-07-30 19:24:48 +00005734
Douglas Gregore1314a62009-12-18 05:02:21 +00005735 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005736 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
Douglas Gregore1314a62009-12-18 05:02:21 +00005737 return Sema::AA_Returning;
5738
Douglas Gregore1314a62009-12-18 05:02:21 +00005739 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005740 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005741 // FIXME: Can we tell apart casting vs. converting?
5742 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005743
Douglas Gregore1314a62009-12-18 05:02:21 +00005744 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005745 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005746 case InitializedEntity::EK_ArrayElement:
5747 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005748 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005749 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005750 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005751 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005752 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005753 return Sema::AA_Initializing;
5754 }
5755
David Blaikie8a40f702012-01-17 06:56:22 +00005756 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005757}
5758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005759/// Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005760/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005761static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005762 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005763 case InitializedEntity::EK_ArrayElement:
5764 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005765 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005766 case InitializedEntity::EK_StmtExprResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005767 case InitializedEntity::EK_New:
5768 case InitializedEntity::EK_Variable:
5769 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005770 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005771 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005772 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005773 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005774 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005775 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005776 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005777 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005778 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779
Douglas Gregore1314a62009-12-18 05:02:21 +00005780 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005781 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005782 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005783 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005784 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005785 return true;
5786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005787
Douglas Gregore1314a62009-12-18 05:02:21 +00005788 llvm_unreachable("missed an InitializedEntity kind?");
5789}
5790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005791/// Whether the given entity, when initialized with an object
Douglas Gregor95562572010-04-24 23:45:46 +00005792/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005793static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005794 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005795 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005796 case InitializedEntity::EK_StmtExprResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005797 case InitializedEntity::EK_New:
5798 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005799 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005800 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005801 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005802 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005803 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005804 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005805 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005806
Richard Smith27874d62013-01-08 00:08:23 +00005807 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005808 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005809 case InitializedEntity::EK_Variable:
5810 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005811 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005812 case InitializedEntity::EK_Temporary:
5813 case InitializedEntity::EK_ArrayElement:
5814 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005815 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005816 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005817 return true;
5818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005819
5820 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005821}
5822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005823/// Get the location at which initialization diagnostics should appear.
Richard Smithc620f552011-10-19 16:55:56 +00005824static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5825 Expr *Initializer) {
5826 switch (Entity.getKind()) {
5827 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005828 case InitializedEntity::EK_StmtExprResult:
Richard Smithc620f552011-10-19 16:55:56 +00005829 return Entity.getReturnLoc();
5830
5831 case InitializedEntity::EK_Exception:
5832 return Entity.getThrowLoc();
5833
5834 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005835 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005836 return Entity.getDecl()->getLocation();
5837
Douglas Gregor19666fb2012-02-15 16:57:26 +00005838 case InitializedEntity::EK_LambdaCapture:
5839 return Entity.getCaptureLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00005840
Richard Smithc620f552011-10-19 16:55:56 +00005841 case InitializedEntity::EK_ArrayElement:
5842 case InitializedEntity::EK_Member:
5843 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005844 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005845 case InitializedEntity::EK_Temporary:
5846 case InitializedEntity::EK_New:
5847 case InitializedEntity::EK_Base:
5848 case InitializedEntity::EK_Delegating:
5849 case InitializedEntity::EK_VectorElement:
5850 case InitializedEntity::EK_ComplexElement:
5851 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005852 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005853 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005854 case InitializedEntity::EK_RelatedResult:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005855 return Initializer->getBeginLoc();
Richard Smithc620f552011-10-19 16:55:56 +00005856 }
5857 llvm_unreachable("missed an InitializedEntity kind?");
5858}
5859
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005860/// Make a (potentially elidable) temporary copy of the object
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005861/// provided by the given initializer by calling the appropriate copy
5862/// constructor.
5863///
5864/// \param S The Sema object used for type-checking.
5865///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005866/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005867/// the type of the initializer expression or a superclass thereof.
5868///
James Dennett634962f2012-06-14 21:40:34 +00005869/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005870///
5871/// \param CurInit The initializer expression.
5872///
5873/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5874/// is permitted in C++03 (but not C++0x) when binding a reference to
5875/// an rvalue.
5876///
5877/// \returns An expression that copies the initializer expression into
5878/// a temporary object, or an error expression if a copy could not be
5879/// created.
John McCalldadc5752010-08-24 06:29:42 +00005880static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005881 QualType T,
5882 const InitializedEntity &Entity,
5883 ExprResult CurInit,
5884 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005885 if (CurInit.isInvalid())
5886 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005887 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005888 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005889 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005890 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005891 Class = cast<CXXRecordDecl>(Record->getDecl());
5892 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005893 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005894
Richard Smithc620f552011-10-19 16:55:56 +00005895 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005896
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005897 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005898 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005899 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005900
Richard Smith7c2bcc92016-09-07 02:14:33 +00005901 // Perform overload resolution using the class's constructors. Per
5902 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005903 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005904 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005905 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005906
Douglas Gregore1314a62009-12-18 05:02:21 +00005907 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005908 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005909 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005910 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5911 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5912 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005913 case OR_Success:
5914 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005915
Douglas Gregore1314a62009-12-18 05:02:21 +00005916 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005917 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5918 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5919 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005920 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005921 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005922 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005923 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005924 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005925 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005926
Douglas Gregore1314a62009-12-18 05:02:21 +00005927 case OR_Ambiguous:
5928 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005929 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005930 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005931 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005932 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005933
Douglas Gregore1314a62009-12-18 05:02:21 +00005934 case OR_Deleted:
5935 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005936 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005937 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005938 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005939 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005940 }
5941
Richard Smith7c2bcc92016-09-07 02:14:33 +00005942 bool HadMultipleCandidates = CandidateSet.size() > 1;
5943
Douglas Gregor5ab11652010-04-17 22:01:05 +00005944 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005945 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005946 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005947
Richard Smith5179eb72016-06-28 19:03:57 +00005948 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5949 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005950
5951 if (IsExtraneousCopy) {
5952 // If this is a totally extraneous copy for C++03 reference
5953 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005954 // expression. We don't generate an (elided) copy operation here
5955 // because doing so would require us to pass down a flag to avoid
5956 // infinite recursion, where each step adds another extraneous,
5957 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005958
Douglas Gregor30b52772010-04-18 07:57:34 +00005959 // Instantiate the default arguments of any extra parameters in
5960 // the selected copy constructor, as if we were going to create a
5961 // proper call to the copy constructor.
5962 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5963 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5964 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005965 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005966 break;
5967
5968 // Build the default argument expression; we don't actually care
5969 // if this succeeds or not, because this routine will complain
5970 // if there was a problem.
5971 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5972 }
5973
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005974 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005976
Douglas Gregor5ab11652010-04-17 22:01:05 +00005977 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005978 // constructor call (we might have derived-to-base conversions, or
5979 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005980 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005981 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005982
Richard Smith7c2bcc92016-09-07 02:14:33 +00005983 // C++0x [class.copy]p32:
5984 // When certain criteria are met, an implementation is allowed to
5985 // omit the copy/move construction of a class object, even if the
5986 // copy/move constructor and/or destructor for the object have
5987 // side effects. [...]
5988 // - when a temporary class object that has not been bound to a
5989 // reference (12.2) would be copied/moved to a class object
5990 // with the same cv-unqualified type, the copy/move operation
5991 // can be omitted by constructing the temporary object
5992 // directly into the target of the omitted copy/move
5993 //
5994 // Note that the other three bullets are handled elsewhere. Copy
5995 // elision for return statements and throw expressions are handled as part
5996 // of constructor initialization, while copy elision for exception handlers
5997 // is handled by the run-time.
5998 //
5999 // FIXME: If the function parameter is not the same type as the temporary, we
6000 // should still be able to elide the copy, but we don't have a way to
6001 // represent in the AST how much should be elided in this case.
6002 bool Elidable =
6003 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6004 S.Context.hasSameUnqualifiedType(
6005 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6006 CurInitExpr->getType());
6007
Douglas Gregord0ace022010-04-25 00:55:24 +00006008 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00006009 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
6010 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006011 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006012 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006013 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006014 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006015 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006016 CXXConstructExpr::CK_Complete,
6017 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006018
Douglas Gregord0ace022010-04-25 00:55:24 +00006019 // If we're supposed to bind temporaries, do so.
6020 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006021 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006022 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006023}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006024
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006025/// Check whether elidable copy construction for binding a reference to
Richard Smithc620f552011-10-19 16:55:56 +00006026/// a temporary would have succeeded if we were building in C++98 mode, for
6027/// -Wc++98-compat.
6028static void CheckCXX98CompatAccessibleCopy(Sema &S,
6029 const InitializedEntity &Entity,
6030 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006031 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00006032
6033 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6034 if (!Record)
6035 return;
6036
6037 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006038 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00006039 return;
6040
6041 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00006042 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00006043 DeclContext::lookup_result Ctors =
6044 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00006045
6046 // Perform overload resolution.
6047 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00006048 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00006049 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00006050 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6051 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6052 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00006053
6054 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6055 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6056 << CurInitExpr->getSourceRange();
6057
6058 switch (OR) {
6059 case OR_Success:
6060 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00006061 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00006062 // FIXME: Check default arguments as far as that's possible.
6063 break;
6064
6065 case OR_No_Viable_Function:
6066 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006067 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00006068 break;
6069
6070 case OR_Ambiguous:
6071 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006072 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00006073 break;
6074
6075 case OR_Deleted:
6076 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00006077 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00006078 break;
6079 }
6080}
6081
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006082void InitializationSequence::PrintInitLocationNote(Sema &S,
6083 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006084 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006085 if (Entity.getDecl()->getLocation().isInvalid())
6086 return;
6087
6088 if (Entity.getDecl()->getDeclName())
6089 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6090 << Entity.getDecl()->getDeclName();
6091 else
6092 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6093 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006094 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6095 Entity.getMethodDecl())
6096 S.Diag(Entity.getMethodDecl()->getLocation(),
6097 diag::note_method_return_type_change)
6098 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006099}
6100
Jordan Rose6c0505e2013-05-06 16:48:12 +00006101/// Returns true if the parameters describe a constructor initialization of
6102/// an explicit temporary object, e.g. "Point(x, y)".
6103static bool isExplicitTemporary(const InitializedEntity &Entity,
6104 const InitializationKind &Kind,
6105 unsigned NumArgs) {
6106 switch (Entity.getKind()) {
6107 case InitializedEntity::EK_Temporary:
6108 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006109 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006110 break;
6111 default:
6112 return false;
6113 }
6114
6115 switch (Kind.getKind()) {
6116 case InitializationKind::IK_DirectList:
6117 return true;
6118 // FIXME: Hack to work around cast weirdness.
6119 case InitializationKind::IK_Direct:
6120 case InitializationKind::IK_Value:
6121 return NumArgs != 1;
6122 default:
6123 return false;
6124 }
6125}
6126
Sebastian Redled2e5322011-12-22 14:44:04 +00006127static ExprResult
6128PerformConstructorInitialization(Sema &S,
6129 const InitializedEntity &Entity,
6130 const InitializationKind &Kind,
6131 MultiExprArg Args,
6132 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006133 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006134 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006135 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006136 SourceLocation LBraceLoc,
6137 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006138 unsigned NumArgs = Args.size();
6139 CXXConstructorDecl *Constructor
6140 = cast<CXXConstructorDecl>(Step.Function.Function);
6141 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6142
6143 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006144 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006145 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6146 ? Kind.getEqualLoc()
6147 : Kind.getLocation();
6148
6149 if (Kind.getKind() == InitializationKind::IK_Default) {
6150 // Force even a trivial, implicit default constructor to be
6151 // semantically checked. We do this explicitly because we don't build
6152 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006153 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006154 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006155 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006156 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6157 }
6158
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006159 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006160
Douglas Gregor6073dca2012-02-24 23:56:31 +00006161 // C++ [over.match.copy]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00006162 // - When initializing a temporary to be bound to the first parameter
6163 // of a constructor that takes a reference to possibly cv-qualified
6164 // T as its first argument, called with a single argument in the
Douglas Gregor6073dca2012-02-24 23:56:31 +00006165 // context of direct-initialization, explicit conversion functions
6166 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006167 bool AllowExplicitConv =
6168 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6169 hasCopyOrMoveCtorParam(S.Context,
6170 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006171
Sebastian Redled2e5322011-12-22 14:44:04 +00006172 // Determine the arguments required to actually perform the constructor
6173 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006174 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006175 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006176 AllowExplicitConv,
6177 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006178 return ExprError();
6179
6180
Jordan Rose6c0505e2013-05-06 16:48:12 +00006181 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006182 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006183 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6184 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006185
6186 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6187 if (!TSInfo)
6188 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumara14a1f92018-01-17 18:53:51 +00006189 SourceRange ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006190
Richard Smith5179eb72016-06-28 19:03:57 +00006191 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006192 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006193 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006194 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6195 return ExprError();
6196 }
Richard Smith5179eb72016-06-28 19:03:57 +00006197 S.MarkFunctionReferenced(Loc, Constructor);
6198
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006199 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00006200 S.Context, Constructor,
6201 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006202 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6203 IsListInitialization, IsStdInitListInitialization,
6204 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006205 } else {
6206 CXXConstructExpr::ConstructionKind ConstructKind =
6207 CXXConstructExpr::CK_Complete;
6208
6209 if (Entity.getKind() == InitializedEntity::EK_Base) {
6210 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6211 CXXConstructExpr::CK_VirtualBase :
6212 CXXConstructExpr::CK_NonVirtualBase;
6213 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6214 ConstructKind = CXXConstructExpr::CK_Delegating;
6215 }
6216
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006217 // Only get the parenthesis or brace range if it is a list initialization or
6218 // direct construction.
6219 SourceRange ParenOrBraceRange;
6220 if (IsListInitialization)
6221 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6222 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006223 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006224
6225 // If the entity allows NRVO, mark the construction as elidable
6226 // unconditionally.
6227 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006228 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006229 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006230 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006231 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006232 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006233 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006234 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006235 ConstructorInitRequiresZeroInit,
6236 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006237 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006238 else
Richard Smith410306b2016-12-12 02:53:20 +00006239 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006240 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006241 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006242 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006243 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006244 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006245 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006246 ConstructorInitRequiresZeroInit,
6247 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006248 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006249 }
6250 if (CurInit.isInvalid())
6251 return ExprError();
6252
6253 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006254 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006255 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6256 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006257
6258 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006259 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006260
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006261 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006262}
6263
Richard Smithd87aab92018-07-17 22:24:09 +00006264namespace {
6265enum LifetimeKind {
6266 /// The lifetime of a temporary bound to this entity ends at the end of the
6267 /// full-expression, and that's (probably) fine.
6268 LK_FullExpression,
6269
6270 /// The lifetime of a temporary bound to this entity is extended to the
6271 /// lifeitme of the entity itself.
6272 LK_Extended,
6273
6274 /// The lifetime of a temporary bound to this entity probably ends too soon,
6275 /// because the entity is allocated in a new-expression.
6276 LK_New,
6277
6278 /// The lifetime of a temporary bound to this entity ends too soon, because
6279 /// the entity is a return object.
6280 LK_Return,
6281
Richard Smith67af95b2018-07-23 19:19:08 +00006282 /// The lifetime of a temporary bound to this entity ends too soon, because
6283 /// the entity is the result of a statement expression.
6284 LK_StmtExprResult,
6285
Richard Smithd87aab92018-07-17 22:24:09 +00006286 /// This is a mem-initializer: if it would extend a temporary (other than via
6287 /// a default member initializer), the program is ill-formed.
6288 LK_MemInitializer,
6289};
6290using LifetimeResult =
6291 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6292}
6293
Richard Smithe6c01442013-06-05 00:46:14 +00006294/// Determine the declaration which an initialized entity ultimately refers to,
6295/// for the purpose of lifetime-extending a temporary bound to a reference in
6296/// the initialization of \p Entity.
Richard Smithca975b22018-07-23 18:50:26 +00006297static LifetimeResult getEntityLifetime(
David Majnemerdaff3702014-05-01 17:50:17 +00006298 const InitializedEntity *Entity,
Richard Smithd87aab92018-07-17 22:24:09 +00006299 const InitializedEntity *InitField = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006300 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006301 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006302 case InitializedEntity::EK_Variable:
6303 // The temporary [...] persists for the lifetime of the reference
Richard Smithd87aab92018-07-17 22:24:09 +00006304 return {Entity, LK_Extended};
Richard Smithe6c01442013-06-05 00:46:14 +00006305
6306 case InitializedEntity::EK_Member:
6307 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006308 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006309 return getEntityLifetime(Entity->getParent(), Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006310
6311 // except:
Richard Smithd87aab92018-07-17 22:24:09 +00006312 // C++17 [class.base.init]p8:
6313 // A temporary expression bound to a reference member in a
6314 // mem-initializer is ill-formed.
6315 // C++17 [class.base.init]p11:
6316 // A temporary expression bound to a reference member from a
6317 // default member initializer is ill-formed.
6318 //
6319 // The context of p11 and its example suggest that it's only the use of a
6320 // default member initializer from a constructor that makes the program
6321 // ill-formed, not its mere existence, and that it can even be used by
6322 // aggregate initialization.
6323 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6324 : LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006325
Richard Smith7873de02016-08-11 22:25:46 +00006326 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006327 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6328 // type.
Richard Smithd87aab92018-07-17 22:24:09 +00006329 return {Entity, LK_Extended};
Richard Smith7873de02016-08-11 22:25:46 +00006330
Richard Smithe6c01442013-06-05 00:46:14 +00006331 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006332 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006333 // -- A temporary bound to a reference parameter in a function call
6334 // persists until the completion of the full-expression containing
6335 // the call.
Richard Smithd87aab92018-07-17 22:24:09 +00006336 return {nullptr, LK_FullExpression};
6337
Richard Smithe6c01442013-06-05 00:46:14 +00006338 case InitializedEntity::EK_Result:
6339 // -- The lifetime of a temporary bound to the returned value in a
6340 // function return statement is not extended; the temporary is
6341 // destroyed at the end of the full-expression in the return statement.
Richard Smithd87aab92018-07-17 22:24:09 +00006342 return {nullptr, LK_Return};
6343
Richard Smith67af95b2018-07-23 19:19:08 +00006344 case InitializedEntity::EK_StmtExprResult:
6345 // FIXME: Should we lifetime-extend through the result of a statement
6346 // expression?
6347 return {nullptr, LK_StmtExprResult};
6348
Richard Smithe6c01442013-06-05 00:46:14 +00006349 case InitializedEntity::EK_New:
6350 // -- A temporary bound to a reference in a new-initializer persists
6351 // until the completion of the full-expression containing the
6352 // new-initializer.
Richard Smithd87aab92018-07-17 22:24:09 +00006353 return {nullptr, LK_New};
Richard Smithe6c01442013-06-05 00:46:14 +00006354
6355 case InitializedEntity::EK_Temporary:
6356 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006357 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006358 // We don't yet know the storage duration of the surrounding temporary.
6359 // Assume it's got full-expression duration for now, it will patch up our
6360 // storage duration if that's not correct.
Richard Smithd87aab92018-07-17 22:24:09 +00006361 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006362
6363 case InitializedEntity::EK_ArrayElement:
6364 // For subobjects, we look at the complete object.
Richard Smithca975b22018-07-23 18:50:26 +00006365 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithe6c01442013-06-05 00:46:14 +00006366
6367 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006368 // For subobjects, we look at the complete object.
6369 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006370 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithd87aab92018-07-17 22:24:09 +00006371 return {InitField, LK_MemInitializer};
6372
Richard Smithe6c01442013-06-05 00:46:14 +00006373 case InitializedEntity::EK_Delegating:
6374 // We can reach this case for aggregate initialization in a constructor:
6375 // struct A { int &&r; };
6376 // struct B : A { B() : A{0} {} };
Richard Smithd87aab92018-07-17 22:24:09 +00006377 // In this case, use the outermost field decl as the context.
6378 return {InitField, LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006379
6380 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006381 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006382 case InitializedEntity::EK_LambdaCapture:
Richard Smithe6c01442013-06-05 00:46:14 +00006383 case InitializedEntity::EK_VectorElement:
6384 case InitializedEntity::EK_ComplexElement:
Richard Smithd87aab92018-07-17 22:24:09 +00006385 return {nullptr, LK_FullExpression};
Richard Smithca975b22018-07-23 18:50:26 +00006386
6387 case InitializedEntity::EK_Exception:
6388 // FIXME: Can we diagnose lifetime problems with exceptions?
6389 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006390 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006391 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006392}
6393
Richard Smithd87aab92018-07-17 22:24:09 +00006394namespace {
Richard Smithca975b22018-07-23 18:50:26 +00006395enum ReferenceKind {
Richard Smithd87aab92018-07-17 22:24:09 +00006396 /// Lifetime would be extended by a reference binding to a temporary.
Richard Smithca975b22018-07-23 18:50:26 +00006397 RK_ReferenceBinding,
Richard Smithd87aab92018-07-17 22:24:09 +00006398 /// Lifetime would be extended by a std::initializer_list object binding to
6399 /// its backing array.
Richard Smithca975b22018-07-23 18:50:26 +00006400 RK_StdInitializerList,
Richard Smithd87aab92018-07-17 22:24:09 +00006401};
Richard Smithca975b22018-07-23 18:50:26 +00006402
Richard Smithafe48f92018-07-23 21:21:22 +00006403/// A temporary or local variable. This will be one of:
6404/// * A MaterializeTemporaryExpr.
6405/// * A DeclRefExpr whose declaration is a local.
6406/// * An AddrLabelExpr.
6407/// * A BlockExpr for a block with captures.
6408using Local = Expr*;
Richard Smithca975b22018-07-23 18:50:26 +00006409
6410/// Expressions we stepped over when looking for the local state. Any steps
6411/// that would inhibit lifetime extension or take us out of subexpressions of
6412/// the initializer are included.
6413struct IndirectLocalPathEntry {
Richard Smithafe48f92018-07-23 21:21:22 +00006414 enum EntryKind {
Richard Smithca975b22018-07-23 18:50:26 +00006415 DefaultInit,
6416 AddressOf,
Richard Smithafe48f92018-07-23 21:21:22 +00006417 VarInit,
6418 LValToRVal,
Richard Smithf4e248c2018-08-01 00:33:25 +00006419 LifetimeBoundCall,
Richard Smithca975b22018-07-23 18:50:26 +00006420 } Kind;
6421 Expr *E;
Richard Smithf4e248c2018-08-01 00:33:25 +00006422 const Decl *D = nullptr;
Richard Smithafe48f92018-07-23 21:21:22 +00006423 IndirectLocalPathEntry() {}
6424 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
Richard Smithf4e248c2018-08-01 00:33:25 +00006425 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
6426 : Kind(K), E(E), D(D) {}
Richard Smithca975b22018-07-23 18:50:26 +00006427};
6428
6429using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
Richard Smithe6c01442013-06-05 00:46:14 +00006430
Richard Smithd87aab92018-07-17 22:24:09 +00006431struct RevertToOldSizeRAII {
Richard Smithca975b22018-07-23 18:50:26 +00006432 IndirectLocalPath &Path;
Richard Smithd87aab92018-07-17 22:24:09 +00006433 unsigned OldSize = Path.size();
Richard Smithca975b22018-07-23 18:50:26 +00006434 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
Richard Smithd87aab92018-07-17 22:24:09 +00006435 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6436};
Richard Smithafe48f92018-07-23 21:21:22 +00006437
6438using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
6439 ReferenceKind RK)>;
Richard Smithd87aab92018-07-17 22:24:09 +00006440}
6441
Richard Smithafe48f92018-07-23 21:21:22 +00006442static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
6443 for (auto E : Path)
6444 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
6445 return true;
6446 return false;
6447}
6448
Richard Smith0e3102d2018-07-24 00:55:08 +00006449static bool pathContainsInit(IndirectLocalPath &Path) {
Fangrui Song3117b172018-10-20 17:53:42 +00006450 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
Richard Smith0e3102d2018-07-24 00:55:08 +00006451 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
6452 E.Kind == IndirectLocalPathEntry::VarInit;
6453 });
6454}
6455
Richard Smithca975b22018-07-23 18:50:26 +00006456static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6457 Expr *Init, LocalVisitor Visit,
6458 bool RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006459
Richard Smithf4e248c2018-08-01 00:33:25 +00006460static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6461 Expr *Init, ReferenceKind RK,
6462 LocalVisitor Visit);
6463
6464static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
6465 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
6466 if (!TSI)
6467 return false;
Martin Storsjod03fa992018-08-02 18:12:08 +00006468 // Don't declare this variable in the second operand of the for-statement;
6469 // GCC miscompiles that by ending its lifetime before evaluating the
6470 // third operand. See gcc.gnu.org/PR86769.
6471 AttributedTypeLoc ATL;
Richard Smithf4e248c2018-08-01 00:33:25 +00006472 for (TypeLoc TL = TSI->getTypeLoc();
Martin Storsjod03fa992018-08-02 18:12:08 +00006473 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
Richard Smithf4e248c2018-08-01 00:33:25 +00006474 TL = ATL.getModifiedLoc()) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006475 if (ATL.getAttrAs<LifetimeBoundAttr>())
Richard Smithf4e248c2018-08-01 00:33:25 +00006476 return true;
6477 }
6478 return false;
6479}
6480
6481static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
6482 LocalVisitor Visit) {
6483 const FunctionDecl *Callee;
6484 ArrayRef<Expr*> Args;
6485
6486 if (auto *CE = dyn_cast<CallExpr>(Call)) {
6487 Callee = CE->getDirectCallee();
6488 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
6489 } else {
6490 auto *CCE = cast<CXXConstructExpr>(Call);
6491 Callee = CCE->getConstructor();
6492 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
6493 }
6494 if (!Callee)
6495 return;
6496
6497 Expr *ObjectArg = nullptr;
6498 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
6499 ObjectArg = Args[0];
6500 Args = Args.slice(1);
6501 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6502 ObjectArg = MCE->getImplicitObjectArgument();
6503 }
6504
6505 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
6506 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
6507 if (Arg->isGLValue())
6508 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6509 Visit);
6510 else
6511 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6512 Path.pop_back();
6513 };
6514
6515 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
6516 VisitLifetimeBoundArg(Callee, ObjectArg);
6517
6518 for (unsigned I = 0,
6519 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
6520 I != N; ++I) {
6521 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
6522 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
6523 }
6524}
6525
Richard Smithca975b22018-07-23 18:50:26 +00006526/// Visit the locals that would be reachable through a reference bound to the
6527/// glvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006528static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6529 Expr *Init, ReferenceKind RK,
6530 LocalVisitor Visit) {
Richard Smithd87aab92018-07-17 22:24:09 +00006531 RevertToOldSizeRAII RAII(Path);
6532
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006533 // Walk past any constructs which we can lifetime-extend across.
6534 Expr *Old;
6535 do {
6536 Old = Init;
6537
Bill Wendling7c44da22018-10-31 03:48:47 +00006538 if (auto *FE = dyn_cast<FullExpr>(Init))
6539 Init = FE->getSubExpr();
Richard Smithafe48f92018-07-23 21:21:22 +00006540
Richard Smithdbc82492015-01-10 01:28:13 +00006541 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithd87aab92018-07-17 22:24:09 +00006542 // If this is just redundant braces around an initializer, step over it.
6543 if (ILE->isTransparent())
Richard Smithdbc82492015-01-10 01:28:13 +00006544 Init = ILE->getInit(0);
Richard Smithdbc82492015-01-10 01:28:13 +00006545 }
6546
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006547 // Step over any subobject adjustments; we may have a materialized
6548 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006549 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006550
6551 // Per current approach for DR1376, look through casts to reference type
6552 // when performing lifetime extension.
6553 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6554 if (CE->getSubExpr()->isGLValue())
6555 Init = CE->getSubExpr();
6556
Richard Smithb3189a12016-12-05 07:49:14 +00006557 // Per the current approach for DR1299, look through array element access
Richard Smithca975b22018-07-23 18:50:26 +00006558 // on array glvalues when performing lifetime extension.
6559 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006560 Init = ASE->getBase();
6561 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
6562 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
6563 Init = ICE->getSubExpr();
6564 else
6565 // We can't lifetime extend through this but we might still find some
6566 // retained temporaries.
6567 return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
Richard Smithca975b22018-07-23 18:50:26 +00006568 }
Richard Smithd87aab92018-07-17 22:24:09 +00006569
6570 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6571 // constructor inherits one as an implicit mem-initializer.
6572 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006573 Path.push_back(
6574 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
Richard Smithd87aab92018-07-17 22:24:09 +00006575 Init = DIE->getExpr();
Richard Smithd87aab92018-07-17 22:24:09 +00006576 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006577 } while (Init != Old);
6578
Richard Smithd87aab92018-07-17 22:24:09 +00006579 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006580 if (Visit(Path, Local(MTE), RK))
6581 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
6582 true);
6583 }
6584
Richard Smithf4e248c2018-08-01 00:33:25 +00006585 if (isa<CallExpr>(Init))
6586 return visitLifetimeBoundArguments(Path, Init, Visit);
6587
Richard Smithafe48f92018-07-23 21:21:22 +00006588 switch (Init->getStmtClass()) {
6589 case Stmt::DeclRefExprClass: {
6590 // If we find the name of a local non-reference parameter, we could have a
6591 // lifetime problem.
6592 auto *DRE = cast<DeclRefExpr>(Init);
Richard Smithca975b22018-07-23 18:50:26 +00006593 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6594 if (VD && VD->hasLocalStorage() &&
6595 !DRE->refersToEnclosingVariableOrCapture()) {
Richard Smithafe48f92018-07-23 21:21:22 +00006596 if (!VD->getType()->isReferenceType()) {
6597 Visit(Path, Local(DRE), RK);
6598 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
6599 // The lifetime of a reference parameter is unknown; assume it's OK
6600 // for now.
6601 break;
6602 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
6603 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6604 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
6605 RK_ReferenceBinding, Visit);
6606 }
Richard Smithca975b22018-07-23 18:50:26 +00006607 }
Richard Smithafe48f92018-07-23 21:21:22 +00006608 break;
6609 }
6610
6611 case Stmt::UnaryOperatorClass: {
6612 // The only unary operator that make sense to handle here
6613 // is Deref. All others don't resolve to a "name." This includes
6614 // handling all sorts of rvalues passed to a unary operator.
6615 const UnaryOperator *U = cast<UnaryOperator>(Init);
6616 if (U->getOpcode() == UO_Deref)
6617 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
6618 break;
6619 }
6620
6621 case Stmt::OMPArraySectionExprClass: {
6622 visitLocalsRetainedByInitializer(
6623 Path, cast<OMPArraySectionExpr>(Init)->getBase(), Visit, true);
6624 break;
6625 }
6626
6627 case Stmt::ConditionalOperatorClass:
6628 case Stmt::BinaryConditionalOperatorClass: {
6629 auto *C = cast<AbstractConditionalOperator>(Init);
6630 if (!C->getTrueExpr()->getType()->isVoidType())
6631 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
6632 if (!C->getFalseExpr()->getType()->isVoidType())
6633 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
6634 break;
6635 }
6636
6637 // FIXME: Visit the left-hand side of an -> or ->*.
6638
6639 default:
6640 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006641 }
6642}
6643
Richard Smithca975b22018-07-23 18:50:26 +00006644/// Visit the locals that would be reachable through an object initialized by
6645/// the prvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006646static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6647 Expr *Init, LocalVisitor Visit,
6648 bool RevisitSubinits) {
Richard Smithd87aab92018-07-17 22:24:09 +00006649 RevertToOldSizeRAII RAII(Path);
6650
Richard Smithf4e248c2018-08-01 00:33:25 +00006651 Expr *Old;
6652 do {
6653 Old = Init;
Richard Smithd87aab92018-07-17 22:24:09 +00006654
Richard Smithf4e248c2018-08-01 00:33:25 +00006655 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6656 // constructor inherits one as an implicit mem-initializer.
6657 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6658 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
6659 Init = DIE->getExpr();
6660 }
Richard Smithafe48f92018-07-23 21:21:22 +00006661
Bill Wendling7c44da22018-10-31 03:48:47 +00006662 if (auto *FE = dyn_cast<FullExpr>(Init))
6663 Init = FE->getSubExpr();
Richard Smithe6c01442013-06-05 00:46:14 +00006664
Richard Smithf4e248c2018-08-01 00:33:25 +00006665 // Dig out the expression which constructs the extended temporary.
6666 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6667
6668 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6669 Init = BTE->getSubExpr();
6670
6671 Init = Init->IgnoreParens();
6672
6673 // Step over value-preserving rvalue casts.
6674 if (auto *CE = dyn_cast<CastExpr>(Init)) {
6675 switch (CE->getCastKind()) {
6676 case CK_LValueToRValue:
6677 // If we can match the lvalue to a const object, we can look at its
6678 // initializer.
6679 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
6680 return visitLocalsRetainedByReferenceBinding(
6681 Path, Init, RK_ReferenceBinding,
6682 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
6683 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
6684 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6685 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
6686 !isVarOnPath(Path, VD)) {
6687 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6688 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true);
6689 }
6690 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
6691 if (MTE->getType().isConstQualified())
6692 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
6693 Visit, true);
6694 }
6695 return false;
6696 });
6697
6698 // We assume that objects can be retained by pointers cast to integers,
6699 // but not if the integer is cast to floating-point type or to _Complex.
6700 // We assume that casts to 'bool' do not preserve enough information to
6701 // retain a local object.
6702 case CK_NoOp:
6703 case CK_BitCast:
6704 case CK_BaseToDerived:
6705 case CK_DerivedToBase:
6706 case CK_UncheckedDerivedToBase:
6707 case CK_Dynamic:
6708 case CK_ToUnion:
6709 case CK_UserDefinedConversion:
6710 case CK_ConstructorConversion:
6711 case CK_IntegralToPointer:
6712 case CK_PointerToIntegral:
6713 case CK_VectorSplat:
6714 case CK_IntegralCast:
6715 case CK_CPointerToObjCPointerCast:
6716 case CK_BlockPointerToObjCPointerCast:
6717 case CK_AnyPointerToBlockPointerCast:
6718 case CK_AddressSpaceConversion:
6719 break;
6720
6721 case CK_ArrayToPointerDecay:
6722 // Model array-to-pointer decay as taking the address of the array
6723 // lvalue.
6724 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
6725 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
6726 RK_ReferenceBinding, Visit);
6727
6728 default:
6729 return;
6730 }
6731
6732 Init = CE->getSubExpr();
6733 }
6734 } while (Old != Init);
Richard Smith736a9472013-06-12 20:42:33 +00006735
Richard Smithd87aab92018-07-17 22:24:09 +00006736 // C++17 [dcl.init.list]p6:
6737 // initializing an initializer_list object from the array extends the
6738 // lifetime of the array exactly like binding a reference to a temporary.
6739 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
Richard Smithca975b22018-07-23 18:50:26 +00006740 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
6741 RK_StdInitializerList, Visit);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006742
Richard Smithe6c01442013-06-05 00:46:14 +00006743 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006744 // We already visited the elements of this initializer list while
6745 // performing the initialization. Don't visit them again unless we've
6746 // changed the lifetime of the initialized entity.
6747 if (!RevisitSubinits)
6748 return;
6749
Richard Smithd87aab92018-07-17 22:24:09 +00006750 if (ILE->isTransparent())
Richard Smithca975b22018-07-23 18:50:26 +00006751 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
6752 RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006753
Richard Smithcc1b96d2013-06-12 22:31:48 +00006754 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006755 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Richard Smithca975b22018-07-23 18:50:26 +00006756 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
6757 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006758 return;
6759 }
6760
Richard Smithcc1b96d2013-06-12 22:31:48 +00006761 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006762 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6763
6764 // If we lifetime-extend a braced initializer which is initializing an
6765 // aggregate, and that aggregate contains reference members which are
6766 // bound to temporaries, those temporaries are also lifetime-extended.
6767 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6768 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006769 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
6770 RK_ReferenceBinding, Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006771 else {
6772 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006773 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006774 if (Index >= ILE->getNumInits())
6775 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006776 if (I->isUnnamedBitfield())
6777 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006778 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006779 if (I->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006780 visitLocalsRetainedByReferenceBinding(Path, SubInit,
6781 RK_ReferenceBinding, Visit);
Richard Smithd87aab92018-07-17 22:24:09 +00006782 else
6783 // This might be either aggregate-initialization of a member or
6784 // initialization of a std::initializer_list object. Regardless,
Richard Smithe6c01442013-06-05 00:46:14 +00006785 // we should recursively lifetime-extend that initializer.
Richard Smithca975b22018-07-23 18:50:26 +00006786 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
6787 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006788 ++Index;
6789 }
6790 }
6791 }
Richard Smithca975b22018-07-23 18:50:26 +00006792 return;
6793 }
6794
Richard Smithb3d203f2018-10-19 19:01:34 +00006795 // The lifetime of an init-capture is that of the closure object constructed
6796 // by a lambda-expression.
6797 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
6798 for (Expr *E : LE->capture_inits()) {
6799 if (!E)
6800 continue;
6801 if (E->isGLValue())
6802 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
6803 Visit);
6804 else
6805 visitLocalsRetainedByInitializer(Path, E, Visit, true);
6806 }
6807 }
6808
Richard Smithf4e248c2018-08-01 00:33:25 +00006809 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init))
6810 return visitLifetimeBoundArguments(Path, Init, Visit);
Richard Smithafe48f92018-07-23 21:21:22 +00006811
Richard Smithafe48f92018-07-23 21:21:22 +00006812 switch (Init->getStmtClass()) {
6813 case Stmt::UnaryOperatorClass: {
6814 auto *UO = cast<UnaryOperator>(Init);
6815 // If the initializer is the address of a local, we could have a lifetime
6816 // problem.
6817 if (UO->getOpcode() == UO_AddrOf) {
Richard Smith0e3102d2018-07-24 00:55:08 +00006818 // If this is &rvalue, then it's ill-formed and we have already diagnosed
6819 // it. Don't produce a redundant warning about the lifetime of the
6820 // temporary.
6821 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
6822 return;
6823
Richard Smithafe48f92018-07-23 21:21:22 +00006824 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
6825 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
6826 RK_ReferenceBinding, Visit);
6827 }
6828 break;
6829 }
6830
6831 case Stmt::BinaryOperatorClass: {
6832 // Handle pointer arithmetic.
6833 auto *BO = cast<BinaryOperator>(Init);
6834 BinaryOperatorKind BOK = BO->getOpcode();
6835 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
6836 break;
6837
6838 if (BO->getLHS()->getType()->isPointerType())
6839 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
6840 else if (BO->getRHS()->getType()->isPointerType())
6841 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
6842 break;
6843 }
6844
6845 case Stmt::ConditionalOperatorClass:
6846 case Stmt::BinaryConditionalOperatorClass: {
6847 auto *C = cast<AbstractConditionalOperator>(Init);
6848 // In C++, we can have a throw-expression operand, which has 'void' type
6849 // and isn't interesting from a lifetime perspective.
6850 if (!C->getTrueExpr()->getType()->isVoidType())
6851 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
6852 if (!C->getFalseExpr()->getType()->isVoidType())
6853 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
6854 break;
6855 }
6856
6857 case Stmt::BlockExprClass:
6858 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
6859 // This is a local block, whose lifetime is that of the function.
6860 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
6861 }
6862 break;
6863
6864 case Stmt::AddrLabelExprClass:
6865 // We want to warn if the address of a label would escape the function.
6866 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
6867 break;
6868
6869 default:
6870 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006871 }
6872}
6873
Richard Smithd87aab92018-07-17 22:24:09 +00006874/// Determine whether this is an indirect path to a temporary that we are
6875/// supposed to lifetime-extend along (but don't).
Richard Smithca975b22018-07-23 18:50:26 +00006876static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
Richard Smithd87aab92018-07-17 22:24:09 +00006877 for (auto Elem : Path) {
Richard Smithf66e4f72018-07-23 22:56:45 +00006878 if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
Richard Smithd87aab92018-07-17 22:24:09 +00006879 return false;
6880 }
6881 return true;
6882}
6883
Richard Smith6a32c052018-07-23 21:21:24 +00006884/// Find the range for the first interesting entry in the path at or after I.
6885static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
6886 Expr *E) {
6887 for (unsigned N = Path.size(); I != N; ++I) {
6888 switch (Path[I].Kind) {
6889 case IndirectLocalPathEntry::AddressOf:
6890 case IndirectLocalPathEntry::LValToRVal:
Richard Smithf4e248c2018-08-01 00:33:25 +00006891 case IndirectLocalPathEntry::LifetimeBoundCall:
Richard Smith6a32c052018-07-23 21:21:24 +00006892 // These exist primarily to mark the path as not permitting or
6893 // supporting lifetime extension.
6894 break;
6895
6896 case IndirectLocalPathEntry::DefaultInit:
6897 case IndirectLocalPathEntry::VarInit:
6898 return Path[I].E->getSourceRange();
6899 }
6900 }
6901 return E->getSourceRange();
6902}
6903
Richard Smithd87aab92018-07-17 22:24:09 +00006904void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
6905 Expr *Init) {
Richard Smithca975b22018-07-23 18:50:26 +00006906 LifetimeResult LR = getEntityLifetime(&Entity);
Richard Smithd87aab92018-07-17 22:24:09 +00006907 LifetimeKind LK = LR.getInt();
6908 const InitializedEntity *ExtendingEntity = LR.getPointer();
6909
6910 // If this entity doesn't have an interesting lifetime, don't bother looking
6911 // for temporaries within its initializer.
6912 if (LK == LK_FullExpression)
6913 return;
6914
Richard Smithca975b22018-07-23 18:50:26 +00006915 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
6916 ReferenceKind RK) -> bool {
Richard Smith6a32c052018-07-23 21:21:24 +00006917 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
6918 SourceLocation DiagLoc = DiagRange.getBegin();
Richard Smithca975b22018-07-23 18:50:26 +00006919
Richard Smithd87aab92018-07-17 22:24:09 +00006920 switch (LK) {
6921 case LK_FullExpression:
6922 llvm_unreachable("already handled this");
6923
Richard Smithafe48f92018-07-23 21:21:22 +00006924 case LK_Extended: {
6925 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
Richard Smith0e3102d2018-07-24 00:55:08 +00006926 if (!MTE) {
6927 // The initialized entity has lifetime beyond the full-expression,
6928 // and the local entity does too, so don't warn.
6929 //
6930 // FIXME: We should consider warning if a static / thread storage
6931 // duration variable retains an automatic storage duration local.
Richard Smithafe48f92018-07-23 21:21:22 +00006932 return false;
Richard Smith0e3102d2018-07-24 00:55:08 +00006933 }
Richard Smithafe48f92018-07-23 21:21:22 +00006934
Richard Smithd87aab92018-07-17 22:24:09 +00006935 // Lifetime-extend the temporary.
6936 if (Path.empty()) {
6937 // Update the storage duration of the materialized temporary.
6938 // FIXME: Rebuild the expression instead of mutating it.
6939 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
6940 ExtendingEntity->allocateManglingNumber());
6941 // Also visit the temporaries lifetime-extended by this initializer.
6942 return true;
6943 }
6944
6945 if (shouldLifetimeExtendThroughPath(Path)) {
6946 // We're supposed to lifetime-extend the temporary along this path (per
6947 // the resolution of DR1815), but we don't support that yet.
6948 //
Richard Smith0e3102d2018-07-24 00:55:08 +00006949 // FIXME: Properly handle this situation. Perhaps the easiest approach
Richard Smithd87aab92018-07-17 22:24:09 +00006950 // would be to clone the initializer expression on each use that would
6951 // lifetime extend its temporaries.
Richard Smith0e3102d2018-07-24 00:55:08 +00006952 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
6953 << RK << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00006954 } else {
Richard Smith0e3102d2018-07-24 00:55:08 +00006955 // If the path goes through the initialization of a variable or field,
6956 // it can't possibly reach a temporary created in this full-expression.
6957 // We will have already diagnosed any problems with the initializer.
6958 if (pathContainsInit(Path))
6959 return false;
6960
6961 Diag(DiagLoc, diag::warn_dangling_variable)
Richard Smithad5bbcc2018-08-01 01:03:33 +00006962 << RK << !Entity.getParent()
6963 << ExtendingEntity->getDecl()->isImplicit()
6964 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00006965 }
6966 break;
Richard Smithafe48f92018-07-23 21:21:22 +00006967 }
Richard Smithd87aab92018-07-17 22:24:09 +00006968
Richard Smithafe48f92018-07-23 21:21:22 +00006969 case LK_MemInitializer: {
George Burgess IV06df2292018-07-24 02:10:53 +00006970 if (isa<MaterializeTemporaryExpr>(L)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006971 // Under C++ DR1696, if a mem-initializer (or a default member
6972 // initializer used by the absence of one) would lifetime-extend a
6973 // temporary, the program is ill-formed.
6974 if (auto *ExtendingDecl =
6975 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
6976 bool IsSubobjectMember = ExtendingEntity != &Entity;
Richard Smith0e3102d2018-07-24 00:55:08 +00006977 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
6978 ? diag::err_dangling_member
6979 : diag::warn_dangling_member)
Richard Smithafe48f92018-07-23 21:21:22 +00006980 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
6981 // Don't bother adding a note pointing to the field if we're inside
6982 // its default member initializer; our primary diagnostic points to
6983 // the same place in that case.
6984 if (Path.empty() ||
6985 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
6986 Diag(ExtendingDecl->getLocation(),
6987 diag::note_lifetime_extending_member_declared_here)
6988 << RK << IsSubobjectMember;
6989 }
6990 } else {
6991 // We have a mem-initializer but no particular field within it; this
6992 // is either a base class or a delegating initializer directly
6993 // initializing the base-class from something that doesn't live long
6994 // enough.
6995 //
6996 // FIXME: Warn on this.
6997 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00006998 }
6999 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00007000 // Paths via a default initializer can only occur during error recovery
7001 // (there's no other way that a default initializer can refer to a
7002 // local). Don't produce a bogus warning on those cases.
Richard Smith0e3102d2018-07-24 00:55:08 +00007003 if (pathContainsInit(Path))
Richard Smithafe48f92018-07-23 21:21:22 +00007004 return false;
7005
7006 auto *DRE = dyn_cast<DeclRefExpr>(L);
7007 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7008 if (!VD) {
7009 // A member was initialized to a local block.
7010 // FIXME: Warn on this.
7011 return false;
7012 }
7013
7014 if (auto *Member =
7015 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
7016 bool IsPointer = Member->getType()->isAnyPointerType();
7017 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
7018 : diag::warn_bind_ref_member_to_parameter)
7019 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
7020 Diag(Member->getLocation(),
7021 diag::note_ref_or_ptr_member_declared_here)
7022 << (unsigned)IsPointer;
7023 }
Richard Smithd87aab92018-07-17 22:24:09 +00007024 }
7025 break;
Richard Smithafe48f92018-07-23 21:21:22 +00007026 }
Richard Smithd87aab92018-07-17 22:24:09 +00007027
7028 case LK_New:
George Burgess IV06df2292018-07-24 02:10:53 +00007029 if (isa<MaterializeTemporaryExpr>(L)) {
Richard Smithafe48f92018-07-23 21:21:22 +00007030 Diag(DiagLoc, RK == RK_ReferenceBinding
7031 ? diag::warn_new_dangling_reference
7032 : diag::warn_new_dangling_initializer_list)
Richard Smith0e3102d2018-07-24 00:55:08 +00007033 << !Entity.getParent() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00007034 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00007035 // We can't determine if the allocation outlives the local declaration.
7036 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00007037 }
7038 break;
7039
7040 case LK_Return:
Richard Smith67af95b2018-07-23 19:19:08 +00007041 case LK_StmtExprResult:
Richard Smithafe48f92018-07-23 21:21:22 +00007042 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7043 // We can't determine if the local variable outlives the statement
7044 // expression.
7045 if (LK == LK_StmtExprResult)
7046 return false;
7047 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
7048 << Entity.getType()->isReferenceType() << DRE->getDecl()
7049 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
7050 } else if (isa<BlockExpr>(L)) {
7051 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
7052 } else if (isa<AddrLabelExpr>(L)) {
Reid Kleckner4c33d192018-08-17 22:11:31 +00007053 // Don't warn when returning a label from a statement expression.
7054 // Leaving the scope doesn't end its lifetime.
7055 if (LK == LK_StmtExprResult)
7056 return false;
Richard Smithafe48f92018-07-23 21:21:22 +00007057 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
7058 } else {
7059 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
7060 << Entity.getType()->isReferenceType() << DiagRange;
7061 }
7062 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00007063 }
7064
Richard Smithafe48f92018-07-23 21:21:22 +00007065 for (unsigned I = 0; I != Path.size(); ++I) {
7066 auto Elem = Path[I];
7067
Richard Smithca975b22018-07-23 18:50:26 +00007068 switch (Elem.Kind) {
Richard Smithafe48f92018-07-23 21:21:22 +00007069 case IndirectLocalPathEntry::AddressOf:
7070 case IndirectLocalPathEntry::LValToRVal:
Richard Smith6a32c052018-07-23 21:21:24 +00007071 // These exist primarily to mark the path as not permitting or
7072 // supporting lifetime extension.
Richard Smithca975b22018-07-23 18:50:26 +00007073 break;
7074
Richard Smithf4e248c2018-08-01 00:33:25 +00007075 case IndirectLocalPathEntry::LifetimeBoundCall:
7076 // FIXME: Consider adding a note for this.
7077 break;
7078
Richard Smithafe48f92018-07-23 21:21:22 +00007079 case IndirectLocalPathEntry::DefaultInit: {
7080 auto *FD = cast<FieldDecl>(Elem.D);
7081 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
Richard Smith6a32c052018-07-23 21:21:24 +00007082 << FD << nextPathEntryRange(Path, I + 1, L);
Richard Smithafe48f92018-07-23 21:21:22 +00007083 break;
7084 }
7085
7086 case IndirectLocalPathEntry::VarInit:
7087 const VarDecl *VD = cast<VarDecl>(Elem.D);
7088 Diag(VD->getLocation(), diag::note_local_var_initializer)
Richard Smithad5bbcc2018-08-01 01:03:33 +00007089 << VD->getType()->isReferenceType()
7090 << VD->isImplicit() << VD->getDeclName()
Richard Smith6a32c052018-07-23 21:21:24 +00007091 << nextPathEntryRange(Path, I + 1, L);
Richard Smithca975b22018-07-23 18:50:26 +00007092 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00007093 }
7094 }
Richard Smithd87aab92018-07-17 22:24:09 +00007095
7096 // We didn't lifetime-extend, so don't go any further; we don't need more
7097 // warnings or errors on inner temporaries within this one's initializer.
7098 return false;
7099 };
7100
Richard Smithca975b22018-07-23 18:50:26 +00007101 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
Richard Smithd87aab92018-07-17 22:24:09 +00007102 if (Init->isGLValue())
Richard Smithca975b22018-07-23 18:50:26 +00007103 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
7104 TemporaryVisitor);
Richard Smithd87aab92018-07-17 22:24:09 +00007105 else
Richard Smithca975b22018-07-23 18:50:26 +00007106 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007107}
7108
Richard Smithaaa0ec42013-09-21 21:19:19 +00007109static void DiagnoseNarrowingInInitList(Sema &S,
7110 const ImplicitConversionSequence &ICS,
7111 QualType PreNarrowingType,
7112 QualType EntityType,
7113 const Expr *PostInit);
7114
Richard Trieuac3eca52015-04-29 01:52:17 +00007115/// Provide warnings when std::move is used on construction.
7116static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7117 bool IsReturnStmt) {
7118 if (!InitExpr)
7119 return;
7120
Richard Smith51ec0cf2017-02-21 01:17:38 +00007121 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00007122 return;
7123
Richard Trieuac3eca52015-04-29 01:52:17 +00007124 QualType DestType = InitExpr->getType();
7125 if (!DestType->isRecordType())
7126 return;
7127
7128 unsigned DiagID = 0;
7129 if (IsReturnStmt) {
7130 const CXXConstructExpr *CCE =
7131 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7132 if (!CCE || CCE->getNumArgs() != 1)
7133 return;
7134
7135 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7136 return;
7137
7138 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00007139 }
7140
7141 // Find the std::move call and get the argument.
7142 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
Nico Weber192184c2018-06-20 15:57:38 +00007143 if (!CE || !CE->isCallToStdMove())
Richard Trieuac3eca52015-04-29 01:52:17 +00007144 return;
7145
7146 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7147
7148 if (IsReturnStmt) {
7149 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7150 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7151 return;
7152
7153 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7154 if (!VD || !VD->hasLocalStorage())
7155 return;
7156
Alex Lorenzbbe51d82017-11-07 21:40:11 +00007157 // __block variables are not moved implicitly.
7158 if (VD->hasAttr<BlocksAttr>())
7159 return;
7160
Richard Trieu8d4006a2015-07-28 19:06:16 +00007161 QualType SourceType = VD->getType();
7162 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00007163 return;
7164
Richard Trieu8d4006a2015-07-28 19:06:16 +00007165 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00007166 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00007167 }
7168
Davide Italiano7842c3f2015-07-18 01:15:19 +00007169 // If we're returning a function parameter, copy elision
7170 // is not possible.
7171 if (isa<ParmVarDecl>(VD))
7172 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00007173 else
7174 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007175 } else {
7176 DiagID = diag::warn_pessimizing_move_on_initialization;
7177 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7178 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
7179 return;
7180 }
7181
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007182 S.Diag(CE->getBeginLoc(), DiagID);
Richard Trieuac3eca52015-04-29 01:52:17 +00007183
7184 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7185 // is within a macro.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007186 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
Richard Trieuac3eca52015-04-29 01:52:17 +00007187 if (CallBegin.isMacroID())
7188 return;
7189 SourceLocation RParen = CE->getRParenLoc();
7190 if (RParen.isMacroID())
7191 return;
7192 SourceLocation LParen;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007193 SourceLocation ArgLoc = Arg->getBeginLoc();
Richard Trieuac3eca52015-04-29 01:52:17 +00007194
7195 // Special testing for the argument location. Since the fix-it needs the
7196 // location right before the argument, the argument location can be in a
7197 // macro only if it is at the beginning of the macro.
7198 while (ArgLoc.isMacroID() &&
7199 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
Richard Smithb5f81712018-04-30 05:25:48 +00007200 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
Richard Trieuac3eca52015-04-29 01:52:17 +00007201 }
7202
7203 if (LParen.isMacroID())
7204 return;
7205
7206 LParen = ArgLoc.getLocWithOffset(-1);
7207
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007208 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
Richard Trieuac3eca52015-04-29 01:52:17 +00007209 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7210 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7211}
7212
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007213static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7214 // Check to see if we are dereferencing a null pointer. If so, this is
7215 // undefined behavior, so warn about it. This only handles the pattern
7216 // "*null", which is a very syntactic check.
7217 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7218 if (UO->getOpcode() == UO_Deref &&
7219 UO->getSubExpr()->IgnoreParenCasts()->
7220 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7221 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7222 S.PDiag(diag::warn_binding_null_to_reference)
7223 << UO->getSubExpr()->getSourceRange());
7224 }
7225}
7226
Tim Shen4a05bb82016-06-21 20:29:17 +00007227MaterializeTemporaryExpr *
7228Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7229 bool BoundToLvalueReference) {
7230 auto MTE = new (Context)
7231 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7232
7233 // Order an ExprWithCleanups for lifetime marks.
7234 //
7235 // TODO: It'll be good to have a single place to check the access of the
7236 // destructor and generate ExprWithCleanups for various uses. Currently these
7237 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7238 // but there may be a chance to merge them.
7239 Cleanup.setExprNeedsCleanups(false);
7240 return MTE;
7241}
7242
Richard Smith4baaa5a2016-12-03 01:14:32 +00007243ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7244 // In C++98, we don't want to implicitly create an xvalue.
7245 // FIXME: This means that AST consumers need to deal with "prvalues" that
7246 // denote materialized temporaries. Maybe we should add another ValueKind
7247 // for "xvalue pretending to be a prvalue" for C++98 support.
7248 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
7249 return E;
7250
7251 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00007252 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7253 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00007254 QualType T = E->getType();
7255 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7256 return ExprError();
7257
7258 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7259}
7260
Anastasia Stulova04307942018-11-16 16:22:56 +00007261ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7262 ExprValueKind VK,
7263 CheckedConversionKind CCK) {
7264 CastKind CK = (Ty.getAddressSpace() != E->getType().getAddressSpace())
7265 ? CK_AddressSpaceConversion
7266 : CK_NoOp;
7267 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7268}
7269
7270ExprResult InitializationSequence::Perform(Sema &S,
7271 const InitializedEntity &Entity,
7272 const InitializationKind &Kind,
7273 MultiExprArg Args,
7274 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007275 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007276 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00007277 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007278 }
Nico Weber337d5aa2015-04-17 08:32:38 +00007279 if (!ZeroInitializationFixit.empty()) {
7280 unsigned DiagID = diag::err_default_init_const;
7281 if (Decl *D = Entity.getDecl())
7282 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
7283 DiagID = diag::ext_default_init_const;
7284
7285 // The initialization would have succeeded with this fixit. Since the fixit
7286 // is on the error, we need to build a valid AST in this case, so this isn't
7287 // handled in the Failed() branch above.
7288 QualType DestType = Entity.getType();
7289 S.Diag(Kind.getLocation(), DiagID)
7290 << DestType << (bool)DestType->getAs<RecordType>()
7291 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7292 ZeroInitializationFixit);
7293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007294
Sebastian Redld201edf2011-06-05 13:59:11 +00007295 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007296 // If the declaration is a non-dependent, incomplete array type
7297 // that has an initializer, then its type will be completed once
7298 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00007299 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00007300 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007301 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007302 if (const IncompleteArrayType *ArrayT
7303 = S.Context.getAsIncompleteArrayType(DeclType)) {
7304 // FIXME: We don't currently have the ability to accurately
7305 // compute the length of an initializer list without
7306 // performing full type-checking of the initializer list
7307 // (since we have to determine where braces are implicitly
7308 // introduced and such). So, we fall back to making the array
7309 // type a dependently-sized array type with no specified
7310 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007311 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007312 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00007313
Douglas Gregor51e77d52009-12-10 17:56:55 +00007314 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00007315 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007316 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7317 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007318 if (IncompleteArrayTypeLoc ArrayLoc =
7319 TL.getAs<IncompleteArrayTypeLoc>())
7320 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00007321 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007322 }
7323
7324 *ResultType
7325 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007326 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00007327 ArrayT->getSizeModifier(),
7328 ArrayT->getIndexTypeCVRQualifiers(),
7329 Brackets);
7330 }
7331
7332 }
7333 }
Sebastian Redla9351792012-02-11 23:51:47 +00007334 if (Kind.getKind() == InitializationKind::IK_Direct &&
7335 !Kind.isExplicitCast()) {
7336 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00007337 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00007338 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007339 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00007340 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00007341 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Fangrui Song6907ce22018-07-30 19:24:48 +00007342 Kind.isExplicitCast() ||
Douglas Gregorbf138952012-04-04 04:06:51 +00007343 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007344 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007345 }
7346
Sebastian Redld201edf2011-06-05 13:59:11 +00007347 // No steps means no initialization.
7348 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007349 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007350
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007351 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007352 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007353 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00007354 // Produce a C++98 compatibility warning if we are initializing a reference
7355 // from an initializer list. For parameters, we produce a better warning
7356 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007357 Expr *Init = Args[0];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007358 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7359 << Init->getSourceRange();
Richard Smith2b349ae2012-04-19 06:58:00 +00007360 }
7361
Egor Churaev3bccec52017-04-05 12:47:10 +00007362 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7363 QualType ETy = Entity.getType();
7364 Qualifiers TyQualifiers = ETy.getQualifiers();
7365 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
7366 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
7367
7368 if (S.getLangOpts().OpenCLVersion >= 200 &&
7369 ETy->isAtomicType() && !HasGlobalAS &&
7370 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007371 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7372 << 1
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007373 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
Egor Churaev3bccec52017-04-05 12:47:10 +00007374 return ExprError();
7375 }
7376
Douglas Gregor1b303932009-12-22 15:35:07 +00007377 QualType DestType = Entity.getType().getNonReferenceType();
7378 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00007379 // the same as Entity.getDecl()->getType() in cases involving type merging,
7380 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00007381 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00007382 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00007383 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007384
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007385 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00007386 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007387
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007388 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00007389 // grab the only argument out the Args and place it into the "current"
7390 // initializer.
7391 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007392 case SK_ResolveAddressOfOverloadedFunction:
7393 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007394 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007395 case SK_CastDerivedToBaseLValue:
7396 case SK_BindReference:
7397 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00007398 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007399 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00007400 case SK_UserConversion:
7401 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007402 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007403 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00007404 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00007405 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007406 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00007407 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00007408 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00007409 case SK_UnwrapInitList:
7410 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00007411 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00007412 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007413 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00007414 case SK_ArrayLoopIndex:
7415 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00007416 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00007417 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00007418 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00007419 case SK_PassByIndirectCopyRestore:
7420 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00007421 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007422 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00007423 case SK_OCLSamplerInit:
Andrew Savonichevb555b762018-10-23 15:19:20 +00007424 case SK_OCLZeroOpaqueType: {
Douglas Gregore1314a62009-12-18 05:02:21 +00007425 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007426 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00007427 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00007428 break;
John McCall34376a62010-12-04 03:47:34 +00007429 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007430
Douglas Gregore1314a62009-12-18 05:02:21 +00007431 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00007432 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007433 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00007434 case SK_ZeroInitialization:
7435 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007437
Richard Smithd6a15082017-01-07 00:48:55 +00007438 // Promote from an unevaluated context to an unevaluated list context in
7439 // C++11 list-initialization; we need to instantiate entities usable in
7440 // constant expressions here in order to perform narrowing checks =(
7441 EnterExpressionEvaluationContext Evaluated(
7442 S, EnterExpressionEvaluationContext::InitList,
7443 CurInit.get() && isa<InitListExpr>(CurInit.get()));
7444
Richard Smith81f5ade2016-12-15 02:28:18 +00007445 // C++ [class.abstract]p2:
7446 // no objects of an abstract class can be created except as subobjects
7447 // of a class derived from it
7448 auto checkAbstractType = [&](QualType T) -> bool {
7449 if (Entity.getKind() == InitializedEntity::EK_Base ||
7450 Entity.getKind() == InitializedEntity::EK_Delegating)
7451 return false;
7452 return S.RequireNonAbstractType(Kind.getLocation(), T,
7453 diag::err_allocation_of_abstract_type);
7454 };
7455
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007456 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007457 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007458 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007459 for (step_iterator Step = step_begin(), StepEnd = step_end();
7460 Step != StepEnd; ++Step) {
7461 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007462 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007463
John Wiegley01296292011-04-08 18:41:53 +00007464 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007465
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007466 switch (Step->Kind) {
7467 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007468 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007469 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00007470 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00007471 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7472 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007473 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00007474 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00007475 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007476 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007477
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007478 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007479 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007480 case SK_CastDerivedToBaseLValue: {
7481 // We have a derived-to-base cast that produces either an rvalue or an
7482 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007483
John McCallcf142162010-08-07 06:22:56 +00007484 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00007485
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007486 // Casts to inaccessible base classes are allowed with C-style casts.
7487 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007488 if (S.CheckDerivedToBaseConversion(
7489 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
7490 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00007491 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492
John McCall2536c6d2010-08-25 10:28:54 +00007493 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007494 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007495 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007496 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007497 VK_XValue :
7498 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007499 CurInit =
7500 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
7501 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007502 break;
7503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007504
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007505 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007506 // Reference binding does not have any corresponding ASTs.
7507
7508 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007509 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007510 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007511
George Burgess IVcfd48d92017-04-13 23:47:08 +00007512 // We don't check for e.g. function pointers here, since address
7513 // availability checks should only occur when the function first decays
7514 // into a pointer or reference.
7515 if (CurInit.get()->getType()->isFunctionProtoType()) {
7516 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7517 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7518 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007519 DRE->getBeginLoc()))
George Burgess IVcfd48d92017-04-13 23:47:08 +00007520 return ExprError();
7521 }
7522 }
7523 }
7524
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007525 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007526 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007527
Richard Smithe6c01442013-06-05 00:46:14 +00007528 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00007529 // Make sure the "temporary" is actually an rvalue.
7530 assert(CurInit.get()->isRValue() && "not a temporary");
7531
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007532 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007533 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007534 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007535
Douglas Gregorfe314812011-06-21 17:03:29 +00007536 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007537 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00007538 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
Richard Smithd87aab92018-07-17 22:24:09 +00007539 CurInit = MTE;
David Majnemerdaff3702014-05-01 17:50:17 +00007540
Brian Kelley762f9282017-03-29 18:16:38 +00007541 // If we're extending this temporary to automatic storage duration -- we
7542 // need to register its cleanup during the full-expression's cleanups.
7543 if (MTE->getStorageDuration() == SD_Automatic &&
7544 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00007545 S.Cleanup.setExprNeedsCleanups(true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007546 break;
Richard Smithe6c01442013-06-05 00:46:14 +00007547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007548
Richard Smithb8c0f552016-12-09 18:49:13 +00007549 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00007550 if (checkAbstractType(Step->Type))
7551 return ExprError();
7552
Richard Smithb8c0f552016-12-09 18:49:13 +00007553 // If the overall initialization is initializing a temporary, we already
7554 // bound our argument if it was necessary to do so. If not (if we're
7555 // ultimately initializing a non-temporary), our argument needs to be
7556 // bound since it's initializing a function parameter.
7557 // FIXME: This is a mess. Rationalize temporary destruction.
7558 if (!shouldBindAsTemporary(Entity))
7559 CurInit = S.MaybeBindToTemporary(CurInit.get());
7560 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7561 /*IsExtraneousCopy=*/false);
7562 break;
7563
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007564 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007565 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007566 /*IsExtraneousCopy=*/true);
7567 break;
7568
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007569 case SK_UserConversion: {
7570 // We have a user-defined conversion that invokes either a constructor
7571 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00007572 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00007573 FunctionDecl *Fn = Step->Function.Function;
7574 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007575 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00007576 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00007577 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007578 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00007579 SmallVector<Expr*, 8> ConstructorArgs;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007580 SourceLocation Loc = CurInit.get()->getBeginLoc();
John McCall760af172010-02-01 03:16:54 +00007581
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007582 // Determine the arguments required to actually perform the constructor
7583 // call.
John Wiegley01296292011-04-08 18:41:53 +00007584 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007585 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00007586 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007587 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00007588 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007589
Richard Smithb24f0672012-02-11 19:22:50 +00007590 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00007591 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
7592 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007593 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007594 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00007595 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007596 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00007597 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00007598 CXXConstructExpr::CK_Complete,
7599 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007600 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007601 return ExprError();
John McCall760af172010-02-01 03:16:54 +00007602
Richard Smith5179eb72016-06-28 19:03:57 +00007603 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7604 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00007605 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7606 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007607
John McCalle3027922010-08-25 11:45:40 +00007608 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00007609 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007610 } else {
7611 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00007612 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00007613 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00007614 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00007615 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7616 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007617
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007618 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7619 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00007620 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007621 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007622
John McCalle3027922010-08-25 11:45:40 +00007623 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00007624 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007626
Richard Smith81f5ade2016-12-15 02:28:18 +00007627 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7628 return ExprError();
7629
Richard Smithb8c0f552016-12-09 18:49:13 +00007630 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
7631 CastKind, CurInit.get(), nullptr,
7632 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00007633
Richard Smithb8c0f552016-12-09 18:49:13 +00007634 if (shouldBindAsTemporary(Entity))
7635 // The overall entity is temporary, so this expression should be
7636 // destroyed at the end of its full-expression.
7637 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7638 else if (CreatedObject && shouldDestroyEntity(Entity)) {
7639 // The object outlasts the full-expression, but we need to prepare for
7640 // a destructor being run on it.
7641 // FIXME: It makes no sense to do this here. This should happen
7642 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00007643 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00007644 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007645 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00007646 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007647 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00007648 S.PDiag(diag::err_access_dtor_temp) << T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007649 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
7650 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
Richard Smith22262ab2013-05-04 06:44:46 +00007651 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00007652 }
7653 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007654 break;
7655 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007656
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007657 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007658 case SK_QualificationConversionXValue:
7659 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007660 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00007661 ExprValueKind VK =
Anastasia Stulova04307942018-11-16 16:22:56 +00007662 Step->Kind == SK_QualificationConversionLValue
7663 ? VK_LValue
7664 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
7665 : VK_RValue);
7666 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007667 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007668 }
7669
Richard Smith77be48a2014-07-31 06:31:19 +00007670 case SK_AtomicConversion: {
7671 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7672 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7673 CK_NonAtomicToAtomic, VK_RValue);
7674 break;
7675 }
7676
Jordan Roseb1312a52013-04-11 00:58:58 +00007677 case SK_LValueToRValue: {
7678 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Richard Smith35018952018-11-03 02:23:33 +00007679 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7680 CK_LValueToRValue, CurInit.get(),
7681 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00007682 break;
7683 }
7684
Richard Smithaaa0ec42013-09-21 21:19:19 +00007685 case SK_ConversionSequence:
7686 case SK_ConversionSequenceNoNarrowing: {
7687 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007688 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7689 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007690 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007691 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007692 ExprResult CurInitExprRes =
7693 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007694 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007695 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007696 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007697
7698 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7699
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007700 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007701
7702 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007703 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007704 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7705 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007706
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007707 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007709
Douglas Gregor51e77d52009-12-10 17:56:55 +00007710 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007711 if (checkAbstractType(Step->Type))
7712 return ExprError();
7713
John Wiegley01296292011-04-08 18:41:53 +00007714 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007715 // If we're not initializing the top-level entity, we need to create an
7716 // InitializeTemporary entity for our target type.
7717 QualType Ty = Step->Type;
7718 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007719 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007720 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7721 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007722 InitList, Ty, /*VerifyOnly=*/false,
7723 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007724 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007725 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007726
Richard Smithcc1b96d2013-06-12 22:31:48 +00007727 // Hack: We must update *ResultType if available in order to set the
7728 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7729 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7730 if (ResultType &&
7731 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007732 if ((*ResultType)->isRValueReferenceType())
7733 Ty = S.Context.getRValueReferenceType(Ty);
7734 else if ((*ResultType)->isLValueReferenceType())
7735 Ty = S.Context.getLValueReferenceType(Ty,
7736 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7737 *ResultType = Ty;
7738 }
7739
7740 InitListExpr *StructuredInitList =
7741 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007742 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007743 CurInit = shouldBindAsTemporary(InitEntity)
7744 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007745 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007746 break;
7747 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007748
Richard Smith53324112014-07-16 21:33:43 +00007749 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007750 if (checkAbstractType(Step->Type))
7751 return ExprError();
7752
Sebastian Redl5a41f682012-02-12 16:37:24 +00007753 // When an initializer list is passed for a parameter of type "reference
7754 // to object", we don't get an EK_Temporary entity, but instead an
7755 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007756 // FIXME: This is a hack. What we really should do is create a user
7757 // conversion step for this case, but this makes it considerably more
7758 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007759 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7760 Entity.getType().getNonReferenceType());
7761 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007762 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007763 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007764 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7765 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007766 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007767 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7768 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007769 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007770 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007771 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007772 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007773 InitList->getLBraceLoc(),
7774 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007775 break;
7776 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007777
Sebastian Redl29526f02011-11-27 16:50:07 +00007778 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007779 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007780 break;
7781
7782 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007783 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007784 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7785 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007786 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007787 ILE->setSyntacticForm(Syntactic);
7788 ILE->setType(E->getType());
7789 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007790 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007791 break;
7792 }
7793
Richard Smith53324112014-07-16 21:33:43 +00007794 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007795 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007796 if (checkAbstractType(Step->Type))
7797 return ExprError();
7798
Sebastian Redl99f66162012-02-19 12:27:56 +00007799 // When an initializer list is passed for a parameter of type "reference
7800 // to object", we don't get an EK_Temporary entity, but instead an
7801 // EK_Parameter entity with reference type.
7802 // FIXME: This is a hack. What we really should do is create a user
7803 // conversion step for this case, but this makes it considerably more
7804 // complicated. For now, this will do.
7805 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7806 Entity.getType().getNonReferenceType());
7807 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00007808 bool IsStdInitListInit =
7809 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00007810 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00007811 SourceRange Range = Kind.hasParenOrBraceRange()
7812 ? Kind.getParenOrBraceRange()
7813 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00007814 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00007815 S, UseTemporary ? TempEntity : Entity, Kind,
7816 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00007817 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00007818 /*IsListInitialization*/ IsStdInitListInit,
7819 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00007820 /*LBraceLoc*/ Range.getBegin(),
7821 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007822 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00007823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007824
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007825 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007826 step_iterator NextStep = Step;
7827 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007828 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007829 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007830 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007831 // The need for zero-initialization is recorded directly into
7832 // the call to the object's constructor within the next step.
7833 ConstructorInitRequiresZeroInit = true;
7834 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007835 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007836 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007837 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7838 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007839 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007840 Kind.getRange().getBegin());
7841
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007842 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007843 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007844 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007845 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007846 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007847 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007848 break;
7849 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007850
7851 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007852 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007853 // Save off the initial CurInit in case we need to emit a diagnostic
7854 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007855 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007856 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007857 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7858 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007859 if (Result.isInvalid())
7860 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007861 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007862
7863 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007864 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007865 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007866 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007867 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007868 == Sema::Compatible)
7869 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007870 if (CurInitExprRes.isInvalid())
7871 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007872 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007873
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007874 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007875 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7876 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007877 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007878 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007879 &Complained)) {
7880 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007881 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007882 } else if (Complained)
7883 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007884 break;
7885 }
Eli Friedman78275202009-12-19 08:11:05 +00007886
7887 case SK_StringInit: {
7888 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007889 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007890 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007891 break;
7892 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007893
7894 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007895 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007896 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007897 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007898 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007899
Richard Smith410306b2016-12-12 02:53:20 +00007900 case SK_ArrayLoopIndex: {
7901 Expr *Cur = CurInit.get();
7902 Expr *BaseExpr = new (S.Context)
7903 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7904 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7905 Expr *IndexExpr =
7906 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7907 CurInit = S.CreateBuiltinArraySubscriptExpr(
7908 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7909 ArrayLoopCommonExprs.push_back(BaseExpr);
7910 break;
7911 }
7912
7913 case SK_ArrayLoopInit: {
7914 assert(!ArrayLoopCommonExprs.empty() &&
7915 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7916 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7917 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7918 CurInit.get());
7919 break;
7920 }
7921
Richard Smith378b8c82016-12-14 03:22:16 +00007922 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007923 // Okay: we checked everything before creating this step. Note that
7924 // this is a GNU extension.
7925 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007926 << Step->Type << CurInit.get()->getType()
7927 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007928 LLVM_FALLTHROUGH;
7929 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007930 // If the destination type is an incomplete array type, update the
7931 // type accordingly.
7932 if (ResultType) {
7933 if (const IncompleteArrayType *IncompleteDest
7934 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7935 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007936 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007937 *ResultType = S.Context.getConstantArrayType(
7938 IncompleteDest->getElementType(),
7939 ConstantSource->getSize(),
7940 ArrayType::Normal, 0);
7941 }
7942 }
7943 }
John McCall31168b02011-06-15 23:02:42 +00007944 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007945
Richard Smithebeed412012-02-15 22:38:09 +00007946 case SK_ParenthesizedArrayInit:
7947 // Okay: we checked everything before creating this step. Note that
7948 // this is a GNU extension.
7949 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7950 << CurInit.get()->getSourceRange();
7951 break;
7952
John McCall31168b02011-06-15 23:02:42 +00007953 case SK_PassByIndirectCopyRestore:
7954 case SK_PassByIndirectRestore:
7955 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007956 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7957 CurInit.get(), Step->Type,
7958 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007959 break;
7960
7961 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007962 CurInit =
7963 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7964 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007965 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007966
7967 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007968 S.Diag(CurInit.get()->getExprLoc(),
7969 diag::warn_cxx98_compat_initializer_list_init)
7970 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007971
Richard Smithcc1b96d2013-06-12 22:31:48 +00007972 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007973 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7974 CurInit.get()->getType(), CurInit.get(),
7975 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007976
Florian Hahn0aa117d2018-07-17 09:23:31 +00007977 // Wrap it in a construction of a std::initializer_list<T>.
7978 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smith0a9969b2018-07-17 00:11:41 +00007979
Richard Smithcc1b96d2013-06-12 22:31:48 +00007980 // Bind the result, in case the library has given initializer_list a
7981 // non-trivial destructor.
7982 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007983 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007984 break;
7985 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007986
Guy Benyei61054192013-02-07 10:55:47 +00007987 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007988 // Sampler initialzation have 5 cases:
7989 // 1. function argument passing
7990 // 1a. argument is a file-scope variable
7991 // 1b. argument is a function-scope variable
7992 // 1c. argument is one of caller function's parameters
7993 // 2. variable initialization
7994 // 2a. initializing a file-scope variable
7995 // 2b. initializing a function-scope variable
7996 //
7997 // For file-scope variables, since they cannot be initialized by function
7998 // call of __translate_sampler_initializer in LLVM IR, their references
7999 // need to be replaced by a cast from their literal initializers to
8000 // sampler type. Since sampler variables can only be used in function
8001 // calls as arguments, we only need to replace them when handling the
8002 // argument passing.
8003 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00008004 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008005 Expr *Init = CurInit.get();
8006 QualType SourceType = Init->getType();
8007 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00008008 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00008009 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00008010 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8011 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008012 break;
8013 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8014 auto Var = cast<VarDecl>(DRE->getDecl());
8015 // Case 1b and 1c
8016 // No cast from integer to sampler is needed.
8017 if (!Var->hasGlobalStorage()) {
8018 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8019 CK_LValueToRValue, Init,
8020 /*BasePath=*/nullptr, VK_RValue);
8021 break;
8022 }
8023 // Case 1a
8024 // For function call with a file-scope sampler variable as argument,
8025 // get the integer literal.
8026 // Do not diagnose if the file-scope variable does not have initializer
8027 // since this has already been diagnosed when parsing the variable
8028 // declaration.
8029 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8030 break;
8031 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8032 Var->getInit()))->getSubExpr();
8033 SourceType = Init->getType();
8034 }
8035 } else {
8036 // Case 2
8037 // Check initializer is 32 bit integer constant.
8038 // If the initializer is taken from global variable, do not diagnose since
8039 // this has already been done when parsing the variable declaration.
8040 if (!Init->isConstantInitializer(S.Context, false))
8041 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00008042
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008043 if (!SourceType->isIntegerType() ||
8044 32 != S.Context.getIntWidth(SourceType)) {
8045 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8046 << SourceType;
8047 break;
8048 }
8049
8050 llvm::APSInt Result;
8051 Init->EvaluateAsInt(Result, S.Context);
8052 const uint64_t SamplerValue = Result.getLimitedValue();
8053 // 32-bit value of sampler's initializer is interpreted as
8054 // bit-field with the following structure:
8055 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8056 // |31 6|5 4|3 1| 0|
8057 // This structure corresponds to enum values of sampler properties
8058 // defined in SPIR spec v1.2 and also opencl-c.h
8059 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8060 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008061 if (FilterMode != 1 && FilterMode != 2 &&
8062 !S.getOpenCLOptions().isEnabled(
8063 "cl_intel_device_side_avc_motion_estimation"))
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008064 S.Diag(Kind.getLocation(),
8065 diag::warn_sampler_initializer_invalid_bits)
8066 << "Filter Mode";
8067 if (AddressingMode > 4)
8068 S.Diag(Kind.getLocation(),
8069 diag::warn_sampler_initializer_invalid_bits)
8070 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00008071 }
8072
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008073 // Cases 1a, 2a and 2b
8074 // Insert cast from integer to sampler.
8075 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
8076 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00008077 break;
8078 }
Andrew Savonichevb555b762018-10-23 15:19:20 +00008079 case SK_OCLZeroOpaqueType: {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008080 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8081 Step->Type->isOCLIntelSubgroupAVCType()) &&
Andrew Savonichevb555b762018-10-23 15:19:20 +00008082 "Wrong type for initialization of OpenCL opaque type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008083
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008084 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Andrew Savonichevb555b762018-10-23 15:19:20 +00008085 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00008086 CurInit.get()->getValueKind());
8087 break;
8088 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008089 }
8090 }
John McCall1f425642010-11-11 03:21:53 +00008091
Richard Smithca975b22018-07-23 18:50:26 +00008092 // Check whether the initializer has a shorter lifetime than the initialized
8093 // entity, and if not, either lifetime-extend or warn as appropriate.
8094 if (auto *Init = CurInit.get())
8095 S.checkInitializerLifetime(Entity, Init);
8096
John McCall1f425642010-11-11 03:21:53 +00008097 // Diagnose non-fatal problems with the completed initialization.
8098 if (Entity.getKind() == InitializedEntity::EK_Member &&
8099 cast<FieldDecl>(Entity.getDecl())->isBitField())
8100 S.CheckBitFieldInitialization(Kind.getLocation(),
8101 cast<FieldDecl>(Entity.getDecl()),
8102 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008103
Richard Trieuac3eca52015-04-29 01:52:17 +00008104 // Check for std::move on construction.
8105 if (const Expr *E = CurInit.get()) {
8106 CheckMoveOnConstruction(S, E,
8107 Entity.getKind() == InitializedEntity::EK_Result);
8108 }
8109
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008110 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008111}
8112
Richard Smith593f9932012-12-08 02:01:17 +00008113/// Somewhere within T there is an uninitialized reference subobject.
8114/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00008115static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8116 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00008117 if (T->isReferenceType()) {
8118 S.Diag(Loc, diag::err_reference_without_init)
8119 << T.getNonReferenceType();
8120 return true;
8121 }
8122
8123 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8124 if (!RD || !RD->hasUninitializedReferenceMember())
8125 return false;
8126
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008127 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00008128 if (FI->isUnnamedBitfield())
8129 continue;
8130
8131 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8132 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8133 return true;
8134 }
8135 }
8136
Aaron Ballman574705e2014-03-13 15:41:46 +00008137 for (const auto &BI : RD->bases()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008138 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00008139 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8140 return true;
8141 }
8142 }
8143
8144 return false;
8145}
8146
8147
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008148//===----------------------------------------------------------------------===//
8149// Diagnose initialization failures
8150//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00008151
8152/// Emit notes associated with an initialization that failed due to a
8153/// "simple" conversion failure.
8154static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8155 Expr *op) {
8156 QualType destType = entity.getType();
8157 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8158 op->getType()->isObjCObjectPointerType()) {
8159
8160 // Emit a possible note about the conversion failing because the
8161 // operand is a message send with a related result type.
8162 S.EmitRelatedResultTypeNote(op);
8163
8164 // Emit a possible note about a return failing because we're
8165 // expecting a related result type.
8166 if (entity.getKind() == InitializedEntity::EK_Result)
8167 S.EmitRelatedResultTypeNoteForReturn(destType);
8168 }
8169}
8170
Richard Smith0449aaf2013-11-21 23:30:57 +00008171static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8172 InitListExpr *InitList) {
8173 QualType DestType = Entity.getType();
8174
8175 QualType E;
8176 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8177 QualType ArrayType = S.Context.getConstantArrayType(
8178 E.withConst(),
8179 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8180 InitList->getNumInits()),
8181 clang::ArrayType::Normal, 0);
8182 InitializedEntity HiddenArray =
8183 InitializedEntity::InitializeTemporary(ArrayType);
8184 return diagnoseListInit(S, HiddenArray, InitList);
8185 }
8186
Richard Smith8d082d12014-09-04 22:13:39 +00008187 if (DestType->isReferenceType()) {
8188 // A list-initialization failure for a reference means that we tried to
8189 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8190 // inner initialization failed.
8191 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
8192 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008193 SourceLocation Loc = InitList->getBeginLoc();
Richard Smith8d082d12014-09-04 22:13:39 +00008194 if (auto *D = Entity.getDecl())
8195 Loc = D->getLocation();
8196 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8197 return;
8198 }
8199
Richard Smith0449aaf2013-11-21 23:30:57 +00008200 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00008201 /*VerifyOnly=*/false,
8202 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00008203 assert(DiagnoseInitList.HadError() &&
8204 "Inconsistent init list check result.");
8205}
8206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008207bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008208 const InitializedEntity &Entity,
8209 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008210 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00008211 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008212 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008213
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008214 // When we want to diagnose only one element of a braced-init-list,
8215 // we need to factor it out.
8216 Expr *OnlyArg;
8217 if (Args.size() == 1) {
8218 auto *List = dyn_cast<InitListExpr>(Args[0]);
8219 if (List && List->getNumInits() == 1)
8220 OnlyArg = List->getInit(0);
8221 else
8222 OnlyArg = Args[0];
8223 }
8224 else
8225 OnlyArg = nullptr;
8226
Douglas Gregor1b303932009-12-22 15:35:07 +00008227 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008228 switch (Failure) {
8229 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008230 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008231 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00008232 // Dig out the reference subobject which is uninitialized and diagnose it.
8233 // If this is value-initialization, this could be nested some way within
8234 // the target type.
8235 assert(Kind.getKind() == InitializationKind::IK_Value ||
8236 DestType->isReferenceType());
8237 bool Diagnosed =
8238 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8239 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8240 (void)Diagnosed;
8241 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008242 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008243 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008244 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00008245 case FK_ParenthesizedListInitForReference:
8246 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8247 << 1 << Entity.getType() << Args[0]->getSourceRange();
8248 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008250 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008251 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008252 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008253 case FK_ArrayNeedsInitListOrStringLiteral:
8254 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8255 break;
8256 case FK_ArrayNeedsInitListOrWideStringLiteral:
8257 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8258 break;
8259 case FK_NarrowStringIntoWideCharArray:
8260 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8261 break;
8262 case FK_WideStringIntoCharArray:
8263 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8264 break;
8265 case FK_IncompatWideStringIntoWideChar:
8266 S.Diag(Kind.getLocation(),
8267 diag::err_array_init_incompat_wide_string_into_wchar);
8268 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00008269 case FK_PlainStringIntoUTF8Char:
8270 S.Diag(Kind.getLocation(),
8271 diag::err_array_init_plain_string_into_char8_t);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008272 S.Diag(Args.front()->getBeginLoc(),
Richard Smith3a8244d2018-05-01 05:02:45 +00008273 diag::note_array_init_plain_string_into_char8_t)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008274 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
Richard Smith3a8244d2018-05-01 05:02:45 +00008275 break;
8276 case FK_UTF8StringIntoPlainChar:
8277 S.Diag(Kind.getLocation(),
Richard Smith28ddb912018-11-14 21:04:34 +00008278 diag::err_array_init_utf8_string_into_char)
8279 << S.getLangOpts().CPlusPlus2a;
Richard Smith3a8244d2018-05-01 05:02:45 +00008280 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008281 case FK_ArrayTypeMismatch:
8282 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00008283 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00008284 (Failure == FK_ArrayTypeMismatch
8285 ? diag::err_array_init_different_type
8286 : diag::err_array_init_non_constant_array))
8287 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008288 << OnlyArg->getType()
Douglas Gregore2f943b2011-02-22 18:29:51 +00008289 << Args[0]->getSourceRange();
8290 break;
8291
John McCalla59dc2f2012-01-05 00:13:19 +00008292 case FK_VariableLengthArrayHasInitializer:
8293 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8294 << Args[0]->getSourceRange();
8295 break;
8296
John McCall16df1e52010-03-30 21:47:33 +00008297 case FK_AddressOfOverloadFailed: {
8298 DeclAccessPair Found;
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008299 S.ResolveAddressOfOverloadedFunction(OnlyArg,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008300 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00008301 true,
8302 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008303 break;
John McCall16df1e52010-03-30 21:47:33 +00008304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008305
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008306 case FK_AddressOfUnaddressableFunction: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008307 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008308 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008309 OnlyArg->getBeginLoc());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008310 break;
8311 }
8312
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008313 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00008314 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008315 switch (FailedOverloadResult) {
8316 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00008317 if (Failure == FK_UserConversionOverloadFailed)
8318 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008319 << OnlyArg->getType() << DestType
Douglas Gregore1314a62009-12-18 05:02:21 +00008320 << Args[0]->getSourceRange();
8321 else
8322 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008323 << DestType << OnlyArg->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00008324 << Args[0]->getSourceRange();
8325
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008326 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008327 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008328
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008329 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00008330 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008331 DestType.getNonReferenceType(),
8332 diag::err_typecheck_nonviable_condition_incomplete,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008333 OnlyArg->getType(), Args[0]->getSourceRange()))
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008334 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00008335 << (Entity.getKind() == InitializedEntity::EK_Result)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008336 << OnlyArg->getType() << Args[0]->getSourceRange()
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008337 << DestType.getNonReferenceType();
8338
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008339 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008340 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008341
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008342 case OR_Deleted: {
8343 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008344 << OnlyArg->getType() << DestType.getNonReferenceType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008345 << Args[0]->getSourceRange();
8346 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008347 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00008348 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008349 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00008350 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008351 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008352 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008353 }
8354 break;
8355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008356
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008357 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008358 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008359 }
8360 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008361
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008362 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00008363 if (isa<InitListExpr>(Args[0])) {
8364 S.Diag(Kind.getLocation(),
8365 diag::err_lvalue_reference_bind_to_initlist)
8366 << DestType.getNonReferenceType().isVolatileQualified()
8367 << DestType.getNonReferenceType()
8368 << Args[0]->getSourceRange();
8369 break;
8370 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008371 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00008372
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008373 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008374 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008375 Failure == FK_NonConstLValueReferenceBindingToTemporary
8376 ? diag::err_lvalue_reference_bind_to_temporary
8377 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00008378 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008379 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008380 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008381 << Args[0]->getSourceRange();
8382 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008383
Richard Smithb8c0f552016-12-09 18:49:13 +00008384 case FK_NonConstLValueReferenceBindingToBitfield: {
8385 // We don't necessarily have an unambiguous source bit-field.
8386 FieldDecl *BitField = Args[0]->getSourceBitField();
8387 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
8388 << DestType.isVolatileQualified()
8389 << (BitField ? BitField->getDeclName() : DeclarationName())
8390 << (BitField != nullptr)
8391 << Args[0]->getSourceRange();
8392 if (BitField)
8393 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8394 break;
8395 }
8396
8397 case FK_NonConstLValueReferenceBindingToVectorElement:
8398 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
8399 << DestType.isVolatileQualified()
8400 << Args[0]->getSourceRange();
8401 break;
8402
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008403 case FK_RValueReferenceBindingToLValue:
8404 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008405 << DestType.getNonReferenceType() << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008406 << Args[0]->getSourceRange();
8407 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008408
Richard Trieuf956a492015-05-16 01:27:03 +00008409 case FK_ReferenceInitDropsQualifiers: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008410 QualType SourceType = OnlyArg->getType();
Richard Trieuf956a492015-05-16 01:27:03 +00008411 QualType NonRefType = DestType.getNonReferenceType();
8412 Qualifiers DroppedQualifiers =
8413 SourceType.getQualifiers() - NonRefType.getQualifiers();
8414
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008415 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00008416 << SourceType
8417 << NonRefType
8418 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008419 << Args[0]->getSourceRange();
8420 break;
Richard Trieuf956a492015-05-16 01:27:03 +00008421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008422
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008423 case FK_ReferenceInitFailed:
8424 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
8425 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008426 << OnlyArg->isLValue()
8427 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008428 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00008429 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008430 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008431
Douglas Gregorb491ed32011-02-19 21:32:49 +00008432 case FK_ConversionFailed: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008433 QualType FromType = OnlyArg->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00008434 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00008435 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008436 << DestType
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008437 << OnlyArg->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00008438 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008439 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008440 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
8441 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00008442 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00008443 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008444 }
John Wiegley01296292011-04-08 18:41:53 +00008445
8446 case FK_ConversionFromPropertyFailed:
8447 // No-op. This error has already been reported.
8448 break;
8449
Douglas Gregor51e77d52009-12-10 17:56:55 +00008450 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00008451 SourceRange R;
8452
David Majnemerbd385442015-04-10 04:52:06 +00008453 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008454 if (InitList && InitList->getNumInits() >= 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008455 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008456 } else {
8457 assert(Args.size() > 1 && "Expected multiple initializers!");
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008458 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008459 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00008460
Alp Tokerb6cc5922014-05-03 03:45:55 +00008461 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00008462 if (Kind.isCStyleOrFunctionalCast())
8463 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
8464 << R;
8465 else
8466 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
8467 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00008468 break;
8469 }
8470
Richard Smith49a6b6e2017-03-24 01:14:25 +00008471 case FK_ParenthesizedListInitForScalar:
8472 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8473 << 0 << Entity.getType() << Args[0]->getSourceRange();
8474 break;
8475
Douglas Gregor51e77d52009-12-10 17:56:55 +00008476 case FK_ReferenceBindingToInitList:
8477 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
8478 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8479 break;
8480
8481 case FK_InitListBadDestinationType:
8482 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8483 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8484 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008485
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008486 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008487 case FK_ConstructorOverloadFailed: {
8488 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008489 if (Args.size())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008490 ArgsRange =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008491 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008492
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008493 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00008494 assert(Args.size() == 1 &&
8495 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008496 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008497 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008498 }
8499
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008500 // FIXME: Using "DestType" for the entity we're printing is probably
8501 // bad.
8502 switch (FailedOverloadResult) {
8503 case OR_Ambiguous:
8504 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
8505 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008506 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008507 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008508
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008509 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008510 if (Kind.getKind() == InitializationKind::IK_Default &&
8511 (Entity.getKind() == InitializedEntity::EK_Base ||
8512 Entity.getKind() == InitializedEntity::EK_Member) &&
8513 isa<CXXConstructorDecl>(S.CurContext)) {
8514 // This is implicit default initialization of a member or
8515 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00008516 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008517 // initialize this base/member.
8518 CXXConstructorDecl *Constructor
8519 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00008520 const CXXRecordDecl *InheritedFrom = nullptr;
8521 if (auto Inherited = Constructor->getInheritedConstructor())
8522 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008523 if (Entity.getKind() == InitializedEntity::EK_Base) {
8524 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008525 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008526 << S.Context.getTypeDeclType(Constructor->getParent())
8527 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00008528 << Entity.getType()
8529 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008530
8531 RecordDecl *BaseDecl
8532 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
8533 ->getDecl();
8534 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8535 << S.Context.getTagDeclType(BaseDecl);
8536 } else {
8537 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008538 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008539 << S.Context.getTypeDeclType(Constructor->getParent())
8540 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00008541 << Entity.getName()
8542 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00008543 S.Diag(Entity.getDecl()->getLocation(),
8544 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008545
8546 if (const RecordType *Record
8547 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008548 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008549 diag::note_previous_decl)
8550 << S.Context.getTagDeclType(Record->getDecl());
8551 }
8552 break;
8553 }
8554
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008555 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
8556 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008557 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008558 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008559
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008560 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008561 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008562 OverloadingResult Ovl
8563 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00008564 if (Ovl != OR_Deleted) {
8565 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8566 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008567 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00008568 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008569 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008570
Douglas Gregor74f7d502012-02-15 19:33:52 +00008571 // If this is a defaulted or implicitly-declared function, then
8572 // it was implicitly deleted. Make it clear that the deletion was
8573 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00008574 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008575 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00008576 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008577 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00008578 else
8579 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8580 << true << DestType << ArgsRange;
8581
8582 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008583 break;
8584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008585
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008586 case OR_Success:
8587 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008588 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008589 }
David Blaikie60deeee2012-01-17 08:24:58 +00008590 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008591
Douglas Gregor85dabae2009-12-16 01:38:02 +00008592 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008593 if (Entity.getKind() == InitializedEntity::EK_Member &&
8594 isa<CXXConstructorDecl>(S.CurContext)) {
8595 // This is implicit default-initialization of a const member in
8596 // a constructor. Complain that it needs to be explicitly
8597 // initialized.
8598 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
8599 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00008600 << (Constructor->getInheritedConstructor() ? 2 :
8601 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008602 << S.Context.getTypeDeclType(Constructor->getParent())
8603 << /*const=*/1
8604 << Entity.getName();
8605 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
8606 << Entity.getName();
8607 } else {
8608 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00008609 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008610 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00008611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008612
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008613 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00008614 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008615 diag::err_init_incomplete_type);
8616 break;
8617
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008618 case FK_ListInitializationFailed: {
8619 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00008620 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8621 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008622 break;
8623 }
John McCall4124c492011-10-17 18:40:02 +00008624
8625 case FK_PlaceholderType: {
8626 // FIXME: Already diagnosed!
8627 break;
8628 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00008629
Sebastian Redl048a6d72012-04-01 19:54:59 +00008630 case FK_ExplicitConstructor: {
8631 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
8632 << Args[0]->getSourceRange();
8633 OverloadCandidateSet::iterator Best;
8634 OverloadingResult Ovl
8635 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00008636 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008637 assert(Ovl == OR_Success && "Inconsistent overload resolution");
8638 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00008639 S.Diag(CtorDecl->getLocation(),
8640 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008641 break;
8642 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008644
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008645 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008646 return true;
8647}
Douglas Gregore1314a62009-12-18 05:02:21 +00008648
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008649void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008650 switch (SequenceKind) {
8651 case FailedSequence: {
8652 OS << "Failed sequence: ";
8653 switch (Failure) {
8654 case FK_TooManyInitsForReference:
8655 OS << "too many initializers for reference";
8656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008657
Richard Smith49a6b6e2017-03-24 01:14:25 +00008658 case FK_ParenthesizedListInitForReference:
8659 OS << "parenthesized list init for reference";
8660 break;
8661
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008662 case FK_ArrayNeedsInitList:
8663 OS << "array requires initializer list";
8664 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008665
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008666 case FK_AddressOfUnaddressableFunction:
8667 OS << "address of unaddressable function was taken";
8668 break;
8669
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008670 case FK_ArrayNeedsInitListOrStringLiteral:
8671 OS << "array requires initializer list or string literal";
8672 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008673
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008674 case FK_ArrayNeedsInitListOrWideStringLiteral:
8675 OS << "array requires initializer list or wide string literal";
8676 break;
8677
8678 case FK_NarrowStringIntoWideCharArray:
8679 OS << "narrow string into wide char array";
8680 break;
8681
8682 case FK_WideStringIntoCharArray:
8683 OS << "wide string into char array";
8684 break;
8685
8686 case FK_IncompatWideStringIntoWideChar:
8687 OS << "incompatible wide string into wide char array";
8688 break;
8689
Richard Smith3a8244d2018-05-01 05:02:45 +00008690 case FK_PlainStringIntoUTF8Char:
8691 OS << "plain string literal into char8_t array";
8692 break;
8693
8694 case FK_UTF8StringIntoPlainChar:
8695 OS << "u8 string literal into char array";
8696 break;
8697
Douglas Gregore2f943b2011-02-22 18:29:51 +00008698 case FK_ArrayTypeMismatch:
8699 OS << "array type mismatch";
8700 break;
8701
8702 case FK_NonConstantArrayInit:
8703 OS << "non-constant array initializer";
8704 break;
8705
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008706 case FK_AddressOfOverloadFailed:
8707 OS << "address of overloaded function failed";
8708 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008709
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008710 case FK_ReferenceInitOverloadFailed:
8711 OS << "overload resolution for reference initialization failed";
8712 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008713
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008714 case FK_NonConstLValueReferenceBindingToTemporary:
8715 OS << "non-const lvalue reference bound to temporary";
8716 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008717
Richard Smithb8c0f552016-12-09 18:49:13 +00008718 case FK_NonConstLValueReferenceBindingToBitfield:
8719 OS << "non-const lvalue reference bound to bit-field";
8720 break;
8721
8722 case FK_NonConstLValueReferenceBindingToVectorElement:
8723 OS << "non-const lvalue reference bound to vector element";
8724 break;
8725
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008726 case FK_NonConstLValueReferenceBindingToUnrelated:
8727 OS << "non-const lvalue reference bound to unrelated type";
8728 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008729
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008730 case FK_RValueReferenceBindingToLValue:
8731 OS << "rvalue reference bound to an lvalue";
8732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008733
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008734 case FK_ReferenceInitDropsQualifiers:
8735 OS << "reference initialization drops qualifiers";
8736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008737
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008738 case FK_ReferenceInitFailed:
8739 OS << "reference initialization failed";
8740 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008741
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008742 case FK_ConversionFailed:
8743 OS << "conversion failed";
8744 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008745
John Wiegley01296292011-04-08 18:41:53 +00008746 case FK_ConversionFromPropertyFailed:
8747 OS << "conversion from property failed";
8748 break;
8749
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008750 case FK_TooManyInitsForScalar:
8751 OS << "too many initializers for scalar";
8752 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008753
Richard Smith49a6b6e2017-03-24 01:14:25 +00008754 case FK_ParenthesizedListInitForScalar:
8755 OS << "parenthesized list init for reference";
8756 break;
8757
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008758 case FK_ReferenceBindingToInitList:
8759 OS << "referencing binding to initializer list";
8760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008761
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008762 case FK_InitListBadDestinationType:
8763 OS << "initializer list for non-aggregate, non-scalar type";
8764 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008765
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008766 case FK_UserConversionOverloadFailed:
8767 OS << "overloading failed for user-defined conversion";
8768 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008769
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008770 case FK_ConstructorOverloadFailed:
8771 OS << "constructor overloading failed";
8772 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008773
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008774 case FK_DefaultInitOfConst:
8775 OS << "default initialization of a const variable";
8776 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008777
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00008778 case FK_Incomplete:
8779 OS << "initialization of incomplete type";
8780 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008781
8782 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008783 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00008784 break;
8785
John McCalla59dc2f2012-01-05 00:13:19 +00008786 case FK_VariableLengthArrayHasInitializer:
8787 OS << "variable length array has an initializer";
8788 break;
8789
John McCall4124c492011-10-17 18:40:02 +00008790 case FK_PlaceholderType:
8791 OS << "initializer expression isn't contextually valid";
8792 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00008793
8794 case FK_ListConstructorOverloadFailed:
8795 OS << "list constructor overloading failed";
8796 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008797
Sebastian Redl048a6d72012-04-01 19:54:59 +00008798 case FK_ExplicitConstructor:
8799 OS << "list copy initialization chose explicit constructor";
8800 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008801 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008802 OS << '\n';
8803 return;
8804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008805
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008806 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00008807 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008808 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008809
Sebastian Redld201edf2011-06-05 13:59:11 +00008810 case NormalSequence:
8811 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008812 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008814
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008815 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8816 if (S != step_begin()) {
8817 OS << " -> ";
8818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008819
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008820 switch (S->Kind) {
8821 case SK_ResolveAddressOfOverloadedFunction:
8822 OS << "resolve address of overloaded function";
8823 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008824
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008825 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008826 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008827 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008828
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008829 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008830 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008831 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008832
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008833 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008834 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008835 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008836
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008837 case SK_BindReference:
8838 OS << "bind reference to lvalue";
8839 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008840
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008841 case SK_BindReferenceToTemporary:
8842 OS << "bind reference to a temporary";
8843 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008844
Richard Smithb8c0f552016-12-09 18:49:13 +00008845 case SK_FinalCopy:
8846 OS << "final copy in class direct-initialization";
8847 break;
8848
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008849 case SK_ExtraneousCopyToTemporary:
8850 OS << "extraneous C++03 copy to temporary";
8851 break;
8852
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008853 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008854 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008855 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008856
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008857 case SK_QualificationConversionRValue:
8858 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008859 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008860
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008861 case SK_QualificationConversionXValue:
8862 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008863 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008864
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008865 case SK_QualificationConversionLValue:
8866 OS << "qualification conversion (lvalue)";
8867 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008868
Richard Smith77be48a2014-07-31 06:31:19 +00008869 case SK_AtomicConversion:
8870 OS << "non-atomic-to-atomic conversion";
8871 break;
8872
Jordan Roseb1312a52013-04-11 00:58:58 +00008873 case SK_LValueToRValue:
8874 OS << "load (lvalue to rvalue)";
8875 break;
8876
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008877 case SK_ConversionSequence:
8878 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008879 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008880 OS << ")";
8881 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008882
Richard Smithaaa0ec42013-09-21 21:19:19 +00008883 case SK_ConversionSequenceNoNarrowing:
8884 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008885 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008886 OS << ")";
8887 break;
8888
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008889 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008890 OS << "list aggregate initialization";
8891 break;
8892
Sebastian Redl29526f02011-11-27 16:50:07 +00008893 case SK_UnwrapInitList:
8894 OS << "unwrap reference initializer list";
8895 break;
8896
8897 case SK_RewrapInitList:
8898 OS << "rewrap reference initializer list";
8899 break;
8900
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008901 case SK_ConstructorInitialization:
8902 OS << "constructor initialization";
8903 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008904
Richard Smith53324112014-07-16 21:33:43 +00008905 case SK_ConstructorInitializationFromList:
8906 OS << "list initialization via constructor";
8907 break;
8908
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008909 case SK_ZeroInitialization:
8910 OS << "zero initialization";
8911 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008912
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008913 case SK_CAssignment:
8914 OS << "C assignment";
8915 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008916
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008917 case SK_StringInit:
8918 OS << "string initialization";
8919 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008920
8921 case SK_ObjCObjectConversion:
8922 OS << "Objective-C object conversion";
8923 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008924
Richard Smith410306b2016-12-12 02:53:20 +00008925 case SK_ArrayLoopIndex:
8926 OS << "indexing for array initialization loop";
8927 break;
8928
8929 case SK_ArrayLoopInit:
8930 OS << "array initialization loop";
8931 break;
8932
Douglas Gregore2f943b2011-02-22 18:29:51 +00008933 case SK_ArrayInit:
8934 OS << "array initialization";
8935 break;
John McCall31168b02011-06-15 23:02:42 +00008936
Richard Smith378b8c82016-12-14 03:22:16 +00008937 case SK_GNUArrayInit:
8938 OS << "array initialization (GNU extension)";
8939 break;
8940
Richard Smithebeed412012-02-15 22:38:09 +00008941 case SK_ParenthesizedArrayInit:
8942 OS << "parenthesized array initialization";
8943 break;
8944
John McCall31168b02011-06-15 23:02:42 +00008945 case SK_PassByIndirectCopyRestore:
8946 OS << "pass by indirect copy and restore";
8947 break;
8948
8949 case SK_PassByIndirectRestore:
8950 OS << "pass by indirect restore";
8951 break;
8952
8953 case SK_ProduceObjCObject:
8954 OS << "Objective-C object retension";
8955 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008956
8957 case SK_StdInitializerList:
8958 OS << "std::initializer_list from initializer list";
8959 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008960
Richard Smithf8adcdc2014-07-17 05:12:35 +00008961 case SK_StdInitializerListConstructorCall:
8962 OS << "list initialization from std::initializer_list";
8963 break;
8964
Guy Benyei61054192013-02-07 10:55:47 +00008965 case SK_OCLSamplerInit:
8966 OS << "OpenCL sampler_t from integer constant";
8967 break;
8968
Andrew Savonichevb555b762018-10-23 15:19:20 +00008969 case SK_OCLZeroOpaqueType:
8970 OS << "OpenCL opaque type from zero";
Egor Churaev89831422016-12-23 14:55:49 +00008971 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008972 }
Richard Smith6b216962013-02-05 05:52:24 +00008973
8974 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008975 }
Richard Smith6b216962013-02-05 05:52:24 +00008976
8977 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008978}
8979
8980void InitializationSequence::dump() const {
8981 dump(llvm::errs());
8982}
8983
Nico Weber3d7f00d2018-06-19 23:19:34 +00008984static bool NarrowingErrs(const LangOptions &L) {
8985 return L.CPlusPlus11 &&
8986 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
8987}
8988
Richard Smithaaa0ec42013-09-21 21:19:19 +00008989static void DiagnoseNarrowingInInitList(Sema &S,
8990 const ImplicitConversionSequence &ICS,
8991 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008992 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008993 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008994 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008995 switch (ICS.getKind()) {
8996 case ImplicitConversionSequence::StandardConversion:
8997 SCS = &ICS.Standard;
8998 break;
8999 case ImplicitConversionSequence::UserDefinedConversion:
9000 SCS = &ICS.UserDefined.After;
9001 break;
9002 case ImplicitConversionSequence::AmbiguousConversion:
9003 case ImplicitConversionSequence::EllipsisConversion:
9004 case ImplicitConversionSequence::BadConversion:
9005 return;
9006 }
9007
Richard Smith66e05fe2012-01-18 05:21:49 +00009008 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9009 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00009010 QualType ConstantType;
9011 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9012 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00009013 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00009014 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00009015 // No narrowing occurred.
9016 return;
9017
9018 case NK_Type_Narrowing:
9019 // This was a floating-to-integer conversion, which is always considered a
9020 // narrowing conversion even if the value is a constant and can be
9021 // represented exactly as an integer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009022 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
Nico Weber3d7f00d2018-06-19 23:19:34 +00009023 ? diag::ext_init_list_type_narrowing
9024 : diag::warn_init_list_type_narrowing)
9025 << PostInit->getSourceRange()
9026 << PreNarrowingType.getLocalUnqualifiedType()
9027 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009028 break;
9029
9030 case NK_Constant_Narrowing:
9031 // A constant value was narrowed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009032 S.Diag(PostInit->getBeginLoc(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00009033 NarrowingErrs(S.getLangOpts())
9034 ? diag::ext_init_list_constant_narrowing
9035 : diag::warn_init_list_constant_narrowing)
9036 << PostInit->getSourceRange()
9037 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9038 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009039 break;
9040
9041 case NK_Variable_Narrowing:
9042 // A variable's value may have been narrowed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009043 S.Diag(PostInit->getBeginLoc(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00009044 NarrowingErrs(S.getLangOpts())
9045 ? diag::ext_init_list_variable_narrowing
9046 : diag::warn_init_list_variable_narrowing)
9047 << PostInit->getSourceRange()
9048 << PreNarrowingType.getLocalUnqualifiedType()
9049 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009050 break;
9051 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009052
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009053 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009054 llvm::raw_svector_ostream OS(StaticCast);
9055 OS << "static_cast<";
9056 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9057 // It's important to use the typedef's name if there is one so that the
9058 // fixit doesn't break code using types like int64_t.
9059 //
9060 // FIXME: This will break if the typedef requires qualification. But
9061 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00009062 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009063 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00009064 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009065 else {
9066 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9067 // with a broken cast.
9068 return;
9069 }
9070 OS << ">(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009071 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009072 << PostInit->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009073 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
Alp Tokerb6cc5922014-05-03 03:45:55 +00009074 << FixItHint::CreateInsertion(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009075 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009076}
9077
Douglas Gregore1314a62009-12-18 05:02:21 +00009078//===----------------------------------------------------------------------===//
9079// Initialization helper functions
9080//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00009081bool
9082Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
9083 ExprResult Init) {
9084 if (Init.isInvalid())
9085 return false;
9086
9087 Expr *InitE = Init.get();
9088 assert(InitE && "No initialization expression");
9089
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009090 InitializationKind Kind =
9091 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00009092 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00009093 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00009094}
9095
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009096ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00009097Sema::PerformCopyInitialization(const InitializedEntity &Entity,
9098 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009099 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00009100 bool TopLevelOfInitList,
9101 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00009102 if (Init.isInvalid())
9103 return ExprError();
9104
John McCall1f425642010-11-11 03:21:53 +00009105 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00009106 assert(InitE && "No initialization expression?");
9107
9108 if (EqualLoc.isInvalid())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009109 EqualLoc = InitE->getBeginLoc();
Douglas Gregore1314a62009-12-18 05:02:21 +00009110
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009111 InitializationKind Kind = InitializationKind::CreateCopy(
9112 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00009113 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009114
Alex Lorenzde69ff92017-05-16 10:23:58 +00009115 // Prevent infinite recursion when performing parameter copy-initialization.
9116 const bool ShouldTrackCopy =
9117 Entity.isParameterKind() && Seq.isConstructorInitialization();
9118 if (ShouldTrackCopy) {
9119 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
9120 CurrentParameterCopyTypes.end()) {
9121 Seq.SetOverloadFailure(
9122 InitializationSequence::FK_ConstructorOverloadFailed,
9123 OR_No_Viable_Function);
9124
9125 // Try to give a meaningful diagnostic note for the problematic
9126 // constructor.
9127 const auto LastStep = Seq.step_end() - 1;
9128 assert(LastStep->Kind ==
9129 InitializationSequence::SK_ConstructorInitialization);
9130 const FunctionDecl *Function = LastStep->Function.Function;
9131 auto Candidate =
9132 llvm::find_if(Seq.getFailedCandidateSet(),
9133 [Function](const OverloadCandidate &Candidate) -> bool {
9134 return Candidate.Viable &&
9135 Candidate.Function == Function &&
9136 Candidate.Conversions.size() > 0;
9137 });
9138 if (Candidate != Seq.getFailedCandidateSet().end() &&
9139 Function->getNumParams() > 0) {
9140 Candidate->Viable = false;
9141 Candidate->FailureKind = ovl_fail_bad_conversion;
9142 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9143 InitE,
9144 Function->getParamDecl(0)->getType());
9145 }
9146 }
9147 CurrentParameterCopyTypes.push_back(Entity.getType());
9148 }
9149
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00009150 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00009151
Alex Lorenzde69ff92017-05-16 10:23:58 +00009152 if (ShouldTrackCopy)
9153 CurrentParameterCopyTypes.pop_back();
9154
Richard Smith66e05fe2012-01-18 05:21:49 +00009155 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00009156}
Richard Smith60437622017-02-09 19:17:44 +00009157
Richard Smith1363e8f2017-09-07 07:22:36 +00009158/// Determine whether RD is, or is derived from, a specialization of CTD.
9159static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
9160 ClassTemplateDecl *CTD) {
9161 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9162 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9163 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9164 };
9165 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9166}
9167
Richard Smith60437622017-02-09 19:17:44 +00009168QualType Sema::DeduceTemplateSpecializationFromInitializer(
9169 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9170 const InitializationKind &Kind, MultiExprArg Inits) {
9171 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9172 TSInfo->getType()->getContainedDeducedType());
9173 assert(DeducedTST && "not a deduced template specialization type");
9174
Richard Smith60437622017-02-09 19:17:44 +00009175 auto TemplateName = DeducedTST->getTemplateName();
Richard Smithcff42012018-09-28 03:18:53 +00009176 if (TemplateName.isDependent())
9177 return Context.DependentTy;
9178
9179 // We can only perform deduction for class templates.
Richard Smith60437622017-02-09 19:17:44 +00009180 auto *Template =
9181 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
9182 if (!Template) {
9183 Diag(Kind.getLocation(),
9184 diag::err_deduced_non_class_template_specialization_type)
9185 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
9186 if (auto *TD = TemplateName.getAsTemplateDecl())
9187 Diag(TD->getLocation(), diag::note_template_decl_here);
9188 return QualType();
9189 }
9190
Richard Smith32918772017-02-14 00:25:28 +00009191 // Can't deduce from dependent arguments.
Richard Smith8eeb16f2018-09-10 20:31:03 +00009192 if (Expr::hasAnyTypeDependentArguments(Inits)) {
9193 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9194 diag::warn_cxx14_compat_class_template_argument_deduction)
9195 << TSInfo->getTypeLoc().getSourceRange() << 0;
Richard Smith32918772017-02-14 00:25:28 +00009196 return Context.DependentTy;
Richard Smith8eeb16f2018-09-10 20:31:03 +00009197 }
Richard Smith32918772017-02-14 00:25:28 +00009198
Richard Smith60437622017-02-09 19:17:44 +00009199 // FIXME: Perform "exact type" matching first, per CWG discussion?
9200 // Or implement this via an implied 'T(T) -> T' deduction guide?
9201
9202 // FIXME: Do we need/want a std::initializer_list<T> special case?
9203
Richard Smith32918772017-02-14 00:25:28 +00009204 // Look up deduction guides, including those synthesized from constructors.
9205 //
Richard Smith60437622017-02-09 19:17:44 +00009206 // C++1z [over.match.class.deduct]p1:
9207 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00009208 // - For each constructor of the class template designated by the
9209 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00009210 // - For each deduction-guide, a function or function template [...]
9211 DeclarationNameInfo NameInfo(
9212 Context.DeclarationNames.getCXXDeductionGuideName(Template),
9213 TSInfo->getTypeLoc().getEndLoc());
9214 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
9215 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00009216
9217 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9218 // clear on this, but they're not found by name so access does not apply.
9219 Guides.suppressDiagnostics();
9220
9221 // Figure out if this is list-initialization.
9222 InitListExpr *ListInit =
9223 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
9224 ? dyn_cast<InitListExpr>(Inits[0])
9225 : nullptr;
9226
9227 // C++1z [over.match.class.deduct]p1:
9228 // Initialization and overload resolution are performed as described in
9229 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9230 // (as appropriate for the type of initialization performed) for an object
9231 // of a hypothetical class type, where the selected functions and function
9232 // templates are considered to be the constructors of that class type
9233 //
9234 // Since we know we're initializing a class type of a type unrelated to that
9235 // of the initializer, this reduces to something fairly reasonable.
9236 OverloadCandidateSet Candidates(Kind.getLocation(),
9237 OverloadCandidateSet::CSK_Normal);
9238 OverloadCandidateSet::iterator Best;
9239 auto tryToResolveOverload =
9240 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00009241 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Richard Smith32918772017-02-14 00:25:28 +00009242 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
9243 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00009244 if (D->isInvalidDecl())
9245 continue;
9246
Richard Smithbc491202017-02-17 20:05:37 +00009247 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
9248 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
9249 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9250 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00009251 continue;
9252
9253 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9254 // For copy-initialization, the candidate functions are all the
9255 // converting constructors (12.3.1) of that class.
9256 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9257 // The converting constructors of T are candidate functions.
9258 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00009259 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00009260 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00009261 continue;
Richard Smith60437622017-02-09 19:17:44 +00009262
9263 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00009264 // could never be called with one argument are not interesting to
9265 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00009266 if (GD->getMinRequiredArguments() > 1 ||
9267 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00009268 continue;
9269 }
9270
9271 // C++ [over.match.list]p1.1: (first phase list initialization)
9272 // Initially, the candidate functions are the initializer-list
9273 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00009274 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00009275 continue;
9276
9277 // C++ [over.match.list]p1.2: (second phase list initialization)
9278 // the candidate functions are all the constructors of the class T
9279 // C++ [over.match.ctor]p1: (all other cases)
9280 // the candidate functions are all the constructors of the class of
9281 // the object being initialized
9282
9283 // C++ [over.best.ics]p4:
9284 // When [...] the constructor [...] is a candidate by
9285 // - [over.match.copy] (in all cases)
9286 // FIXME: The "second phase of [over.match.list] case can also
9287 // theoretically happen here, but it's not clear whether we can
9288 // ever have a parameter of the right type.
9289 bool SuppressUserConversions = Kind.isCopyInit();
9290
Richard Smith60437622017-02-09 19:17:44 +00009291 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00009292 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
9293 Inits, Candidates,
9294 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00009295 else
Richard Smithbc491202017-02-17 20:05:37 +00009296 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00009297 SuppressUserConversions);
9298 }
9299 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
9300 };
9301
9302 OverloadingResult Result = OR_No_Viable_Function;
9303
9304 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9305 // try initializer-list constructors.
9306 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00009307 bool TryListConstructors = true;
9308
9309 // Try list constructors unless the list is empty and the class has one or
9310 // more default constructors, in which case those constructors win.
9311 if (!ListInit->getNumInits()) {
9312 for (NamedDecl *D : Guides) {
9313 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9314 if (FD && FD->getMinRequiredArguments() == 0) {
9315 TryListConstructors = false;
9316 break;
9317 }
9318 }
Richard Smith1363e8f2017-09-07 07:22:36 +00009319 } else if (ListInit->getNumInits() == 1) {
9320 // C++ [over.match.class.deduct]:
9321 // As an exception, the first phase in [over.match.list] (considering
9322 // initializer-list constructors) is omitted if the initializer list
9323 // consists of a single expression of type cv U, where U is a
9324 // specialization of C or a class derived from a specialization of C.
9325 Expr *E = ListInit->getInit(0);
9326 auto *RD = E->getType()->getAsCXXRecordDecl();
9327 if (!isa<InitListExpr>(E) && RD &&
Erik Pilkingtondd0b3442018-07-26 23:40:42 +00009328 isCompleteType(Kind.getLocation(), E->getType()) &&
Richard Smith1363e8f2017-09-07 07:22:36 +00009329 isOrIsDerivedFromSpecializationOf(RD, Template))
9330 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00009331 }
9332
9333 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00009334 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
9335 // Then unwrap the initializer list and try again considering all
9336 // constructors.
9337 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
9338 }
9339
9340 // If list-initialization fails, or if we're doing any other kind of
9341 // initialization, we (eventually) consider constructors.
9342 if (Result == OR_No_Viable_Function)
9343 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
9344
9345 switch (Result) {
9346 case OR_Ambiguous:
9347 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
9348 << TemplateName;
9349 // FIXME: For list-initialization candidates, it'd usually be better to
9350 // list why they were not viable when given the initializer list itself as
9351 // an argument.
9352 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
9353 return QualType();
9354
Richard Smith32918772017-02-14 00:25:28 +00009355 case OR_No_Viable_Function: {
9356 CXXRecordDecl *Primary =
9357 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
9358 bool Complete =
9359 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00009360 Diag(Kind.getLocation(),
9361 Complete ? diag::err_deduced_class_template_ctor_no_viable
9362 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00009363 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00009364 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
9365 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00009366 }
Richard Smith60437622017-02-09 19:17:44 +00009367
9368 case OR_Deleted: {
9369 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
9370 << TemplateName;
9371 NoteDeletedFunction(Best->Function);
9372 return QualType();
9373 }
9374
9375 case OR_Success:
9376 // C++ [over.match.list]p1:
9377 // In copy-list-initialization, if an explicit constructor is chosen, the
9378 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00009379 if (Kind.isCopyInit() && ListInit &&
9380 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00009381 bool IsDeductionGuide = !Best->Function->isImplicit();
9382 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
9383 << TemplateName << IsDeductionGuide;
9384 Diag(Best->Function->getLocation(),
9385 diag::note_explicit_ctor_deduction_guide_here)
9386 << IsDeductionGuide;
9387 return QualType();
9388 }
9389
9390 // Make sure we didn't select an unusable deduction guide, and mark it
9391 // as referenced.
9392 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
9393 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
9394 break;
9395 }
9396
9397 // C++ [dcl.type.class.deduct]p1:
9398 // The placeholder is replaced by the return type of the function selected
9399 // by overload resolution for class template deduction.
Richard Smith8eeb16f2018-09-10 20:31:03 +00009400 QualType DeducedType =
9401 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
9402 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9403 diag::warn_cxx14_compat_class_template_argument_deduction)
9404 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
9405 return DeducedType;
Richard Smith60437622017-02-09 19:17:44 +00009406}