blob: 0811d3fd14e7ad5581ab5a405e3dd3565c076981 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Steve Narofff8ecff22008-05-01 22:18:59 +00006//
7//===----------------------------------------------------------------------===//
8//
Sebastian Redl26bcc942011-09-24 17:47:39 +00009// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000010//
Steve Narofff8ecff22008-05-01 22:18:59 +000011//===----------------------------------------------------------------------===//
12
Steve Narofff8ecff22008-05-01 22:18:59 +000013#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000014#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000015#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000016#include "clang/AST/ExprObjC.h"
Richard Smithafe48f92018-07-23 21:21:22 +000017#include "clang/AST/ExprOpenMP.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000018#include "clang/AST/TypeLoc.h"
Gabor Horvathbfe0c372019-08-14 16:34:56 +000019#include "clang/Basic/CharInfo.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);
Eli Friedman3bf72d72019-02-08 21:18:46 +0000148 E->setValueKind(VK_RValue);
Eli Friedman88fccbd2019-02-11 22:54:27 +0000149 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
Richard Smithd74b16062013-05-06 00:35:47 +0000150 break;
Eli Friedman88fccbd2019-02-11 22:54:27 +0000151 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Richard Smithd74b16062013-05-06 00:35:47 +0000152 E = PE->getSubExpr();
Eli Friedman88fccbd2019-02-11 22:54:27 +0000153 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
154 assert(UO->getOpcode() == UO_Extension);
Richard Smithd74b16062013-05-06 00:35:47 +0000155 E = UO->getSubExpr();
Eli Friedman88fccbd2019-02-11 22:54:27 +0000156 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
Richard Smithd74b16062013-05-06 00:35:47 +0000157 E = GSE->getResultExpr();
Eli Friedman88fccbd2019-02-11 22:54:27 +0000158 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
159 E = CE->getChosenSubExpr();
160 } else {
Richard Smithd74b16062013-05-06 00:35:47 +0000161 llvm_unreachable("unexpected expr in string literal init");
Eli Friedman88fccbd2019-02-11 22:54:27 +0000162 }
163 }
164}
165
166/// Fix a compound literal initializing an array so it's correctly marked
167/// as an rvalue.
168static void updateGNUCompoundLiteralRValue(Expr *E) {
169 while (true) {
170 E->setValueKind(VK_RValue);
171 if (isa<CompoundLiteralExpr>(E)) {
172 break;
173 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
174 E = PE->getSubExpr();
175 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
176 assert(UO->getOpcode() == UO_Extension);
177 E = UO->getSubExpr();
178 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
179 E = GSE->getResultExpr();
180 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
181 E = CE->getChosenSubExpr();
182 } else {
183 llvm_unreachable("unexpected expr in array compound literal init");
184 }
Richard Smith430c23b2013-05-05 16:40:13 +0000185 }
Richard Smith430c23b2013-05-05 16:40:13 +0000186}
187
John McCall5decec92011-02-21 07:57:55 +0000188static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
189 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000190 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000191 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000192 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000193 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattner0cb78032009-02-24 22:27:37 +0000195 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000196 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000197 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000198 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000199 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000200 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
201 ConstVal,
202 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000203 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000204 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000205 }
Mike Stump11289f42009-09-09 15:08:12 +0000206
Eli Friedman893abe42009-05-29 18:22:49 +0000207 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000208
Eli Friedman554eba92011-04-11 00:23:45 +0000209 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000210 // the size may be smaller or larger than the string we are initializing.
211 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000212 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000213 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000214 // For Pascal strings it's OK to strip off the terminating null character,
215 // so the example below is valid:
216 //
217 // unsigned char a[2] = "\pa";
218 if (SL->isPascal())
219 StrLength--;
220 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000221
Eli Friedman554eba92011-04-11 00:23:45 +0000222 // [dcl.init.string]p2
223 if (StrLength > CAT->getSize().getZExtValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000224 S.Diag(Str->getBeginLoc(),
Eli Friedman554eba92011-04-11 00:23:45 +0000225 diag::err_initializer_string_for_char_array_too_long)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000226 << Str->getSourceRange();
Eli Friedman554eba92011-04-11 00:23:45 +0000227 } else {
228 // C99 6.7.8p14.
229 if (StrLength-1 > CAT->getSize().getZExtValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000230 S.Diag(Str->getBeginLoc(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000231 diag::ext_initializer_string_for_char_array_too_long)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000232 << Str->getSourceRange();
Eli Friedman554eba92011-04-11 00:23:45 +0000233 }
Mike Stump11289f42009-09-09 15:08:12 +0000234
Eli Friedman893abe42009-05-29 18:22:49 +0000235 // Set the type to the actual size that we are initializing. If we have
236 // something like:
237 // char x[1] = "foo";
238 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000239 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000240}
241
Chris Lattner0cb78032009-02-24 22:27:37 +0000242//===----------------------------------------------------------------------===//
243// Semantic checking for initializer lists.
244//===----------------------------------------------------------------------===//
245
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000246namespace {
247
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000248/// Semantic checking for initializer lists.
Douglas Gregorcde232f2009-01-29 01:05:33 +0000249///
250/// The InitListChecker class contains a set of routines that each
251/// handle the initialization of a certain kind of entity, e.g.,
252/// arrays, vectors, struct/union types, scalars, etc. The
253/// InitListChecker itself performs a recursive walk of the subobject
254/// structure of the type to be initialized, while stepping through
255/// the initializer list one element at a time. The IList and Index
256/// parameters to each of the Check* routines contain the active
257/// (syntactic) initializer list and the index into that initializer
258/// list that represents the current initializer. Each routine is
259/// responsible for moving that Index forward as it consumes elements.
260///
261/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000262/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000263/// initializer list and the index into that initializer list where we
264/// are copying initializers as we map them over to the semantic
265/// list. Once we have completed our recursive walk of the subobject
266/// structure, we will have constructed a full semantic initializer
267/// list.
268///
269/// C99 designators cause changes in the initializer list traversal,
270/// because they make the initialization "jump" into a specific
271/// subobject and then continue the initialization from that
272/// point. CheckDesignatedInitializer() recursively steps into the
273/// designated subobject and manages backing out the recursion to
274/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000275class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000276 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000277 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000278 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000279 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000280 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000281 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000282
Anders Carlsson6cabf312010-01-23 23:23:01 +0000283 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000284 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000285 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000286 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000287 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000288 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000289 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000290 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000291 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000292 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000293 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000294 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000295 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000296 unsigned &StructuredIndex,
297 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000298 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000299 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000300 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000303 void CheckComplexType(const InitializedEntity &Entity,
304 InitListExpr *IList, QualType DeclType,
305 unsigned &Index,
306 InitListExpr *StructuredList,
307 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000308 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000309 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000310 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000311 InitListExpr *StructuredList,
312 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000313 void CheckReferenceType(const InitializedEntity &Entity,
314 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000315 unsigned &Index,
316 InitListExpr *StructuredList,
317 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000318 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000319 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000320 InitListExpr *StructuredList,
321 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000322 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000323 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000324 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000325 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000326 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000327 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000328 unsigned &StructuredIndex,
329 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000330 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000331 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000332 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000333 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000334 InitListExpr *StructuredList,
335 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000336 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000337 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000338 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000339 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000340 RecordDecl::field_iterator *NextField,
341 llvm::APSInt *NextElementIndex,
342 unsigned &Index,
343 InitListExpr *StructuredList,
344 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000345 bool FinishSubobjectInit,
346 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000347 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
348 QualType CurrentObjectType,
349 InitListExpr *StructuredList,
350 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000351 SourceRange InitRange,
352 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000353 void UpdateStructuredListElement(InitListExpr *StructuredList,
354 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000355 Expr *expr);
356 int numArrayElements(QualType DeclType);
357 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000358
Richard Smith454a7cd2014-06-03 08:26:00 +0000359 static ExprResult PerformEmptyInit(Sema &SemaRef,
360 SourceLocation Loc,
361 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000362 bool VerifyOnly,
363 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000364
365 // Explanation on the "FillWithNoInit" mode:
366 //
367 // Assume we have the following definitions (Case#1):
368 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
369 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
370 //
371 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
372 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
373 //
374 // But if we have (Case#2):
375 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
376 //
377 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
378 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
379 //
380 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
381 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
382 // initializers but with special "NoInitExpr" place holders, which tells the
383 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000384 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
385 const InitializedEntity &ParentEntity,
386 InitListExpr *ILE, bool &RequiresSecondPass,
387 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000388 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000389 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000390 InitListExpr *ILE, bool &RequiresSecondPass,
391 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000392 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000393 InitListExpr *ILE, bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000394 InitListExpr *OuterILE, unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000395 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000396 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
397 Expr *InitExpr, FieldDecl *Field,
398 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000399 void CheckEmptyInitializable(const InitializedEntity &Entity,
400 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000401
Douglas Gregor85df8d82009-01-29 00:45:39 +0000402public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000404 InitListExpr *IL, QualType &T, bool VerifyOnly,
405 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000406 bool HadError() { return hadError; }
407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000408 // Retrieves the fully-structured initializer list used for
Douglas Gregor85df8d82009-01-29 00:45:39 +0000409 // semantic analysis and code generation.
410 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
411};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000412
Chris Lattner9ececce2009-02-24 22:48:58 +0000413} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000414
Richard Smith454a7cd2014-06-03 08:26:00 +0000415ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
416 SourceLocation Loc,
417 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000418 bool VerifyOnly,
419 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000420 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
421 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000422 MultiExprArg SubInit;
423 Expr *InitExpr;
424 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
425
426 // C++ [dcl.init.aggr]p7:
427 // If there are fewer initializer-clauses in the list than there are
428 // members in the aggregate, then each member not explicitly initialized
429 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000430 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
431 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
432 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000433 // C++1y / DR1070:
434 // shall be initialized [...] from an empty initializer list.
435 //
436 // We apply the resolution of this DR to C++11 but not C++98, since C++98
437 // does not have useful semantics for initialization from an init list.
438 // We treat this as copy-initialization, because aggregate initialization
439 // always performs copy-initialization on its elements.
440 //
441 // Only do this if we're initializing a class type, to avoid filling in
442 // the initializer list where possible.
443 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
444 InitListExpr(SemaRef.Context, Loc, None, Loc);
445 InitExpr->setType(SemaRef.Context.VoidTy);
446 SubInit = InitExpr;
447 Kind = InitializationKind::CreateCopy(Loc, Loc);
448 } else {
449 // C++03:
450 // shall be value-initialized.
451 }
452
453 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000454 // libstdc++4.6 marks the vector default constructor as explicit in
455 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
456 // stlport does so too. Look for std::__debug for libstdc++, and for
457 // std:: for stlport. This is effectively a compiler-side implementation of
458 // LWG2193.
459 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
460 InitializationSequence::FK_ExplicitConstructor) {
461 OverloadCandidateSet::iterator Best;
462 OverloadingResult O =
463 InitSeq.getFailedCandidateSet()
464 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
465 (void)O;
466 assert(O == OR_Success && "Inconsistent overload resolution");
467 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
468 CXXRecordDecl *R = CtorDecl->getParent();
469
470 if (CtorDecl->getMinRequiredArguments() == 0 &&
471 CtorDecl->isExplicit() && R->getDeclName() &&
472 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000473 bool IsInStd = false;
474 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000475 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000476 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
477 IsInStd = true;
478 }
479
Fangrui Song6907ce22018-07-30 19:24:48 +0000480 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
Nico Weberbcb70ee2014-07-02 23:51:09 +0000481 .Cases("basic_string", "deque", "forward_list", true)
482 .Cases("list", "map", "multimap", "multiset", true)
483 .Cases("priority_queue", "queue", "set", "stack", true)
484 .Cases("unordered_map", "unordered_set", "vector", true)
485 .Default(false)) {
486 InitSeq.InitializeFrom(
487 SemaRef, Entity,
488 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000489 MultiExprArg(), /*TopLevelOfInitList=*/false,
490 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000491 // Emit a warning for this. System header warnings aren't shown
492 // by default, but people working on system headers should see it.
493 if (!VerifyOnly) {
494 SemaRef.Diag(CtorDecl->getLocation(),
495 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000496 if (Entity.getKind() == InitializedEntity::EK_Member)
497 SemaRef.Diag(Entity.getDecl()->getLocation(),
498 diag::note_used_in_initialization_here);
499 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
500 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000501 }
502 }
503 }
504 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000505 if (!InitSeq) {
506 if (!VerifyOnly) {
507 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
508 if (Entity.getKind() == InitializedEntity::EK_Member)
509 SemaRef.Diag(Entity.getDecl()->getLocation(),
510 diag::note_in_omitted_aggregate_initializer)
511 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000512 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
513 bool IsTrailingArrayNewMember =
514 Entity.getParent() &&
515 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000516 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000517 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
518 << Entity.getElementIndex();
519 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000520 }
521 return ExprError();
522 }
523
524 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
525 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
526}
527
528void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
529 SourceLocation Loc) {
530 assert(VerifyOnly &&
531 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000532 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
533 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000534 hadError = true;
535}
536
Richard Smith872307e2016-03-08 22:17:41 +0000537void InitListChecker::FillInEmptyInitForBase(
538 unsigned Init, const CXXBaseSpecifier &Base,
539 const InitializedEntity &ParentEntity, InitListExpr *ILE,
540 bool &RequiresSecondPass, bool FillWithNoInit) {
541 assert(Init < ILE->getNumInits() && "should have been expanded");
542
543 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
544 SemaRef.Context, &Base, false, &ParentEntity);
545
546 if (!ILE->getInit(Init)) {
547 ExprResult BaseInit =
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000548 FillWithNoInit
549 ? new (SemaRef.Context) NoInitExpr(Base.getType())
550 : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
551 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000552 if (BaseInit.isInvalid()) {
553 hadError = true;
554 return;
555 }
556
557 ILE->setInit(Init, BaseInit.getAs<Expr>());
558 } else if (InitListExpr *InnerILE =
559 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
Richard Smithf3b4ca82018-02-07 22:25:16 +0000560 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
561 ILE, Init, FillWithNoInit);
Richard Smith872307e2016-03-08 22:17:41 +0000562 } else if (DesignatedInitUpdateExpr *InnerDIUE =
563 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
564 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000565 RequiresSecondPass, ILE, Init,
566 /*FillWithNoInit =*/true);
Richard Smith872307e2016-03-08 22:17:41 +0000567 }
568}
569
Richard Smith454a7cd2014-06-03 08:26:00 +0000570void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000571 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000573 bool &RequiresSecondPass,
574 bool FillWithNoInit) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000575 SourceLocation Loc = ILE->getEndLoc();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000576 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000578 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000579
580 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
581 if (!RType->getDecl()->isUnion())
582 assert(Init < NumInits && "This ILE should have been expanded");
583
Douglas Gregor2bb07652009-12-22 00:05:34 +0000584 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000585 if (FillWithNoInit) {
586 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
587 if (Init < NumInits)
588 ILE->setInit(Init, Filler);
589 else
590 ILE->updateInit(SemaRef.Context, Init, Filler);
591 return;
592 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000593 // C++1y [dcl.init.aggr]p7:
594 // If there are fewer initializer-clauses in the list than there are
595 // members in the aggregate, then each member not explicitly initialized
596 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000597 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000598 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
599 if (DIE.isInvalid()) {
600 hadError = true;
601 return;
602 }
Richard Smithd87aab92018-07-17 22:24:09 +0000603 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000604 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000605 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000606 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000607 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000608 RequiresSecondPass = true;
609 }
610 return;
611 }
612
Douglas Gregor2bb07652009-12-22 00:05:34 +0000613 if (Field->getType()->isReferenceType()) {
614 // C++ [dcl.init.aggr]p9:
615 // If an incomplete or empty initializer-list leaves a
616 // member of reference type uninitialized, the program is
617 // ill-formed.
618 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
619 << Field->getType()
620 << ILE->getSyntacticForm()->getSourceRange();
621 SemaRef.Diag(Field->getLocation(),
622 diag::note_uninit_reference_member);
623 hadError = true;
624 return;
625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Richard Smith454a7cd2014-06-03 08:26:00 +0000627 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000628 /*VerifyOnly*/false,
629 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000630 if (MemberInit.isInvalid()) {
631 hadError = true;
632 return;
633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregor2bb07652009-12-22 00:05:34 +0000635 if (hadError) {
636 // Do nothing
637 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000638 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000639 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
640 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000641 // extend the initializer list to include the constructor
642 // call and make a note that we'll need to take another pass
643 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000644 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000645 RequiresSecondPass = true;
646 }
647 } else if (InitListExpr *InnerILE
648 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000649 FillInEmptyInitializations(MemberEntity, InnerILE,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000650 RequiresSecondPass, ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000651 else if (DesignatedInitUpdateExpr *InnerDIUE
652 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
653 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000654 RequiresSecondPass, ILE, Init,
655 /*FillWithNoInit =*/true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000656}
657
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000658/// Recursively replaces NULL values within the given initializer list
659/// with expressions that perform value-initialization of the
Richard Smithf3b4ca82018-02-07 22:25:16 +0000660/// appropriate type, and finish off the InitListExpr formation.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661void
Richard Smith454a7cd2014-06-03 08:26:00 +0000662InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000663 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000664 bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000665 InitListExpr *OuterILE,
666 unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000667 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000668 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000669 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000670
Richard Smithf3b4ca82018-02-07 22:25:16 +0000671 // If this is a nested initializer list, we might have changed its contents
672 // (and therefore some of its properties, such as instantiation-dependence)
673 // while filling it in. Inform the outer initializer list so that its state
674 // can be updated to match.
675 // FIXME: We should fully build the inner initializers before constructing
676 // the outer InitListExpr instead of mutating AST nodes after they have
677 // been used as subexpressions of other nodes.
678 struct UpdateOuterILEWithUpdatedInit {
679 InitListExpr *Outer;
680 unsigned OuterIndex;
681 ~UpdateOuterILEWithUpdatedInit() {
682 if (Outer)
683 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
684 }
685 } UpdateOuterRAII = {OuterILE, OuterIndex};
686
Richard Smith382bc512017-02-23 22:41:47 +0000687 // A transparent ILE is not performing aggregate initialization and should
688 // not be filled in.
689 if (ILE->isTransparent())
690 return;
691
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000692 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000693 const RecordDecl *RDecl = RType->getDecl();
694 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000695 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000696 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000697 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
698 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000699 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000700 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000701 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
702 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000703 break;
704 }
705 }
706 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000707 // The fields beyond ILE->getNumInits() are default initialized, so in
708 // order to leave them uninitialized, the ILE is expanded and the extra
709 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000710 unsigned NumElems = numStructUnionElements(ILE->getType());
711 if (RDecl->hasFlexibleArrayMember())
712 ++NumElems;
713 if (ILE->getNumInits() < NumElems)
714 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000715
Douglas Gregor2bb07652009-12-22 00:05:34 +0000716 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000717
718 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
719 for (auto &Base : CXXRD->bases()) {
720 if (hadError)
721 return;
722
723 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
724 FillWithNoInit);
725 ++Init;
726 }
727 }
728
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000729 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000730 if (Field->isUnnamedBitfield())
731 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000732
Douglas Gregor2bb07652009-12-22 00:05:34 +0000733 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000734 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000735
Yunzhong Gaocb779302015-06-10 00:27:52 +0000736 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
737 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000738 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000739 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000740
Douglas Gregor2bb07652009-12-22 00:05:34 +0000741 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000742
Douglas Gregor2bb07652009-12-22 00:05:34 +0000743 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000744 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000745 break;
746 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000747 }
748
749 return;
Mike Stump11289f42009-09-09 15:08:12 +0000750 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000751
752 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Douglas Gregor723796a2009-12-16 06:35:08 +0000754 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000755 unsigned NumInits = ILE->getNumInits();
756 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000757 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000758 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000759 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000760 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000761 // For an array new with an unknown bound, ask for one additional element
762 // in order to populate the array filler.
763 if (Entity.isVariableLengthArrayNew())
764 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000766 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000767 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000768 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000769 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000770 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000771 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000772 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000773 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000774
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000775 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000776 if (hadError)
777 return;
778
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000779 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
780 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000781 ElementEntity.setElementIndex(Init);
782
Richard Smith3e268632018-05-23 23:41:38 +0000783 if (Init >= NumInits && ILE->hasArrayFiller())
784 return;
785
Craig Topperc3ec1492014-05-26 06:22:03 +0000786 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000787 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
788 ILE->setInit(Init, ILE->getArrayFiller());
789 else if (!InitExpr && !ILE->hasArrayFiller()) {
790 Expr *Filler = nullptr;
791
792 if (FillWithNoInit)
793 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
794 else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000795 ExprResult ElementInit =
796 PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
797 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000798 if (ElementInit.isInvalid()) {
799 hadError = true;
800 return;
801 }
802
803 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000804 }
805
806 if (hadError) {
807 // Do nothing
808 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000809 // For arrays, just set the expression used for value-initialization
810 // of the "holes" in the array.
811 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000812 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000813 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000814 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000815 } else {
816 // For arrays, just set the expression used for value-initialization
817 // of the rest of elements and exit.
818 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000819 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000820 return;
821 }
822
Yunzhong Gaocb779302015-06-10 00:27:52 +0000823 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000824 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000825 // extend the initializer list to include the constructor
826 // call and make a note that we'll need to take another pass
827 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000828 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000829 RequiresSecondPass = true;
830 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000831 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000832 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000833 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000834 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000835 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000836 else if (DesignatedInitUpdateExpr *InnerDIUE
837 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
838 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000839 RequiresSecondPass, ILE, Init,
840 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000841 }
842}
843
Douglas Gregor723796a2009-12-16 06:35:08 +0000844InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000845 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000846 bool VerifyOnly,
847 bool TreatUnavailableAsInvalid)
848 : SemaRef(S), VerifyOnly(VerifyOnly),
849 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000850 // FIXME: Check that IL isn't already the semantic form of some other
851 // InitListExpr. If it is, we'd create a broken AST.
852
Steve Narofff8ecff22008-05-01 22:18:59 +0000853 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000854
Richard Smith4e0d2e42013-09-20 20:10:22 +0000855 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000856 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000857 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000858 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000859
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000860 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000861 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000862 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
863 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000864 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000865 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000866 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000867 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000868}
869
870int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000871 // FIXME: use a proper constant
872 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000873 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000874 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000875 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
876 }
877 return maxElements;
878}
879
880int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000881 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000882 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000883 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
884 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000885 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000886 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000887 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000888
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000889 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000890 return std::min(InitializableMembers, 1);
891 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000892}
893
Richard Smith283e2072017-10-03 20:36:00 +0000894/// Determine whether Entity is an entity for which it is idiomatic to elide
895/// the braces in aggregate initialization.
896static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
897 // Recursive initialization of the one and only field within an aggregate
898 // class is considered idiomatic. This case arises in particular for
899 // initialization of std::array, where the C++ standard suggests the idiom of
900 //
901 // std::array<T, N> arr = {1, 2, 3};
902 //
903 // (where std::array is an aggregate struct containing a single array field.
904
905 // FIXME: Should aggregate initialization of a struct with a single
906 // base class and no members also suppress the warning?
907 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
908 return false;
909
910 auto *ParentRD =
911 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
912 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
913 if (CXXRD->getNumBases())
914 return false;
915
916 auto FieldIt = ParentRD->field_begin();
917 assert(FieldIt != ParentRD->field_end() &&
918 "no fields but have initializer for member?");
919 return ++FieldIt == ParentRD->field_end();
920}
921
Richard Smith4e0d2e42013-09-20 20:10:22 +0000922/// Check whether the range of the initializer \p ParentIList from element
923/// \p Index onwards can be used to initialize an object of type \p T. Update
924/// \p Index to indicate how many elements of the list were consumed.
925///
926/// This also fills in \p StructuredList, from element \p StructuredIndex
927/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000928void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000929 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000930 QualType T, unsigned &Index,
931 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000932 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000933 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000934
Steve Narofff8ecff22008-05-01 22:18:59 +0000935 if (T->isArrayType())
936 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000937 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000938 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000939 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000940 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000941 else
David Blaikie83d382b2011-09-23 05:06:16 +0000942 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000943
Eli Friedmane0f832b2008-05-25 13:49:22 +0000944 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000945 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000946 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000947 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000948 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000949 hadError = true;
950 return;
951 }
952
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000953 // Build a structured initializer list corresponding to this subobject.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000954 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
955 ParentIList, Index, T, StructuredList, StructuredIndex,
956 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
957 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000958 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000959
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000960 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000961 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000962 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000963 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000964 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000965 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000966
Richard Smithde229232013-06-06 11:41:05 +0000967 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000968 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000969
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000970 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000971 // Update the structured sub-object initializer so that it's ending
972 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000973 if (EndIndex < ParentIList->getNumInits() &&
974 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000975 SourceLocation EndLoc
976 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
977 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000979
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000980 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000981 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000982 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
983 !isIdiomaticBraceElisionEntity(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000984 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
Richard Smithde229232013-06-06 11:41:05 +0000985 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000986 << StructuredSubobjectInitList->getSourceRange()
987 << FixItHint::CreateInsertion(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000988 StructuredSubobjectInitList->getBeginLoc(), "{")
Alp Tokerb6cc5922014-05-03 03:45:55 +0000989 << FixItHint::CreateInsertion(
990 SemaRef.getLocForEndOfToken(
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000991 StructuredSubobjectInitList->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +0000992 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000993 }
Richard Smith79c88c32018-09-26 19:00:16 +0000994
995 // Warn if this type won't be an aggregate in future versions of C++.
996 auto *CXXRD = T->getAsCXXRecordDecl();
997 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
998 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
999 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1000 << StructuredSubobjectInitList->getSourceRange() << T;
1001 }
Tanya Lattner5029d562010-03-07 04:17:15 +00001002 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001003}
1004
Richard Smith420fa122015-02-12 01:50:05 +00001005/// Warn that \p Entity was of scalar type and was initialized by a
1006/// single-element braced initializer list.
1007static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1008 SourceRange Braces) {
1009 // Don't warn during template instantiation. If the initialization was
1010 // non-dependent, we warned during the initial parse; otherwise, the
1011 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +00001012 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +00001013 return;
1014
1015 unsigned DiagID = 0;
1016
1017 switch (Entity.getKind()) {
1018 case InitializedEntity::EK_VectorElement:
1019 case InitializedEntity::EK_ComplexElement:
1020 case InitializedEntity::EK_ArrayElement:
1021 case InitializedEntity::EK_Parameter:
1022 case InitializedEntity::EK_Parameter_CF_Audited:
1023 case InitializedEntity::EK_Result:
1024 // Extra braces here are suspicious.
1025 DiagID = diag::warn_braces_around_scalar_init;
1026 break;
1027
1028 case InitializedEntity::EK_Member:
1029 // Warn on aggregate initialization but not on ctor init list or
1030 // default member initializer.
1031 if (Entity.getParent())
1032 DiagID = diag::warn_braces_around_scalar_init;
1033 break;
1034
1035 case InitializedEntity::EK_Variable:
1036 case InitializedEntity::EK_LambdaCapture:
1037 // No warning, might be direct-list-initialization.
1038 // FIXME: Should we warn for copy-list-initialization in these cases?
1039 break;
1040
1041 case InitializedEntity::EK_New:
1042 case InitializedEntity::EK_Temporary:
1043 case InitializedEntity::EK_CompoundLiteralInit:
1044 // No warning, braces are part of the syntax of the underlying construct.
1045 break;
1046
1047 case InitializedEntity::EK_RelatedResult:
1048 // No warning, we already warned when initializing the result.
1049 break;
1050
1051 case InitializedEntity::EK_Exception:
1052 case InitializedEntity::EK_Base:
1053 case InitializedEntity::EK_Delegating:
1054 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001055 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001056 case InitializedEntity::EK_Binding:
Richard Smith67af95b2018-07-23 19:19:08 +00001057 case InitializedEntity::EK_StmtExprResult:
Richard Smith420fa122015-02-12 01:50:05 +00001058 llvm_unreachable("unexpected braced scalar init");
1059 }
1060
1061 if (DiagID) {
1062 S.Diag(Braces.getBegin(), DiagID)
1063 << Braces
1064 << FixItHint::CreateRemoval(Braces.getBegin())
1065 << FixItHint::CreateRemoval(Braces.getEnd());
1066 }
1067}
1068
Richard Smith4e0d2e42013-09-20 20:10:22 +00001069/// Check whether the initializer \p IList (that was written with explicit
1070/// braces) can be used to initialize an object of type \p T.
1071///
1072/// This also fills in \p StructuredList with the fully-braced, desugared
1073/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001074void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001075 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001076 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001077 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001078 if (!VerifyOnly) {
1079 SyntacticToSemantic[IList] = StructuredList;
1080 StructuredList->setSyntacticForm(IList);
1081 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001082
1083 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001085 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001086 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001087 QualType ExprTy = T;
1088 if (!ExprTy->isArrayType())
1089 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001090 IList->setType(ExprTy);
1091 StructuredList->setType(ExprTy);
1092 }
Eli Friedman85f54972008-05-25 13:22:35 +00001093 if (hadError)
1094 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001095
Eli Friedman85f54972008-05-25 13:22:35 +00001096 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001097 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001098 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001099 if (SemaRef.getLangOpts().CPlusPlus ||
1100 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001101 IList->getType()->isVectorType())) {
1102 hadError = true;
1103 }
1104 return;
1105 }
1106
Eli Friedmanbd327452009-05-29 20:20:05 +00001107 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001108 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1109 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001110 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001111 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001112 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001113 hadError = true;
1114 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001115 // Special-case
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001116 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1117 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001118 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001119 // Don't complain for incomplete types, since we'll get an error
1120 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001121 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001122 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001123 CurrentObjectType->isArrayType()? 0 :
1124 CurrentObjectType->isVectorType()? 1 :
1125 CurrentObjectType->isScalarType()? 2 :
1126 CurrentObjectType->isUnionType()? 3 :
1127 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001128
Richard Smith1b98ccc2014-07-19 01:39:17 +00001129 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001130 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001131 DK = diag::err_excess_initializers;
1132 hadError = true;
1133 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001134 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001135 DK = diag::err_excess_initializers;
1136 hadError = true;
1137 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001138
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001139 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1140 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001141 }
1142 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001143
Richard Smith79c88c32018-09-26 19:00:16 +00001144 if (!VerifyOnly) {
1145 if (T->isScalarType() && IList->getNumInits() == 1 &&
1146 !isa<InitListExpr>(IList->getInit(0)))
1147 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1148
1149 // Warn if this is a class type that won't be an aggregate in future
1150 // versions of C++.
1151 auto *CXXRD = T->getAsCXXRecordDecl();
1152 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1153 // Don't warn if there's an equivalent default constructor that would be
1154 // used instead.
1155 bool HasEquivCtor = false;
1156 if (IList->getNumInits() == 0) {
1157 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1158 HasEquivCtor = CD && !CD->isDeleted();
1159 }
1160
1161 if (!HasEquivCtor) {
1162 SemaRef.Diag(IList->getBeginLoc(),
1163 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1164 << IList->getSourceRange() << T;
1165 }
1166 }
1167 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001168}
1169
Anders Carlsson6cabf312010-01-23 23:23:01 +00001170void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001171 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001172 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001173 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001174 unsigned &Index,
1175 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001176 unsigned &StructuredIndex,
1177 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001178 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1179 // Explicitly braced initializer for complex type can be real+imaginary
1180 // parts.
1181 CheckComplexType(Entity, IList, DeclType, Index,
1182 StructuredList, StructuredIndex);
1183 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001184 CheckScalarType(Entity, IList, DeclType, Index,
1185 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001186 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001187 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001188 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001189 } else if (DeclType->isRecordType()) {
1190 assert(DeclType->isAggregateType() &&
1191 "non-aggregate records should be handed in CheckSubElementType");
1192 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001193 auto Bases =
1194 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1195 CXXRecordDecl::base_class_iterator());
1196 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1197 Bases = CXXRD->bases();
1198 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1199 SubobjectIsDesignatorContext, Index, StructuredList,
1200 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001201 } else if (DeclType->isArrayType()) {
1202 llvm::APSInt Zero(
1203 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1204 false);
1205 CheckArrayType(Entity, IList, DeclType, Zero,
1206 SubobjectIsDesignatorContext, Index,
1207 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001208 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1209 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001210 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001211 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001212 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1213 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001214 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001215 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001216 CheckReferenceType(Entity, IList, DeclType, Index,
1217 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001218 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001219 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001220 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001221 hadError = true;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001222 } else if (DeclType->isOCLIntelSubgroupAVCType()) {
1223 // Checks for scalar type are sufficient for these types too.
1224 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1225 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001226 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001227 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001228 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1229 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001230 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001231 }
1232}
1233
Anders Carlsson6cabf312010-01-23 23:23:01 +00001234void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001235 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001236 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001237 unsigned &Index,
1238 InitListExpr *StructuredList,
1239 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001240 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001241
1242 if (ElemType->isReferenceType())
1243 return CheckReferenceType(Entity, IList, ElemType, Index,
1244 StructuredList, StructuredIndex);
1245
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001246 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001247 if (SubInitList->getNumInits() == 1 &&
1248 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1249 SIF_None) {
1250 expr = SubInitList->getInit(0);
1251 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001252 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001253 = getStructuredSubobjectInit(IList, Index, ElemType,
1254 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001255 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001256 CheckExplicitInitList(Entity, SubInitList, ElemType,
1257 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001258
1259 if (!hadError && !VerifyOnly) {
1260 bool RequiresSecondPass = false;
1261 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001262 RequiresSecondPass, StructuredList,
1263 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001264 if (RequiresSecondPass && !hadError)
1265 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001266 RequiresSecondPass, StructuredList,
1267 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001268 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001269 ++StructuredIndex;
1270 ++Index;
1271 return;
1272 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001273 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001274 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001275 // This happens during template instantiation when we see an InitListExpr
1276 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001277 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001278 "found implicit initialization for the wrong type");
1279 if (!VerifyOnly)
1280 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1281 ++Index;
1282 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001283 }
1284
Richard Smith3c567fc2015-02-12 01:55:09 +00001285 if (SemaRef.getLangOpts().CPlusPlus) {
1286 // C++ [dcl.init.aggr]p2:
1287 // Each member is copy-initialized from the corresponding
1288 // initializer-clause.
1289
1290 // FIXME: Better EqualLoc?
1291 InitializationKind Kind =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001292 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
Anastasia Stulova8d99a5c02019-08-02 11:19:35 +00001293
1294 // Vector elements can be initialized from other vectors in which case
1295 // we need initialization entity with a type of a vector (and not a vector
1296 // element!) initializing multiple vector elements.
1297 auto TmpEntity =
1298 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1299 ? InitializedEntity::InitializeTemporary(ElemType)
1300 : Entity;
1301
1302 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
Richard Smith3c567fc2015-02-12 01:55:09 +00001303 /*TopLevelOfInitList*/ true);
1304
1305 // C++14 [dcl.init.aggr]p13:
1306 // If the assignment-expression can initialize a member, the member is
1307 // initialized. Otherwise [...] brace elision is assumed
1308 //
1309 // Brace elision is never performed if the element is not an
1310 // assignment-expression.
1311 if (Seq || isa<InitListExpr>(expr)) {
1312 if (!VerifyOnly) {
Anastasia Stulova8d99a5c02019-08-02 11:19:35 +00001313 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
Richard Smith3c567fc2015-02-12 01:55:09 +00001314 if (Result.isInvalid())
1315 hadError = true;
1316
1317 UpdateStructuredListElement(StructuredList, StructuredIndex,
1318 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001319 } else if (!Seq)
1320 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001321 ++Index;
1322 return;
1323 }
1324
1325 // Fall through for subaggregate initialization
1326 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1327 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001328 return CheckScalarType(Entity, IList, ElemType, Index,
1329 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001330 } else if (const ArrayType *arrayType =
1331 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001332 // arrayType can be incomplete if we're initializing a flexible
1333 // array member. There's nothing we can do with the completed
1334 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001336 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001337 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001338 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1339 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001340 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001341 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001342 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001343 }
John McCall5decec92011-02-21 07:57:55 +00001344
1345 // Fall through for subaggregate initialization.
1346
John McCall5decec92011-02-21 07:57:55 +00001347 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001348 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001349 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001350
John McCall5decec92011-02-21 07:57:55 +00001351 // C99 6.7.8p13:
1352 //
1353 // The initializer for a structure or union object that has
1354 // automatic storage duration shall be either an initializer
1355 // list as described below, or a single expression that has
1356 // compatible structure or union type. In the latter case, the
1357 // initial value of the object, including unnamed members, is
1358 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001359 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001360 if (SemaRef.CheckSingleAssignmentConstraints(
1361 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001362 if (ExprRes.isInvalid())
1363 hadError = true;
1364 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001365 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001366 if (ExprRes.isInvalid())
1367 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001368 }
1369 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001370 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001371 ++Index;
1372 return;
1373 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001374 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001375 // Fall through for subaggregate initialization
1376 }
1377
1378 // C++ [dcl.init.aggr]p12:
1379 //
1380 // [...] Otherwise, if the member is itself a non-empty
1381 // subaggregate, brace elision is assumed and the initializer is
1382 // considered for the initialization of the first member of
1383 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001384 // OpenCL vector initializer is handled elsewhere.
1385 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1386 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001387 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1388 StructuredIndex);
1389 ++StructuredIndex;
1390 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001391 if (!VerifyOnly) {
1392 // We cannot initialize this element, so let
1393 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001394 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001395 /*TopLevelOfInitList=*/true);
1396 }
John McCall5decec92011-02-21 07:57:55 +00001397 hadError = true;
1398 ++Index;
1399 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001400 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001401}
1402
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001403void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1404 InitListExpr *IList, QualType DeclType,
1405 unsigned &Index,
1406 InitListExpr *StructuredList,
1407 unsigned &StructuredIndex) {
1408 assert(Index == 0 && "Index in explicit init list must be zero");
1409
1410 // As an extension, clang supports complex initializers, which initialize
1411 // a complex number component-wise. When an explicit initializer list for
1412 // a complex number contains two two initializers, this extension kicks in:
1413 // it exepcts the initializer list to contain two elements convertible to
1414 // the element type of the complex type. The first element initializes
1415 // the real part, and the second element intitializes the imaginary part.
1416
1417 if (IList->getNumInits() != 2)
1418 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1419 StructuredIndex);
1420
1421 // This is an extension in C. (The builtin _Complex type does not exist
1422 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001423 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001424 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1425 << IList->getSourceRange();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001426
1427 // Initialize the complex number.
1428 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1429 InitializedEntity ElementEntity =
1430 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1431
1432 for (unsigned i = 0; i < 2; ++i) {
1433 ElementEntity.setElementIndex(Index);
1434 CheckSubElementType(ElementEntity, IList, elementType, Index,
1435 StructuredList, StructuredIndex);
1436 }
1437}
1438
Anders Carlsson6cabf312010-01-23 23:23:01 +00001439void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001440 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001441 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001442 InitListExpr *StructuredList,
1443 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001444 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001445 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001446 SemaRef.Diag(IList->getBeginLoc(),
1447 SemaRef.getLangOpts().CPlusPlus11
1448 ? diag::warn_cxx98_compat_empty_scalar_initializer
1449 : diag::err_empty_scalar_initializer)
1450 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001451 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001452 ++Index;
1453 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001454 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001455 }
John McCall643169b2010-11-11 00:46:36 +00001456
1457 Expr *expr = IList->getInit(Index);
1458 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001459 // FIXME: This is invalid, and accepting it causes overload resolution
1460 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001461 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001462 SemaRef.Diag(SubIList->getBeginLoc(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001463 diag::ext_many_braces_around_scalar_init)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001464 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001465
1466 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1467 StructuredIndex);
1468 return;
1469 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001470 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001471 SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
1472 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001473 hadError = true;
1474 ++Index;
1475 ++StructuredIndex;
1476 return;
1477 }
1478
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001479 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001480 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001481 hadError = true;
1482 ++Index;
1483 return;
1484 }
1485
John McCall643169b2010-11-11 00:46:36 +00001486 ExprResult Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001487 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1488 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001489
Craig Topperc3ec1492014-05-26 06:22:03 +00001490 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001491
1492 if (Result.isInvalid())
1493 hadError = true; // types weren't compatible.
1494 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001495 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496
John McCall643169b2010-11-11 00:46:36 +00001497 if (ResultExpr != expr) {
1498 // The type was promoted, update initializer list.
1499 IList->setInit(Index, ResultExpr);
1500 }
1501 }
1502 if (hadError)
1503 ++StructuredIndex;
1504 else
1505 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1506 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001507}
1508
Anders Carlsson6cabf312010-01-23 23:23:01 +00001509void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1510 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001511 unsigned &Index,
1512 InitListExpr *StructuredList,
1513 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001514 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001515 // FIXME: It would be wonderful if we could point at the actual member. In
1516 // general, it would be useful to pass location information down the stack,
1517 // so that we know the location (or decl) of the "current object" being
1518 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001519 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001520 SemaRef.Diag(IList->getBeginLoc(),
1521 diag::err_init_reference_member_uninitialized)
1522 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001523 hadError = true;
1524 ++Index;
1525 ++StructuredIndex;
1526 return;
1527 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001528
1529 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001530 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001531 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001532 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1533 << DeclType << IList->getSourceRange();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001534 hadError = true;
1535 ++Index;
1536 ++StructuredIndex;
1537 return;
1538 }
1539
1540 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001541 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001542 hadError = true;
1543 ++Index;
1544 return;
1545 }
1546
1547 ExprResult Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001548 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001549 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001550
1551 if (Result.isInvalid())
1552 hadError = true;
1553
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001554 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001555 IList->setInit(Index, expr);
1556
1557 if (hadError)
1558 ++StructuredIndex;
1559 else
1560 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1561 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001562}
1563
Anders Carlsson6cabf312010-01-23 23:23:01 +00001564void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001565 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001566 unsigned &Index,
1567 InitListExpr *StructuredList,
1568 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001569 const VectorType *VT = DeclType->getAs<VectorType>();
1570 unsigned maxElements = VT->getNumElements();
1571 unsigned numEltsInit = 0;
1572 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001573
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001574 if (Index >= IList->getNumInits()) {
1575 // Make sure the element type can be value-initialized.
1576 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001577 CheckEmptyInitializable(
1578 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001579 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001580 return;
1581 }
1582
David Blaikiebbafb8a2012-03-11 07:00:24 +00001583 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001584 // If the initializing element is a vector, try to copy-initialize
1585 // instead of breaking it apart (which is doomed to failure anyway).
1586 Expr *Init = IList->getInit(Index);
1587 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001588 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001589 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001590 hadError = true;
1591 ++Index;
1592 return;
1593 }
1594
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001595 ExprResult Result =
1596 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1597 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001598
Craig Topperc3ec1492014-05-26 06:22:03 +00001599 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001600 if (Result.isInvalid())
1601 hadError = true; // types weren't compatible.
1602 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001603 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001604
John McCall6a16b2f2010-10-30 00:11:39 +00001605 if (ResultExpr != Init) {
1606 // The type was promoted, update initializer list.
1607 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001608 }
1609 }
John McCall6a16b2f2010-10-30 00:11:39 +00001610 if (hadError)
1611 ++StructuredIndex;
1612 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001613 UpdateStructuredListElement(StructuredList, StructuredIndex,
1614 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001615 ++Index;
1616 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001617 }
Mike Stump11289f42009-09-09 15:08:12 +00001618
John McCall6a16b2f2010-10-30 00:11:39 +00001619 InitializedEntity ElementEntity =
1620 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621
John McCall6a16b2f2010-10-30 00:11:39 +00001622 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1623 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001624 if (Index >= IList->getNumInits()) {
1625 if (VerifyOnly)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001626 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
John McCall6a16b2f2010-10-30 00:11:39 +00001627 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629
John McCall6a16b2f2010-10-30 00:11:39 +00001630 ElementEntity.setElementIndex(Index);
1631 CheckSubElementType(ElementEntity, IList, elementType, Index,
1632 StructuredList, StructuredIndex);
1633 }
James Molloy9eef2652014-06-20 14:35:13 +00001634
1635 if (VerifyOnly)
1636 return;
1637
1638 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1639 const VectorType *T = Entity.getType()->getAs<VectorType>();
1640 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1641 T->getVectorKind() == VectorType::NeonPolyVector)) {
1642 // The ability to use vector initializer lists is a GNU vector extension
1643 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
Fangrui Song6907ce22018-07-30 19:24:48 +00001644 // endian machines it works fine, however on big endian machines it
James Molloy9eef2652014-06-20 14:35:13 +00001645 // exhibits surprising behaviour:
1646 //
1647 // uint32x2_t x = {42, 64};
1648 // return vget_lane_u32(x, 0); // Will return 64.
1649 //
1650 // Because of this, explicitly call out that it is non-portable.
1651 //
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001652 SemaRef.Diag(IList->getBeginLoc(),
James Molloy9eef2652014-06-20 14:35:13 +00001653 diag::warn_neon_vector_initializer_non_portable);
1654
1655 const char *typeCode;
1656 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1657
1658 if (elementType->isFloatingType())
1659 typeCode = "f";
1660 else if (elementType->isSignedIntegerType())
1661 typeCode = "s";
1662 else if (elementType->isUnsignedIntegerType())
1663 typeCode = "u";
1664 else
1665 llvm_unreachable("Invalid element type!");
1666
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001667 SemaRef.Diag(IList->getBeginLoc(),
1668 SemaRef.Context.getTypeSize(VT) > 64
1669 ? diag::note_neon_vector_initializer_non_portable_q
1670 : diag::note_neon_vector_initializer_non_portable)
1671 << typeCode << typeSize;
James Molloy9eef2652014-06-20 14:35:13 +00001672 }
1673
John McCall6a16b2f2010-10-30 00:11:39 +00001674 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001675 }
John McCall6a16b2f2010-10-30 00:11:39 +00001676
1677 InitializedEntity ElementEntity =
1678 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679
John McCall6a16b2f2010-10-30 00:11:39 +00001680 // OpenCL initializers allows vectors to be constructed from vectors.
1681 for (unsigned i = 0; i < maxElements; ++i) {
1682 // Don't attempt to go past the end of the init list
1683 if (Index >= IList->getNumInits())
1684 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001685
John McCall6a16b2f2010-10-30 00:11:39 +00001686 ElementEntity.setElementIndex(Index);
1687
1688 QualType IType = IList->getInit(Index)->getType();
1689 if (!IType->isVectorType()) {
1690 CheckSubElementType(ElementEntity, IList, elementType, Index,
1691 StructuredList, StructuredIndex);
1692 ++numEltsInit;
1693 } else {
1694 QualType VecType;
1695 const VectorType *IVT = IType->getAs<VectorType>();
1696 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697
John McCall6a16b2f2010-10-30 00:11:39 +00001698 if (IType->isExtVectorType())
1699 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1700 else
1701 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001702 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001703 CheckSubElementType(ElementEntity, IList, VecType, Index,
1704 StructuredList, StructuredIndex);
1705 numEltsInit += numIElts;
1706 }
1707 }
1708
1709 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001710 if (numEltsInit != maxElements) {
1711 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001712 SemaRef.Diag(IList->getBeginLoc(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001713 diag::err_vector_incorrect_num_initializers)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001714 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001715 hadError = true;
1716 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001717}
1718
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00001719/// Check if the type of a class element has an accessible destructor, and marks
1720/// it referenced. Returns true if we shouldn't form a reference to the
1721/// destructor.
1722///
1723/// Aggregate initialization requires a class element's destructor be
1724/// accessible per 11.6.1 [dcl.init.aggr]:
1725///
1726/// The destructor for each element of class type is potentially invoked
1727/// (15.4 [class.dtor]) from the context where the aggregate initialization
1728/// occurs.
1729static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1730 Sema &SemaRef) {
1731 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1732 if (!CXXRD)
1733 return false;
1734
1735 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1736 SemaRef.CheckDestructorAccess(Loc, Destructor,
1737 SemaRef.PDiag(diag::err_access_dtor_temp)
1738 << ElementType);
1739 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1740 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1741}
1742
Anders Carlsson6cabf312010-01-23 23:23:01 +00001743void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001744 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001745 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001746 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001747 unsigned &Index,
1748 InitListExpr *StructuredList,
1749 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001750 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1751
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00001752 if (!VerifyOnly) {
1753 if (checkDestructorReference(arrayType->getElementType(),
1754 IList->getEndLoc(), SemaRef)) {
1755 hadError = true;
1756 return;
1757 }
1758 }
1759
Steve Narofff8ecff22008-05-01 22:18:59 +00001760 // Check for the special-case of initializing an array with a string.
1761 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001762 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1763 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001764 // We place the string literal directly into the resulting
1765 // initializer list. This is the only place where the structure
1766 // of the structured initializer list doesn't match exactly,
1767 // because doing so would involve allocating one character
1768 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001769 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001770 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1771 UpdateStructuredListElement(StructuredList, StructuredIndex,
1772 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001773 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1774 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001775 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001776 return;
1777 }
1778 }
John McCall66884dd2011-02-21 07:22:22 +00001779 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001780 // Check for VLAs; in standard C it would be possible to check this
1781 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1782 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001783 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001784 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1785 diag::err_variable_object_no_init)
1786 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001787 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001788 ++Index;
1789 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001790 return;
1791 }
1792
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001793 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1795 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001796 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001797 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001798 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001799 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001800 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001801 maxElementsKnown = true;
1802 }
1803
John McCall66884dd2011-02-21 07:22:22 +00001804 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001805 while (Index < IList->getNumInits()) {
1806 Expr *Init = IList->getInit(Index);
1807 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001808 // If we're not the subobject that matches up with the '{' for
1809 // the designator, we shouldn't be handling the
1810 // designator. Return immediately.
1811 if (!SubobjectIsDesignatorContext)
1812 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001813
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001814 // Handle this designated initializer. elementIndex will be
1815 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001816 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001817 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001818 StructuredList, StructuredIndex, true,
1819 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001820 hadError = true;
1821 continue;
1822 }
1823
Douglas Gregor033d1252009-01-23 16:54:12 +00001824 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001825 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001826 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001827 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001828 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001829
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001830 // If the array is of incomplete type, keep track of the number of
1831 // elements in the initializer.
1832 if (!maxElementsKnown && elementIndex > maxElements)
1833 maxElements = elementIndex;
1834
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001835 continue;
1836 }
1837
1838 // If we know the maximum number of elements, and we've already
1839 // hit it, stop consuming elements in the initializer list.
1840 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001841 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001842
Anders Carlsson6cabf312010-01-23 23:23:01 +00001843 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001845 Entity);
1846 // Check this element.
1847 CheckSubElementType(ElementEntity, IList, elementType, Index,
1848 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001849 ++elementIndex;
1850
1851 // If the array is of incomplete type, keep track of the number of
1852 // elements in the initializer.
1853 if (!maxElementsKnown && elementIndex > maxElements)
1854 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001855 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001856 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001857 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001858 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001859 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001860 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001861 // Sizing an array implicitly to zero is not allowed by ISO C,
1862 // but is supported by GNU.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001863 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001864 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001865
Mike Stump11289f42009-09-09 15:08:12 +00001866 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001867 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001868 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001869 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001870 // If there are any members of the array that get value-initialized, check
1871 // that is possible. That happens if we know the bound and don't have
1872 // enough elements, or if we're performing an array new with an unknown
1873 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001874 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001875 if ((maxElementsKnown && elementIndex < maxElements) ||
1876 Entity.isVariableLengthArrayNew())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001877 CheckEmptyInitializable(
1878 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1879 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001880 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001881}
1882
Eli Friedman3fa64df2011-08-23 22:24:57 +00001883bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1884 Expr *InitExpr,
1885 FieldDecl *Field,
1886 bool TopLevelObject) {
1887 // Handle GNU flexible array initializers.
1888 unsigned FlexArrayDiag;
1889 if (isa<InitListExpr>(InitExpr) &&
1890 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1891 // Empty flexible array init always allowed as an extension
1892 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001893 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001894 // Disallow flexible array init in C++; it is not required for gcc
1895 // compatibility, and it needs work to IRGen correctly in general.
1896 FlexArrayDiag = diag::err_flexible_array_init;
1897 } else if (!TopLevelObject) {
1898 // Disallow flexible array init on non-top-level object
1899 FlexArrayDiag = diag::err_flexible_array_init;
1900 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1901 // Disallow flexible array init on anything which is not a variable.
1902 FlexArrayDiag = diag::err_flexible_array_init;
1903 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1904 // Disallow flexible array init on local variables.
1905 FlexArrayDiag = diag::err_flexible_array_init;
1906 } else {
1907 // Allow other cases.
1908 FlexArrayDiag = diag::ext_flexible_array_init;
1909 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001910
1911 if (!VerifyOnly) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001912 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
1913 << InitExpr->getBeginLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001914 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1915 << Field;
1916 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001917
1918 return FlexArrayDiag != diag::ext_flexible_array_init;
1919}
1920
Richard Smith872307e2016-03-08 22:17:41 +00001921void InitListChecker::CheckStructUnionTypes(
1922 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1923 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1924 bool SubobjectIsDesignatorContext, unsigned &Index,
1925 InitListExpr *StructuredList, unsigned &StructuredIndex,
1926 bool TopLevelObject) {
1927 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001928
Eli Friedman23a9e312008-05-19 19:16:24 +00001929 // If the record is invalid, some of it's members are invalid. To avoid
1930 // confusion, we forgo checking the intializer for the entire record.
1931 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001932 // Assume it was supposed to consume a single initializer.
1933 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001934 hadError = true;
1935 return;
Mike Stump11289f42009-09-09 15:08:12 +00001936 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001937
1938 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001939 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001940
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001941 if (!VerifyOnly)
1942 for (FieldDecl *FD : RD->fields()) {
1943 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00001944 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001945 hadError = true;
1946 return;
1947 }
1948 }
1949
Richard Smith852c9db2013-04-20 22:23:05 +00001950 // If there's a default initializer, use it.
1951 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1952 if (VerifyOnly)
1953 return;
1954 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1955 Field != FieldEnd; ++Field) {
1956 if (Field->hasInClassInitializer()) {
1957 StructuredList->setInitializedFieldInUnion(*Field);
1958 // FIXME: Actually build a CXXDefaultInitExpr?
1959 return;
1960 }
1961 }
1962 }
1963
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001964 // Value-initialize the first member of the union that isn't an unnamed
1965 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001966 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1967 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001968 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001969 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001970 CheckEmptyInitializable(
1971 InitializedEntity::InitializeMember(*Field, &Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001972 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001973 else
David Blaikie40ed2972012-06-06 20:45:41 +00001974 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001975 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001976 }
1977 }
1978 return;
1979 }
1980
Richard Smith872307e2016-03-08 22:17:41 +00001981 bool InitializedSomething = false;
1982
1983 // If we have any base classes, they are initialized prior to the fields.
1984 for (auto &Base : Bases) {
1985 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
Richard Smith872307e2016-03-08 22:17:41 +00001986
1987 // Designated inits always initialize fields, so if we see one, all
1988 // remaining base classes have no explicit initializer.
1989 if (Init && isa<DesignatedInitExpr>(Init))
1990 Init = nullptr;
1991
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00001992 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
Richard Smith872307e2016-03-08 22:17:41 +00001993 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1994 SemaRef.Context, &Base, false, &Entity);
1995 if (Init) {
1996 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1997 StructuredList, StructuredIndex);
1998 InitializedSomething = true;
1999 } else if (VerifyOnly) {
2000 CheckEmptyInitializable(BaseEntity, InitLoc);
2001 }
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002002
2003 if (!VerifyOnly)
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00002004 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002005 hadError = true;
2006 return;
2007 }
Richard Smith872307e2016-03-08 22:17:41 +00002008 }
2009
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002010 // If structDecl is a forward declaration, this loop won't do
2011 // anything except look at designated initializers; That's okay,
2012 // because an error should get printed out elsewhere. It might be
2013 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002014 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002015 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002016 bool CheckForMissingFields =
2017 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002018 bool HasDesignatedInit = false;
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002019
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002020 while (Index < IList->getNumInits()) {
2021 Expr *Init = IList->getInit(Index);
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002022 SourceLocation InitLoc = Init->getBeginLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002023
2024 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002025 // If we're not the subobject that matches up with the '{' for
2026 // the designator, we shouldn't be handling the
2027 // designator. Return immediately.
2028 if (!SubobjectIsDesignatorContext)
2029 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002030
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002031 HasDesignatedInit = true;
2032
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002033 // Handle this designated initializer. Field will be updated to
2034 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002035 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00002036 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002037 StructuredList, StructuredIndex,
2038 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002039 hadError = true;
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002040 else if (!VerifyOnly) {
2041 // Find the field named by the designated initializer.
2042 RecordDecl::field_iterator F = RD->field_begin();
2043 while (std::next(F) != Field)
2044 ++F;
2045 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00002046 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002047 hadError = true;
2048 return;
2049 }
2050 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002051
Douglas Gregora9add4e2009-02-12 19:00:39 +00002052 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00002053
2054 // Disable check for missing fields when designators are used.
2055 // This matches gcc behaviour.
2056 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002057 continue;
2058 }
2059
2060 if (Field == FieldEnd) {
2061 // We've run out of fields. We're done.
2062 break;
2063 }
2064
Douglas Gregora9add4e2009-02-12 19:00:39 +00002065 // We've already initialized a member of a union. We're done.
2066 if (InitializedSomething && DeclType->isUnionType())
2067 break;
2068
Douglas Gregor91f84212008-12-11 16:49:14 +00002069 // If we've hit the flexible array member at the end, we're done.
2070 if (Field->getType()->isIncompleteArrayType())
2071 break;
2072
Douglas Gregor51695702009-01-29 16:53:55 +00002073 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002074 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002075 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00002076 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00002077 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002078
Douglas Gregora82064c2011-06-29 21:51:31 +00002079 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002080 bool InvalidUse;
2081 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002082 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002083 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002084 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2085 *Field, IList->getInit(Index)->getBeginLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002086 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002087 ++Index;
2088 ++Field;
2089 hadError = true;
2090 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002091 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002092
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002093 if (!VerifyOnly) {
2094 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00002095 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002096 hadError = true;
2097 return;
2098 }
2099 }
2100
Anders Carlsson6cabf312010-01-23 23:23:01 +00002101 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002102 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002103 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2104 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00002105 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00002106
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002107 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00002108 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00002109 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00002110 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002111
2112 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00002113 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002114
John McCalle40b58e2010-03-11 19:32:38 +00002115 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002116 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2117 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2118 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00002119 // It is possible we have one or more unnamed bitfields remaining.
2120 // Find first (if any) named field and emit warning.
2121 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2122 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00002123 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00002124 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00002125 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00002126 break;
2127 }
2128 }
2129 }
2130
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002131 // Check that any remaining fields can be value-initialized.
2132 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2133 !Field->getType()->isIncompleteArrayType()) {
2134 // FIXME: Should check for holes left by designated initializers too.
2135 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00002136 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00002137 CheckEmptyInitializable(
2138 InitializedEntity::InitializeMember(*Field, &Entity),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002139 IList->getEndLoc());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002140 }
2141 }
2142
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002143 // Check that the types of the remaining fields have accessible destructors.
2144 if (!VerifyOnly) {
2145 // If the initializer expression has a designated initializer, check the
2146 // elements for which a designated initializer is not provided too.
2147 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2148 : Field;
2149 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2150 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00002151 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
Akira Hatanaka2ccb3192018-09-07 02:38:01 +00002152 hadError = true;
2153 return;
2154 }
2155 }
2156 }
2157
Mike Stump11289f42009-09-09 15:08:12 +00002158 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002159 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002160 return;
2161
David Blaikie40ed2972012-06-06 20:45:41 +00002162 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002163 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002164 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002165 ++Index;
2166 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002167 }
2168
Anders Carlsson6cabf312010-01-23 23:23:01 +00002169 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002170 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171
Anders Carlsson6cabf312010-01-23 23:23:01 +00002172 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002174 StructuredList, StructuredIndex);
2175 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002177 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002178}
Steve Narofff8ecff22008-05-01 22:18:59 +00002179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002180/// Expand a field designator that refers to a member of an
Douglas Gregord5846a12009-04-15 06:41:24 +00002181/// anonymous struct or union into a series of field designators that
2182/// refers to the field within the appropriate subobject.
2183///
Douglas Gregord5846a12009-04-15 06:41:24 +00002184static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002185 DesignatedInitExpr *DIE,
2186 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002187 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002188 typedef DesignatedInitExpr::Designator Designator;
2189
Douglas Gregord5846a12009-04-15 06:41:24 +00002190 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002191 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002192 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2193 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2194 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002195 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002196 DIE->getDesignator(DesigIdx)->getDotLoc(),
2197 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2198 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002199 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2200 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002201 assert(isa<FieldDecl>(*PI));
2202 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002203 }
2204
2205 // Expand the current designator into the set of replacement
2206 // designators, so we have a full subobject path down to where the
2207 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002208 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002209 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002210}
Mike Stump11289f42009-09-09 15:08:12 +00002211
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002212static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2213 DesignatedInitExpr *DIE) {
2214 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2215 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2216 for (unsigned I = 0; I < NumIndexExprs; ++I)
2217 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002218 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2219 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002220 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002221 DIE->usesGNUSyntax(), DIE->getInit());
2222}
2223
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002224namespace {
2225
2226// Callback to only accept typo corrections that are for field members of
2227// the given struct or union.
Bruno Ricci70ad3962019-03-25 17:08:51 +00002228class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002229 public:
2230 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2231 : Record(RD) {}
2232
Craig Toppere14c0f82014-03-12 04:55:44 +00002233 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002234 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2235 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2236 }
2237
Bruno Ricci70ad3962019-03-25 17:08:51 +00002238 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2239 return llvm::make_unique<FieldInitializerValidatorCCC>(*this);
2240 }
2241
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002242 private:
2243 RecordDecl *Record;
2244};
2245
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002246} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002247
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002248/// Check the well-formedness of a C99 designated initializer.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002249///
2250/// Determines whether the designated initializer @p DIE, which
2251/// resides at the given @p Index within the initializer list @p
2252/// IList, is well-formed for a current object of type @p DeclType
2253/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002254/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002255/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002256///
2257/// @param IList The initializer list in which this designated
2258/// initializer occurs.
2259///
Douglas Gregora5324162009-04-15 04:56:10 +00002260/// @param DIE The designated initializer expression.
2261///
2262/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002263///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002264/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002265/// into which the designation in @p DIE should refer.
2266///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002267/// @param NextField If non-NULL and the first designator in @p DIE is
2268/// a field, this will be set to the field declaration corresponding
2269/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002270///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002271/// @param NextElementIndex If non-NULL and the first designator in @p
2272/// DIE is an array designator or GNU array-range designator, this
2273/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002274///
2275/// @param Index Index into @p IList where the designated initializer
2276/// @p DIE occurs.
2277///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002278/// @param StructuredList The initializer list expression that
2279/// describes all of the subobject initializers in the order they'll
2280/// actually be initialized.
2281///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002282/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002283bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002284InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002285 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002286 DesignatedInitExpr *DIE,
2287 unsigned DesigIdx,
2288 QualType &CurrentObjectType,
2289 RecordDecl::field_iterator *NextField,
2290 llvm::APSInt *NextElementIndex,
2291 unsigned &Index,
2292 InitListExpr *StructuredList,
2293 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002294 bool FinishSubobjectInit,
2295 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002296 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002297 // Check the actual initialization for the designated object type.
2298 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002299
2300 // Temporarily remove the designator expression from the
2301 // initializer list that the child calls see, so that we don't try
2302 // to re-process the designator.
2303 unsigned OldIndex = Index;
2304 IList->setInit(OldIndex, DIE->getInit());
2305
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002306 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002307 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002308
2309 // Restore the designated initializer expression in the syntactic
2310 // form of the initializer list.
2311 if (IList->getInit(OldIndex) != DIE->getInit())
2312 DIE->setInit(IList->getInit(OldIndex));
2313 IList->setInit(OldIndex, DIE);
2314
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002315 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002316 }
2317
Douglas Gregora5324162009-04-15 04:56:10 +00002318 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002319 bool IsFirstDesignator = (DesigIdx == 0);
2320 if (!VerifyOnly) {
2321 assert((IsFirstDesignator || StructuredList) &&
2322 "Need a non-designated initializer list to start from");
2323
2324 // Determine the structural initializer list that corresponds to the
2325 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002326 if (IsFirstDesignator)
2327 StructuredList = SyntacticToSemantic.lookup(IList);
2328 else {
2329 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2330 StructuredList->getInit(StructuredIndex) : nullptr;
2331 if (!ExistingInit && StructuredList->hasArrayFiller())
2332 ExistingInit = StructuredList->getArrayFiller();
2333
2334 if (!ExistingInit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002335 StructuredList = getStructuredSubobjectInit(
2336 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002337 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
Yunzhong Gaocb779302015-06-10 00:27:52 +00002338 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2339 StructuredList = Result;
2340 else {
2341 if (DesignatedInitUpdateExpr *E =
2342 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2343 StructuredList = E->getUpdater();
2344 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002345 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2346 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002347 ExistingInit, DIE->getEndLoc());
Yunzhong Gaocb779302015-06-10 00:27:52 +00002348 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2349 StructuredList = DIUE->getUpdater();
2350 }
2351
2352 // We need to check on source range validity because the previous
2353 // initializer does not have to be an explicit initializer. e.g.,
2354 //
2355 // struct P { int a, b; };
2356 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2357 //
2358 // There is an overwrite taking place because the first braced initializer
2359 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2360 if (ExistingInit->getSourceRange().isValid()) {
2361 // We are creating an initializer list that initializes the
2362 // subobjects of the current object, but there was already an
2363 // initialization that completely initialized the current
2364 // subobject, e.g., by a compound literal:
2365 //
2366 // struct X { int a, b; };
2367 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2368 //
2369 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2370 // designated initializer re-initializes the whole
2371 // subobject [0], overwriting previous initializers.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002372 SemaRef.Diag(D->getBeginLoc(),
Yunzhong Gaocb779302015-06-10 00:27:52 +00002373 diag::warn_subobject_initializer_overrides)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002374 << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00002375
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002376 SemaRef.Diag(ExistingInit->getBeginLoc(),
Yunzhong Gaocb779302015-06-10 00:27:52 +00002377 diag::note_previous_initializer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002378 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002379 }
2380 }
2381 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002382 assert(StructuredList && "Expected a structured initializer list");
2383 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002384
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002385 if (D->isFieldDesignator()) {
2386 // C99 6.7.8p7:
2387 //
2388 // If a designator has the form
2389 //
2390 // . identifier
2391 //
2392 // then the current object (defined below) shall have
2393 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002394 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002395 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002396 if (!RT) {
2397 SourceLocation Loc = D->getDotLoc();
2398 if (Loc.isInvalid())
2399 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002400 if (!VerifyOnly)
2401 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002402 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002403 ++Index;
2404 return true;
2405 }
2406
Douglas Gregord5846a12009-04-15 06:41:24 +00002407 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002408 if (!KnownField) {
2409 IdentifierInfo *FieldName = D->getFieldName();
2410 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2411 for (NamedDecl *ND : Lookup) {
2412 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2413 KnownField = FD;
2414 break;
2415 }
2416 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002417 // In verify mode, don't modify the original.
2418 if (VerifyOnly)
2419 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002420 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002421 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002422 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002423 break;
2424 }
2425 }
David Majnemer36ef8982014-08-11 18:33:59 +00002426 if (!KnownField) {
2427 if (VerifyOnly) {
2428 ++Index;
2429 return true; // No typo correction when just trying this out.
2430 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002431
David Majnemer36ef8982014-08-11 18:33:59 +00002432 // Name lookup found something, but it wasn't a field.
2433 if (!Lookup.empty()) {
2434 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2435 << FieldName;
2436 SemaRef.Diag(Lookup.front()->getLocation(),
2437 diag::note_field_designator_found);
2438 ++Index;
2439 return true;
2440 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002441
David Majnemer36ef8982014-08-11 18:33:59 +00002442 // Name lookup didn't find anything.
2443 // Determine whether this was a typo for another field name.
Bruno Ricci70ad3962019-03-25 17:08:51 +00002444 FieldInitializerValidatorCCC CCC(RT->getDecl());
Richard Smithf9b15102013-08-17 00:46:16 +00002445 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2446 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Bruno Ricci70ad3962019-03-25 17:08:51 +00002447 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002448 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002449 SemaRef.diagnoseTypo(
2450 Corrected,
2451 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002452 << FieldName << CurrentObjectType);
2453 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002454 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002455 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002456 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002457 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2458 << FieldName << CurrentObjectType;
2459 ++Index;
2460 return true;
2461 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002462 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002463 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002464
David Majnemer58e4ea92014-08-23 01:48:50 +00002465 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002466
2467 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2468 FieldIndex = CXXRD->getNumBases();
2469
David Majnemer58e4ea92014-08-23 01:48:50 +00002470 for (auto *FI : RT->getDecl()->fields()) {
2471 if (FI->isUnnamedBitfield())
2472 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002473 if (declaresSameEntity(KnownField, FI)) {
2474 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002475 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002476 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002477 ++FieldIndex;
2478 }
2479
David Majnemer36ef8982014-08-11 18:33:59 +00002480 RecordDecl::field_iterator Field =
2481 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2482
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002483 // All of the fields of a union are located at the same place in
2484 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002485 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002486 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002487 if (!VerifyOnly) {
2488 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002489 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002490 assert(StructuredList->getNumInits() == 1
2491 && "A union should never have more than one initializer!");
2492
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002493 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002494 if (ExistingInit) {
2495 // We're about to throw away an initializer, emit warning.
2496 SemaRef.Diag(D->getFieldLoc(),
2497 diag::warn_initializer_overrides)
2498 << D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002499 SemaRef.Diag(ExistingInit->getBeginLoc(),
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002500 diag::note_previous_initializer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002501 << /*FIXME:has side effects=*/0
2502 << ExistingInit->getSourceRange();
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002503 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002504
2505 // remove existing initializer
2506 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002507 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002508 }
2509
David Blaikie40ed2972012-06-06 20:45:41 +00002510 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002511 }
Douglas Gregor51695702009-01-29 16:53:55 +00002512 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002513
Douglas Gregora82064c2011-06-29 21:51:31 +00002514 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002515 bool InvalidUse;
2516 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002517 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002518 else
David Blaikie40ed2972012-06-06 20:45:41 +00002519 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002520 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002521 ++Index;
2522 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002523 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002524
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002525 if (!VerifyOnly) {
2526 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002527 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002528
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002529 // Make sure that our non-designated initializer list has space
2530 // for a subobject corresponding to this field.
2531 if (FieldIndex >= StructuredList->getNumInits())
2532 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2533 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002534
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002535 // This designator names a flexible array member.
2536 if (Field->getType()->isIncompleteArrayType()) {
2537 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002538 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002539 // We can't designate an object within the flexible array
2540 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002541 if (!VerifyOnly) {
2542 DesignatedInitExpr::Designator *NextD
2543 = DIE->getDesignator(DesigIdx + 1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002544 SemaRef.Diag(NextD->getBeginLoc(),
2545 diag::err_designator_into_flexible_array_member)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002546 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002547 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002548 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002549 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002550 Invalid = true;
2551 }
2552
Chris Lattner001b29c2010-10-10 17:49:49 +00002553 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2554 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002555 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002556 if (!VerifyOnly) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002557 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2558 diag::err_flexible_array_init_needs_braces)
2559 << DIE->getInit()->getSourceRange();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002560 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002561 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002562 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002563 Invalid = true;
2564 }
2565
Eli Friedman3fa64df2011-08-23 22:24:57 +00002566 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002567 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002568 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002569 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002570
2571 if (Invalid) {
2572 ++Index;
2573 return true;
2574 }
2575
2576 // Initialize the array.
2577 bool prevHadError = hadError;
2578 unsigned newStructuredIndex = FieldIndex;
2579 unsigned OldIndex = Index;
2580 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002581
2582 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002583 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002584 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002585 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002586
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002587 IList->setInit(OldIndex, DIE);
2588 if (hadError && !prevHadError) {
2589 ++Field;
2590 ++FieldIndex;
2591 if (NextField)
2592 *NextField = Field;
2593 StructuredIndex = FieldIndex;
2594 return true;
2595 }
2596 } else {
2597 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002598 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002599 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002600
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002601 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002602 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002603 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002604 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002605 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002606 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002607 return true;
2608 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002609
2610 // Find the position of the next field to be initialized in this
2611 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002612 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002613 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002614
2615 // If this the first designator, our caller will continue checking
2616 // the rest of this struct/class/union subobject.
2617 if (IsFirstDesignator) {
2618 if (NextField)
2619 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002620 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002621 return false;
2622 }
2623
Douglas Gregor17bd0942009-01-28 23:36:17 +00002624 if (!FinishSubobjectInit)
2625 return false;
2626
Douglas Gregord5846a12009-04-15 06:41:24 +00002627 // We've already initialized something in the union; we're done.
2628 if (RT->getDecl()->isUnion())
2629 return hadError;
2630
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002631 // Check the remaining fields within this class/struct/union subobject.
2632 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002633
Richard Smith872307e2016-03-08 22:17:41 +00002634 auto NoBases =
2635 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2636 CXXRecordDecl::base_class_iterator());
2637 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2638 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002639 return hadError && !prevHadError;
2640 }
2641
2642 // C99 6.7.8p6:
2643 //
2644 // If a designator has the form
2645 //
2646 // [ constant-expression ]
2647 //
2648 // then the current object (defined below) shall have array
2649 // type and the expression shall be an integer constant
2650 // expression. If the array is of unknown size, any
2651 // nonnegative value is valid.
2652 //
2653 // Additionally, cope with the GNU extension that permits
2654 // designators of the form
2655 //
2656 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002657 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002658 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002659 if (!VerifyOnly)
2660 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2661 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002662 ++Index;
2663 return true;
2664 }
2665
Craig Topperc3ec1492014-05-26 06:22:03 +00002666 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002667 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2668 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002669 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002670 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002671 DesignatedEndIndex = DesignatedStartIndex;
2672 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002673 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002674
Mike Stump11289f42009-09-09 15:08:12 +00002675 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002676 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002677 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002678 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002679 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002680
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002681 // Codegen can't handle evaluating array range designators that have side
2682 // effects, because we replicate the AST value for each initialized element.
2683 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2684 // elements with something that has a side effect, so codegen can emit an
2685 // "error unsupported" error instead of miscompiling the app.
2686 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002687 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002688 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002689 }
2690
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002691 if (isa<ConstantArrayType>(AT)) {
2692 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002693 DesignatedStartIndex
2694 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002695 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002696 DesignatedEndIndex
2697 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002698 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2699 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002700 if (!VerifyOnly)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002701 SemaRef.Diag(IndexExpr->getBeginLoc(),
2702 diag::err_array_designator_too_large)
2703 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2704 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002705 ++Index;
2706 return true;
2707 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002708 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002709 unsigned DesignatedIndexBitWidth =
2710 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2711 DesignatedStartIndex =
2712 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2713 DesignatedEndIndex =
2714 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002715 DesignatedStartIndex.setIsUnsigned(true);
2716 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002717 }
Mike Stump11289f42009-09-09 15:08:12 +00002718
Eli Friedman1f16b742013-06-11 21:48:11 +00002719 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2720 // We're modifying a string literal init; we have to decompose the string
2721 // so we can modify the individual characters.
2722 ASTContext &Context = SemaRef.Context;
2723 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2724
2725 // Compute the character type
2726 QualType CharTy = AT->getElementType();
2727
2728 // Compute the type of the integer literals.
2729 QualType PromotedCharTy = CharTy;
2730 if (CharTy->isPromotableIntegerType())
2731 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2732 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2733
2734 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2735 // Get the length of the string.
2736 uint64_t StrLen = SL->getLength();
2737 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2738 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2739 StructuredList->resizeInits(Context, StrLen);
2740
2741 // Build a literal for each character in the string, and put them into
2742 // the init list.
2743 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2744 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2745 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002746 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002747 if (CharTy != PromotedCharTy)
2748 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002749 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002750 StructuredList->updateInit(Context, i, Init);
2751 }
2752 } else {
2753 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2754 std::string Str;
2755 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2756
2757 // Get the length of the string.
2758 uint64_t StrLen = Str.size();
2759 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2760 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2761 StructuredList->resizeInits(Context, StrLen);
2762
2763 // Build a literal for each character in the string, and put them into
2764 // the init list.
2765 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2766 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2767 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002768 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002769 if (CharTy != PromotedCharTy)
2770 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002771 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002772 StructuredList->updateInit(Context, i, Init);
2773 }
2774 }
2775 }
2776
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002777 // Make sure that our non-designated initializer list has space
2778 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002779 if (!VerifyOnly &&
2780 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002781 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002782 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002783
Douglas Gregor17bd0942009-01-28 23:36:17 +00002784 // Repeatedly perform subobject initializations in the range
2785 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002786
Douglas Gregor17bd0942009-01-28 23:36:17 +00002787 // Move to the next designator
2788 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2789 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002790
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002791 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002792 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002793
Douglas Gregor17bd0942009-01-28 23:36:17 +00002794 while (DesignatedStartIndex <= DesignatedEndIndex) {
2795 // Recurse to check later designated subobjects.
2796 QualType ElementType = AT->getElementType();
2797 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002799 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002800 if (CheckDesignatedInitializer(
2801 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2802 nullptr, Index, StructuredList, ElementIndex,
2803 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2804 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002805 return true;
2806
2807 // Move to the next index in the array that we'll be initializing.
2808 ++DesignatedStartIndex;
2809 ElementIndex = DesignatedStartIndex.getZExtValue();
2810 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002811
2812 // If this the first designator, our caller will continue checking
2813 // the rest of this array subobject.
2814 if (IsFirstDesignator) {
2815 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002816 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002817 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002818 return false;
2819 }
Mike Stump11289f42009-09-09 15:08:12 +00002820
Douglas Gregor17bd0942009-01-28 23:36:17 +00002821 if (!FinishSubobjectInit)
2822 return false;
2823
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002824 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002825 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002827 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002828 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002829 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002830}
2831
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002832// Get the structured initializer list for a subobject of type
2833// @p CurrentObjectType.
2834InitListExpr *
2835InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2836 QualType CurrentObjectType,
2837 InitListExpr *StructuredList,
2838 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002839 SourceRange InitRange,
2840 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002841 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002842 return nullptr; // No structured list in verification-only mode.
2843 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002844 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002845 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002846 else if (StructuredIndex < StructuredList->getNumInits())
2847 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002848
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002849 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002850 // There might have already been initializers for subobjects of the current
2851 // object, but a subsequent initializer list will overwrite the entirety
2852 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2853 //
2854 // struct P { char x[6]; };
2855 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2856 //
2857 // The first designated initializer is ignored, and l.x is just "f".
2858 if (!IsFullyOverwritten)
2859 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002860
2861 if (ExistingInit) {
2862 // We are creating an initializer list that initializes the
2863 // subobjects of the current object, but there was already an
2864 // initialization that completely initialized the current
2865 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002866 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002867 // struct X { int a, b; };
2868 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002869 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002870 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2871 // designated initializer re-initializes the whole
2872 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002873 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002874 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002875 << InitRange;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002876 SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
2877 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002878 }
2879
Mike Stump11289f42009-09-09 15:08:12 +00002880 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002881 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002882 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002883 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002884
Eli Friedman91f5ae52012-02-23 02:25:10 +00002885 QualType ResultType = CurrentObjectType;
2886 if (!ResultType->isArrayType())
2887 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2888 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002889
Douglas Gregor6d00c992009-03-20 23:58:33 +00002890 // Pre-allocate storage for the structured initializer list.
2891 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002892 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002893 bool GotNumInits = false;
2894 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002895 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002896 GotNumInits = true;
2897 } else if (Index < IList->getNumInits()) {
2898 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002899 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002900 GotNumInits = true;
2901 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002902 }
2903
Mike Stump11289f42009-09-09 15:08:12 +00002904 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002905 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2906 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2907 NumElements = CAType->getSize().getZExtValue();
2908 // Simple heuristic so that we don't allocate a very large
2909 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002910 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002911 NumElements = 0;
2912 }
John McCall9dd450b2009-09-21 23:43:11 +00002913 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002914 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002915 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002916 RecordDecl *RDecl = RType->getDecl();
2917 if (RDecl->isUnion())
2918 NumElements = 1;
2919 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002920 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002921 }
2922
Ted Kremenekac034612010-04-13 23:39:13 +00002923 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002924
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002925 // Link this new initializer list into the structured initializer
2926 // lists.
2927 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002928 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002929 else {
2930 Result->setSyntacticForm(IList);
2931 SyntacticToSemantic[IList] = Result;
2932 }
2933
2934 return Result;
2935}
2936
2937/// Update the initializer at index @p StructuredIndex within the
2938/// structured initializer list to the value @p expr.
2939void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2940 unsigned &StructuredIndex,
2941 Expr *expr) {
2942 // No structured initializer list to update
2943 if (!StructuredList)
2944 return;
2945
Ted Kremenekac034612010-04-13 23:39:13 +00002946 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2947 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002948 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002949 // We need to check on source range validity because the previous
2950 // initializer does not have to be an explicit initializer.
2951 // struct P { int a, b; };
2952 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2953 // There is an overwrite taking place because the first braced initializer
2954 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2955 if (PrevInit->getSourceRange().isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002956 SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
2957 << expr->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002958
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002959 SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
2960 << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
Yunzhong Gaocb779302015-06-10 00:27:52 +00002961 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002962 }
Mike Stump11289f42009-09-09 15:08:12 +00002963
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002964 ++StructuredIndex;
2965}
2966
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002967/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002968/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002969/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002970/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002971/// failure. Returns the index expression, possibly with an implicit cast
2972/// added, on success. If everything went okay, Value will receive the
2973/// value of the constant expression.
2974static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002975CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002976 SourceLocation Loc = Index->getBeginLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002977
2978 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002979 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2980 if (Result.isInvalid())
2981 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002982
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002983 if (Value.isSigned() && Value.isNegative())
2984 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002985 << Value.toString(10) << Index->getSourceRange();
2986
Douglas Gregor51650d32009-01-23 21:04:18 +00002987 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002988 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002989}
2990
John McCalldadc5752010-08-24 06:29:42 +00002991ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002992 SourceLocation Loc,
2993 bool GNUSyntax,
2994 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002995 typedef DesignatedInitExpr::Designator ASTDesignator;
2996
2997 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002998 SmallVector<ASTDesignator, 32> Designators;
2999 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003000
3001 // Build designators and check array designator expressions.
3002 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3003 const Designator &D = Desig.getDesignator(Idx);
3004 switch (D.getKind()) {
3005 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00003006 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003007 D.getFieldLoc()));
3008 break;
3009
3010 case Designator::ArrayDesignator: {
3011 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3012 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00003013 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003014 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00003015 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003016 Invalid = true;
3017 else {
3018 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00003019 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003020 D.getRBracketLoc()));
3021 InitExpressions.push_back(Index);
3022 }
3023 break;
3024 }
3025
3026 case Designator::ArrayRangeDesignator: {
3027 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3028 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3029 llvm::APSInt StartValue;
3030 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003031 bool StartDependent = StartIndex->isTypeDependent() ||
3032 StartIndex->isValueDependent();
3033 bool EndDependent = EndIndex->isTypeDependent() ||
3034 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00003035 if (!StartDependent)
3036 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003037 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00003038 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003039 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00003040
3041 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003042 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00003043 else {
3044 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003045 if (StartDependent || EndDependent) {
3046 // Nothing to compute.
3047 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00003048 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00003049 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00003050 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00003051
Douglas Gregor0f9d4002009-05-21 23:30:39 +00003052 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00003053 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00003054 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00003055 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3056 Invalid = true;
3057 } else {
3058 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00003059 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00003060 D.getEllipsisLoc(),
3061 D.getRBracketLoc()));
3062 InitExpressions.push_back(StartIndex);
3063 InitExpressions.push_back(EndIndex);
3064 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003065 }
3066 break;
3067 }
3068 }
3069 }
3070
3071 if (Invalid || Init.isInvalid())
3072 return ExprError();
3073
3074 // Clear out the expressions within the designation.
3075 Desig.ClearExprs(*this);
3076
3077 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00003078 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00003079 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003080 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003081 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082
David Blaikiebbafb8a2012-03-11 07:00:24 +00003083 if (!getLangOpts().C99)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003084 Diag(DIE->getBeginLoc(), diag::ext_designated_init)
3085 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003086
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003087 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003088}
Douglas Gregor85df8d82009-01-29 00:45:39 +00003089
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003090//===----------------------------------------------------------------------===//
3091// Initialization entity
3092//===----------------------------------------------------------------------===//
3093
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00003095 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00003097{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003098 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3099 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00003100 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003101 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003102 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003103 Type = VT->getElementType();
3104 } else {
3105 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3106 assert(CT && "Unexpected type");
3107 Kind = EK_ComplexElement;
3108 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003109 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003110}
3111
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003112InitializedEntity
3113InitializedEntity::InitializeBase(ASTContext &Context,
3114 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00003115 bool IsInheritedVirtualBase,
3116 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003117 InitializedEntity Result;
3118 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00003119 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00003120 Result.Base = reinterpret_cast<uintptr_t>(Base);
3121 if (IsInheritedVirtualBase)
3122 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123
Douglas Gregor1b303932009-12-22 15:35:07 +00003124 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003125 return Result;
3126}
3127
Douglas Gregor85dabae2009-12-16 01:38:02 +00003128DeclarationName InitializedEntity::getName() const {
3129 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003130 case EK_Parameter:
3131 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00003132 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3133 return (D ? D->getDeclName() : DeclarationName());
3134 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003135
3136 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003137 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003138 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003139 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003140
Douglas Gregor19666fb2012-02-15 16:57:26 +00003141 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003142 return DeclarationName(Capture.VarID);
Fangrui Song6907ce22018-07-30 19:24:48 +00003143
Douglas Gregor85dabae2009-12-16 01:38:02 +00003144 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003145 case EK_StmtExprResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003146 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003147 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003148 case EK_Temporary:
3149 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003150 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003151 case EK_ArrayElement:
3152 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003153 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003154 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003155 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003156 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003157 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003158 return DeclarationName();
3159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003160
David Blaikie8a40f702012-01-17 06:56:22 +00003161 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003162}
3163
Richard Smith7873de02016-08-11 22:25:46 +00003164ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003165 switch (getKind()) {
3166 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003167 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003168 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003169 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003170
John McCall31168b02011-06-15 23:02:42 +00003171 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003172 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003173 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3174
Douglas Gregora4b592a2009-12-19 03:01:41 +00003175 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003176 case EK_StmtExprResult:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003177 case EK_Exception:
3178 case EK_New:
3179 case EK_Temporary:
3180 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003181 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003182 case EK_ArrayElement:
3183 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003184 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003185 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003186 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003187 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003188 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003189 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003190 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192
David Blaikie8a40f702012-01-17 06:56:22 +00003193 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003194}
3195
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003196bool InitializedEntity::allowsNRVO() const {
3197 switch (getKind()) {
3198 case EK_Result:
3199 case EK_Exception:
3200 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003201
Richard Smith67af95b2018-07-23 19:19:08 +00003202 case EK_StmtExprResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003203 case EK_Variable:
3204 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003205 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003206 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003207 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003208 case EK_New:
3209 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003210 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003211 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003212 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003213 case EK_ArrayElement:
3214 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003215 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003216 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003217 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003218 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003219 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003220 break;
3221 }
3222
3223 return false;
3224}
3225
Richard Smithe6c01442013-06-05 00:46:14 +00003226unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003227 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003228 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3229 for (unsigned I = 0; I != Depth; ++I)
3230 OS << "`-";
3231
3232 switch (getKind()) {
3233 case EK_Variable: OS << "Variable"; break;
3234 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003235 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3236 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003237 case EK_Result: OS << "Result"; break;
Richard Smith67af95b2018-07-23 19:19:08 +00003238 case EK_StmtExprResult: OS << "StmtExprResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003239 case EK_Exception: OS << "Exception"; break;
3240 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003241 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003242 case EK_New: OS << "New"; break;
3243 case EK_Temporary: OS << "Temporary"; break;
3244 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003245 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003246 case EK_Base: OS << "Base"; break;
3247 case EK_Delegating: OS << "Delegating"; break;
3248 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3249 case EK_VectorElement: OS << "VectorElement " << Index; break;
3250 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3251 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003252 case EK_LambdaToBlockConversionBlockElement:
3253 OS << "Block (lambda)";
3254 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003255 case EK_LambdaCapture:
3256 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003257 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003258 break;
3259 }
3260
Richard Smith7873de02016-08-11 22:25:46 +00003261 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003262 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003263 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003264 }
3265
3266 OS << " '" << getType().getAsString() << "'\n";
3267
3268 return Depth + 1;
3269}
3270
Yaron Kerencdae9412016-01-29 19:38:18 +00003271LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003272 dumpImpl(llvm::errs());
3273}
3274
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003275//===----------------------------------------------------------------------===//
3276// Initialization sequence
3277//===----------------------------------------------------------------------===//
3278
3279void InitializationSequence::Step::Destroy() {
3280 switch (Kind) {
3281 case SK_ResolveAddressOfOverloadedFunction:
3282 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003283 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003284 case SK_CastDerivedToBaseLValue:
3285 case SK_BindReference:
3286 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003287 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003288 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003289 case SK_UserConversion:
3290 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003291 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003292 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003293 case SK_AtomicConversion:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003294 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003295 case SK_UnwrapInitList:
3296 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003297 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003298 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003299 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003300 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003301 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003302 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003303 case SK_ArrayLoopIndex:
3304 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003305 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003306 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003307 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003308 case SK_PassByIndirectCopyRestore:
3309 case SK_PassByIndirectRestore:
3310 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003311 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003312 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003313 case SK_OCLSamplerInit:
Andrew Savonichevb555b762018-10-23 15:19:20 +00003314 case SK_OCLZeroOpaqueType:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003315 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003317 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003318 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003319 delete ICS;
3320 }
3321}
3322
Douglas Gregor838fcc32010-03-26 20:14:36 +00003323bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003324 // There can be some lvalue adjustments after the SK_BindReference step.
3325 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3326 if (I->Kind == SK_BindReference)
3327 return true;
3328 if (I->Kind == SK_BindReferenceToTemporary)
3329 return false;
3330 }
3331 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003332}
3333
3334bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003335 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003336 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337
Douglas Gregor838fcc32010-03-26 20:14:36 +00003338 switch (getFailureKind()) {
3339 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003340 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003341 case FK_ArrayNeedsInitList:
3342 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003343 case FK_ArrayNeedsInitListOrWideStringLiteral:
3344 case FK_NarrowStringIntoWideCharArray:
3345 case FK_WideStringIntoCharArray:
3346 case FK_IncompatWideStringIntoWideChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00003347 case FK_PlainStringIntoUTF8Char:
3348 case FK_UTF8StringIntoPlainChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003349 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3350 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003351 case FK_NonConstLValueReferenceBindingToBitfield:
3352 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003353 case FK_NonConstLValueReferenceBindingToUnrelated:
3354 case FK_RValueReferenceBindingToLValue:
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00003355 case FK_ReferenceAddrspaceMismatchTemporary:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003356 case FK_ReferenceInitDropsQualifiers:
3357 case FK_ReferenceInitFailed:
3358 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003359 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003360 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003361 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003362 case FK_ReferenceBindingToInitList:
3363 case FK_InitListBadDestinationType:
3364 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003365 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003366 case FK_ArrayTypeMismatch:
3367 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003368 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003369 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003370 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003371 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003372 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003373 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374
Douglas Gregor838fcc32010-03-26 20:14:36 +00003375 case FK_ReferenceInitOverloadFailed:
3376 case FK_UserConversionOverloadFailed:
3377 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003378 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003379 return FailedOverloadResult == OR_Ambiguous;
3380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381
David Blaikie8a40f702012-01-17 06:56:22 +00003382 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003383}
3384
Douglas Gregorb33eed02010-04-16 22:09:46 +00003385bool InitializationSequence::isConstructorInitialization() const {
3386 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3387}
3388
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003389void
3390InitializationSequence
3391::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3392 DeclAccessPair Found,
3393 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003394 Step S;
3395 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3396 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003397 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003398 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003399 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003400 Steps.push_back(S);
3401}
3402
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003404 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003405 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003406 switch (VK) {
3407 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3408 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3409 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003410 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003411 S.Type = BaseType;
3412 Steps.push_back(S);
3413}
3414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003416 bool BindingTemporary) {
3417 Step S;
3418 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3419 S.Type = T;
3420 Steps.push_back(S);
3421}
3422
Richard Smithb8c0f552016-12-09 18:49:13 +00003423void InitializationSequence::AddFinalCopy(QualType T) {
3424 Step S;
3425 S.Kind = SK_FinalCopy;
3426 S.Type = T;
3427 Steps.push_back(S);
3428}
3429
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003430void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3431 Step S;
3432 S.Kind = SK_ExtraneousCopyToTemporary;
3433 S.Type = T;
3434 Steps.push_back(S);
3435}
3436
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003437void
3438InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3439 DeclAccessPair FoundDecl,
3440 QualType T,
3441 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003442 Step S;
3443 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003444 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003445 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003446 S.Function.Function = Function;
3447 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003448 Steps.push_back(S);
3449}
3450
3451void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003452 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003453 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003454 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003455 switch (VK) {
3456 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003457 S.Kind = SK_QualificationConversionRValue;
3458 break;
John McCall2536c6d2010-08-25 10:28:54 +00003459 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003460 S.Kind = SK_QualificationConversionXValue;
3461 break;
John McCall2536c6d2010-08-25 10:28:54 +00003462 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003463 S.Kind = SK_QualificationConversionLValue;
3464 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003465 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003466 S.Type = Ty;
3467 Steps.push_back(S);
3468}
3469
Richard Smith77be48a2014-07-31 06:31:19 +00003470void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3471 Step S;
3472 S.Kind = SK_AtomicConversion;
3473 S.Type = Ty;
3474 Steps.push_back(S);
3475}
3476
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003477void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003478 const ImplicitConversionSequence &ICS, QualType T,
3479 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003480 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003481 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3482 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003483 S.Type = T;
3484 S.ICS = new ImplicitConversionSequence(ICS);
3485 Steps.push_back(S);
3486}
3487
Douglas Gregor51e77d52009-12-10 17:56:55 +00003488void InitializationSequence::AddListInitializationStep(QualType T) {
3489 Step S;
3490 S.Kind = SK_ListInitialization;
3491 S.Type = T;
3492 Steps.push_back(S);
3493}
3494
Richard Smith55c28882016-05-12 23:45:49 +00003495void InitializationSequence::AddConstructorInitializationStep(
3496 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3497 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003498 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003499 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003500 : SK_ConstructorInitializationFromList
3501 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003502 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003503 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003504 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003505 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003506 Steps.push_back(S);
3507}
3508
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003509void InitializationSequence::AddZeroInitializationStep(QualType T) {
3510 Step S;
3511 S.Kind = SK_ZeroInitialization;
3512 S.Type = T;
3513 Steps.push_back(S);
3514}
3515
Douglas Gregore1314a62009-12-18 05:02:21 +00003516void InitializationSequence::AddCAssignmentStep(QualType T) {
3517 Step S;
3518 S.Kind = SK_CAssignment;
3519 S.Type = T;
3520 Steps.push_back(S);
3521}
3522
Eli Friedman78275202009-12-19 08:11:05 +00003523void InitializationSequence::AddStringInitStep(QualType T) {
3524 Step S;
3525 S.Kind = SK_StringInit;
3526 S.Type = T;
3527 Steps.push_back(S);
3528}
3529
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003530void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3531 Step S;
3532 S.Kind = SK_ObjCObjectConversion;
3533 S.Type = T;
3534 Steps.push_back(S);
3535}
3536
Richard Smith378b8c82016-12-14 03:22:16 +00003537void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003538 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003539 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003540 S.Type = T;
3541 Steps.push_back(S);
3542}
3543
Richard Smith410306b2016-12-12 02:53:20 +00003544void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3545 Step S;
3546 S.Kind = SK_ArrayLoopIndex;
3547 S.Type = EltT;
3548 Steps.insert(Steps.begin(), S);
3549
3550 S.Kind = SK_ArrayLoopInit;
3551 S.Type = T;
3552 Steps.push_back(S);
3553}
3554
Richard Smithebeed412012-02-15 22:38:09 +00003555void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3556 Step S;
3557 S.Kind = SK_ParenthesizedArrayInit;
3558 S.Type = T;
3559 Steps.push_back(S);
3560}
3561
John McCall31168b02011-06-15 23:02:42 +00003562void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3563 bool shouldCopy) {
3564 Step s;
3565 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3566 : SK_PassByIndirectRestore);
3567 s.Type = type;
3568 Steps.push_back(s);
3569}
3570
3571void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3572 Step S;
3573 S.Kind = SK_ProduceObjCObject;
3574 S.Type = T;
3575 Steps.push_back(S);
3576}
3577
Sebastian Redlc1839b12012-01-17 22:49:42 +00003578void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3579 Step S;
3580 S.Kind = SK_StdInitializerList;
3581 S.Type = T;
3582 Steps.push_back(S);
3583}
3584
Guy Benyei61054192013-02-07 10:55:47 +00003585void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3586 Step S;
3587 S.Kind = SK_OCLSamplerInit;
3588 S.Type = T;
3589 Steps.push_back(S);
3590}
3591
Andrew Savonichevb555b762018-10-23 15:19:20 +00003592void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003593 Step S;
Andrew Savonichevb555b762018-10-23 15:19:20 +00003594 S.Kind = SK_OCLZeroOpaqueType;
Egor Churaev89831422016-12-23 14:55:49 +00003595 S.Type = T;
3596 Steps.push_back(S);
3597}
3598
Sebastian Redl29526f02011-11-27 16:50:07 +00003599void InitializationSequence::RewrapReferenceInitList(QualType T,
3600 InitListExpr *Syntactic) {
3601 assert(Syntactic->getNumInits() == 1 &&
3602 "Can only rewrap trivial init lists.");
3603 Step S;
3604 S.Kind = SK_UnwrapInitList;
3605 S.Type = Syntactic->getInit(0)->getType();
3606 Steps.insert(Steps.begin(), S);
3607
3608 S.Kind = SK_RewrapInitList;
3609 S.Type = T;
3610 S.WrappingSyntacticList = Syntactic;
3611 Steps.push_back(S);
3612}
3613
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003614void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003615 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003616 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003617 this->Failure = Failure;
3618 this->FailedOverloadResult = Result;
3619}
3620
3621//===----------------------------------------------------------------------===//
3622// Attempt initialization
3623//===----------------------------------------------------------------------===//
3624
Nico Weber337d5aa2015-04-17 08:32:38 +00003625/// Tries to add a zero initializer. Returns true if that worked.
3626static bool
3627maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3628 const InitializedEntity &Entity) {
3629 if (Entity.getKind() != InitializedEntity::EK_Variable)
3630 return false;
3631
3632 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003633 if (VD->getInit() || VD->getEndLoc().isMacroID())
Nico Weber337d5aa2015-04-17 08:32:38 +00003634 return false;
3635
3636 QualType VariableTy = VD->getType().getCanonicalType();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003637 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
Nico Weber337d5aa2015-04-17 08:32:38 +00003638 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3639 if (!Init.empty()) {
3640 Sequence.AddZeroInitializationStep(Entity.getType());
3641 Sequence.SetZeroInitializationFixit(Init, Loc);
3642 return true;
3643 }
3644 return false;
3645}
3646
John McCall31168b02011-06-15 23:02:42 +00003647static void MaybeProduceObjCObject(Sema &S,
3648 InitializationSequence &Sequence,
3649 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003650 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003651
3652 /// When initializing a parameter, produce the value if it's marked
3653 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003654 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003655 if (!Entity.isParameterConsumed())
3656 return;
3657
3658 assert(Entity.getType()->isObjCRetainableType() &&
3659 "consuming an object of unretainable type?");
3660 Sequence.AddProduceObjCObjectStep(Entity.getType());
3661
3662 /// When initializing a return value, if the return type is a
3663 /// retainable type, then returns need to immediately retain the
3664 /// object. If an autorelease is required, it will be done at the
3665 /// last instant.
Richard Smith67af95b2018-07-23 19:19:08 +00003666 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3667 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
John McCall31168b02011-06-15 23:02:42 +00003668 if (!Entity.getType()->isObjCRetainableType())
3669 return;
3670
3671 Sequence.AddProduceObjCObjectStep(Entity.getType());
3672 }
3673}
3674
Richard Smithcc1b96d2013-06-12 22:31:48 +00003675static void TryListInitialization(Sema &S,
3676 const InitializedEntity &Entity,
3677 const InitializationKind &Kind,
3678 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003679 InitializationSequence &Sequence,
3680 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003681
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003682/// When initializing from init list via constructor, handle
Richard Smithd86812d2012-07-05 08:39:21 +00003683/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003684///
Richard Smithd86812d2012-07-05 08:39:21 +00003685/// \return true if we have handled initialization of an object of type
3686/// std::initializer_list<T>, false otherwise.
3687static bool TryInitializerListConstruction(Sema &S,
3688 InitListExpr *List,
3689 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003690 InitializationSequence &Sequence,
3691 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003692 QualType E;
3693 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003694 return false;
3695
Richard Smithdb0ac552015-12-18 22:40:25 +00003696 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003697 Sequence.setIncompleteTypeFailure(E);
3698 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003699 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003700
3701 // Try initializing a temporary array from the init list.
3702 QualType ArrayType = S.Context.getConstantArrayType(
3703 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3704 List->getNumInits()),
3705 clang::ArrayType::Normal, 0);
3706 InitializedEntity HiddenArray =
3707 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003708 InitializationKind Kind = InitializationKind::CreateDirectList(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003709 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
Manman Ren073db022016-03-10 18:53:19 +00003710 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3711 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003712 if (Sequence)
3713 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003714 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003715}
3716
Richard Smith7c2bcc92016-09-07 02:14:33 +00003717/// Determine if the constructor has the signature of a copy or move
3718/// constructor for the type T of the class in which it was found. That is,
3719/// determine if its first parameter is of type T or reference to (possibly
3720/// cv-qualified) T.
3721static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3722 const ConstructorInfo &Info) {
3723 if (Info.Constructor->getNumParams() == 0)
3724 return false;
3725
3726 QualType ParmT =
3727 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3728 QualType ClassT =
3729 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3730
3731 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3732}
3733
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003734static OverloadingResult
3735ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003736 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003737 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003738 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003739 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003740 OverloadCandidateSet::iterator &Best,
3741 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003742 bool OnlyListConstructors, bool IsListInit,
3743 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003744 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Anastasia Stulovac25ea862019-06-20 16:23:28 +00003745 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003746
Richard Smith40c78062015-02-21 02:31:57 +00003747 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003748 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003749 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003750 continue;
3751
Richard Smith7c2bcc92016-09-07 02:14:33 +00003752 if (!AllowExplicit && Info.Constructor->isExplicit())
3753 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003754
Richard Smith7c2bcc92016-09-07 02:14:33 +00003755 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3756 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003757
Richard Smith7c2bcc92016-09-07 02:14:33 +00003758 // C++11 [over.best.ics]p4:
3759 // ... and the constructor or user-defined conversion function is a
3760 // candidate by
3761 // - 13.3.1.3, when the argument is the temporary in the second step
3762 // of a class copy-initialization, or
3763 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3764 // - the second phase of 13.3.1.7 when the initializer list has exactly
3765 // one element that is itself an initializer list, and the target is
3766 // the first parameter of a constructor of class X, and the conversion
3767 // is to X or reference to (possibly cv-qualified X),
3768 // user-defined conversion sequences are not considered.
3769 bool SuppressUserConversions =
3770 SecondStepOfCopyInit ||
3771 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3772 hasCopyOrMoveCtorParam(S.Context, Info));
3773
3774 if (Info.ConstructorTmpl)
Richard Smith76b90272019-05-09 03:59:21 +00003775 S.AddTemplateOverloadCandidate(
3776 Info.ConstructorTmpl, Info.FoundDecl,
3777 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
3778 /*PartialOverloading=*/false, AllowExplicit);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003779 else {
3780 // C++ [over.match.copy]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00003781 // - When initializing a temporary to be bound to the first parameter
Richard Smith7c2bcc92016-09-07 02:14:33 +00003782 // of a constructor [for type T] that takes a reference to possibly
3783 // cv-qualified T as its first argument, called with a single
3784 // argument in the context of direct-initialization, explicit
3785 // conversion functions are also considered.
3786 // FIXME: What if a constructor template instantiates to such a signature?
Fangrui Song6907ce22018-07-30 19:24:48 +00003787 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Richard Smith7c2bcc92016-09-07 02:14:33 +00003788 Args.size() == 1 &&
3789 hasCopyOrMoveCtorParam(S.Context, Info);
3790 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3791 CandidateSet, SuppressUserConversions,
Richard Smith76b90272019-05-09 03:59:21 +00003792 /*PartialOverloading=*/false, AllowExplicit,
3793 AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003794 }
3795 }
3796
Richard Smith67ef14f2017-09-26 18:37:55 +00003797 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3798 //
3799 // When initializing an object of class type T by constructor
3800 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3801 // from a single expression of class type U, conversion functions of
3802 // U that convert to the non-reference type cv T are candidates.
3803 // Explicit conversion functions are only candidates during
3804 // direct-initialization.
3805 //
3806 // Note: SecondStepOfCopyInit is only ever true in this case when
3807 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003808 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003809 !SecondStepOfCopyInit) {
3810 Expr *Initializer = Args[0];
3811 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3812 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3813 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3814 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3815 NamedDecl *D = *I;
3816 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3817 D = D->getUnderlyingDecl();
3818
3819 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3820 CXXConversionDecl *Conv;
3821 if (ConvTemplate)
3822 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3823 else
3824 Conv = cast<CXXConversionDecl>(D);
3825
Richard Smith76b90272019-05-09 03:59:21 +00003826 if (AllowExplicit || !Conv->isExplicit()) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003827 if (ConvTemplate)
Richard Smith76b90272019-05-09 03:59:21 +00003828 S.AddTemplateConversionCandidate(
3829 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
3830 CandidateSet, AllowExplicit, AllowExplicit,
3831 /*AllowResultConversion*/ false);
Richard Smith67ef14f2017-09-26 18:37:55 +00003832 else
3833 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3834 DestType, CandidateSet, AllowExplicit,
Richard Smith76b90272019-05-09 03:59:21 +00003835 AllowExplicit,
3836 /*AllowResultConversion*/ false);
Richard Smith67ef14f2017-09-26 18:37:55 +00003837 }
3838 }
3839 }
3840 }
3841
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003842 // Perform overload resolution and return the result.
3843 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3844}
3845
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003846/// Attempt initialization by constructor (C++ [dcl.init]), which
Sebastian Redled2e5322011-12-22 14:44:04 +00003847/// enumerates the constructors of the initialized entity and performs overload
3848/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003849/// \param DestType The destination class type.
3850/// \param DestArrayType The destination type, which is either DestType or
3851/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003852/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003853/// \param IsInitListCopy Is this non-list-initialization resulting from a
3854/// list-initialization from {x} where x is the same
3855/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003856static void TryConstructorInitialization(Sema &S,
3857 const InitializedEntity &Entity,
3858 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003859 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003860 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003861 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003862 bool IsListInit = false,
3863 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003864 assert(((!IsListInit && !IsInitListCopy) ||
3865 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3866 "IsListInit/IsInitListCopy must come with a single initializer list "
3867 "argument.");
3868 InitListExpr *ILE =
3869 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3870 MultiExprArg UnwrappedArgs =
3871 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003872
Sebastian Redled2e5322011-12-22 14:44:04 +00003873 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003874 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003875 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003876 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003877 }
3878
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003879 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003880 // - If the initializer expression is a prvalue and the cv-unqualified
3881 // version of the source type is the same class as the class of the
3882 // destination, the initializer expression is used to initialize the
3883 // destination object.
3884 // Per DR (no number yet), this does not apply when initializing a base
3885 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003886 // ObjC++: Lambda captured by the block in the lambda to block conversion
3887 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003888 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003889 Entity.getKind() != InitializedEntity::EK_Base &&
3890 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003891 Entity.getKind() !=
3892 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003893 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3894 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3895 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003896 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003897 if (ILE)
3898 Sequence.RewrapReferenceInitList(DestType, ILE);
3899 return;
3900 }
3901
Sebastian Redled2e5322011-12-22 14:44:04 +00003902 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3903 assert(DestRecordType && "Constructor initialization requires record type");
3904 CXXRecordDecl *DestRecordDecl
3905 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3906
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003907 // Build the candidate set directly in the initialization sequence
3908 // structure, so that it will persist if we fail.
3909 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3910
3911 // Determine whether we are allowed to call explicit constructors or
3912 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003913 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003914 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003915
Sebastian Redled2e5322011-12-22 14:44:04 +00003916 // - Otherwise, if T is a class type, constructors are considered. The
3917 // applicable constructors are enumerated, and the best one is chosen
3918 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003919 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003920
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003921 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003922 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003923 bool AsInitializerList = false;
3924
Larisse Voufo19d08672015-01-27 18:47:05 +00003925 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003926 // When objects of non-aggregate type T are list-initialized, such that
3927 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3928 // according to the rules in this section, overload resolution selects
3929 // the constructor in two phases:
3930 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003931 // - Initially, the candidate functions are the initializer-list
3932 // constructors of the class T and the argument list consists of the
3933 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003934 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003935 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003936
3937 // If the initializer list has no elements and T has a default constructor,
3938 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003939 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003940 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003941 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003942 CopyInitialization, AllowExplicit,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003943 /*OnlyListConstructors=*/true,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003944 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003945 }
3946
3947 // C++11 [over.match.list]p1:
3948 // - If no viable initializer-list constructor is found, overload resolution
3949 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003950 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003951 // elements of the initializer list.
3952 if (Result == OR_No_Viable_Function) {
3953 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003954 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003955 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003956 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003957 /*OnlyListConstructors=*/false,
3958 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003959 }
3960 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003961 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003962 InitializationSequence::FK_ListConstructorOverloadFailed :
3963 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003964 Result);
3965 return;
3966 }
3967
Richard Smith67ef14f2017-09-26 18:37:55 +00003968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3969
3970 // In C++17, ResolveConstructorOverload can select a conversion function
3971 // instead of a constructor.
3972 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3973 // Add the user-defined conversion step that calls the conversion function.
3974 QualType ConvType = CD->getConversionType();
3975 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3976 "should not have selected this conversion function");
3977 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3978 HadMultipleCandidates);
3979 if (!S.Context.hasSameType(ConvType, DestType))
3980 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3981 if (IsListInit)
3982 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3983 return;
3984 }
3985
Richard Smithd86812d2012-07-05 08:39:21 +00003986 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003987 // If a program calls for the default initialization of an object
3988 // of a const-qualified type T, T shall be a class type with a
3989 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003990 // C++ core issue 253 proposal:
3991 // If the implicit default constructor initializes all subobjects, no
3992 // initializer should be required.
3993 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3994 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003995 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003996 Entity.getType().isConstQualified()) {
3997 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3998 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3999 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4000 return;
4001 }
Sebastian Redled2e5322011-12-22 14:44:04 +00004002 }
4003
Sebastian Redl048a6d72012-04-01 19:54:59 +00004004 // C++11 [over.match.list]p1:
4005 // In copy-list-initialization, if an explicit constructor is chosen, the
4006 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00004007 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00004008 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4009 return;
4010 }
4011
Sebastian Redled2e5322011-12-22 14:44:04 +00004012 // Add the constructor initialization step. Any cv-qualification conversion is
4013 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00004014 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00004015 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00004016 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00004017}
4018
Sebastian Redl29526f02011-11-27 16:50:07 +00004019static bool
4020ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4021 Expr *Initializer,
4022 QualType &SourceType,
4023 QualType &UnqualifiedSourceType,
4024 QualType UnqualifiedTargetType,
4025 InitializationSequence &Sequence) {
4026 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4027 S.Context.OverloadTy) {
4028 DeclAccessPair Found;
4029 bool HadMultipleCandidates = false;
4030 if (FunctionDecl *Fn
4031 = S.ResolveAddressOfOverloadedFunction(Initializer,
4032 UnqualifiedTargetType,
4033 false, Found,
4034 &HadMultipleCandidates)) {
4035 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4036 HadMultipleCandidates);
4037 SourceType = Fn->getType();
4038 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4039 } else if (!UnqualifiedTargetType->isRecordType()) {
4040 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4041 return true;
4042 }
4043 }
4044 return false;
4045}
4046
4047static void TryReferenceInitializationCore(Sema &S,
4048 const InitializedEntity &Entity,
4049 const InitializationKind &Kind,
4050 Expr *Initializer,
4051 QualType cv1T1, QualType T1,
4052 Qualifiers T1Quals,
4053 QualType cv2T2, QualType T2,
4054 Qualifiers T2Quals,
4055 InitializationSequence &Sequence);
4056
Richard Smithd86812d2012-07-05 08:39:21 +00004057static void TryValueInitialization(Sema &S,
4058 const InitializedEntity &Entity,
4059 const InitializationKind &Kind,
4060 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00004061 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00004062
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004063/// Attempt list initialization of a reference.
Sebastian Redl29526f02011-11-27 16:50:07 +00004064static void TryReferenceListInitialization(Sema &S,
4065 const InitializedEntity &Entity,
4066 const InitializationKind &Kind,
4067 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004068 InitializationSequence &Sequence,
4069 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00004070 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004071 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00004072 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4073 return;
4074 }
David Majnemer9370dc22015-04-26 07:35:03 +00004075 // Can't reference initialize a compound literal.
4076 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4077 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4078 return;
4079 }
Sebastian Redl29526f02011-11-27 16:50:07 +00004080
4081 QualType DestType = Entity.getType();
4082 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4083 Qualifiers T1Quals;
4084 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4085
4086 // Reference initialization via an initializer list works thus:
4087 // If the initializer list consists of a single element that is
4088 // reference-related to the referenced type, bind directly to that element
4089 // (possibly creating temporaries).
4090 // Otherwise, initialize a temporary with the initializer list and
4091 // bind to that.
4092 if (InitList->getNumInits() == 1) {
4093 Expr *Initializer = InitList->getInit(0);
4094 QualType cv2T2 = Initializer->getType();
4095 Qualifiers T2Quals;
4096 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4097
4098 // If this fails, creating a temporary wouldn't work either.
4099 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4100 T1, Sequence))
4101 return;
4102
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004103 SourceLocation DeclLoc = Initializer->getBeginLoc();
Sebastian Redl29526f02011-11-27 16:50:07 +00004104 bool dummy1, dummy2, dummy3;
4105 Sema::ReferenceCompareResult RefRelationship
4106 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
4107 dummy2, dummy3);
4108 if (RefRelationship >= Sema::Ref_Related) {
4109 // Try to bind the reference here.
4110 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4111 T1Quals, cv2T2, T2, T2Quals, Sequence);
4112 if (Sequence)
4113 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4114 return;
4115 }
Richard Smith03d93932013-01-15 07:58:29 +00004116
4117 // Update the initializer if we've resolved an overloaded function.
4118 if (Sequence.step_begin() != Sequence.step_end())
4119 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00004120 }
4121
4122 // Not reference-related. Create a temporary and bind to that.
4123 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4124
Manman Ren073db022016-03-10 18:53:19 +00004125 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4126 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00004127 if (Sequence) {
4128 if (DestType->isRValueReferenceType() ||
4129 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004130 Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
Sebastian Redl29526f02011-11-27 16:50:07 +00004131 else
4132 Sequence.SetFailed(
4133 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4134 }
4135}
4136
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004137/// Attempt list initialization (C++0x [dcl.init.list])
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004138static void TryListInitialization(Sema &S,
4139 const InitializedEntity &Entity,
4140 const InitializationKind &Kind,
4141 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004142 InitializationSequence &Sequence,
4143 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004144 QualType DestType = Entity.getType();
4145
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004146 // C++ doesn't allow scalar initialization with more than one argument.
4147 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004148 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004149 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4150 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4151 return;
4152 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004153 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004154 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4155 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004156 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004157 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004158
Larisse Voufod2010992015-01-24 23:09:54 +00004159 if (DestType->isRecordType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004160 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004161 Sequence.setIncompleteTypeFailure(DestType);
4162 return;
4163 }
Richard Smithd86812d2012-07-05 08:39:21 +00004164
Larisse Voufo19d08672015-01-27 18:47:05 +00004165 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004166 // - If T is a class type and the initializer list has a single element of
4167 // type cv U, where U is T or a class derived from T, the object is
4168 // initialized from that element (by copy-initialization for
4169 // copy-list-initialization, or by direct-initialization for
4170 // direct-list-initialization).
4171 // - Otherwise, if T is a character array and the initializer list has a
4172 // single element that is an appropriately-typed string literal
4173 // (8.5.2 [dcl.init.string]), initialization is performed as described
4174 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004175 // - Otherwise, if T is an aggregate, [...] (continue below).
4176 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004177 if (DestType->isRecordType()) {
4178 QualType InitType = InitList->getInit(0)->getType();
4179 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004180 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004181 Expr *InitListAsExpr = InitList;
4182 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004183 DestType, Sequence,
4184 /*InitListSyntax*/false,
4185 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004186 return;
4187 }
4188 }
4189 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4190 Expr *SubInit[1] = {InitList->getInit(0)};
4191 if (!isa<VariableArrayType>(DestAT) &&
4192 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4193 InitializationKind SubKind =
4194 Kind.getKind() == InitializationKind::IK_DirectList
4195 ? InitializationKind::CreateDirect(Kind.getLocation(),
4196 InitList->getLBraceLoc(),
4197 InitList->getRBraceLoc())
4198 : Kind;
4199 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004200 /*TopLevelOfInitList*/ true,
4201 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004202
4203 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4204 // the element is not an appropriately-typed string literal, in which
4205 // case we should proceed as in C++11 (below).
4206 if (Sequence) {
4207 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4208 return;
4209 }
4210 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004211 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004212 }
Larisse Voufod2010992015-01-24 23:09:54 +00004213
4214 // C++11 [dcl.init.list]p3:
4215 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004216 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4217 (S.getLangOpts().CPlusPlus11 &&
4218 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004219 if (S.getLangOpts().CPlusPlus11) {
4220 // - Otherwise, if the initializer list has no elements and T is a
4221 // class type with a default constructor, the object is
4222 // value-initialized.
4223 if (InitList->getNumInits() == 0) {
4224 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4225 if (RD->hasDefaultConstructor()) {
4226 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4227 return;
4228 }
4229 }
4230
4231 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4232 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004233 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4234 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004235 return;
4236
4237 // - Otherwise, if T is a class type, constructors are considered.
4238 Expr *InitListAsExpr = InitList;
4239 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004240 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004241 } else
4242 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4243 return;
4244 }
4245
Richard Smith089c3162013-09-21 21:55:46 +00004246 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004247 InitList->getNumInits() == 1) {
4248 Expr *E = InitList->getInit(0);
4249
4250 // - Otherwise, if T is an enumeration with a fixed underlying type,
4251 // the initializer-list has a single element v, and the initialization
4252 // is direct-list-initialization, the object is initialized with the
4253 // value T(v); if a narrowing conversion is required to convert v to
4254 // the underlying type of T, the program is ill-formed.
4255 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004256 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004257 Kind.getKind() == InitializationKind::IK_DirectList &&
4258 ET && ET->getDecl()->isFixed() &&
4259 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4260 (E->getType()->isIntegralOrEnumerationType() ||
4261 E->getType()->isFloatingType())) {
4262 // There are two ways that T(v) can work when T is an enumeration type.
4263 // If there is either an implicit conversion sequence from v to T or
4264 // a conversion function that can convert from v to T, then we use that.
4265 // Otherwise, if v is of integral, enumeration, or floating-point type,
4266 // it is converted to the enumeration type via its underlying type.
4267 // There is no overlap possible between these two cases (except when the
4268 // source value is already of the destination type), and the first
4269 // case is handled by the general case for single-element lists below.
4270 ImplicitConversionSequence ICS;
4271 ICS.setStandard();
4272 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004273 if (!E->isRValue())
4274 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004275 // If E is of a floating-point type, then the conversion is ill-formed
4276 // due to narrowing, but go through the motions in order to produce the
4277 // right diagnostic.
4278 ICS.Standard.Second = E->getType()->isFloatingType()
4279 ? ICK_Floating_Integral
4280 : ICK_Integral_Conversion;
4281 ICS.Standard.setFromType(E->getType());
4282 ICS.Standard.setToType(0, E->getType());
4283 ICS.Standard.setToType(1, DestType);
4284 ICS.Standard.setToType(2, DestType);
4285 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4286 /*TopLevelOfInitList*/true);
4287 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4288 return;
4289 }
4290
Richard Smith089c3162013-09-21 21:55:46 +00004291 // - Otherwise, if the initializer list has a single element of type E
4292 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004293 // initialized from that element (by copy-initialization for
4294 // copy-list-initialization, or by direct-initialization for
4295 // direct-list-initialization); if a narrowing conversion is required
4296 // to convert the element to T, the program is ill-formed.
4297 //
Richard Smith089c3162013-09-21 21:55:46 +00004298 // Per core-24034, this is direct-initialization if we were performing
4299 // direct-list-initialization and copy-initialization otherwise.
4300 // We can't use InitListChecker for this, because it always performs
4301 // copy-initialization. This only matters if we might use an 'explicit'
4302 // conversion operator, so we only need to handle the cases where the source
4303 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004304 if (InitList->getInit(0)->getType()->isRecordType()) {
4305 InitializationKind SubKind =
4306 Kind.getKind() == InitializationKind::IK_DirectList
4307 ? InitializationKind::CreateDirect(Kind.getLocation(),
4308 InitList->getLBraceLoc(),
4309 InitList->getRBraceLoc())
4310 : Kind;
4311 Expr *SubInit[1] = { InitList->getInit(0) };
4312 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4313 /*TopLevelOfInitList*/true,
4314 TreatUnavailableAsInvalid);
4315 if (Sequence)
4316 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4317 return;
4318 }
Richard Smith089c3162013-09-21 21:55:46 +00004319 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004320
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004321 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004322 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004323 if (CheckInitList.HadError()) {
4324 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4325 return;
4326 }
4327
4328 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004329 Sequence.AddListInitializationStep(DestType);
4330}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004331
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004332/// Try a reference initialization that involves calling a conversion
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004333/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004334static OverloadingResult TryRefInitWithConversionFunction(
4335 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4336 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4337 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004338 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004339 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4340 QualType T1 = cv1T1.getUnqualifiedType();
4341 QualType cv2T2 = Initializer->getType();
4342 QualType T2 = cv2T2.getUnqualifiedType();
4343
4344 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004345 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004346 bool ObjCLifetimeConversion;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004347 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
4348 DerivedToBase, ObjCConversion,
John McCall31168b02011-06-15 23:02:42 +00004349 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004350 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004351 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004352 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004353 (void)ObjCLifetimeConversion;
Fangrui Song6907ce22018-07-30 19:24:48 +00004354
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004355 // Build the candidate set directly in the initialization sequence
4356 // structure, so that it will persist if we fail.
4357 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004358 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004359
Richard Smithb368ea82018-07-02 23:25:22 +00004360 // Determine whether we are allowed to call explicit conversion operators.
4361 // Note that none of [over.match.copy], [over.match.conv], nor
4362 // [over.match.ref] permit an explicit constructor to be chosen when
4363 // initializing a reference, not even for direct-initialization.
4364 bool AllowExplicitCtors = false;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004365 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4366
Craig Topperc3ec1492014-05-26 06:22:03 +00004367 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004368 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004369 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004370 // The type we're converting to is a class type. Enumerate its constructors
4371 // to see if there is a suitable conversion.
4372 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004373
Richard Smith40c78062015-02-21 02:31:57 +00004374 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004375 auto Info = getConstructorInfo(D);
4376 if (!Info.Constructor)
4377 continue;
John McCalla0296f72010-03-19 07:35:19 +00004378
Richard Smithc2bebe92016-05-11 20:37:46 +00004379 if (!Info.Constructor->isInvalidDecl() &&
Richard Smithb368ea82018-07-02 23:25:22 +00004380 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004381 if (Info.ConstructorTmpl)
Richard Smith76b90272019-05-09 03:59:21 +00004382 S.AddTemplateOverloadCandidate(
4383 Info.ConstructorTmpl, Info.FoundDecl,
4384 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4385 /*SuppressUserConversions=*/true,
4386 /*PartialOverloading*/ false, AllowExplicitCtors);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004387 else
Richard Smith76b90272019-05-09 03:59:21 +00004388 S.AddOverloadCandidate(
4389 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4390 /*SuppressUserConversions=*/true,
4391 /*PartialOverloading*/ false, AllowExplicitCtors);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004394 }
John McCall3696dcb2010-08-17 07:23:57 +00004395 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4396 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
Craig Topperc3ec1492014-05-26 06:22:03 +00004398 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004399 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004400 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004401 // The type we're converting from is a class type, enumerate its conversion
4402 // functions.
4403 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4404
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004405 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4406 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004407 NamedDecl *D = *I;
4408 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4409 if (isa<UsingShadowDecl>(D))
4410 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004412 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4413 CXXConversionDecl *Conv;
4414 if (ConvTemplate)
4415 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4416 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004417 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004419 // If the conversion function doesn't return a reference type,
4420 // it can't be considered for this conversion unless we're allowed to
4421 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422 // FIXME: Do we need to make sure that we only consider conversion
4423 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004424 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004425 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Richard Smith76b90272019-05-09 03:59:21 +00004426 (AllowRValues ||
4427 Conv->getConversionType()->isLValueReferenceType())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004428 if (ConvTemplate)
Richard Smith76b90272019-05-09 03:59:21 +00004429 S.AddTemplateConversionCandidate(
4430 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4431 CandidateSet,
4432 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004433 else
Richard Smith76b90272019-05-09 03:59:21 +00004434 S.AddConversionCandidate(
4435 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4436 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004437 }
4438 }
4439 }
John McCall3696dcb2010-08-17 07:23:57 +00004440 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4441 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004443 SourceLocation DeclLoc = Initializer->getBeginLoc();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004444
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004446 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004448 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004449 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004450
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004451 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004452 // This is the overload that will be used for this initialization step if we
4453 // use this initialization. Mark it as referenced.
4454 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004455
Richard Smithb8c0f552016-12-09 18:49:13 +00004456 // Compute the returned type and value kind of the conversion.
4457 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004458 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004459 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004460 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004461 cv3T3 = T1;
4462
4463 ExprValueKind VK = VK_RValue;
4464 if (cv3T3->isLValueReferenceType())
4465 VK = VK_LValue;
4466 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4467 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4468 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004469
4470 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004471 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004472 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004473 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004474
Richard Smithb8c0f552016-12-09 18:49:13 +00004475 // Determine whether we'll need to perform derived-to-base adjustments or
4476 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004477 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004478 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004479 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004480 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004481 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004482 NewDerivedToBase, NewObjCConversion,
4483 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004484
4485 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004486 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004487 assert(!isa<CXXConstructorDecl>(Function) &&
4488 "should not have conversion after constructor");
4489
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004490 ImplicitConversionSequence ICS;
4491 ICS.setStandard();
4492 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004493 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4494
4495 // Every implicit conversion results in a prvalue, except for a glvalue
4496 // derived-to-base conversion, which we handle below.
4497 cv3T3 = ICS.Standard.getToType(2);
4498 VK = VK_RValue;
4499 }
4500
4501 // If the converted initializer is a prvalue, its type T4 is adjusted to
4502 // type "cv1 T4" and the temporary materialization conversion is applied.
4503 //
4504 // We adjust the cv-qualifications to match the reference regardless of
4505 // whether we have a prvalue so that the AST records the change. In this
4506 // case, T4 is "cv3 T3".
4507 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4508 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4509 Sequence.AddQualificationConversionStep(cv1T4, VK);
4510 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4511 VK = IsLValueRef ? VK_LValue : VK_XValue;
4512
4513 if (NewDerivedToBase)
4514 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004515 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004516 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004517
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004518 return OR_Success;
4519}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
Richard Smithc620f552011-10-19 16:55:56 +00004521static void CheckCXX98CompatAccessibleCopy(Sema &S,
4522 const InitializedEntity &Entity,
4523 Expr *CurInitExpr);
4524
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004525/// Attempt reference initialization (C++0x [dcl.init.ref])
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004527 const InitializedEntity &Entity,
4528 const InitializationKind &Kind,
4529 Expr *Initializer,
4530 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004531 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004532 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004533 Qualifiers T1Quals;
4534 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004535 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004536 Qualifiers T2Quals;
4537 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004538
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004539 // If the initializer is the address of an overloaded function, try
4540 // to resolve the overloaded function. If all goes well, T2 is the
4541 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004542 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4543 T1, Sequence))
4544 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004545
Sebastian Redl29526f02011-11-27 16:50:07 +00004546 // Delegate everything else to a subfunction.
4547 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4548 T1Quals, cv2T2, T2, T2Quals, Sequence);
4549}
4550
Richard Smithb8c0f552016-12-09 18:49:13 +00004551/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004552/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004553/// such a glvalue will always create a temporary.
4554static bool isNonReferenceableGLValue(Expr *E) {
4555 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004556}
4557
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004558/// Reference initialization without resolving overloaded functions.
Sebastian Redl29526f02011-11-27 16:50:07 +00004559static void TryReferenceInitializationCore(Sema &S,
4560 const InitializedEntity &Entity,
4561 const InitializationKind &Kind,
4562 Expr *Initializer,
4563 QualType cv1T1, QualType T1,
4564 Qualifiers T1Quals,
4565 QualType cv2T2, QualType T2,
4566 Qualifiers T2Quals,
4567 InitializationSequence &Sequence) {
4568 QualType DestType = Entity.getType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004569 SourceLocation DeclLoc = Initializer->getBeginLoc();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004570 // Compute some basic properties of the types and the initializer.
4571 bool isLValueRef = DestType->isLValueReferenceType();
4572 bool isRValueRef = !isLValueRef;
4573 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004574 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004575 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004576 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004577 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004578 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004579 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004580
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004581 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004582 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004583 // "cv2 T2" as follows:
4584 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004586 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004587 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004588 // there are no function rvalues in C++, rvalue refs to functions are treated
4589 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004590 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004591 bool T1Function = T1->isFunctionType();
4592 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004593 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004594 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004596 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004598 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004599 if (T1Quals != T2Quals)
4600 // Convert to cv1 T2. This should only add qualifiers unless this is a
4601 // c-style cast. The removal of qualifiers in that case notionally
4602 // happens after the reference binding, but that doesn't matter.
4603 Sequence.AddQualificationConversionStep(
4604 S.Context.getQualifiedType(T2, T1Quals),
4605 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004606 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004607 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004608 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004609 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004610
Richard Smithb8c0f552016-12-09 18:49:13 +00004611 // We only create a temporary here when binding a reference to a
4612 // bit-field or vector element. Those cases are't supposed to be
4613 // handled by this bullet, but the outcome is the same either way.
4614 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004615 return;
4616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617
4618 // - has a class type (i.e., T2 is a class type), where T1 is not
4619 // reference-related to T2, and can be implicitly converted to an
4620 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4621 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004622 // applicable conversion functions (13.3.1.6) and choosing the best
4623 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004624 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004625 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004626 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4627 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004628 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004629 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4630 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004631 if (ConvOvlResult == OR_Success)
4632 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004633 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004634 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004635 InitializationSequence::FK_ReferenceInitOverloadFailed,
4636 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004637 }
4638 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004639
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004641 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004642 // shall be an rvalue reference.
Anastasia Stulova3562edb2019-06-21 11:36:15 +00004643 // For address spaces, we interpret this to mean that an addr space
4644 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4645 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
4646 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004647 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4648 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4649 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004650 Sequence.SetOverloadFailure(
4651 InitializationSequence::FK_ReferenceInitOverloadFailed,
4652 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004653 else if (!InitCategory.isLValue())
4654 Sequence.SetFailed(
Anastasia Stulova3562edb2019-06-21 11:36:15 +00004655 T1Quals.isAddressSpaceSupersetOf(T2Quals)
4656 ? InitializationSequence::
4657 FK_NonConstLValueReferenceBindingToTemporary
4658 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
Richard Smithb8c0f552016-12-09 18:49:13 +00004659 else {
4660 InitializationSequence::FailureKind FK;
4661 switch (RefRelationship) {
4662 case Sema::Ref_Compatible:
4663 if (Initializer->refersToBitField())
4664 FK = InitializationSequence::
4665 FK_NonConstLValueReferenceBindingToBitfield;
4666 else if (Initializer->refersToVectorElement())
4667 FK = InitializationSequence::
4668 FK_NonConstLValueReferenceBindingToVectorElement;
4669 else
4670 llvm_unreachable("unexpected kind of compatible initializer");
4671 break;
4672 case Sema::Ref_Related:
4673 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4674 break;
4675 case Sema::Ref_Incompatible:
4676 FK = InitializationSequence::
4677 FK_NonConstLValueReferenceBindingToUnrelated;
4678 break;
4679 }
4680 Sequence.SetFailed(FK);
4681 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004682 return;
4683 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004684
Douglas Gregor92e460e2011-01-20 16:44:54 +00004685 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004686 // - is an
4687 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4688 // [1z] rvalue (but not a bit-field) or
4689 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4690 //
4691 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004692 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004693 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004694 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004695 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004696 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004697 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004698 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004699 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004700 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004701 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004702 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4703 // compiler the freedom to perform a copy here or bind to the
4704 // object, while C++0x requires that we bind directly to the
4705 // object. Hence, we always bind to the object without making an
4706 // extra copy. However, in C++03 requires that we check for the
4707 // presence of a suitable copy constructor:
4708 //
4709 // The constructor that would be used to make the copy shall
4710 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004711 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004712 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004713 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004714 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716
Richard Smithb8c0f552016-12-09 18:49:13 +00004717 // C++1z [dcl.init.ref]/5.2.1.2:
4718 // If the converted initializer is a prvalue, its type T4 is adjusted
4719 // to type "cv1 T4" and the temporary materialization conversion is
4720 // applied.
Anastasia Stulovad1986d12019-01-14 11:44:22 +00004721 // Postpone address space conversions to after the temporary materialization
4722 // conversion to allow creating temporaries in the alloca address space.
Anastasia Stulovae368e4d2019-02-05 11:32:58 +00004723 auto T1QualsIgnoreAS = T1Quals;
4724 auto T2QualsIgnoreAS = T2Quals;
4725 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4726 T1QualsIgnoreAS.removeAddressSpace();
4727 T2QualsIgnoreAS.removeAddressSpace();
4728 }
4729 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
4730 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
Richard Smithb8c0f552016-12-09 18:49:13 +00004731 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4732 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4733 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
Anastasia Stulovae368e4d2019-02-05 11:32:58 +00004734 // Add addr space conversion if required.
4735 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4736 auto T4Quals = cv1T4.getQualifiers();
4737 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
4738 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
4739 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
Anastasia Stulovad1986d12019-01-14 11:44:22 +00004740 }
Richard Smithb8c0f552016-12-09 18:49:13 +00004741
4742 // In any case, the reference is bound to the resulting glvalue (or to
4743 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004744 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004745 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004746 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004747 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750
4751 // - has a class type (i.e., T2 is a class type), where T1 is not
4752 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004753 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4754 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004755 //
4756 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004757 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004758 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004759 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004760 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4761 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004762 if (ConvOvlResult)
4763 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004764 InitializationSequence::FK_ReferenceInitOverloadFailed,
4765 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004766
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004767 return;
4768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769
Richard Smithce766292016-10-21 23:01:55 +00004770 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004771 isRValueRef && InitCategory.isLValue()) {
4772 Sequence.SetFailed(
4773 InitializationSequence::FK_RValueReferenceBindingToLValue);
4774 return;
4775 }
4776
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004777 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4778 return;
4779 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004780
4781 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004782 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004783 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004784 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004785
Anastasia Stulovad3ae87e2019-03-06 13:02:41 +00004786 // Ignore address space of reference type at this point and perform address
4787 // space conversion after the reference binding step.
4788 QualType cv1T1IgnoreAS =
4789 T1Quals.hasAddressSpace()
4790 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
4791 : cv1T1;
4792
4793 InitializedEntity TempEntity =
4794 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
John McCallec6f4e92010-06-04 02:29:22 +00004795
Richard Smith2eabf782013-06-13 00:57:57 +00004796 // FIXME: Why do we use an implicit conversion here rather than trying
4797 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004798 ImplicitConversionSequence ICS
4799 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004800 /*SuppressUserConversions=*/false,
4801 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004802 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004803 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4804 /*AllowObjCWritebackConversion=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00004805
John McCall31168b02011-06-15 23:02:42 +00004806 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004807 // FIXME: Use the conversion function set stored in ICS to turn
4808 // this into an overloading ambiguity diagnostic. However, we need
4809 // to keep that set as an OverloadCandidateSet rather than as some
4810 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004811 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4812 Sequence.SetOverloadFailure(
4813 InitializationSequence::FK_ReferenceInitOverloadFailed,
4814 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004815 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4816 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004817 else
4818 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004819 return;
John McCall31168b02011-06-15 23:02:42 +00004820 } else {
4821 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004822 }
4823
4824 // [...] If T1 is reference-related to T2, cv1 must be the
4825 // same cv-qualification as, or greater cv-qualification
4826 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004827 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4828 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Anastasia Stulovad3ae87e2019-03-06 13:02:41 +00004829 if ((RefRelationship == Sema::Ref_Related &&
4830 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) ||
4831 !T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004832 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4833 return;
4834 }
4835
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004837 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004839 InitCategory.isLValue()) {
4840 Sequence.SetFailed(
4841 InitializationSequence::FK_RValueReferenceBindingToLValue);
4842 return;
4843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004845 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
Anastasia Stulovad3ae87e2019-03-06 13:02:41 +00004846
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00004847 if (T1Quals.hasAddressSpace()) {
4848 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
4849 LangAS::Default)) {
4850 Sequence.SetFailed(
4851 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
4852 return;
4853 }
Anastasia Stulovad3ae87e2019-03-06 13:02:41 +00004854 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
4855 : VK_XValue);
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00004856 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004857}
4858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004859/// Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004860/// (C++ [dcl.init.string], C99 6.7.8).
4861static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004862 const InitializedEntity &Entity,
4863 const InitializationKind &Kind,
4864 Expr *Initializer,
4865 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004866 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004867}
4868
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004869/// Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004870static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004871 const InitializedEntity &Entity,
4872 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004873 InitializationSequence &Sequence,
4874 InitListExpr *InitList) {
4875 assert((!InitList || InitList->getNumInits() == 0) &&
4876 "Shouldn't use value-init for non-empty init lists");
4877
Richard Smith1bfe0682012-02-14 21:14:13 +00004878 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004879 //
4880 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004881 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004882
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004883 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004884 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004886 if (const RecordType *RT = T->getAs<RecordType>()) {
4887 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004888 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004889 // C++98:
4890 // -- if T is a class type (clause 9) with a user-declared constructor
4891 // (12.1), then the default constructor for T is called (and the
4892 // initialization is ill-formed if T has no accessible default
4893 // constructor);
4894 // C++11:
4895 // -- if T is a class type (clause 9) with either no default constructor
4896 // (12.1 [class.ctor]) or a default constructor that is user-provided
4897 // or deleted, then the object is default-initialized;
4898 //
4899 // Note that the C++11 rule is the same as the C++98 rule if there are no
4900 // defaulted or deleted constructors, so we just use it unconditionally.
4901 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4902 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4903 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004904
Richard Smith1bfe0682012-02-14 21:14:13 +00004905 // -- if T is a (possibly cv-qualified) non-union class type without a
4906 // user-provided or deleted default constructor, then the object is
4907 // zero-initialized and, if T has a non-trivial default constructor,
4908 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004909 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4910 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004911 if (NeedZeroInitialization)
4912 Sequence.AddZeroInitializationStep(Entity.getType());
4913
Richard Smith593f9932012-12-08 02:01:17 +00004914 // C++03:
4915 // -- if T is a non-union class type without a user-declared constructor,
4916 // then every non-static data member and base class component of T is
4917 // value-initialized;
4918 // [...] A program that calls for [...] value-initialization of an
4919 // entity of reference type is ill-formed.
4920 //
4921 // C++11 doesn't need this handling, because value-initialization does not
4922 // occur recursively there, and the implicit default constructor is
4923 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004924 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004925 ClassDecl->hasUninitializedReferenceMember()) {
4926 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4927 return;
4928 }
4929
Richard Smithd86812d2012-07-05 08:39:21 +00004930 // If this is list-value-initialization, pass the empty init list on when
4931 // building the constructor call. This affects the semantics of a few
4932 // things (such as whether an explicit default constructor can be called).
4933 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004934 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004935 bool InitListSyntax = InitList;
4936
Richard Smith81f5ade2016-12-15 02:28:18 +00004937 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004938 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4939 return TryConstructorInitialization(
4940 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004941 }
4942 }
4943
Douglas Gregor1b303932009-12-22 15:35:07 +00004944 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004945}
4946
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004947/// Attempt default initialization (C++ [dcl.init]p6).
Douglas Gregor85dabae2009-12-16 01:38:02 +00004948static void TryDefaultInitialization(Sema &S,
4949 const InitializedEntity &Entity,
4950 const InitializationKind &Kind,
4951 InitializationSequence &Sequence) {
4952 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
Douglas Gregor85dabae2009-12-16 01:38:02 +00004954 // C++ [dcl.init]p6:
4955 // To default-initialize an object of type T means:
4956 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004957 QualType DestType = S.Context.getBaseElementType(Entity.getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00004958
Douglas Gregor85dabae2009-12-16 01:38:02 +00004959 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4960 // constructor for T is called (and the initialization is ill-formed if
4961 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004962 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004963 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4964 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004965 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004967
Douglas Gregor85dabae2009-12-16 01:38:02 +00004968 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969
Douglas Gregor85dabae2009-12-16 01:38:02 +00004970 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004971 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004972 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004973 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004974 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4975 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004976 return;
4977 }
4978
4979 // If the destination type has a lifetime property, zero-initialize it.
4980 if (DestType.getQualifiers().hasObjCLifetime()) {
4981 Sequence.AddZeroInitializationStep(Entity.getType());
4982 return;
4983 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004984}
4985
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004986/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004987/// which enumerates all conversion functions and performs overload resolution
4988/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004989static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004990 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004991 const InitializationKind &Kind,
4992 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004993 InitializationSequence &Sequence,
4994 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004995 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4996 QualType SourceType = Initializer->getType();
4997 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4998 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999
Douglas Gregor540c3b02009-12-14 17:27:33 +00005000 // Build the candidate set directly in the initialization sequence
5001 // structure, so that it will persist if we fail.
5002 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00005003 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Anastasia Stulovac25ea862019-06-20 16:23:28 +00005004 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Douglas Gregor540c3b02009-12-14 17:27:33 +00005006 // Determine whether we are allowed to call explicit constructors or
5007 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00005008 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009
Douglas Gregor540c3b02009-12-14 17:27:33 +00005010 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5011 // The type we're converting to is a class type. Enumerate its constructors
5012 // to see if there is a suitable conversion.
5013 CXXRecordDecl *DestRecordDecl
5014 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015
Douglas Gregord9848152010-04-26 14:36:57 +00005016 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00005017 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00005018 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00005019 auto Info = getConstructorInfo(D);
5020 if (!Info.Constructor)
5021 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022
Richard Smithc2bebe92016-05-11 20:37:46 +00005023 if (!Info.Constructor->isInvalidDecl() &&
5024 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
5025 if (Info.ConstructorTmpl)
Richard Smith76b90272019-05-09 03:59:21 +00005026 S.AddTemplateOverloadCandidate(
5027 Info.ConstructorTmpl, Info.FoundDecl,
5028 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5029 /*SuppressUserConversions=*/true,
5030 /*PartialOverloading*/ false, AllowExplicit);
Douglas Gregord9848152010-04-26 14:36:57 +00005031 else
Richard Smithc2bebe92016-05-11 20:37:46 +00005032 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005033 Initializer, CandidateSet,
Richard Smith76b90272019-05-09 03:59:21 +00005034 /*SuppressUserConversions=*/true,
5035 /*PartialOverloading*/ false, AllowExplicit);
Douglas Gregord9848152010-04-26 14:36:57 +00005036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037 }
Douglas Gregord9848152010-04-26 14:36:57 +00005038 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00005039 }
Eli Friedman78275202009-12-19 08:11:05 +00005040
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005041 SourceLocation DeclLoc = Initializer->getBeginLoc();
Eli Friedman78275202009-12-19 08:11:05 +00005042
Douglas Gregor540c3b02009-12-14 17:27:33 +00005043 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5044 // The type we're converting from is a class type, enumerate its conversion
5045 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00005046
Eli Friedman4afe9a32009-12-20 22:12:03 +00005047 // We can only enumerate the conversion functions for a complete type; if
5048 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00005049 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00005050 CXXRecordDecl *SourceRecordDecl
5051 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005053 const auto &Conversions =
5054 SourceRecordDecl->getVisibleConversionFunctions();
5055 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00005056 NamedDecl *D = *I;
5057 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5058 if (isa<UsingShadowDecl>(D))
5059 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005060
Eli Friedman4afe9a32009-12-20 22:12:03 +00005061 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5062 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00005063 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00005064 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00005065 else
John McCallda4458e2010-03-31 01:36:47 +00005066 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
Eli Friedman4afe9a32009-12-20 22:12:03 +00005068 if (AllowExplicit || !Conv->isExplicit()) {
5069 if (ConvTemplate)
Richard Smith76b90272019-05-09 03:59:21 +00005070 S.AddTemplateConversionCandidate(
5071 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5072 CandidateSet, AllowExplicit, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00005073 else
Richard Smith76b90272019-05-09 03:59:21 +00005074 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5075 DestType, CandidateSet, AllowExplicit,
Douglas Gregor68782142013-12-18 21:46:16 +00005076 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00005077 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00005078 }
5079 }
5080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081
5082 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00005083 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00005084 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00005085 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00005086 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005087 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00005088 Result);
5089 return;
5090 }
John McCall0d1da222010-01-12 00:44:57 +00005091
Douglas Gregor540c3b02009-12-14 17:27:33 +00005092 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00005093 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005094 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095
Douglas Gregor540c3b02009-12-14 17:27:33 +00005096 if (isa<CXXConstructorDecl>(Function)) {
5097 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00005098 // subsumed by the initialization. Per DR5, the created temporary is of the
5099 // cv-unqualified type of the destination.
5100 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5101 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005102 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00005103
5104 // C++14 and before:
5105 // - if the function is a constructor, the call initializes a temporary
5106 // of the cv-unqualified version of the destination type. The [...]
5107 // temporary [...] is then used to direct-initialize, according to the
5108 // rules above, the object that is the destination of the
5109 // copy-initialization.
5110 // Note that this just performs a simple object copy from the temporary.
5111 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005112 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00005113 // - if the function is a constructor, the call is a prvalue of the
5114 // cv-unqualified version of the destination type whose return object
5115 // is initialized by the constructor. The call is used to
5116 // direct-initialize, according to the rules above, the object that
5117 // is the destination of the copy-initialization.
5118 // Therefore we need to do nothing further.
5119 //
5120 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005121 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00005122 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00005123 else if (DestType.hasQualifiers())
5124 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00005125 return;
5126 }
5127
5128 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005129 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00005130 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5131 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005132
Richard Smithb8c0f552016-12-09 18:49:13 +00005133 if (ConvType->getAs<RecordType>()) {
5134 // The call is used to direct-initialize [...] the object that is the
5135 // destination of the copy-initialization.
5136 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005137 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00005138 // - If the initializer expression is a prvalue and the cv-unqualified
5139 // version of the source type is the same as the class of the
5140 // destination [... do not make an extra copy]
5141 //
5142 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005143 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00005144 Function->getReturnType()->isReferenceType() ||
5145 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5146 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00005147 else if (!S.Context.hasSameType(ConvType, DestType))
5148 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00005149 return;
5150 }
5151
Douglas Gregor5ab11652010-04-17 22:01:05 +00005152 // If the conversion following the call to the conversion function
5153 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00005154 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5155 Best->FinalConversion.Third) {
5156 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00005157 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00005158 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005159 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00005160 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005161}
5162
Richard Smithf032001b2013-06-20 02:18:31 +00005163/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5164/// a function with a pointer return type contains a 'return false;' statement.
5165/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5166/// code using that header.
5167///
5168/// Work around this by treating 'return false;' as zero-initializing the result
5169/// if it's used in a pointer-returning function in a system header.
5170static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5171 const InitializedEntity &Entity,
5172 const Expr *Init) {
5173 return S.getLangOpts().CPlusPlus11 &&
5174 Entity.getKind() == InitializedEntity::EK_Result &&
5175 Entity.getType()->isPointerType() &&
5176 isa<CXXBoolLiteralExpr>(Init) &&
5177 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5178 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5179}
5180
John McCall31168b02011-06-15 23:02:42 +00005181/// The non-zero enum values here are indexes into diagnostic alternatives.
5182enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5183
5184/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00005185static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005186 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00005187 // Skip parens.
5188 e = e->IgnoreParens();
5189
5190 // Skip address-of nodes.
5191 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5192 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005193 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5194 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005195
5196 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005197 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5198 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005199 case CK_Dependent:
5200 case CK_BitCast:
5201 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005202 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005203 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005204
5205 case CK_ArrayToPointerDecay:
5206 return IIK_nonscalar;
5207
5208 case CK_NullToPointer:
5209 return IIK_okay;
5210
5211 default:
5212 break;
5213 }
5214
5215 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005216 } else if (isa<DeclRefExpr>(e)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005217 // set isWeakAccess to true, to mean that there will be an implicit
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005218 // load which requires a cleanup.
5219 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5220 isWeakAccess = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00005221
John McCall63f84442011-06-27 23:59:58 +00005222 if (!isAddressOf) return IIK_nonlocal;
5223
John McCall113bee02012-03-10 09:33:50 +00005224 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5225 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005226
5227 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005228
5229 // If we have a conditional operator, check both sides.
5230 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005231 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5232 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005233 return iik;
5234
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005235 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005236
5237 // These are never scalar.
5238 } else if (isa<ArraySubscriptExpr>(e)) {
5239 return IIK_nonscalar;
5240
5241 // Otherwise, it needs to be a null pointer constant.
5242 } else {
5243 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5244 ? IIK_okay : IIK_nonlocal);
5245 }
5246
5247 return IIK_nonlocal;
5248}
5249
5250/// Check whether the given expression is a valid operand for an
5251/// indirect copy/restore.
5252static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5253 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005254 bool isWeakAccess = false;
5255 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
Fangrui Song6907ce22018-07-30 19:24:48 +00005256 // If isWeakAccess to true, there will be an implicit
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005257 // load which requires a cleanup.
5258 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005259 S.Cleanup.setExprNeedsCleanups(true);
5260
John McCall31168b02011-06-15 23:02:42 +00005261 if (iik == IIK_okay) return;
5262
5263 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5264 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5265 << src->getSourceRange();
5266}
5267
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005268/// Determine whether we have compatible array types for the
Douglas Gregore2f943b2011-02-22 18:29:51 +00005269/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005270static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005271 const ArrayType *Source) {
5272 // If the source and destination array types are equivalent, we're
5273 // done.
5274 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5275 return true;
5276
5277 // Make sure that the element types are the same.
5278 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5279 return false;
5280
5281 // The only mismatch we allow is when the destination is an
5282 // incomplete array type and the source is a constant array type.
5283 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5284}
5285
John McCall31168b02011-06-15 23:02:42 +00005286static bool tryObjCWritebackConversion(Sema &S,
5287 InitializationSequence &Sequence,
5288 const InitializedEntity &Entity,
5289 Expr *Initializer) {
5290 bool ArrayDecay = false;
5291 QualType ArgType = Initializer->getType();
5292 QualType ArgPointee;
5293 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5294 ArrayDecay = true;
5295 ArgPointee = ArgArrayType->getElementType();
5296 ArgType = S.Context.getPointerType(ArgPointee);
5297 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005298
John McCall31168b02011-06-15 23:02:42 +00005299 // Handle write-back conversion.
5300 QualType ConvertedArgType;
5301 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5302 ConvertedArgType))
5303 return false;
5304
5305 // We should copy unless we're passing to an argument explicitly
5306 // marked 'out'.
5307 bool ShouldCopy = true;
5308 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5309 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5310
5311 // Do we need an lvalue conversion?
5312 if (ArrayDecay || Initializer->isGLValue()) {
5313 ImplicitConversionSequence ICS;
5314 ICS.setStandard();
5315 ICS.Standard.setAsIdentityConversion();
5316
5317 QualType ResultType;
5318 if (ArrayDecay) {
5319 ICS.Standard.First = ICK_Array_To_Pointer;
5320 ResultType = S.Context.getPointerType(ArgPointee);
5321 } else {
5322 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5323 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5324 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005325
John McCall31168b02011-06-15 23:02:42 +00005326 Sequence.AddConversionSequenceStep(ICS, ResultType);
5327 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005328
John McCall31168b02011-06-15 23:02:42 +00005329 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5330 return true;
5331}
5332
Guy Benyei61054192013-02-07 10:55:47 +00005333static bool TryOCLSamplerInitialization(Sema &S,
5334 InitializationSequence &Sequence,
5335 QualType DestType,
5336 Expr *Initializer) {
5337 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005338 (!Initializer->isIntegerConstantExpr(S.Context) &&
5339 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005340 return false;
5341
5342 Sequence.AddOCLSamplerInitStep(DestType);
5343 return true;
5344}
5345
Andrew Savonichev3fee3512018-11-08 11:25:41 +00005346static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5347 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5348 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5349}
5350
Andrew Savonichevb555b762018-10-23 15:19:20 +00005351static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5352 InitializationSequence &Sequence,
5353 QualType DestType,
5354 Expr *Initializer) {
5355 if (!S.getLangOpts().OpenCL)
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005356 return false;
5357
Andrew Savonichevb555b762018-10-23 15:19:20 +00005358 //
5359 // OpenCL 1.2 spec, s6.12.10
5360 //
5361 // The event argument can also be used to associate the
5362 // async_work_group_copy with a previous async copy allowing
5363 // an event to be shared by multiple async copies; otherwise
5364 // event should be zero.
5365 //
5366 if (DestType->isEventT() || DestType->isQueueT()) {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00005367 if (!IsZeroInitializer(Initializer, S))
5368 return false;
5369
5370 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5371 return true;
5372 }
5373
5374 // We should allow zero initialization for all types defined in the
5375 // cl_intel_device_side_avc_motion_estimation extension, except
5376 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5377 if (S.getOpenCLOptions().isEnabled(
5378 "cl_intel_device_side_avc_motion_estimation") &&
5379 DestType->isOCLIntelSubgroupAVCType()) {
5380 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5381 DestType->isOCLIntelSubgroupAVCMceResultType())
5382 return false;
5383 if (!IsZeroInitializer(Initializer, S))
Andrew Savonichevb555b762018-10-23 15:19:20 +00005384 return false;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005385
Andrew Savonichevb555b762018-10-23 15:19:20 +00005386 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5387 return true;
5388 }
Egor Churaev89831422016-12-23 14:55:49 +00005389
Andrew Savonichevb555b762018-10-23 15:19:20 +00005390 return false;
Egor Churaev89831422016-12-23 14:55:49 +00005391}
5392
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005393InitializationSequence::InitializationSequence(Sema &S,
5394 const InitializedEntity &Entity,
5395 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005396 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005397 bool TopLevelOfInitList,
5398 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005399 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005400 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5401 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005402}
5403
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005404/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5405/// address of that function, this returns true. Otherwise, it returns false.
5406static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5407 auto *DRE = dyn_cast<DeclRefExpr>(E);
5408 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5409 return false;
5410
5411 return !S.checkAddressOfFunctionIsAvailable(
5412 cast<FunctionDecl>(DRE->getDecl()));
5413}
5414
Richard Smith410306b2016-12-12 02:53:20 +00005415/// Determine whether we can perform an elementwise array copy for this kind
5416/// of entity.
5417static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5418 switch (Entity.getKind()) {
5419 case InitializedEntity::EK_LambdaCapture:
5420 // C++ [expr.prim.lambda]p24:
5421 // For array members, the array elements are direct-initialized in
5422 // increasing subscript order.
5423 return true;
5424
5425 case InitializedEntity::EK_Variable:
5426 // C++ [dcl.decomp]p1:
5427 // [...] each element is copy-initialized or direct-initialized from the
5428 // corresponding element of the assignment-expression [...]
5429 return isa<DecompositionDecl>(Entity.getDecl());
5430
5431 case InitializedEntity::EK_Member:
5432 // C++ [class.copy.ctor]p14:
5433 // - if the member is an array, each element is direct-initialized with
5434 // the corresponding subobject of x
5435 return Entity.isImplicitMemberInitializer();
5436
5437 case InitializedEntity::EK_ArrayElement:
5438 // All the above cases are intended to apply recursively, even though none
5439 // of them actually say that.
5440 if (auto *E = Entity.getParent())
5441 return canPerformArrayCopy(*E);
5442 break;
5443
5444 default:
5445 break;
5446 }
5447
5448 return false;
5449}
5450
Richard Smith089c3162013-09-21 21:55:46 +00005451void InitializationSequence::InitializeFrom(Sema &S,
5452 const InitializedEntity &Entity,
5453 const InitializationKind &Kind,
5454 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005455 bool TopLevelOfInitList,
5456 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005457 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005458
John McCall5e77d762013-04-16 07:28:30 +00005459 // Eliminate non-overload placeholder types in the arguments. We
5460 // need to do this before checking whether types are dependent
5461 // because lowering a pseudo-object expression might well give us
5462 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005463 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005464 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5465 // FIXME: should we be doing this here?
5466 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5467 if (result.isInvalid()) {
5468 SetFailed(FK_PlaceholderType);
5469 return;
5470 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005471 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005472 }
5473
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005474 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475 // The semantics of initializers are as follows. The destination type is
5476 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005477 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005479 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005480 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005481
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005482 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005483 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005484 SequenceKind = DependentSequence;
5485 return;
5486 }
5487
Sebastian Redld201edf2011-06-05 13:59:11 +00005488 // Almost everything is a normal sequence.
5489 setSequenceKind(NormalSequence);
5490
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005491 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005492 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005493 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005494 Initializer = Args[0];
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005495 if (S.getLangOpts().ObjC) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005496 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005497 DestType, Initializer->getType(),
5498 Initializer) ||
5499 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5500 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005501 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005502 if (!isa<InitListExpr>(Initializer))
5503 SourceType = Initializer->getType();
5504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
Sebastian Redl0501c632012-02-12 16:37:36 +00005506 // - If the initializer is a (non-parenthesized) braced-init-list, the
5507 // object is list-initialized (8.5.4).
5508 if (Kind.getKind() != InitializationKind::IK_Direct) {
5509 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005510 TryListInitialization(S, Entity, Kind, InitList, *this,
5511 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005512 return;
5513 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005515
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005516 // - If the destination type is a reference type, see 8.5.3.
5517 if (DestType->isReferenceType()) {
5518 // C++0x [dcl.init.ref]p1:
5519 // A variable declared to be a T& or T&&, that is, "reference to type T"
5520 // (8.3.2), shall be initialized by an object, or function, of type T or
5521 // by an object that can be converted into a T.
5522 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005523 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005524 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005525 // C++17 [dcl.init.ref]p5:
5526 // A reference [...] is initialized by an expression [...] as follows:
5527 // If the initializer is not an expression, presumably we should reject,
5528 // but the standard fails to actually say so.
5529 else if (isa<InitListExpr>(Args[0]))
5530 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005531 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005532 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005533 return;
5534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005536 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005537 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005538 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005539 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005540 return;
5541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005542
Douglas Gregor85dabae2009-12-16 01:38:02 +00005543 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005544 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005545 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005546 return;
5547 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005548
John McCall66884dd2011-02-21 07:22:22 +00005549 // - If the destination type is an array of characters, an array of
5550 // char16_t, an array of char32_t, or an array of wchar_t, and the
5551 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005553 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005554 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005555 if (Initializer && isa<VariableArrayType>(DestAT)) {
5556 SetFailed(FK_VariableLengthArrayHasInitializer);
5557 return;
5558 }
5559
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005560 if (Initializer) {
5561 switch (IsStringInit(Initializer, DestAT, Context)) {
5562 case SIF_None:
5563 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5564 return;
5565 case SIF_NarrowStringIntoWideChar:
5566 SetFailed(FK_NarrowStringIntoWideCharArray);
5567 return;
5568 case SIF_WideStringIntoChar:
5569 SetFailed(FK_WideStringIntoCharArray);
5570 return;
5571 case SIF_IncompatWideStringIntoWideChar:
5572 SetFailed(FK_IncompatWideStringIntoWideChar);
5573 return;
Richard Smith3a8244d2018-05-01 05:02:45 +00005574 case SIF_PlainStringIntoUTF8Char:
5575 SetFailed(FK_PlainStringIntoUTF8Char);
5576 return;
5577 case SIF_UTF8StringIntoPlainChar:
5578 SetFailed(FK_UTF8StringIntoPlainChar);
5579 return;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005580 case SIF_Other:
5581 break;
5582 }
John McCall66884dd2011-02-21 07:22:22 +00005583 }
5584
Richard Smith410306b2016-12-12 02:53:20 +00005585 // Some kinds of initialization permit an array to be initialized from
5586 // another array of the same type, and perform elementwise initialization.
5587 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5588 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5589 Entity.getType()) &&
5590 canPerformArrayCopy(Entity)) {
5591 // If source is a prvalue, use it directly.
5592 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005593 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005594 return;
5595 }
5596
5597 // Emit element-at-a-time copy loop.
5598 InitializedEntity Element =
5599 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5600 QualType InitEltT =
5601 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005602 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5603 Initializer->getValueKind(),
5604 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005605 Expr *OVEAsExpr = &OVE;
5606 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5607 TreatUnavailableAsInvalid);
5608 if (!Failed())
5609 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5610 return;
5611 }
5612
Douglas Gregore2f943b2011-02-22 18:29:51 +00005613 // Note: as an GNU C extension, we allow initialization of an
5614 // array from a compound literal that creates an array of the same
5615 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005616 if (!S.getLangOpts().CPlusPlus && Initializer &&
Eli Friedman88fccbd2019-02-11 22:54:27 +00005617 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005618 Initializer->getType()->isArrayType()) {
5619 const ArrayType *SourceAT
5620 = Context.getAsArrayType(Initializer->getType());
5621 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005622 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005623 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005624 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005625 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005626 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005627 }
Richard Smithebeed412012-02-15 22:38:09 +00005628 }
Richard Smithd86812d2012-07-05 08:39:21 +00005629 // Note: as a GNU C++ extension, we allow list-initialization of a
5630 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005631 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005632 Entity.getKind() == InitializedEntity::EK_Member &&
5633 Initializer && isa<InitListExpr>(Initializer)) {
5634 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005635 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005636 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005637 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005638 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005639 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5640 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005641 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005642 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005643
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005644 return;
5645 }
Eli Friedman78275202009-12-19 08:11:05 +00005646
Larisse Voufod2010992015-01-24 23:09:54 +00005647 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005648 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005649 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005650 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005651
Neil Hickey8ece3b62019-07-16 14:57:32 +00005652 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5653 return;
5654
John McCall31168b02011-06-15 23:02:42 +00005655 // We're at the end of the line for C: it's either a write-back conversion
5656 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005657 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005658 // If allowed, check whether this is an Objective-C writeback conversion.
5659 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005660 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005661 return;
5662 }
Guy Benyei61054192013-02-07 10:55:47 +00005663
Andrew Savonichevb555b762018-10-23 15:19:20 +00005664 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005665 return;
5666
John McCall31168b02011-06-15 23:02:42 +00005667 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005668 AddCAssignmentStep(DestType);
5669 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005670 return;
5671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005672
David Blaikiebbafb8a2012-03-11 07:00:24 +00005673 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005674
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005675 // - If the destination type is a (possibly cv-qualified) class type:
5676 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005677 // - If the initialization is direct-initialization, or if it is
5678 // copy-initialization where the cv-unqualified version of the
5679 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005680 // class of the destination, constructors are considered. [...]
5681 if (Kind.getKind() == InitializationKind::IK_Direct ||
5682 (Kind.getKind() == InitializationKind::IK_Copy &&
5683 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005684 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005685 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005686 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005687 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005688 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005689 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005690 // used) to a derived class thereof are enumerated as described in
5691 // 13.3.1.4, and the best one is chosen through overload resolution
5692 // (13.3).
5693 else
Richard Smith77be48a2014-07-31 06:31:19 +00005694 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005695 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005696 return;
5697 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005698
Richard Smith49a6b6e2017-03-24 01:14:25 +00005699 assert(Args.size() >= 1 && "Zero-argument case handled above");
5700
5701 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005702 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005703 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005704 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005705 } else if (isa<InitListExpr>(Args[0])) {
5706 SetFailed(FK_ParenthesizedListInitForScalar);
5707 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709
5710 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005711 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005712 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005713 // For a conversion to _Atomic(T) from either T or a class type derived
5714 // from T, initialize the T object then convert to _Atomic type.
5715 bool NeedAtomicConversion = false;
5716 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5717 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005718 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
Richard Smith0f59cb32015-12-18 21:45:41 +00005719 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005720 DestType = Atomic->getValueType();
5721 NeedAtomicConversion = true;
5722 }
5723 }
5724
5725 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005726 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005727 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005728 if (!Failed() && NeedAtomicConversion)
5729 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005730 return;
5731 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005732
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005733 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005734 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005735 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005737 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005738
John McCall31168b02011-06-15 23:02:42 +00005739 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005740 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005741 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005742 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005743 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005744 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5745 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005746
5747 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005748 ICS.Standard.Second == ICK_Writeback_Conversion) {
5749 // Objective-C ARC writeback conversion.
Fangrui Song6907ce22018-07-30 19:24:48 +00005750
John McCall31168b02011-06-15 23:02:42 +00005751 // We should copy unless we're passing to an argument explicitly
5752 // marked 'out'.
5753 bool ShouldCopy = true;
5754 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5755 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
Fangrui Song6907ce22018-07-30 19:24:48 +00005756
John McCall31168b02011-06-15 23:02:42 +00005757 // If there was an lvalue adjustment, add it as a separate conversion.
5758 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5759 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5760 ImplicitConversionSequence LvalueICS;
5761 LvalueICS.setStandard();
5762 LvalueICS.Standard.setAsIdentityConversion();
5763 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5764 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005765 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005766 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005767
Richard Smith77be48a2014-07-31 06:31:19 +00005768 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005769 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005770 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005771 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5772 AddZeroInitializationStep(Entity.getType());
5773 } else if (Initializer->getType() == Context.OverloadTy &&
5774 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5775 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005776 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005777 else if (Initializer->getType()->isFunctionType() &&
5778 isExprAnUnaddressableFunction(S, Initializer))
5779 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005780 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005781 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005782 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005783 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005784
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005785 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005786 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005787}
5788
5789InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005790 for (auto &S : Steps)
5791 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005792}
5793
5794//===----------------------------------------------------------------------===//
5795// Perform initialization
5796//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005797static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005798getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005799 switch(Entity.getKind()) {
5800 case InitializedEntity::EK_Variable:
5801 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005802 case InitializedEntity::EK_Exception:
5803 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005804 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005805 return Sema::AA_Initializing;
5806
5807 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005808 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005809 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5810 return Sema::AA_Sending;
5811
Douglas Gregore1314a62009-12-18 05:02:21 +00005812 return Sema::AA_Passing;
5813
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005814 case InitializedEntity::EK_Parameter_CF_Audited:
5815 if (Entity.getDecl() &&
5816 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5817 return Sema::AA_Sending;
Fangrui Song6907ce22018-07-30 19:24:48 +00005818
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005819 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
Fangrui Song6907ce22018-07-30 19:24:48 +00005820
Douglas Gregore1314a62009-12-18 05:02:21 +00005821 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005822 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
Douglas Gregore1314a62009-12-18 05:02:21 +00005823 return Sema::AA_Returning;
5824
Douglas Gregore1314a62009-12-18 05:02:21 +00005825 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005826 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005827 // FIXME: Can we tell apart casting vs. converting?
5828 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829
Douglas Gregore1314a62009-12-18 05:02:21 +00005830 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005831 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005832 case InitializedEntity::EK_ArrayElement:
5833 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005834 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005835 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005836 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005837 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005838 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005839 return Sema::AA_Initializing;
5840 }
5841
David Blaikie8a40f702012-01-17 06:56:22 +00005842 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005843}
5844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005845/// Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005846/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005847static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005848 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005849 case InitializedEntity::EK_ArrayElement:
5850 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005851 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005852 case InitializedEntity::EK_StmtExprResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005853 case InitializedEntity::EK_New:
5854 case InitializedEntity::EK_Variable:
5855 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005856 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005857 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005858 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005859 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005860 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005861 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005862 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005863 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005864 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005865
Douglas Gregore1314a62009-12-18 05:02:21 +00005866 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005867 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005868 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005869 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005870 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005871 return true;
5872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005873
Douglas Gregore1314a62009-12-18 05:02:21 +00005874 llvm_unreachable("missed an InitializedEntity kind?");
5875}
5876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005877/// Whether the given entity, when initialized with an object
Douglas Gregor95562572010-04-24 23:45:46 +00005878/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005879static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005880 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005881 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005882 case InitializedEntity::EK_StmtExprResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005883 case InitializedEntity::EK_New:
5884 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005885 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005886 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005887 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005888 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005889 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005890 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005891 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005892
Richard Smith27874d62013-01-08 00:08:23 +00005893 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005894 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005895 case InitializedEntity::EK_Variable:
5896 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005897 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005898 case InitializedEntity::EK_Temporary:
5899 case InitializedEntity::EK_ArrayElement:
5900 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005901 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005902 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005903 return true;
5904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005905
5906 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005907}
5908
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005909/// Get the location at which initialization diagnostics should appear.
Richard Smithc620f552011-10-19 16:55:56 +00005910static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5911 Expr *Initializer) {
5912 switch (Entity.getKind()) {
5913 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005914 case InitializedEntity::EK_StmtExprResult:
Richard Smithc620f552011-10-19 16:55:56 +00005915 return Entity.getReturnLoc();
5916
5917 case InitializedEntity::EK_Exception:
5918 return Entity.getThrowLoc();
5919
5920 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005921 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005922 return Entity.getDecl()->getLocation();
5923
Douglas Gregor19666fb2012-02-15 16:57:26 +00005924 case InitializedEntity::EK_LambdaCapture:
5925 return Entity.getCaptureLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00005926
Richard Smithc620f552011-10-19 16:55:56 +00005927 case InitializedEntity::EK_ArrayElement:
5928 case InitializedEntity::EK_Member:
5929 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005930 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005931 case InitializedEntity::EK_Temporary:
5932 case InitializedEntity::EK_New:
5933 case InitializedEntity::EK_Base:
5934 case InitializedEntity::EK_Delegating:
5935 case InitializedEntity::EK_VectorElement:
5936 case InitializedEntity::EK_ComplexElement:
5937 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005938 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005939 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005940 case InitializedEntity::EK_RelatedResult:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005941 return Initializer->getBeginLoc();
Richard Smithc620f552011-10-19 16:55:56 +00005942 }
5943 llvm_unreachable("missed an InitializedEntity kind?");
5944}
5945
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005946/// Make a (potentially elidable) temporary copy of the object
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005947/// provided by the given initializer by calling the appropriate copy
5948/// constructor.
5949///
5950/// \param S The Sema object used for type-checking.
5951///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005952/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005953/// the type of the initializer expression or a superclass thereof.
5954///
James Dennett634962f2012-06-14 21:40:34 +00005955/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005956///
5957/// \param CurInit The initializer expression.
5958///
5959/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5960/// is permitted in C++03 (but not C++0x) when binding a reference to
5961/// an rvalue.
5962///
5963/// \returns An expression that copies the initializer expression into
5964/// a temporary object, or an error expression if a copy could not be
5965/// created.
John McCalldadc5752010-08-24 06:29:42 +00005966static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005967 QualType T,
5968 const InitializedEntity &Entity,
5969 ExprResult CurInit,
5970 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005971 if (CurInit.isInvalid())
5972 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005973 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005974 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005975 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005976 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005977 Class = cast<CXXRecordDecl>(Record->getDecl());
5978 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005979 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005980
Richard Smithc620f552011-10-19 16:55:56 +00005981 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005982
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005983 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005984 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005985 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005986
Richard Smith7c2bcc92016-09-07 02:14:33 +00005987 // Perform overload resolution using the class's constructors. Per
5988 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005989 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005990 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005991 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005992
Douglas Gregore1314a62009-12-18 05:02:21 +00005993 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005994 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005995 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005996 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5997 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5998 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005999 case OR_Success:
6000 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006001
Douglas Gregore1314a62009-12-18 05:02:21 +00006002 case OR_No_Viable_Function:
David Blaikie5e328052019-05-03 00:44:50 +00006003 CandidateSet.NoteCandidates(
6004 PartialDiagnosticAt(
6005 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6006 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6007 : diag::err_temp_copy_no_viable)
6008 << (int)Entity.getKind() << CurInitExpr->getType()
6009 << CurInitExpr->getSourceRange()),
6010 S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00006011 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00006012 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006013 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006014
Douglas Gregore1314a62009-12-18 05:02:21 +00006015 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00006016 CandidateSet.NoteCandidates(
6017 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6018 << (int)Entity.getKind()
6019 << CurInitExpr->getType()
6020 << CurInitExpr->getSourceRange()),
6021 S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00006022 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006023
Douglas Gregore1314a62009-12-18 05:02:21 +00006024 case OR_Deleted:
6025 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00006026 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00006027 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00006028 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00006029 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006030 }
6031
Richard Smith7c2bcc92016-09-07 02:14:33 +00006032 bool HadMultipleCandidates = CandidateSet.size() > 1;
6033
Douglas Gregor5ab11652010-04-17 22:01:05 +00006034 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00006035 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006036 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006037
Richard Smith5179eb72016-06-28 19:03:57 +00006038 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6039 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006040
6041 if (IsExtraneousCopy) {
6042 // If this is a totally extraneous copy for C++03 reference
6043 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00006044 // expression. We don't generate an (elided) copy operation here
6045 // because doing so would require us to pass down a flag to avoid
6046 // infinite recursion, where each step adds another extraneous,
6047 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006048
Douglas Gregor30b52772010-04-18 07:57:34 +00006049 // Instantiate the default arguments of any extra parameters in
6050 // the selected copy constructor, as if we were going to create a
6051 // proper call to the copy constructor.
6052 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6053 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6054 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006055 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00006056 break;
6057
6058 // Build the default argument expression; we don't actually care
6059 // if this succeeds or not, because this routine will complain
6060 // if there was a problem.
6061 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6062 }
6063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006064 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006066
Douglas Gregor5ab11652010-04-17 22:01:05 +00006067 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006068 // constructor call (we might have derived-to-base conversions, or
6069 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006070 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006071 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006072
Richard Smith7c2bcc92016-09-07 02:14:33 +00006073 // C++0x [class.copy]p32:
6074 // When certain criteria are met, an implementation is allowed to
6075 // omit the copy/move construction of a class object, even if the
6076 // copy/move constructor and/or destructor for the object have
6077 // side effects. [...]
6078 // - when a temporary class object that has not been bound to a
6079 // reference (12.2) would be copied/moved to a class object
6080 // with the same cv-unqualified type, the copy/move operation
6081 // can be omitted by constructing the temporary object
6082 // directly into the target of the omitted copy/move
6083 //
6084 // Note that the other three bullets are handled elsewhere. Copy
6085 // elision for return statements and throw expressions are handled as part
6086 // of constructor initialization, while copy elision for exception handlers
6087 // is handled by the run-time.
6088 //
6089 // FIXME: If the function parameter is not the same type as the temporary, we
6090 // should still be able to elide the copy, but we don't have a way to
6091 // represent in the AST how much should be elided in this case.
6092 bool Elidable =
6093 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6094 S.Context.hasSameUnqualifiedType(
6095 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6096 CurInitExpr->getType());
6097
Douglas Gregord0ace022010-04-25 00:55:24 +00006098 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00006099 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
6100 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006101 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006102 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006103 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006104 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006105 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006106 CXXConstructExpr::CK_Complete,
6107 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006108
Douglas Gregord0ace022010-04-25 00:55:24 +00006109 // If we're supposed to bind temporaries, do so.
6110 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006111 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006112 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006113}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006114
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006115/// Check whether elidable copy construction for binding a reference to
Richard Smithc620f552011-10-19 16:55:56 +00006116/// a temporary would have succeeded if we were building in C++98 mode, for
6117/// -Wc++98-compat.
6118static void CheckCXX98CompatAccessibleCopy(Sema &S,
6119 const InitializedEntity &Entity,
6120 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006121 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00006122
6123 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6124 if (!Record)
6125 return;
6126
6127 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006128 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00006129 return;
6130
6131 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00006132 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00006133 DeclContext::lookup_result Ctors =
6134 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00006135
6136 // Perform overload resolution.
6137 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00006138 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00006139 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00006140 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6141 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6142 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00006143
6144 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6145 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6146 << CurInitExpr->getSourceRange();
6147
6148 switch (OR) {
6149 case OR_Success:
6150 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00006151 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00006152 // FIXME: Check default arguments as far as that's possible.
6153 break;
6154
6155 case OR_No_Viable_Function:
David Blaikie5e328052019-05-03 00:44:50 +00006156 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6157 OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00006158 break;
6159
6160 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00006161 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6162 OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00006163 break;
6164
6165 case OR_Deleted:
6166 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00006167 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00006168 break;
6169 }
6170}
6171
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006172void InitializationSequence::PrintInitLocationNote(Sema &S,
6173 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006174 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006175 if (Entity.getDecl()->getLocation().isInvalid())
6176 return;
6177
6178 if (Entity.getDecl()->getDeclName())
6179 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6180 << Entity.getDecl()->getDeclName();
6181 else
6182 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6183 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006184 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6185 Entity.getMethodDecl())
6186 S.Diag(Entity.getMethodDecl()->getLocation(),
6187 diag::note_method_return_type_change)
6188 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006189}
6190
Jordan Rose6c0505e2013-05-06 16:48:12 +00006191/// Returns true if the parameters describe a constructor initialization of
6192/// an explicit temporary object, e.g. "Point(x, y)".
6193static bool isExplicitTemporary(const InitializedEntity &Entity,
6194 const InitializationKind &Kind,
6195 unsigned NumArgs) {
6196 switch (Entity.getKind()) {
6197 case InitializedEntity::EK_Temporary:
6198 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006199 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006200 break;
6201 default:
6202 return false;
6203 }
6204
6205 switch (Kind.getKind()) {
6206 case InitializationKind::IK_DirectList:
6207 return true;
6208 // FIXME: Hack to work around cast weirdness.
6209 case InitializationKind::IK_Direct:
6210 case InitializationKind::IK_Value:
6211 return NumArgs != 1;
6212 default:
6213 return false;
6214 }
6215}
6216
Sebastian Redled2e5322011-12-22 14:44:04 +00006217static ExprResult
6218PerformConstructorInitialization(Sema &S,
6219 const InitializedEntity &Entity,
6220 const InitializationKind &Kind,
6221 MultiExprArg Args,
6222 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006223 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006224 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006225 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006226 SourceLocation LBraceLoc,
6227 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006228 unsigned NumArgs = Args.size();
6229 CXXConstructorDecl *Constructor
6230 = cast<CXXConstructorDecl>(Step.Function.Function);
6231 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6232
6233 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006234 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006235 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6236 ? Kind.getEqualLoc()
6237 : Kind.getLocation();
6238
6239 if (Kind.getKind() == InitializationKind::IK_Default) {
6240 // Force even a trivial, implicit default constructor to be
6241 // semantically checked. We do this explicitly because we don't build
6242 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006243 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006244 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006245 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006246 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6247 }
6248
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006249 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006250
Douglas Gregor6073dca2012-02-24 23:56:31 +00006251 // C++ [over.match.copy]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00006252 // - When initializing a temporary to be bound to the first parameter
6253 // of a constructor that takes a reference to possibly cv-qualified
6254 // T as its first argument, called with a single argument in the
Douglas Gregor6073dca2012-02-24 23:56:31 +00006255 // context of direct-initialization, explicit conversion functions
6256 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006257 bool AllowExplicitConv =
6258 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6259 hasCopyOrMoveCtorParam(S.Context,
6260 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006261
Sebastian Redled2e5322011-12-22 14:44:04 +00006262 // Determine the arguments required to actually perform the constructor
6263 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006264 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006265 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006266 AllowExplicitConv,
6267 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006268 return ExprError();
6269
6270
Jordan Rose6c0505e2013-05-06 16:48:12 +00006271 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006272 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006273 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6274 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006275
6276 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6277 if (!TSInfo)
6278 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumarc9a95312018-11-19 20:10:21 +00006279 SourceRange ParenOrBraceRange =
6280 (Kind.getKind() == InitializationKind::IK_DirectList)
6281 ? SourceRange(LBraceLoc, RBraceLoc)
6282 : Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006283
Richard Smith5179eb72016-06-28 19:03:57 +00006284 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006285 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006286 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006287 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6288 return ExprError();
6289 }
Richard Smith5179eb72016-06-28 19:03:57 +00006290 S.MarkFunctionReferenced(Loc, Constructor);
6291
Bruno Ricciddb8f6b2018-12-22 14:39:30 +00006292 CurInit = CXXTemporaryObjectExpr::Create(
Richard Smith60437622017-02-09 19:17:44 +00006293 S.Context, Constructor,
6294 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006295 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6296 IsListInitialization, IsStdInitListInitialization,
6297 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006298 } else {
6299 CXXConstructExpr::ConstructionKind ConstructKind =
6300 CXXConstructExpr::CK_Complete;
6301
6302 if (Entity.getKind() == InitializedEntity::EK_Base) {
6303 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6304 CXXConstructExpr::CK_VirtualBase :
6305 CXXConstructExpr::CK_NonVirtualBase;
6306 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6307 ConstructKind = CXXConstructExpr::CK_Delegating;
6308 }
6309
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006310 // Only get the parenthesis or brace range if it is a list initialization or
6311 // direct construction.
6312 SourceRange ParenOrBraceRange;
6313 if (IsListInitialization)
6314 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6315 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006316 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006317
6318 // If the entity allows NRVO, mark the construction as elidable
6319 // unconditionally.
6320 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006321 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006322 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006323 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006324 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006325 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006326 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006327 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006328 ConstructorInitRequiresZeroInit,
6329 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006330 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006331 else
Richard Smith410306b2016-12-12 02:53:20 +00006332 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006333 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006334 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006335 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006336 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006337 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006338 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006339 ConstructorInitRequiresZeroInit,
6340 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006341 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006342 }
6343 if (CurInit.isInvalid())
6344 return ExprError();
6345
6346 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006347 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006348 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6349 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006350
Erik Pilkingtonf8ccf052019-05-10 17:52:26 +00006351 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
6352 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
6353 return ExprError();
6354
Sebastian Redled2e5322011-12-22 14:44:04 +00006355 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006356 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006357
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006358 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006359}
6360
Richard Smithd87aab92018-07-17 22:24:09 +00006361namespace {
6362enum LifetimeKind {
6363 /// The lifetime of a temporary bound to this entity ends at the end of the
6364 /// full-expression, and that's (probably) fine.
6365 LK_FullExpression,
6366
6367 /// The lifetime of a temporary bound to this entity is extended to the
6368 /// lifeitme of the entity itself.
6369 LK_Extended,
6370
6371 /// The lifetime of a temporary bound to this entity probably ends too soon,
6372 /// because the entity is allocated in a new-expression.
6373 LK_New,
6374
6375 /// The lifetime of a temporary bound to this entity ends too soon, because
6376 /// the entity is a return object.
6377 LK_Return,
6378
Richard Smith67af95b2018-07-23 19:19:08 +00006379 /// The lifetime of a temporary bound to this entity ends too soon, because
6380 /// the entity is the result of a statement expression.
6381 LK_StmtExprResult,
6382
Richard Smithd87aab92018-07-17 22:24:09 +00006383 /// This is a mem-initializer: if it would extend a temporary (other than via
6384 /// a default member initializer), the program is ill-formed.
6385 LK_MemInitializer,
6386};
6387using LifetimeResult =
6388 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6389}
6390
Richard Smithe6c01442013-06-05 00:46:14 +00006391/// Determine the declaration which an initialized entity ultimately refers to,
6392/// for the purpose of lifetime-extending a temporary bound to a reference in
6393/// the initialization of \p Entity.
Richard Smithca975b22018-07-23 18:50:26 +00006394static LifetimeResult getEntityLifetime(
David Majnemerdaff3702014-05-01 17:50:17 +00006395 const InitializedEntity *Entity,
Richard Smithd87aab92018-07-17 22:24:09 +00006396 const InitializedEntity *InitField = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006397 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006398 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006399 case InitializedEntity::EK_Variable:
6400 // The temporary [...] persists for the lifetime of the reference
Richard Smithd87aab92018-07-17 22:24:09 +00006401 return {Entity, LK_Extended};
Richard Smithe6c01442013-06-05 00:46:14 +00006402
6403 case InitializedEntity::EK_Member:
6404 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006405 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006406 return getEntityLifetime(Entity->getParent(), Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006407
6408 // except:
Richard Smithd87aab92018-07-17 22:24:09 +00006409 // C++17 [class.base.init]p8:
6410 // A temporary expression bound to a reference member in a
6411 // mem-initializer is ill-formed.
6412 // C++17 [class.base.init]p11:
6413 // A temporary expression bound to a reference member from a
6414 // default member initializer is ill-formed.
6415 //
6416 // The context of p11 and its example suggest that it's only the use of a
6417 // default member initializer from a constructor that makes the program
6418 // ill-formed, not its mere existence, and that it can even be used by
6419 // aggregate initialization.
6420 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6421 : LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006422
Richard Smith7873de02016-08-11 22:25:46 +00006423 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006424 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6425 // type.
Richard Smithd87aab92018-07-17 22:24:09 +00006426 return {Entity, LK_Extended};
Richard Smith7873de02016-08-11 22:25:46 +00006427
Richard Smithe6c01442013-06-05 00:46:14 +00006428 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006429 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006430 // -- A temporary bound to a reference parameter in a function call
6431 // persists until the completion of the full-expression containing
6432 // the call.
Richard Smithd87aab92018-07-17 22:24:09 +00006433 return {nullptr, LK_FullExpression};
6434
Richard Smithe6c01442013-06-05 00:46:14 +00006435 case InitializedEntity::EK_Result:
6436 // -- The lifetime of a temporary bound to the returned value in a
6437 // function return statement is not extended; the temporary is
6438 // destroyed at the end of the full-expression in the return statement.
Richard Smithd87aab92018-07-17 22:24:09 +00006439 return {nullptr, LK_Return};
6440
Richard Smith67af95b2018-07-23 19:19:08 +00006441 case InitializedEntity::EK_StmtExprResult:
6442 // FIXME: Should we lifetime-extend through the result of a statement
6443 // expression?
6444 return {nullptr, LK_StmtExprResult};
6445
Richard Smithe6c01442013-06-05 00:46:14 +00006446 case InitializedEntity::EK_New:
6447 // -- A temporary bound to a reference in a new-initializer persists
6448 // until the completion of the full-expression containing the
6449 // new-initializer.
Richard Smithd87aab92018-07-17 22:24:09 +00006450 return {nullptr, LK_New};
Richard Smithe6c01442013-06-05 00:46:14 +00006451
6452 case InitializedEntity::EK_Temporary:
6453 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006454 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006455 // We don't yet know the storage duration of the surrounding temporary.
6456 // Assume it's got full-expression duration for now, it will patch up our
6457 // storage duration if that's not correct.
Richard Smithd87aab92018-07-17 22:24:09 +00006458 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006459
6460 case InitializedEntity::EK_ArrayElement:
6461 // For subobjects, we look at the complete object.
Richard Smithca975b22018-07-23 18:50:26 +00006462 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithe6c01442013-06-05 00:46:14 +00006463
6464 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006465 // For subobjects, we look at the complete object.
6466 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006467 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithd87aab92018-07-17 22:24:09 +00006468 return {InitField, LK_MemInitializer};
6469
Richard Smithe6c01442013-06-05 00:46:14 +00006470 case InitializedEntity::EK_Delegating:
6471 // We can reach this case for aggregate initialization in a constructor:
6472 // struct A { int &&r; };
6473 // struct B : A { B() : A{0} {} };
Richard Smithd87aab92018-07-17 22:24:09 +00006474 // In this case, use the outermost field decl as the context.
6475 return {InitField, LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006476
6477 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006478 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006479 case InitializedEntity::EK_LambdaCapture:
Richard Smithe6c01442013-06-05 00:46:14 +00006480 case InitializedEntity::EK_VectorElement:
6481 case InitializedEntity::EK_ComplexElement:
Richard Smithd87aab92018-07-17 22:24:09 +00006482 return {nullptr, LK_FullExpression};
Richard Smithca975b22018-07-23 18:50:26 +00006483
6484 case InitializedEntity::EK_Exception:
6485 // FIXME: Can we diagnose lifetime problems with exceptions?
6486 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006487 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006488 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006489}
6490
Richard Smithd87aab92018-07-17 22:24:09 +00006491namespace {
Richard Smithca975b22018-07-23 18:50:26 +00006492enum ReferenceKind {
Richard Smithd87aab92018-07-17 22:24:09 +00006493 /// Lifetime would be extended by a reference binding to a temporary.
Richard Smithca975b22018-07-23 18:50:26 +00006494 RK_ReferenceBinding,
Richard Smithd87aab92018-07-17 22:24:09 +00006495 /// Lifetime would be extended by a std::initializer_list object binding to
6496 /// its backing array.
Richard Smithca975b22018-07-23 18:50:26 +00006497 RK_StdInitializerList,
Richard Smithd87aab92018-07-17 22:24:09 +00006498};
Richard Smithca975b22018-07-23 18:50:26 +00006499
Richard Smithafe48f92018-07-23 21:21:22 +00006500/// A temporary or local variable. This will be one of:
6501/// * A MaterializeTemporaryExpr.
6502/// * A DeclRefExpr whose declaration is a local.
6503/// * An AddrLabelExpr.
6504/// * A BlockExpr for a block with captures.
6505using Local = Expr*;
Richard Smithca975b22018-07-23 18:50:26 +00006506
6507/// Expressions we stepped over when looking for the local state. Any steps
6508/// that would inhibit lifetime extension or take us out of subexpressions of
6509/// the initializer are included.
6510struct IndirectLocalPathEntry {
Richard Smithafe48f92018-07-23 21:21:22 +00006511 enum EntryKind {
Richard Smithca975b22018-07-23 18:50:26 +00006512 DefaultInit,
6513 AddressOf,
Richard Smithafe48f92018-07-23 21:21:22 +00006514 VarInit,
6515 LValToRVal,
Richard Smithf4e248c2018-08-01 00:33:25 +00006516 LifetimeBoundCall,
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006517 GslPointerInit
Richard Smithca975b22018-07-23 18:50:26 +00006518 } Kind;
6519 Expr *E;
Richard Smithf4e248c2018-08-01 00:33:25 +00006520 const Decl *D = nullptr;
Richard Smithafe48f92018-07-23 21:21:22 +00006521 IndirectLocalPathEntry() {}
6522 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
Richard Smithf4e248c2018-08-01 00:33:25 +00006523 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
6524 : Kind(K), E(E), D(D) {}
Richard Smithca975b22018-07-23 18:50:26 +00006525};
6526
6527using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
Richard Smithe6c01442013-06-05 00:46:14 +00006528
Richard Smithd87aab92018-07-17 22:24:09 +00006529struct RevertToOldSizeRAII {
Richard Smithca975b22018-07-23 18:50:26 +00006530 IndirectLocalPath &Path;
Richard Smithd87aab92018-07-17 22:24:09 +00006531 unsigned OldSize = Path.size();
Richard Smithca975b22018-07-23 18:50:26 +00006532 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
Richard Smithd87aab92018-07-17 22:24:09 +00006533 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6534};
Richard Smithafe48f92018-07-23 21:21:22 +00006535
6536using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
6537 ReferenceKind RK)>;
Richard Smithd87aab92018-07-17 22:24:09 +00006538}
6539
Richard Smithafe48f92018-07-23 21:21:22 +00006540static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
6541 for (auto E : Path)
6542 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
6543 return true;
6544 return false;
6545}
6546
Richard Smith0e3102d2018-07-24 00:55:08 +00006547static bool pathContainsInit(IndirectLocalPath &Path) {
Fangrui Song3117b172018-10-20 17:53:42 +00006548 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
Richard Smith0e3102d2018-07-24 00:55:08 +00006549 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
6550 E.Kind == IndirectLocalPathEntry::VarInit;
6551 });
6552}
6553
Richard Smithca975b22018-07-23 18:50:26 +00006554static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6555 Expr *Init, LocalVisitor Visit,
6556 bool RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006557
Richard Smithf4e248c2018-08-01 00:33:25 +00006558static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6559 Expr *Init, ReferenceKind RK,
6560 LocalVisitor Visit);
6561
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006562template <typename T> static bool isRecordWithAttr(QualType Type) {
6563 if (auto *RD = Type->getAsCXXRecordDecl())
6564 return RD->getCanonicalDecl()->hasAttr<T>();
6565 return false;
6566}
6567
Gabor Horvathbfe0c372019-08-14 16:34:56 +00006568// Decl::isInStdNamespace will return false for iterators in some STL
6569// implementations due to them being defined in a namespace outside of the std
6570// namespace.
6571static bool isInStlNamespace(const Decl *D) {
6572 const DeclContext *DC = D->getDeclContext();
6573 if (!DC)
6574 return false;
6575 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
6576 if (const IdentifierInfo *II = ND->getIdentifier()) {
6577 StringRef Name = II->getName();
6578 if (Name.size() >= 2 && Name.front() == '_' &&
6579 (Name[1] == '_' || isUppercase(Name[1])))
6580 return true;
6581 }
6582
6583 return DC->isStdNamespace();
6584}
6585
Gabor Horvathc1dafd72019-08-09 15:16:35 +00006586static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
6587 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
6588 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
6589 return true;
Gabor Horvathbfe0c372019-08-14 16:34:56 +00006590 if (!isInStlNamespace(Callee->getParent()))
Gabor Horvathc1dafd72019-08-09 15:16:35 +00006591 return false;
6592 if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) &&
6593 !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType()))
6594 return false;
Gabor Horvath795c3662019-08-09 23:03:50 +00006595 if (Callee->getReturnType()->isPointerType() ||
6596 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
6597 if (!Callee->getIdentifier())
6598 return false;
6599 return llvm::StringSwitch<bool>(Callee->getName())
6600 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
6601 .Cases("end", "rend", "cend", "crend", true)
6602 .Cases("c_str", "data", "get", true)
6603 // Map and set types.
6604 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
6605 .Default(false);
6606 } else if (Callee->getReturnType()->isReferenceType()) {
6607 if (!Callee->getIdentifier()) {
6608 auto OO = Callee->getOverloadedOperator();
6609 return OO == OverloadedOperatorKind::OO_Subscript ||
6610 OO == OverloadedOperatorKind::OO_Star;
6611 }
6612 return llvm::StringSwitch<bool>(Callee->getName())
6613 .Cases("front", "back", "at", true)
6614 .Default(false);
6615 }
6616 return false;
Gabor Horvathc1dafd72019-08-09 15:16:35 +00006617}
6618
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006619static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
6620 LocalVisitor Visit) {
6621 auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
6622 Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
6623 if (Arg->isGLValue())
6624 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6625 Visit);
6626 else
6627 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6628 Path.pop_back();
6629 };
6630
6631 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
Gabor Horvathc1dafd72019-08-09 15:16:35 +00006632 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
6633 if (MD && shouldTrackImplicitObjectArg(MD))
6634 VisitPointerArg(MD, MCE->getImplicitObjectArgument());
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006635 return;
Gabor Horvath795c3662019-08-09 23:03:50 +00006636 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
6637 FunctionDecl *Callee = OCE->getDirectCallee();
6638 if (Callee && Callee->isCXXInstanceMember() &&
6639 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
6640 VisitPointerArg(Callee, OCE->getArg(0));
6641 return;
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006642 }
6643
6644 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
6645 const auto *Ctor = CCE->getConstructor();
6646 const CXXRecordDecl *RD = Ctor->getParent()->getCanonicalDecl();
6647 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
6648 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0]);
6649 }
6650}
6651
Richard Smithf4e248c2018-08-01 00:33:25 +00006652static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
6653 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
6654 if (!TSI)
6655 return false;
Martin Storsjod03fa992018-08-02 18:12:08 +00006656 // Don't declare this variable in the second operand of the for-statement;
6657 // GCC miscompiles that by ending its lifetime before evaluating the
6658 // third operand. See gcc.gnu.org/PR86769.
6659 AttributedTypeLoc ATL;
Richard Smithf4e248c2018-08-01 00:33:25 +00006660 for (TypeLoc TL = TSI->getTypeLoc();
Martin Storsjod03fa992018-08-02 18:12:08 +00006661 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
Richard Smithf4e248c2018-08-01 00:33:25 +00006662 TL = ATL.getModifiedLoc()) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006663 if (ATL.getAttrAs<LifetimeBoundAttr>())
Richard Smithf4e248c2018-08-01 00:33:25 +00006664 return true;
6665 }
6666 return false;
6667}
6668
6669static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
6670 LocalVisitor Visit) {
6671 const FunctionDecl *Callee;
6672 ArrayRef<Expr*> Args;
6673
6674 if (auto *CE = dyn_cast<CallExpr>(Call)) {
6675 Callee = CE->getDirectCallee();
6676 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
6677 } else {
6678 auto *CCE = cast<CXXConstructExpr>(Call);
6679 Callee = CCE->getConstructor();
6680 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
6681 }
6682 if (!Callee)
6683 return;
6684
6685 Expr *ObjectArg = nullptr;
6686 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
6687 ObjectArg = Args[0];
6688 Args = Args.slice(1);
6689 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6690 ObjectArg = MCE->getImplicitObjectArgument();
6691 }
6692
6693 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
6694 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
6695 if (Arg->isGLValue())
6696 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6697 Visit);
6698 else
6699 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6700 Path.pop_back();
6701 };
6702
6703 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
6704 VisitLifetimeBoundArg(Callee, ObjectArg);
6705
6706 for (unsigned I = 0,
6707 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
6708 I != N; ++I) {
6709 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
6710 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
6711 }
6712}
6713
Richard Smithca975b22018-07-23 18:50:26 +00006714/// Visit the locals that would be reachable through a reference bound to the
6715/// glvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006716static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6717 Expr *Init, ReferenceKind RK,
6718 LocalVisitor Visit) {
Richard Smithd87aab92018-07-17 22:24:09 +00006719 RevertToOldSizeRAII RAII(Path);
6720
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006721 // Walk past any constructs which we can lifetime-extend across.
6722 Expr *Old;
6723 do {
6724 Old = Init;
6725
Bill Wendling7c44da22018-10-31 03:48:47 +00006726 if (auto *FE = dyn_cast<FullExpr>(Init))
6727 Init = FE->getSubExpr();
Richard Smithafe48f92018-07-23 21:21:22 +00006728
Richard Smithdbc82492015-01-10 01:28:13 +00006729 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithd87aab92018-07-17 22:24:09 +00006730 // If this is just redundant braces around an initializer, step over it.
6731 if (ILE->isTransparent())
Richard Smithdbc82492015-01-10 01:28:13 +00006732 Init = ILE->getInit(0);
Richard Smithdbc82492015-01-10 01:28:13 +00006733 }
6734
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006735 // Step over any subobject adjustments; we may have a materialized
6736 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006737 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006738
6739 // Per current approach for DR1376, look through casts to reference type
6740 // when performing lifetime extension.
6741 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6742 if (CE->getSubExpr()->isGLValue())
6743 Init = CE->getSubExpr();
6744
Richard Smithb3189a12016-12-05 07:49:14 +00006745 // Per the current approach for DR1299, look through array element access
Richard Smithca975b22018-07-23 18:50:26 +00006746 // on array glvalues when performing lifetime extension.
6747 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006748 Init = ASE->getBase();
6749 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
6750 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
6751 Init = ICE->getSubExpr();
6752 else
6753 // We can't lifetime extend through this but we might still find some
6754 // retained temporaries.
6755 return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
Richard Smithca975b22018-07-23 18:50:26 +00006756 }
Richard Smithd87aab92018-07-17 22:24:09 +00006757
6758 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6759 // constructor inherits one as an implicit mem-initializer.
6760 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006761 Path.push_back(
6762 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
Richard Smithd87aab92018-07-17 22:24:09 +00006763 Init = DIE->getExpr();
Richard Smithd87aab92018-07-17 22:24:09 +00006764 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006765 } while (Init != Old);
6766
Richard Smithd87aab92018-07-17 22:24:09 +00006767 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006768 if (Visit(Path, Local(MTE), RK))
6769 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
6770 true);
6771 }
6772
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006773 if (isa<CallExpr>(Init)) {
6774 handleGslAnnotatedTypes(Path, Init, Visit);
Richard Smithf4e248c2018-08-01 00:33:25 +00006775 return visitLifetimeBoundArguments(Path, Init, Visit);
Gabor Horvathe5e10b52019-08-06 19:13:29 +00006776 }
Richard Smithf4e248c2018-08-01 00:33:25 +00006777
Richard Smithafe48f92018-07-23 21:21:22 +00006778 switch (Init->getStmtClass()) {
6779 case Stmt::DeclRefExprClass: {
6780 // If we find the name of a local non-reference parameter, we could have a
6781 // lifetime problem.
6782 auto *DRE = cast<DeclRefExpr>(Init);
Richard Smithca975b22018-07-23 18:50:26 +00006783 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6784 if (VD && VD->hasLocalStorage() &&
6785 !DRE->refersToEnclosingVariableOrCapture()) {
Richard Smithafe48f92018-07-23 21:21:22 +00006786 if (!VD->getType()->isReferenceType()) {
6787 Visit(Path, Local(DRE), RK);
6788 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
6789 // The lifetime of a reference parameter is unknown; assume it's OK
6790 // for now.
6791 break;
6792 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
6793 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6794 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
6795 RK_ReferenceBinding, Visit);
6796 }
Richard Smithca975b22018-07-23 18:50:26 +00006797 }
Richard Smithafe48f92018-07-23 21:21:22 +00006798 break;
6799 }
6800
6801 case Stmt::UnaryOperatorClass: {
6802 // The only unary operator that make sense to handle here
6803 // is Deref. All others don't resolve to a "name." This includes
6804 // handling all sorts of rvalues passed to a unary operator.
6805 const UnaryOperator *U = cast<UnaryOperator>(Init);
6806 if (U->getOpcode() == UO_Deref)
6807 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
6808 break;
6809 }
6810
6811 case Stmt::OMPArraySectionExprClass: {
6812 visitLocalsRetainedByInitializer(
6813 Path, cast<OMPArraySectionExpr>(Init)->getBase(), Visit, true);
6814 break;
6815 }
6816
6817 case Stmt::ConditionalOperatorClass:
6818 case Stmt::BinaryConditionalOperatorClass: {
6819 auto *C = cast<AbstractConditionalOperator>(Init);
6820 if (!C->getTrueExpr()->getType()->isVoidType())
6821 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
6822 if (!C->getFalseExpr()->getType()->isVoidType())
6823 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
6824 break;
6825 }
6826
6827 // FIXME: Visit the left-hand side of an -> or ->*.
6828
6829 default:
6830 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006831 }
6832}
6833
Richard Smithca975b22018-07-23 18:50:26 +00006834/// Visit the locals that would be reachable through an object initialized by
6835/// the prvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006836static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6837 Expr *Init, LocalVisitor Visit,
6838 bool RevisitSubinits) {
Richard Smithd87aab92018-07-17 22:24:09 +00006839 RevertToOldSizeRAII RAII(Path);
6840
Richard Smithf4e248c2018-08-01 00:33:25 +00006841 Expr *Old;
6842 do {
6843 Old = Init;
Richard Smithd87aab92018-07-17 22:24:09 +00006844
Richard Smithf4e248c2018-08-01 00:33:25 +00006845 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6846 // constructor inherits one as an implicit mem-initializer.
6847 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6848 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
6849 Init = DIE->getExpr();
6850 }
Richard Smithafe48f92018-07-23 21:21:22 +00006851
Bill Wendling7c44da22018-10-31 03:48:47 +00006852 if (auto *FE = dyn_cast<FullExpr>(Init))
6853 Init = FE->getSubExpr();
Richard Smithe6c01442013-06-05 00:46:14 +00006854
Richard Smithf4e248c2018-08-01 00:33:25 +00006855 // Dig out the expression which constructs the extended temporary.
6856 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6857
6858 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6859 Init = BTE->getSubExpr();
6860
6861 Init = Init->IgnoreParens();
6862
6863 // Step over value-preserving rvalue casts.
6864 if (auto *CE = dyn_cast<CastExpr>(Init)) {
6865 switch (CE->getCastKind()) {
6866 case CK_LValueToRValue:
6867 // If we can match the lvalue to a const object, we can look at its
6868 // initializer.
6869 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
6870 return visitLocalsRetainedByReferenceBinding(
6871 Path, Init, RK_ReferenceBinding,
6872 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
6873 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
6874 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6875 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
6876 !isVarOnPath(Path, VD)) {
6877 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6878 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true);
6879 }
6880 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
6881 if (MTE->getType().isConstQualified())
6882 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
6883 Visit, true);
6884 }
6885 return false;
6886 });
6887
6888 // We assume that objects can be retained by pointers cast to integers,
6889 // but not if the integer is cast to floating-point type or to _Complex.
6890 // We assume that casts to 'bool' do not preserve enough information to
6891 // retain a local object.
6892 case CK_NoOp:
6893 case CK_BitCast:
6894 case CK_BaseToDerived:
6895 case CK_DerivedToBase:
6896 case CK_UncheckedDerivedToBase:
6897 case CK_Dynamic:
6898 case CK_ToUnion:
6899 case CK_UserDefinedConversion:
6900 case CK_ConstructorConversion:
6901 case CK_IntegralToPointer:
6902 case CK_PointerToIntegral:
6903 case CK_VectorSplat:
6904 case CK_IntegralCast:
6905 case CK_CPointerToObjCPointerCast:
6906 case CK_BlockPointerToObjCPointerCast:
6907 case CK_AnyPointerToBlockPointerCast:
6908 case CK_AddressSpaceConversion:
6909 break;
6910
6911 case CK_ArrayToPointerDecay:
6912 // Model array-to-pointer decay as taking the address of the array
6913 // lvalue.
6914 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
6915 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
6916 RK_ReferenceBinding, Visit);
6917
6918 default:
6919 return;
6920 }
6921
6922 Init = CE->getSubExpr();
6923 }
6924 } while (Old != Init);
Richard Smith736a9472013-06-12 20:42:33 +00006925
Richard Smithd87aab92018-07-17 22:24:09 +00006926 // C++17 [dcl.init.list]p6:
6927 // initializing an initializer_list object from the array extends the
6928 // lifetime of the array exactly like binding a reference to a temporary.
6929 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
Richard Smithca975b22018-07-23 18:50:26 +00006930 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
6931 RK_StdInitializerList, Visit);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006932
Richard Smithe6c01442013-06-05 00:46:14 +00006933 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006934 // We already visited the elements of this initializer list while
6935 // performing the initialization. Don't visit them again unless we've
6936 // changed the lifetime of the initialized entity.
6937 if (!RevisitSubinits)
6938 return;
6939
Richard Smithd87aab92018-07-17 22:24:09 +00006940 if (ILE->isTransparent())
Richard Smithca975b22018-07-23 18:50:26 +00006941 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
6942 RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006943
Richard Smithcc1b96d2013-06-12 22:31:48 +00006944 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006945 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Richard Smithca975b22018-07-23 18:50:26 +00006946 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
6947 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006948 return;
6949 }
6950
Richard Smithcc1b96d2013-06-12 22:31:48 +00006951 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006952 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6953
6954 // If we lifetime-extend a braced initializer which is initializing an
6955 // aggregate, and that aggregate contains reference members which are
6956 // bound to temporaries, those temporaries are also lifetime-extended.
6957 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6958 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006959 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
6960 RK_ReferenceBinding, Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006961 else {
6962 unsigned Index = 0;
Richard Smithc69cc842019-06-12 18:32:22 +00006963 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
6964 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
6965 RevisitSubinits);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006966 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006967 if (Index >= ILE->getNumInits())
6968 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006969 if (I->isUnnamedBitfield())
6970 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006971 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006972 if (I->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006973 visitLocalsRetainedByReferenceBinding(Path, SubInit,
6974 RK_ReferenceBinding, Visit);
Richard Smithd87aab92018-07-17 22:24:09 +00006975 else
6976 // This might be either aggregate-initialization of a member or
6977 // initialization of a std::initializer_list object. Regardless,
Richard Smithe6c01442013-06-05 00:46:14 +00006978 // we should recursively lifetime-extend that initializer.
Richard Smithca975b22018-07-23 18:50:26 +00006979 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
6980 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006981 ++Index;
6982 }
6983 }
6984 }
Richard Smithca975b22018-07-23 18:50:26 +00006985 return;
6986 }
6987
Richard Smithb3d203f2018-10-19 19:01:34 +00006988 // The lifetime of an init-capture is that of the closure object constructed
6989 // by a lambda-expression.
6990 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
6991 for (Expr *E : LE->capture_inits()) {
6992 if (!E)
6993 continue;
6994 if (E->isGLValue())
6995 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
6996 Visit);
6997 else
6998 visitLocalsRetainedByInitializer(Path, E, Visit, true);
6999 }
7000 }
7001
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007002 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7003 handleGslAnnotatedTypes(Path, Init, Visit);
Richard Smithf4e248c2018-08-01 00:33:25 +00007004 return visitLifetimeBoundArguments(Path, Init, Visit);
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007005 }
Richard Smithafe48f92018-07-23 21:21:22 +00007006
Richard Smithafe48f92018-07-23 21:21:22 +00007007 switch (Init->getStmtClass()) {
7008 case Stmt::UnaryOperatorClass: {
7009 auto *UO = cast<UnaryOperator>(Init);
7010 // If the initializer is the address of a local, we could have a lifetime
7011 // problem.
7012 if (UO->getOpcode() == UO_AddrOf) {
Richard Smith0e3102d2018-07-24 00:55:08 +00007013 // If this is &rvalue, then it's ill-formed and we have already diagnosed
7014 // it. Don't produce a redundant warning about the lifetime of the
7015 // temporary.
7016 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7017 return;
7018
Richard Smithafe48f92018-07-23 21:21:22 +00007019 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7020 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7021 RK_ReferenceBinding, Visit);
7022 }
7023 break;
7024 }
7025
7026 case Stmt::BinaryOperatorClass: {
7027 // Handle pointer arithmetic.
7028 auto *BO = cast<BinaryOperator>(Init);
7029 BinaryOperatorKind BOK = BO->getOpcode();
7030 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
7031 break;
7032
7033 if (BO->getLHS()->getType()->isPointerType())
7034 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
7035 else if (BO->getRHS()->getType()->isPointerType())
7036 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
7037 break;
7038 }
7039
7040 case Stmt::ConditionalOperatorClass:
7041 case Stmt::BinaryConditionalOperatorClass: {
7042 auto *C = cast<AbstractConditionalOperator>(Init);
7043 // In C++, we can have a throw-expression operand, which has 'void' type
7044 // and isn't interesting from a lifetime perspective.
7045 if (!C->getTrueExpr()->getType()->isVoidType())
7046 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
7047 if (!C->getFalseExpr()->getType()->isVoidType())
7048 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
7049 break;
7050 }
7051
7052 case Stmt::BlockExprClass:
7053 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
7054 // This is a local block, whose lifetime is that of the function.
7055 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
7056 }
7057 break;
7058
7059 case Stmt::AddrLabelExprClass:
7060 // We want to warn if the address of a label would escape the function.
7061 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
7062 break;
7063
7064 default:
7065 break;
Richard Smithe6c01442013-06-05 00:46:14 +00007066 }
7067}
7068
Richard Smithd87aab92018-07-17 22:24:09 +00007069/// Determine whether this is an indirect path to a temporary that we are
7070/// supposed to lifetime-extend along (but don't).
Richard Smithca975b22018-07-23 18:50:26 +00007071static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
Richard Smithd87aab92018-07-17 22:24:09 +00007072 for (auto Elem : Path) {
Richard Smithf66e4f72018-07-23 22:56:45 +00007073 if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
Richard Smithd87aab92018-07-17 22:24:09 +00007074 return false;
7075 }
7076 return true;
7077}
7078
Richard Smith6a32c052018-07-23 21:21:24 +00007079/// Find the range for the first interesting entry in the path at or after I.
7080static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
7081 Expr *E) {
7082 for (unsigned N = Path.size(); I != N; ++I) {
7083 switch (Path[I].Kind) {
7084 case IndirectLocalPathEntry::AddressOf:
7085 case IndirectLocalPathEntry::LValToRVal:
Richard Smithf4e248c2018-08-01 00:33:25 +00007086 case IndirectLocalPathEntry::LifetimeBoundCall:
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007087 case IndirectLocalPathEntry::GslPointerInit:
Richard Smith6a32c052018-07-23 21:21:24 +00007088 // These exist primarily to mark the path as not permitting or
7089 // supporting lifetime extension.
7090 break;
7091
Gabor Horvathfd85c892019-08-09 18:58:09 +00007092 case IndirectLocalPathEntry::VarInit:
Gabor Horvathc6802b22019-08-12 16:19:39 +00007093 if (cast<VarDecl>(Path[I].D)->isImplicit())
7094 return SourceRange();
7095 LLVM_FALLTHROUGH;
7096 case IndirectLocalPathEntry::DefaultInit:
Richard Smith6a32c052018-07-23 21:21:24 +00007097 return Path[I].E->getSourceRange();
7098 }
7099 }
7100 return E->getSourceRange();
7101}
7102
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007103static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
Gabor Horvath3560ed02019-08-11 08:05:28 +00007104 for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
7105 if (It->Kind == IndirectLocalPathEntry::VarInit)
7106 continue;
7107 return It->Kind == IndirectLocalPathEntry::GslPointerInit;
7108 }
7109 return false;
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007110}
7111
Richard Smithd87aab92018-07-17 22:24:09 +00007112void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7113 Expr *Init) {
Richard Smithca975b22018-07-23 18:50:26 +00007114 LifetimeResult LR = getEntityLifetime(&Entity);
Richard Smithd87aab92018-07-17 22:24:09 +00007115 LifetimeKind LK = LR.getInt();
7116 const InitializedEntity *ExtendingEntity = LR.getPointer();
7117
7118 // If this entity doesn't have an interesting lifetime, don't bother looking
7119 // for temporaries within its initializer.
7120 if (LK == LK_FullExpression)
7121 return;
7122
Richard Smithca975b22018-07-23 18:50:26 +00007123 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
7124 ReferenceKind RK) -> bool {
Richard Smith6a32c052018-07-23 21:21:24 +00007125 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
7126 SourceLocation DiagLoc = DiagRange.getBegin();
Richard Smithca975b22018-07-23 18:50:26 +00007127
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007128 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007129
Gabor Horvathbfe0c372019-08-14 16:34:56 +00007130 bool IsGslPtrInitWithGslTempOwner = false;
7131 bool IsLocalGslOwner = false;
7132 if (pathOnlyInitializesGslPointer(Path)) {
7133 if (isa<DeclRefExpr>(L)) {
7134 // We do not want to follow the references when returning a pointer originating
7135 // from a local owner to avoid the following false positive:
7136 // int &p = *localUniquePtr;
7137 // someContainer.add(std::move(localUniquePtr));
7138 // return p;
7139 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
7140 if (pathContainsInit(Path) || !IsLocalGslOwner)
7141 return false;
7142 } else {
7143 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
7144 isRecordWithAttr<OwnerAttr>(MTE->getType());
7145 // Skipping a chain of initializing gsl::Pointer annotated objects.
7146 // We are looking only for the final source to find out if it was
7147 // a local or temporary owner or the address of a local variable/param.
7148 if (!IsGslPtrInitWithGslTempOwner)
7149 return true;
7150 }
7151 }
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007152
Richard Smithd87aab92018-07-17 22:24:09 +00007153 switch (LK) {
7154 case LK_FullExpression:
7155 llvm_unreachable("already handled this");
7156
Richard Smithafe48f92018-07-23 21:21:22 +00007157 case LK_Extended: {
Richard Smith0e3102d2018-07-24 00:55:08 +00007158 if (!MTE) {
7159 // The initialized entity has lifetime beyond the full-expression,
7160 // and the local entity does too, so don't warn.
7161 //
7162 // FIXME: We should consider warning if a static / thread storage
7163 // duration variable retains an automatic storage duration local.
Richard Smithafe48f92018-07-23 21:21:22 +00007164 return false;
Richard Smith0e3102d2018-07-24 00:55:08 +00007165 }
Richard Smithafe48f92018-07-23 21:21:22 +00007166
Gabor Horvathc6802b22019-08-12 16:19:39 +00007167 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007168 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
7169 return false;
7170 }
7171
Richard Smithd87aab92018-07-17 22:24:09 +00007172 // Lifetime-extend the temporary.
7173 if (Path.empty()) {
7174 // Update the storage duration of the materialized temporary.
7175 // FIXME: Rebuild the expression instead of mutating it.
7176 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
7177 ExtendingEntity->allocateManglingNumber());
7178 // Also visit the temporaries lifetime-extended by this initializer.
7179 return true;
7180 }
7181
7182 if (shouldLifetimeExtendThroughPath(Path)) {
7183 // We're supposed to lifetime-extend the temporary along this path (per
7184 // the resolution of DR1815), but we don't support that yet.
7185 //
Richard Smith0e3102d2018-07-24 00:55:08 +00007186 // FIXME: Properly handle this situation. Perhaps the easiest approach
Richard Smithd87aab92018-07-17 22:24:09 +00007187 // would be to clone the initializer expression on each use that would
7188 // lifetime extend its temporaries.
Richard Smith0e3102d2018-07-24 00:55:08 +00007189 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
7190 << RK << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00007191 } else {
Richard Smith0e3102d2018-07-24 00:55:08 +00007192 // If the path goes through the initialization of a variable or field,
7193 // it can't possibly reach a temporary created in this full-expression.
7194 // We will have already diagnosed any problems with the initializer.
7195 if (pathContainsInit(Path))
7196 return false;
7197
7198 Diag(DiagLoc, diag::warn_dangling_variable)
Richard Smithad5bbcc2018-08-01 01:03:33 +00007199 << RK << !Entity.getParent()
7200 << ExtendingEntity->getDecl()->isImplicit()
7201 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00007202 }
7203 break;
Richard Smithafe48f92018-07-23 21:21:22 +00007204 }
Richard Smithd87aab92018-07-17 22:24:09 +00007205
Richard Smithafe48f92018-07-23 21:21:22 +00007206 case LK_MemInitializer: {
George Burgess IV06df2292018-07-24 02:10:53 +00007207 if (isa<MaterializeTemporaryExpr>(L)) {
Richard Smithafe48f92018-07-23 21:21:22 +00007208 // Under C++ DR1696, if a mem-initializer (or a default member
7209 // initializer used by the absence of one) would lifetime-extend a
7210 // temporary, the program is ill-formed.
7211 if (auto *ExtendingDecl =
7212 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007213 if (IsGslPtrInitWithGslTempOwner) {
7214 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
7215 << ExtendingDecl << DiagRange;
7216 Diag(ExtendingDecl->getLocation(),
7217 diag::note_ref_or_ptr_member_declared_here)
7218 << true;
7219 return false;
7220 }
Richard Smithafe48f92018-07-23 21:21:22 +00007221 bool IsSubobjectMember = ExtendingEntity != &Entity;
Richard Smith0e3102d2018-07-24 00:55:08 +00007222 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
7223 ? diag::err_dangling_member
7224 : diag::warn_dangling_member)
Richard Smithafe48f92018-07-23 21:21:22 +00007225 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
7226 // Don't bother adding a note pointing to the field if we're inside
7227 // its default member initializer; our primary diagnostic points to
7228 // the same place in that case.
7229 if (Path.empty() ||
7230 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
7231 Diag(ExtendingDecl->getLocation(),
7232 diag::note_lifetime_extending_member_declared_here)
7233 << RK << IsSubobjectMember;
7234 }
7235 } else {
7236 // We have a mem-initializer but no particular field within it; this
7237 // is either a base class or a delegating initializer directly
7238 // initializing the base-class from something that doesn't live long
7239 // enough.
7240 //
7241 // FIXME: Warn on this.
7242 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00007243 }
7244 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00007245 // Paths via a default initializer can only occur during error recovery
7246 // (there's no other way that a default initializer can refer to a
7247 // local). Don't produce a bogus warning on those cases.
Richard Smith0e3102d2018-07-24 00:55:08 +00007248 if (pathContainsInit(Path))
Richard Smithafe48f92018-07-23 21:21:22 +00007249 return false;
7250
Gabor Horvath3560ed02019-08-11 08:05:28 +00007251 // Suppress false positives for code like the one below:
Gabor Horvatheb563af2019-08-10 00:32:29 +00007252 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
7253 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
7254 return false;
7255
Richard Smithafe48f92018-07-23 21:21:22 +00007256 auto *DRE = dyn_cast<DeclRefExpr>(L);
7257 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7258 if (!VD) {
7259 // A member was initialized to a local block.
7260 // FIXME: Warn on this.
7261 return false;
7262 }
7263
7264 if (auto *Member =
7265 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007266 bool IsPointer = !Member->getType()->isReferenceType();
Richard Smithafe48f92018-07-23 21:21:22 +00007267 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
7268 : diag::warn_bind_ref_member_to_parameter)
7269 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
7270 Diag(Member->getLocation(),
7271 diag::note_ref_or_ptr_member_declared_here)
7272 << (unsigned)IsPointer;
7273 }
Richard Smithd87aab92018-07-17 22:24:09 +00007274 }
7275 break;
Richard Smithafe48f92018-07-23 21:21:22 +00007276 }
Richard Smithd87aab92018-07-17 22:24:09 +00007277
7278 case LK_New:
George Burgess IV06df2292018-07-24 02:10:53 +00007279 if (isa<MaterializeTemporaryExpr>(L)) {
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007280 if (IsGslPtrInitWithGslTempOwner)
7281 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
7282 else
7283 Diag(DiagLoc, RK == RK_ReferenceBinding
7284 ? diag::warn_new_dangling_reference
7285 : diag::warn_new_dangling_initializer_list)
7286 << !Entity.getParent() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00007287 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00007288 // We can't determine if the allocation outlives the local declaration.
7289 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00007290 }
7291 break;
7292
7293 case LK_Return:
Richard Smith67af95b2018-07-23 19:19:08 +00007294 case LK_StmtExprResult:
Richard Smithafe48f92018-07-23 21:21:22 +00007295 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7296 // We can't determine if the local variable outlives the statement
7297 // expression.
7298 if (LK == LK_StmtExprResult)
7299 return false;
7300 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
7301 << Entity.getType()->isReferenceType() << DRE->getDecl()
7302 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
7303 } else if (isa<BlockExpr>(L)) {
7304 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
7305 } else if (isa<AddrLabelExpr>(L)) {
Reid Kleckner4c33d192018-08-17 22:11:31 +00007306 // Don't warn when returning a label from a statement expression.
7307 // Leaving the scope doesn't end its lifetime.
7308 if (LK == LK_StmtExprResult)
7309 return false;
Richard Smithafe48f92018-07-23 21:21:22 +00007310 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
7311 } else {
7312 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
7313 << Entity.getType()->isReferenceType() << DiagRange;
7314 }
7315 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00007316 }
7317
Richard Smithafe48f92018-07-23 21:21:22 +00007318 for (unsigned I = 0; I != Path.size(); ++I) {
7319 auto Elem = Path[I];
7320
Richard Smithca975b22018-07-23 18:50:26 +00007321 switch (Elem.Kind) {
Richard Smithafe48f92018-07-23 21:21:22 +00007322 case IndirectLocalPathEntry::AddressOf:
7323 case IndirectLocalPathEntry::LValToRVal:
Richard Smith6a32c052018-07-23 21:21:24 +00007324 // These exist primarily to mark the path as not permitting or
7325 // supporting lifetime extension.
Richard Smithca975b22018-07-23 18:50:26 +00007326 break;
7327
Richard Smithf4e248c2018-08-01 00:33:25 +00007328 case IndirectLocalPathEntry::LifetimeBoundCall:
Gabor Horvathe5e10b52019-08-06 19:13:29 +00007329 case IndirectLocalPathEntry::GslPointerInit:
7330 // FIXME: Consider adding a note for these.
Richard Smithf4e248c2018-08-01 00:33:25 +00007331 break;
7332
Richard Smithafe48f92018-07-23 21:21:22 +00007333 case IndirectLocalPathEntry::DefaultInit: {
7334 auto *FD = cast<FieldDecl>(Elem.D);
7335 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
Richard Smith6a32c052018-07-23 21:21:24 +00007336 << FD << nextPathEntryRange(Path, I + 1, L);
Richard Smithafe48f92018-07-23 21:21:22 +00007337 break;
7338 }
7339
7340 case IndirectLocalPathEntry::VarInit:
7341 const VarDecl *VD = cast<VarDecl>(Elem.D);
7342 Diag(VD->getLocation(), diag::note_local_var_initializer)
Richard Smithad5bbcc2018-08-01 01:03:33 +00007343 << VD->getType()->isReferenceType()
7344 << VD->isImplicit() << VD->getDeclName()
Richard Smith6a32c052018-07-23 21:21:24 +00007345 << nextPathEntryRange(Path, I + 1, L);
Richard Smithca975b22018-07-23 18:50:26 +00007346 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00007347 }
7348 }
Richard Smithd87aab92018-07-17 22:24:09 +00007349
7350 // We didn't lifetime-extend, so don't go any further; we don't need more
7351 // warnings or errors on inner temporaries within this one's initializer.
7352 return false;
7353 };
7354
Richard Smithca975b22018-07-23 18:50:26 +00007355 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
Richard Smithd87aab92018-07-17 22:24:09 +00007356 if (Init->isGLValue())
Richard Smithca975b22018-07-23 18:50:26 +00007357 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
7358 TemporaryVisitor);
Richard Smithd87aab92018-07-17 22:24:09 +00007359 else
Richard Smithca975b22018-07-23 18:50:26 +00007360 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007361}
7362
Richard Smithaaa0ec42013-09-21 21:19:19 +00007363static void DiagnoseNarrowingInInitList(Sema &S,
7364 const ImplicitConversionSequence &ICS,
7365 QualType PreNarrowingType,
7366 QualType EntityType,
7367 const Expr *PostInit);
7368
Richard Trieuac3eca52015-04-29 01:52:17 +00007369/// Provide warnings when std::move is used on construction.
7370static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7371 bool IsReturnStmt) {
7372 if (!InitExpr)
7373 return;
7374
Richard Smith51ec0cf2017-02-21 01:17:38 +00007375 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00007376 return;
7377
Richard Trieuac3eca52015-04-29 01:52:17 +00007378 QualType DestType = InitExpr->getType();
7379 if (!DestType->isRecordType())
7380 return;
7381
Richard Trieu155b8d02019-08-08 00:12:51 +00007382 const CXXConstructExpr *CCE =
7383 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7384 if (!CCE || CCE->getNumArgs() != 1)
7385 return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007386
Richard Trieu155b8d02019-08-08 00:12:51 +00007387 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7388 return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007389
Richard Trieu155b8d02019-08-08 00:12:51 +00007390 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00007391
7392 // Find the std::move call and get the argument.
7393 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
Nico Weber192184c2018-06-20 15:57:38 +00007394 if (!CE || !CE->isCallToStdMove())
Richard Trieuac3eca52015-04-29 01:52:17 +00007395 return;
7396
Richard Trieu155b8d02019-08-08 00:12:51 +00007397 const Expr *Arg = CE->getArg(0);
Richard Trieuac3eca52015-04-29 01:52:17 +00007398
Richard Trieu155b8d02019-08-08 00:12:51 +00007399 unsigned DiagID = 0;
7400
7401 if (!IsReturnStmt && !isa<MaterializeTemporaryExpr>(Arg))
7402 return;
7403
7404 if (isa<MaterializeTemporaryExpr>(Arg)) {
7405 DiagID = diag::warn_pessimizing_move_on_initialization;
7406 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7407 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
7408 return;
7409 } else { // IsReturnStmt
Richard Trieuac3eca52015-04-29 01:52:17 +00007410 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7411 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7412 return;
7413
7414 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7415 if (!VD || !VD->hasLocalStorage())
7416 return;
7417
Alex Lorenzbbe51d82017-11-07 21:40:11 +00007418 // __block variables are not moved implicitly.
7419 if (VD->hasAttr<BlocksAttr>())
7420 return;
7421
Richard Trieu8d4006a2015-07-28 19:06:16 +00007422 QualType SourceType = VD->getType();
7423 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00007424 return;
7425
Richard Trieu8d4006a2015-07-28 19:06:16 +00007426 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00007427 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00007428 }
7429
Davide Italiano7842c3f2015-07-18 01:15:19 +00007430 // If we're returning a function parameter, copy elision
7431 // is not possible.
7432 if (isa<ParmVarDecl>(VD))
7433 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00007434 else
7435 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007436 }
7437
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007438 S.Diag(CE->getBeginLoc(), DiagID);
Richard Trieuac3eca52015-04-29 01:52:17 +00007439
7440 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7441 // is within a macro.
Richard Trieu155b8d02019-08-08 00:12:51 +00007442 SourceLocation BeginLoc = CCE->getBeginLoc();
7443 if (BeginLoc.isMacroID())
Richard Trieuac3eca52015-04-29 01:52:17 +00007444 return;
7445 SourceLocation RParen = CE->getRParenLoc();
7446 if (RParen.isMacroID())
7447 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007448 SourceLocation ArgLoc = Arg->getBeginLoc();
Richard Trieuac3eca52015-04-29 01:52:17 +00007449
7450 // Special testing for the argument location. Since the fix-it needs the
7451 // location right before the argument, the argument location can be in a
7452 // macro only if it is at the beginning of the macro.
7453 while (ArgLoc.isMacroID() &&
7454 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
Richard Smithb5f81712018-04-30 05:25:48 +00007455 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
Richard Trieuac3eca52015-04-29 01:52:17 +00007456 }
7457
Richard Trieu155b8d02019-08-08 00:12:51 +00007458 SourceLocation LParen = ArgLoc.getLocWithOffset(-1);
Richard Trieuac3eca52015-04-29 01:52:17 +00007459 if (LParen.isMacroID())
7460 return;
Richard Trieu155b8d02019-08-08 00:12:51 +00007461 SourceLocation EndLoc = CCE->getEndLoc();
7462 if (EndLoc.isMacroID())
7463 return;
Richard Trieuac3eca52015-04-29 01:52:17 +00007464
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007465 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
Richard Trieu155b8d02019-08-08 00:12:51 +00007466 << FixItHint::CreateRemoval(SourceRange(BeginLoc, LParen))
7467 << FixItHint::CreateRemoval(SourceRange(RParen, EndLoc));
Richard Trieuac3eca52015-04-29 01:52:17 +00007468}
7469
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007470static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7471 // Check to see if we are dereferencing a null pointer. If so, this is
7472 // undefined behavior, so warn about it. This only handles the pattern
7473 // "*null", which is a very syntactic check.
7474 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7475 if (UO->getOpcode() == UO_Deref &&
7476 UO->getSubExpr()->IgnoreParenCasts()->
7477 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7478 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7479 S.PDiag(diag::warn_binding_null_to_reference)
7480 << UO->getSubExpr()->getSourceRange());
7481 }
7482}
7483
Tim Shen4a05bb82016-06-21 20:29:17 +00007484MaterializeTemporaryExpr *
7485Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7486 bool BoundToLvalueReference) {
7487 auto MTE = new (Context)
7488 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7489
7490 // Order an ExprWithCleanups for lifetime marks.
7491 //
7492 // TODO: It'll be good to have a single place to check the access of the
7493 // destructor and generate ExprWithCleanups for various uses. Currently these
7494 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7495 // but there may be a chance to merge them.
7496 Cleanup.setExprNeedsCleanups(false);
7497 return MTE;
7498}
7499
Richard Smith4baaa5a2016-12-03 01:14:32 +00007500ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7501 // In C++98, we don't want to implicitly create an xvalue.
7502 // FIXME: This means that AST consumers need to deal with "prvalues" that
7503 // denote materialized temporaries. Maybe we should add another ValueKind
7504 // for "xvalue pretending to be a prvalue" for C++98 support.
7505 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
7506 return E;
7507
7508 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00007509 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7510 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00007511 QualType T = E->getType();
7512 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7513 return ExprError();
7514
7515 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7516}
7517
Anastasia Stulova04307942018-11-16 16:22:56 +00007518ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7519 ExprValueKind VK,
7520 CheckedConversionKind CCK) {
Anastasia Stulova094c7262019-04-04 10:48:36 +00007521
7522 CastKind CK = CK_NoOp;
7523
7524 if (VK == VK_RValue) {
7525 auto PointeeTy = Ty->getPointeeType();
7526 auto ExprPointeeTy = E->getType()->getPointeeType();
7527 if (!PointeeTy.isNull() &&
7528 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7529 CK = CK_AddressSpaceConversion;
7530 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7531 CK = CK_AddressSpaceConversion;
7532 }
7533
Anastasia Stulova04307942018-11-16 16:22:56 +00007534 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7535}
7536
7537ExprResult InitializationSequence::Perform(Sema &S,
7538 const InitializedEntity &Entity,
7539 const InitializationKind &Kind,
7540 MultiExprArg Args,
7541 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007542 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007543 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00007544 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007545 }
Nico Weber337d5aa2015-04-17 08:32:38 +00007546 if (!ZeroInitializationFixit.empty()) {
7547 unsigned DiagID = diag::err_default_init_const;
7548 if (Decl *D = Entity.getDecl())
7549 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
7550 DiagID = diag::ext_default_init_const;
7551
7552 // The initialization would have succeeded with this fixit. Since the fixit
7553 // is on the error, we need to build a valid AST in this case, so this isn't
7554 // handled in the Failed() branch above.
7555 QualType DestType = Entity.getType();
7556 S.Diag(Kind.getLocation(), DiagID)
7557 << DestType << (bool)DestType->getAs<RecordType>()
7558 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7559 ZeroInitializationFixit);
7560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007561
Sebastian Redld201edf2011-06-05 13:59:11 +00007562 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007563 // If the declaration is a non-dependent, incomplete array type
7564 // that has an initializer, then its type will be completed once
7565 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00007566 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00007567 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007568 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007569 if (const IncompleteArrayType *ArrayT
7570 = S.Context.getAsIncompleteArrayType(DeclType)) {
7571 // FIXME: We don't currently have the ability to accurately
7572 // compute the length of an initializer list without
7573 // performing full type-checking of the initializer list
7574 // (since we have to determine where braces are implicitly
7575 // introduced and such). So, we fall back to making the array
7576 // type a dependently-sized array type with no specified
7577 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007578 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007579 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00007580
Douglas Gregor51e77d52009-12-10 17:56:55 +00007581 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00007582 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007583 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7584 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007585 if (IncompleteArrayTypeLoc ArrayLoc =
7586 TL.getAs<IncompleteArrayTypeLoc>())
7587 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00007588 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007589 }
7590
7591 *ResultType
7592 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007593 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00007594 ArrayT->getSizeModifier(),
7595 ArrayT->getIndexTypeCVRQualifiers(),
7596 Brackets);
7597 }
7598
7599 }
7600 }
Sebastian Redla9351792012-02-11 23:51:47 +00007601 if (Kind.getKind() == InitializationKind::IK_Direct &&
7602 !Kind.isExplicitCast()) {
7603 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00007604 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00007605 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007606 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00007607 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00007608 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Fangrui Song6907ce22018-07-30 19:24:48 +00007609 Kind.isExplicitCast() ||
Douglas Gregorbf138952012-04-04 04:06:51 +00007610 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007611 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007612 }
7613
Sebastian Redld201edf2011-06-05 13:59:11 +00007614 // No steps means no initialization.
7615 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007616 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007617
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007618 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007619 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007620 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00007621 // Produce a C++98 compatibility warning if we are initializing a reference
7622 // from an initializer list. For parameters, we produce a better warning
7623 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007624 Expr *Init = Args[0];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007625 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7626 << Init->getSourceRange();
Richard Smith2b349ae2012-04-19 06:58:00 +00007627 }
7628
Egor Churaev3bccec52017-04-05 12:47:10 +00007629 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7630 QualType ETy = Entity.getType();
7631 Qualifiers TyQualifiers = ETy.getQualifiers();
7632 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
7633 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
7634
7635 if (S.getLangOpts().OpenCLVersion >= 200 &&
7636 ETy->isAtomicType() && !HasGlobalAS &&
7637 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007638 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7639 << 1
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007640 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
Egor Churaev3bccec52017-04-05 12:47:10 +00007641 return ExprError();
7642 }
7643
Douglas Gregor1b303932009-12-22 15:35:07 +00007644 QualType DestType = Entity.getType().getNonReferenceType();
7645 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00007646 // the same as Entity.getDecl()->getType() in cases involving type merging,
7647 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00007648 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00007649 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00007650 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007651
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007652 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00007653 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007654
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007655 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00007656 // grab the only argument out the Args and place it into the "current"
7657 // initializer.
7658 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007659 case SK_ResolveAddressOfOverloadedFunction:
7660 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007661 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007662 case SK_CastDerivedToBaseLValue:
7663 case SK_BindReference:
7664 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00007665 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007666 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00007667 case SK_UserConversion:
7668 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007669 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007670 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00007671 case SK_AtomicConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00007672 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00007673 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00007674 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00007675 case SK_UnwrapInitList:
7676 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00007677 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00007678 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007679 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00007680 case SK_ArrayLoopIndex:
7681 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00007682 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00007683 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00007684 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00007685 case SK_PassByIndirectCopyRestore:
7686 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00007687 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007688 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00007689 case SK_OCLSamplerInit:
Andrew Savonichevb555b762018-10-23 15:19:20 +00007690 case SK_OCLZeroOpaqueType: {
Douglas Gregore1314a62009-12-18 05:02:21 +00007691 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007692 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00007693 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00007694 break;
John McCall34376a62010-12-04 03:47:34 +00007695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007696
Douglas Gregore1314a62009-12-18 05:02:21 +00007697 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00007698 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007699 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00007700 case SK_ZeroInitialization:
7701 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007703
Richard Smithd6a15082017-01-07 00:48:55 +00007704 // Promote from an unevaluated context to an unevaluated list context in
7705 // C++11 list-initialization; we need to instantiate entities usable in
7706 // constant expressions here in order to perform narrowing checks =(
7707 EnterExpressionEvaluationContext Evaluated(
7708 S, EnterExpressionEvaluationContext::InitList,
7709 CurInit.get() && isa<InitListExpr>(CurInit.get()));
7710
Richard Smith81f5ade2016-12-15 02:28:18 +00007711 // C++ [class.abstract]p2:
7712 // no objects of an abstract class can be created except as subobjects
7713 // of a class derived from it
7714 auto checkAbstractType = [&](QualType T) -> bool {
7715 if (Entity.getKind() == InitializedEntity::EK_Base ||
7716 Entity.getKind() == InitializedEntity::EK_Delegating)
7717 return false;
7718 return S.RequireNonAbstractType(Kind.getLocation(), T,
7719 diag::err_allocation_of_abstract_type);
7720 };
7721
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007722 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007723 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007724 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007725 for (step_iterator Step = step_begin(), StepEnd = step_end();
7726 Step != StepEnd; ++Step) {
7727 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007728 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007729
John Wiegley01296292011-04-08 18:41:53 +00007730 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007731
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007732 switch (Step->Kind) {
7733 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007734 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007735 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00007736 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00007737 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7738 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007739 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00007740 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00007741 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007742 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007743
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007744 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007745 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007746 case SK_CastDerivedToBaseLValue: {
7747 // We have a derived-to-base cast that produces either an rvalue or an
7748 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007749
John McCallcf142162010-08-07 06:22:56 +00007750 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00007751
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007752 // Casts to inaccessible base classes are allowed with C-style casts.
7753 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007754 if (S.CheckDerivedToBaseConversion(
7755 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
7756 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00007757 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007758
John McCall2536c6d2010-08-25 10:28:54 +00007759 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007760 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007761 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007762 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007763 VK_XValue :
7764 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007765 CurInit =
7766 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
7767 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007768 break;
7769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007770
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007771 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007772 // Reference binding does not have any corresponding ASTs.
7773
7774 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007775 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007776 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007777
George Burgess IVcfd48d92017-04-13 23:47:08 +00007778 // We don't check for e.g. function pointers here, since address
7779 // availability checks should only occur when the function first decays
7780 // into a pointer or reference.
7781 if (CurInit.get()->getType()->isFunctionProtoType()) {
7782 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7783 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7784 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007785 DRE->getBeginLoc()))
George Burgess IVcfd48d92017-04-13 23:47:08 +00007786 return ExprError();
7787 }
7788 }
7789 }
7790
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007791 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007792 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007793
Richard Smithe6c01442013-06-05 00:46:14 +00007794 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00007795 // Make sure the "temporary" is actually an rvalue.
7796 assert(CurInit.get()->isRValue() && "not a temporary");
7797
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007798 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007799 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007800 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007801
Douglas Gregorfe314812011-06-21 17:03:29 +00007802 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007803 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00007804 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
Richard Smithd87aab92018-07-17 22:24:09 +00007805 CurInit = MTE;
David Majnemerdaff3702014-05-01 17:50:17 +00007806
Brian Kelley762f9282017-03-29 18:16:38 +00007807 // If we're extending this temporary to automatic storage duration -- we
7808 // need to register its cleanup during the full-expression's cleanups.
7809 if (MTE->getStorageDuration() == SD_Automatic &&
7810 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00007811 S.Cleanup.setExprNeedsCleanups(true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007812 break;
Richard Smithe6c01442013-06-05 00:46:14 +00007813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007814
Richard Smithb8c0f552016-12-09 18:49:13 +00007815 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00007816 if (checkAbstractType(Step->Type))
7817 return ExprError();
7818
Richard Smithb8c0f552016-12-09 18:49:13 +00007819 // If the overall initialization is initializing a temporary, we already
7820 // bound our argument if it was necessary to do so. If not (if we're
7821 // ultimately initializing a non-temporary), our argument needs to be
7822 // bound since it's initializing a function parameter.
7823 // FIXME: This is a mess. Rationalize temporary destruction.
7824 if (!shouldBindAsTemporary(Entity))
7825 CurInit = S.MaybeBindToTemporary(CurInit.get());
7826 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7827 /*IsExtraneousCopy=*/false);
7828 break;
7829
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007830 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007831 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007832 /*IsExtraneousCopy=*/true);
7833 break;
7834
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007835 case SK_UserConversion: {
7836 // We have a user-defined conversion that invokes either a constructor
7837 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00007838 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00007839 FunctionDecl *Fn = Step->Function.Function;
7840 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007841 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00007842 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00007843 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007844 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00007845 SmallVector<Expr*, 8> ConstructorArgs;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007846 SourceLocation Loc = CurInit.get()->getBeginLoc();
John McCall760af172010-02-01 03:16:54 +00007847
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007848 // Determine the arguments required to actually perform the constructor
7849 // call.
John Wiegley01296292011-04-08 18:41:53 +00007850 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007851 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00007852 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007853 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00007854 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007855
Richard Smithb24f0672012-02-11 19:22:50 +00007856 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00007857 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
7858 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007859 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007860 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00007861 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007862 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00007863 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00007864 CXXConstructExpr::CK_Complete,
7865 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007866 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007867 return ExprError();
John McCall760af172010-02-01 03:16:54 +00007868
Richard Smith5179eb72016-06-28 19:03:57 +00007869 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7870 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00007871 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7872 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007873
John McCalle3027922010-08-25 11:45:40 +00007874 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00007875 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007876 } else {
7877 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00007878 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00007879 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00007880 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00007881 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7882 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007883
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007884 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7885 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00007886 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007887 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007888
John McCalle3027922010-08-25 11:45:40 +00007889 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00007890 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007892
Richard Smith81f5ade2016-12-15 02:28:18 +00007893 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7894 return ExprError();
7895
Richard Smithb8c0f552016-12-09 18:49:13 +00007896 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
7897 CastKind, CurInit.get(), nullptr,
7898 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00007899
Richard Smithb8c0f552016-12-09 18:49:13 +00007900 if (shouldBindAsTemporary(Entity))
7901 // The overall entity is temporary, so this expression should be
7902 // destroyed at the end of its full-expression.
7903 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7904 else if (CreatedObject && shouldDestroyEntity(Entity)) {
7905 // The object outlasts the full-expression, but we need to prepare for
7906 // a destructor being run on it.
7907 // FIXME: It makes no sense to do this here. This should happen
7908 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00007909 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00007910 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007911 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00007912 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007913 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00007914 S.PDiag(diag::err_access_dtor_temp) << T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007915 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
7916 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
Richard Smith22262ab2013-05-04 06:44:46 +00007917 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00007918 }
7919 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007920 break;
7921 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007922
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007923 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007924 case SK_QualificationConversionXValue:
7925 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007926 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00007927 ExprValueKind VK =
Anastasia Stulova04307942018-11-16 16:22:56 +00007928 Step->Kind == SK_QualificationConversionLValue
7929 ? VK_LValue
7930 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
7931 : VK_RValue);
7932 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007933 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007934 }
7935
Richard Smith77be48a2014-07-31 06:31:19 +00007936 case SK_AtomicConversion: {
7937 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7938 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7939 CK_NonAtomicToAtomic, VK_RValue);
7940 break;
7941 }
7942
Richard Smithaaa0ec42013-09-21 21:19:19 +00007943 case SK_ConversionSequence:
7944 case SK_ConversionSequenceNoNarrowing: {
Leonard Chanad7ac962018-12-06 01:05:54 +00007945 if (const auto *FromPtrType =
7946 CurInit.get()->getType()->getAs<PointerType>()) {
7947 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
7948 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
7949 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
7950 S.Diag(CurInit.get()->getExprLoc(),
7951 diag::warn_noderef_to_dereferenceable_pointer)
7952 << CurInit.get()->getSourceRange();
7953 }
7954 }
7955 }
7956
Richard Smithaaa0ec42013-09-21 21:19:19 +00007957 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007958 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7959 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007960 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007961 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007962 ExprResult CurInitExprRes =
7963 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007964 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007965 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007966 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007967
7968 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7969
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007970 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007971
7972 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007973 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007974 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7975 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007976
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007977 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007979
Douglas Gregor51e77d52009-12-10 17:56:55 +00007980 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007981 if (checkAbstractType(Step->Type))
7982 return ExprError();
7983
John Wiegley01296292011-04-08 18:41:53 +00007984 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007985 // If we're not initializing the top-level entity, we need to create an
7986 // InitializeTemporary entity for our target type.
7987 QualType Ty = Step->Type;
7988 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007989 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007990 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7991 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007992 InitList, Ty, /*VerifyOnly=*/false,
7993 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007994 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007995 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007996
Richard Smithcc1b96d2013-06-12 22:31:48 +00007997 // Hack: We must update *ResultType if available in order to set the
7998 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7999 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8000 if (ResultType &&
8001 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00008002 if ((*ResultType)->isRValueReferenceType())
8003 Ty = S.Context.getRValueReferenceType(Ty);
8004 else if ((*ResultType)->isLValueReferenceType())
8005 Ty = S.Context.getLValueReferenceType(Ty,
8006 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
8007 *ResultType = Ty;
8008 }
8009
8010 InitListExpr *StructuredInitList =
8011 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008012 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00008013 CurInit = shouldBindAsTemporary(InitEntity)
8014 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008015 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00008016 break;
8017 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008018
Richard Smith53324112014-07-16 21:33:43 +00008019 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00008020 if (checkAbstractType(Step->Type))
8021 return ExprError();
8022
Sebastian Redl5a41f682012-02-12 16:37:24 +00008023 // When an initializer list is passed for a parameter of type "reference
8024 // to object", we don't get an EK_Temporary entity, but instead an
8025 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00008026 // FIXME: This is a hack. What we really should do is create a user
8027 // conversion step for this case, but this makes it considerably more
8028 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00008029 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8030 Entity.getType().getNonReferenceType());
8031 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00008032 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008033 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00008034 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8035 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00008036 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00008037 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8038 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008039 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00008040 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00008041 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00008042 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00008043 InitList->getLBraceLoc(),
8044 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00008045 break;
8046 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008047
Sebastian Redl29526f02011-11-27 16:50:07 +00008048 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008049 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00008050 break;
8051
8052 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008053 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00008054 InitListExpr *Syntactic = Step->WrappingSyntacticList;
8055 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00008056 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00008057 ILE->setSyntacticForm(Syntactic);
8058 ILE->setType(E->getType());
8059 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008060 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00008061 break;
8062 }
8063
Richard Smith53324112014-07-16 21:33:43 +00008064 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00008065 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00008066 if (checkAbstractType(Step->Type))
8067 return ExprError();
8068
Sebastian Redl99f66162012-02-19 12:27:56 +00008069 // When an initializer list is passed for a parameter of type "reference
8070 // to object", we don't get an EK_Temporary entity, but instead an
8071 // EK_Parameter entity with reference type.
8072 // FIXME: This is a hack. What we really should do is create a user
8073 // conversion step for this case, but this makes it considerably more
8074 // complicated. For now, this will do.
8075 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8076 Entity.getType().getNonReferenceType());
8077 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00008078 bool IsStdInitListInit =
8079 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00008080 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00008081 SourceRange Range = Kind.hasParenOrBraceRange()
8082 ? Kind.getParenOrBraceRange()
8083 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00008084 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00008085 S, UseTemporary ? TempEntity : Entity, Kind,
8086 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00008087 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00008088 /*IsListInitialization*/ IsStdInitListInit,
8089 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00008090 /*LBraceLoc*/ Range.getBegin(),
8091 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008092 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00008093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008094
Douglas Gregor7dc42e52009-12-15 00:01:57 +00008095 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008096 step_iterator NextStep = Step;
8097 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008098 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00008099 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00008100 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008101 // The need for zero-initialization is recorded directly into
8102 // the call to the object's constructor within the next step.
8103 ConstructorInitRequiresZeroInit = true;
8104 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008105 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008106 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00008107 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8108 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008109 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00008110 Kind.getRange().getBegin());
8111
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008112 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00008113 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008114 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008115 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008116 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008117 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00008118 break;
8119 }
Douglas Gregore1314a62009-12-18 05:02:21 +00008120
8121 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00008122 QualType SourceType = CurInit.get()->getType();
Leonard Chanad7ac962018-12-06 01:05:54 +00008123
George Burgess IV5f21c712015-10-12 19:57:04 +00008124 // Save off the initial CurInit in case we need to emit a diagnostic
8125 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008126 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00008127 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00008128 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
8129 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00008130 if (Result.isInvalid())
8131 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008132 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00008133
8134 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008135 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00008136 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00008137 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00008138 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00008139 == Sema::Compatible)
8140 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00008141 if (CurInitExprRes.isInvalid())
8142 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008143 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00008144
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008145 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00008146 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8147 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00008148 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00008149 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008150 &Complained)) {
8151 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00008152 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008153 } else if (Complained)
8154 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00008155 break;
8156 }
Eli Friedman78275202009-12-19 08:11:05 +00008157
8158 case SK_StringInit: {
8159 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00008160 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00008161 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00008162 break;
8163 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008164
8165 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008166 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00008167 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00008168 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008169 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008170
Richard Smith410306b2016-12-12 02:53:20 +00008171 case SK_ArrayLoopIndex: {
8172 Expr *Cur = CurInit.get();
8173 Expr *BaseExpr = new (S.Context)
8174 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8175 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8176 Expr *IndexExpr =
8177 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
8178 CurInit = S.CreateBuiltinArraySubscriptExpr(
8179 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8180 ArrayLoopCommonExprs.push_back(BaseExpr);
8181 break;
8182 }
8183
8184 case SK_ArrayLoopInit: {
8185 assert(!ArrayLoopCommonExprs.empty() &&
8186 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8187 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8188 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8189 CurInit.get());
8190 break;
8191 }
8192
Richard Smith378b8c82016-12-14 03:22:16 +00008193 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00008194 // Okay: we checked everything before creating this step. Note that
8195 // this is a GNU extension.
8196 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00008197 << Step->Type << CurInit.get()->getType()
8198 << CurInit.get()->getSourceRange();
Eli Friedman88fccbd2019-02-11 22:54:27 +00008199 updateGNUCompoundLiteralRValue(CurInit.get());
Richard Smith378b8c82016-12-14 03:22:16 +00008200 LLVM_FALLTHROUGH;
8201 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00008202 // If the destination type is an incomplete array type, update the
8203 // type accordingly.
8204 if (ResultType) {
8205 if (const IncompleteArrayType *IncompleteDest
8206 = S.Context.getAsIncompleteArrayType(Step->Type)) {
8207 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00008208 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00008209 *ResultType = S.Context.getConstantArrayType(
8210 IncompleteDest->getElementType(),
8211 ConstantSource->getSize(),
8212 ArrayType::Normal, 0);
8213 }
8214 }
8215 }
John McCall31168b02011-06-15 23:02:42 +00008216 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008217
Richard Smithebeed412012-02-15 22:38:09 +00008218 case SK_ParenthesizedArrayInit:
8219 // Okay: we checked everything before creating this step. Note that
8220 // this is a GNU extension.
8221 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8222 << CurInit.get()->getSourceRange();
8223 break;
8224
John McCall31168b02011-06-15 23:02:42 +00008225 case SK_PassByIndirectCopyRestore:
8226 case SK_PassByIndirectRestore:
8227 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008228 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8229 CurInit.get(), Step->Type,
8230 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00008231 break;
8232
8233 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008234 CurInit =
8235 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
8236 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00008237 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008238
8239 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00008240 S.Diag(CurInit.get()->getExprLoc(),
8241 diag::warn_cxx98_compat_initializer_list_init)
8242 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00008243
Richard Smithcc1b96d2013-06-12 22:31:48 +00008244 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00008245 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8246 CurInit.get()->getType(), CurInit.get(),
8247 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00008248
Florian Hahn0aa117d2018-07-17 09:23:31 +00008249 // Wrap it in a construction of a std::initializer_list<T>.
8250 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smith0a9969b2018-07-17 00:11:41 +00008251
Richard Smithcc1b96d2013-06-12 22:31:48 +00008252 // Bind the result, in case the library has given initializer_list a
8253 // non-trivial destructor.
8254 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008255 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00008256 break;
8257 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00008258
Guy Benyei61054192013-02-07 10:55:47 +00008259 case SK_OCLSamplerInit: {
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008260 // Sampler initialization have 5 cases:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008261 // 1. function argument passing
8262 // 1a. argument is a file-scope variable
8263 // 1b. argument is a function-scope variable
8264 // 1c. argument is one of caller function's parameters
8265 // 2. variable initialization
8266 // 2a. initializing a file-scope variable
8267 // 2b. initializing a function-scope variable
8268 //
8269 // For file-scope variables, since they cannot be initialized by function
8270 // call of __translate_sampler_initializer in LLVM IR, their references
8271 // need to be replaced by a cast from their literal initializers to
8272 // sampler type. Since sampler variables can only be used in function
8273 // calls as arguments, we only need to replace them when handling the
8274 // argument passing.
8275 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00008276 "Sampler initialization on non-sampler type.");
Sven van Haastregt06385d02019-08-12 12:44:26 +00008277 Expr *Init = CurInit.get()->IgnoreParens();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008278 QualType SourceType = Init->getType();
8279 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00008280 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00008281 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00008282 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8283 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008284 break;
8285 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8286 auto Var = cast<VarDecl>(DRE->getDecl());
8287 // Case 1b and 1c
8288 // No cast from integer to sampler is needed.
8289 if (!Var->hasGlobalStorage()) {
8290 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8291 CK_LValueToRValue, Init,
8292 /*BasePath=*/nullptr, VK_RValue);
8293 break;
8294 }
8295 // Case 1a
8296 // For function call with a file-scope sampler variable as argument,
8297 // get the integer literal.
8298 // Do not diagnose if the file-scope variable does not have initializer
8299 // since this has already been diagnosed when parsing the variable
8300 // declaration.
8301 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8302 break;
8303 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8304 Var->getInit()))->getSubExpr();
8305 SourceType = Init->getType();
8306 }
8307 } else {
8308 // Case 2
8309 // Check initializer is 32 bit integer constant.
8310 // If the initializer is taken from global variable, do not diagnose since
8311 // this has already been done when parsing the variable declaration.
8312 if (!Init->isConstantInitializer(S.Context, false))
8313 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00008314
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008315 if (!SourceType->isIntegerType() ||
8316 32 != S.Context.getIntWidth(SourceType)) {
8317 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8318 << SourceType;
8319 break;
8320 }
8321
Fangrui Song407659a2018-11-30 23:41:18 +00008322 Expr::EvalResult EVResult;
8323 Init->EvaluateAsInt(EVResult, S.Context);
8324 llvm::APSInt Result = EVResult.Val.getInt();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008325 const uint64_t SamplerValue = Result.getLimitedValue();
8326 // 32-bit value of sampler's initializer is interpreted as
8327 // bit-field with the following structure:
8328 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8329 // |31 6|5 4|3 1| 0|
8330 // This structure corresponds to enum values of sampler properties
8331 // defined in SPIR spec v1.2 and also opencl-c.h
8332 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8333 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008334 if (FilterMode != 1 && FilterMode != 2 &&
8335 !S.getOpenCLOptions().isEnabled(
8336 "cl_intel_device_side_avc_motion_estimation"))
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008337 S.Diag(Kind.getLocation(),
8338 diag::warn_sampler_initializer_invalid_bits)
8339 << "Filter Mode";
8340 if (AddressingMode > 4)
8341 S.Diag(Kind.getLocation(),
8342 diag::warn_sampler_initializer_invalid_bits)
8343 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00008344 }
8345
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008346 // Cases 1a, 2a and 2b
8347 // Insert cast from integer to sampler.
8348 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
8349 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00008350 break;
8351 }
Andrew Savonichevb555b762018-10-23 15:19:20 +00008352 case SK_OCLZeroOpaqueType: {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008353 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8354 Step->Type->isOCLIntelSubgroupAVCType()) &&
Andrew Savonichevb555b762018-10-23 15:19:20 +00008355 "Wrong type for initialization of OpenCL opaque type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008356
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008357 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Andrew Savonichevb555b762018-10-23 15:19:20 +00008358 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00008359 CurInit.get()->getValueKind());
8360 break;
8361 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008362 }
8363 }
John McCall1f425642010-11-11 03:21:53 +00008364
Richard Smithca975b22018-07-23 18:50:26 +00008365 // Check whether the initializer has a shorter lifetime than the initialized
8366 // entity, and if not, either lifetime-extend or warn as appropriate.
8367 if (auto *Init = CurInit.get())
8368 S.checkInitializerLifetime(Entity, Init);
8369
John McCall1f425642010-11-11 03:21:53 +00008370 // Diagnose non-fatal problems with the completed initialization.
8371 if (Entity.getKind() == InitializedEntity::EK_Member &&
8372 cast<FieldDecl>(Entity.getDecl())->isBitField())
8373 S.CheckBitFieldInitialization(Kind.getLocation(),
8374 cast<FieldDecl>(Entity.getDecl()),
8375 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008376
Richard Trieuac3eca52015-04-29 01:52:17 +00008377 // Check for std::move on construction.
8378 if (const Expr *E = CurInit.get()) {
8379 CheckMoveOnConstruction(S, E,
8380 Entity.getKind() == InitializedEntity::EK_Result);
8381 }
8382
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008383 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008384}
8385
Richard Smith593f9932012-12-08 02:01:17 +00008386/// Somewhere within T there is an uninitialized reference subobject.
8387/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00008388static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8389 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00008390 if (T->isReferenceType()) {
8391 S.Diag(Loc, diag::err_reference_without_init)
8392 << T.getNonReferenceType();
8393 return true;
8394 }
8395
8396 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8397 if (!RD || !RD->hasUninitializedReferenceMember())
8398 return false;
8399
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008400 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00008401 if (FI->isUnnamedBitfield())
8402 continue;
8403
8404 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8405 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8406 return true;
8407 }
8408 }
8409
Aaron Ballman574705e2014-03-13 15:41:46 +00008410 for (const auto &BI : RD->bases()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008411 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00008412 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8413 return true;
8414 }
8415 }
8416
8417 return false;
8418}
8419
8420
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008421//===----------------------------------------------------------------------===//
8422// Diagnose initialization failures
8423//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00008424
8425/// Emit notes associated with an initialization that failed due to a
8426/// "simple" conversion failure.
8427static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8428 Expr *op) {
8429 QualType destType = entity.getType();
8430 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8431 op->getType()->isObjCObjectPointerType()) {
8432
8433 // Emit a possible note about the conversion failing because the
8434 // operand is a message send with a related result type.
8435 S.EmitRelatedResultTypeNote(op);
8436
8437 // Emit a possible note about a return failing because we're
8438 // expecting a related result type.
8439 if (entity.getKind() == InitializedEntity::EK_Result)
8440 S.EmitRelatedResultTypeNoteForReturn(destType);
8441 }
8442}
8443
Richard Smith0449aaf2013-11-21 23:30:57 +00008444static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8445 InitListExpr *InitList) {
8446 QualType DestType = Entity.getType();
8447
8448 QualType E;
8449 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8450 QualType ArrayType = S.Context.getConstantArrayType(
8451 E.withConst(),
8452 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8453 InitList->getNumInits()),
8454 clang::ArrayType::Normal, 0);
8455 InitializedEntity HiddenArray =
8456 InitializedEntity::InitializeTemporary(ArrayType);
8457 return diagnoseListInit(S, HiddenArray, InitList);
8458 }
8459
Richard Smith8d082d12014-09-04 22:13:39 +00008460 if (DestType->isReferenceType()) {
8461 // A list-initialization failure for a reference means that we tried to
8462 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8463 // inner initialization failed.
8464 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
8465 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008466 SourceLocation Loc = InitList->getBeginLoc();
Richard Smith8d082d12014-09-04 22:13:39 +00008467 if (auto *D = Entity.getDecl())
8468 Loc = D->getLocation();
8469 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8470 return;
8471 }
8472
Richard Smith0449aaf2013-11-21 23:30:57 +00008473 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00008474 /*VerifyOnly=*/false,
8475 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00008476 assert(DiagnoseInitList.HadError() &&
8477 "Inconsistent init list check result.");
8478}
8479
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008480bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008481 const InitializedEntity &Entity,
8482 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008483 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00008484 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008485 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008486
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008487 // When we want to diagnose only one element of a braced-init-list,
8488 // we need to factor it out.
8489 Expr *OnlyArg;
8490 if (Args.size() == 1) {
8491 auto *List = dyn_cast<InitListExpr>(Args[0]);
8492 if (List && List->getNumInits() == 1)
8493 OnlyArg = List->getInit(0);
8494 else
8495 OnlyArg = Args[0];
8496 }
8497 else
8498 OnlyArg = nullptr;
8499
Douglas Gregor1b303932009-12-22 15:35:07 +00008500 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008501 switch (Failure) {
8502 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008503 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008504 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00008505 // Dig out the reference subobject which is uninitialized and diagnose it.
8506 // If this is value-initialization, this could be nested some way within
8507 // the target type.
8508 assert(Kind.getKind() == InitializationKind::IK_Value ||
8509 DestType->isReferenceType());
8510 bool Diagnosed =
8511 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8512 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8513 (void)Diagnosed;
8514 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008515 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008516 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008517 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00008518 case FK_ParenthesizedListInitForReference:
8519 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8520 << 1 << Entity.getType() << Args[0]->getSourceRange();
8521 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008522
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008523 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008524 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008525 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008526 case FK_ArrayNeedsInitListOrStringLiteral:
8527 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8528 break;
8529 case FK_ArrayNeedsInitListOrWideStringLiteral:
8530 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8531 break;
8532 case FK_NarrowStringIntoWideCharArray:
8533 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8534 break;
8535 case FK_WideStringIntoCharArray:
8536 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8537 break;
8538 case FK_IncompatWideStringIntoWideChar:
8539 S.Diag(Kind.getLocation(),
8540 diag::err_array_init_incompat_wide_string_into_wchar);
8541 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00008542 case FK_PlainStringIntoUTF8Char:
8543 S.Diag(Kind.getLocation(),
8544 diag::err_array_init_plain_string_into_char8_t);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008545 S.Diag(Args.front()->getBeginLoc(),
Richard Smith3a8244d2018-05-01 05:02:45 +00008546 diag::note_array_init_plain_string_into_char8_t)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008547 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
Richard Smith3a8244d2018-05-01 05:02:45 +00008548 break;
8549 case FK_UTF8StringIntoPlainChar:
8550 S.Diag(Kind.getLocation(),
Richard Smith28ddb912018-11-14 21:04:34 +00008551 diag::err_array_init_utf8_string_into_char)
8552 << S.getLangOpts().CPlusPlus2a;
Richard Smith3a8244d2018-05-01 05:02:45 +00008553 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008554 case FK_ArrayTypeMismatch:
8555 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00008556 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00008557 (Failure == FK_ArrayTypeMismatch
8558 ? diag::err_array_init_different_type
8559 : diag::err_array_init_non_constant_array))
8560 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008561 << OnlyArg->getType()
Douglas Gregore2f943b2011-02-22 18:29:51 +00008562 << Args[0]->getSourceRange();
8563 break;
8564
John McCalla59dc2f2012-01-05 00:13:19 +00008565 case FK_VariableLengthArrayHasInitializer:
8566 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8567 << Args[0]->getSourceRange();
8568 break;
8569
John McCall16df1e52010-03-30 21:47:33 +00008570 case FK_AddressOfOverloadFailed: {
8571 DeclAccessPair Found;
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008572 S.ResolveAddressOfOverloadedFunction(OnlyArg,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008573 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00008574 true,
8575 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008576 break;
John McCall16df1e52010-03-30 21:47:33 +00008577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008578
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008579 case FK_AddressOfUnaddressableFunction: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008580 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008581 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008582 OnlyArg->getBeginLoc());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008583 break;
8584 }
8585
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008586 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00008587 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008588 switch (FailedOverloadResult) {
8589 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00008590
David Blaikie5e328052019-05-03 00:44:50 +00008591 FailedCandidateSet.NoteCandidates(
8592 PartialDiagnosticAt(
8593 Kind.getLocation(),
8594 Failure == FK_UserConversionOverloadFailed
8595 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
8596 << OnlyArg->getType() << DestType
8597 << Args[0]->getSourceRange())
8598 : (S.PDiag(diag::err_ref_init_ambiguous)
8599 << DestType << OnlyArg->getType()
8600 << Args[0]->getSourceRange())),
8601 S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008602 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008603
David Blaikie5e328052019-05-03 00:44:50 +00008604 case OR_No_Viable_Function: {
8605 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
Larisse Voufo70bb43a2013-06-27 03:36:30 +00008606 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008607 DestType.getNonReferenceType(),
8608 diag::err_typecheck_nonviable_condition_incomplete,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008609 OnlyArg->getType(), Args[0]->getSourceRange()))
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008610 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00008611 << (Entity.getKind() == InitializedEntity::EK_Result)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008612 << OnlyArg->getType() << Args[0]->getSourceRange()
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008613 << DestType.getNonReferenceType();
8614
David Blaikie5e328052019-05-03 00:44:50 +00008615 FailedCandidateSet.NoteCandidates(S, Args, Cands);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008616 break;
David Blaikie5e328052019-05-03 00:44:50 +00008617 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008618 case OR_Deleted: {
8619 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008620 << OnlyArg->getType() << DestType.getNonReferenceType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008621 << Args[0]->getSourceRange();
8622 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008623 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00008624 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008625 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00008626 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008627 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008628 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008629 }
8630 break;
8631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008632
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008633 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008634 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008635 }
8636 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008637
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008638 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00008639 if (isa<InitListExpr>(Args[0])) {
8640 S.Diag(Kind.getLocation(),
8641 diag::err_lvalue_reference_bind_to_initlist)
8642 << DestType.getNonReferenceType().isVolatileQualified()
8643 << DestType.getNonReferenceType()
8644 << Args[0]->getSourceRange();
8645 break;
8646 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008647 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00008648
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008649 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008650 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008651 Failure == FK_NonConstLValueReferenceBindingToTemporary
8652 ? diag::err_lvalue_reference_bind_to_temporary
8653 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00008654 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008655 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008656 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008657 << Args[0]->getSourceRange();
8658 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008659
Richard Smithb8c0f552016-12-09 18:49:13 +00008660 case FK_NonConstLValueReferenceBindingToBitfield: {
8661 // We don't necessarily have an unambiguous source bit-field.
8662 FieldDecl *BitField = Args[0]->getSourceBitField();
8663 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
8664 << DestType.isVolatileQualified()
8665 << (BitField ? BitField->getDeclName() : DeclarationName())
8666 << (BitField != nullptr)
8667 << Args[0]->getSourceRange();
8668 if (BitField)
8669 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8670 break;
8671 }
8672
8673 case FK_NonConstLValueReferenceBindingToVectorElement:
8674 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
8675 << DestType.isVolatileQualified()
8676 << Args[0]->getSourceRange();
8677 break;
8678
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008679 case FK_RValueReferenceBindingToLValue:
8680 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008681 << DestType.getNonReferenceType() << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008682 << Args[0]->getSourceRange();
8683 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008684
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00008685 case FK_ReferenceAddrspaceMismatchTemporary:
8686 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
8687 << DestType << Args[0]->getSourceRange();
8688 break;
8689
Richard Trieuf956a492015-05-16 01:27:03 +00008690 case FK_ReferenceInitDropsQualifiers: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008691 QualType SourceType = OnlyArg->getType();
Richard Trieuf956a492015-05-16 01:27:03 +00008692 QualType NonRefType = DestType.getNonReferenceType();
8693 Qualifiers DroppedQualifiers =
8694 SourceType.getQualifiers() - NonRefType.getQualifiers();
8695
Anastasia Stulova3562edb2019-06-21 11:36:15 +00008696 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
8697 SourceType.getQualifiers()))
8698 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8699 << NonRefType << SourceType << 1 /*addr space*/
8700 << Args[0]->getSourceRange();
8701 else
8702 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8703 << NonRefType << SourceType << 0 /*cv quals*/
8704 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
8705 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008706 break;
Richard Trieuf956a492015-05-16 01:27:03 +00008707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008708
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008709 case FK_ReferenceInitFailed:
8710 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
8711 << DestType.getNonReferenceType()
Eric Fiselier1147f712019-02-01 22:06:02 +00008712 << DestType.getNonReferenceType()->isIncompleteType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008713 << OnlyArg->isLValue()
8714 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008715 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00008716 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008717 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008718
Douglas Gregorb491ed32011-02-19 21:32:49 +00008719 case FK_ConversionFailed: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008720 QualType FromType = OnlyArg->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00008721 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00008722 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008723 << DestType
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008724 << OnlyArg->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00008725 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008726 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008727 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
8728 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00008729 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00008730 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008731 }
John Wiegley01296292011-04-08 18:41:53 +00008732
8733 case FK_ConversionFromPropertyFailed:
8734 // No-op. This error has already been reported.
8735 break;
8736
Douglas Gregor51e77d52009-12-10 17:56:55 +00008737 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00008738 SourceRange R;
8739
David Majnemerbd385442015-04-10 04:52:06 +00008740 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008741 if (InitList && InitList->getNumInits() >= 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008742 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008743 } else {
8744 assert(Args.size() > 1 && "Expected multiple initializers!");
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008745 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008746 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00008747
Alp Tokerb6cc5922014-05-03 03:45:55 +00008748 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00008749 if (Kind.isCStyleOrFunctionalCast())
8750 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
8751 << R;
8752 else
8753 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
8754 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00008755 break;
8756 }
8757
Richard Smith49a6b6e2017-03-24 01:14:25 +00008758 case FK_ParenthesizedListInitForScalar:
8759 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8760 << 0 << Entity.getType() << Args[0]->getSourceRange();
8761 break;
8762
Douglas Gregor51e77d52009-12-10 17:56:55 +00008763 case FK_ReferenceBindingToInitList:
8764 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
8765 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8766 break;
8767
8768 case FK_InitListBadDestinationType:
8769 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8770 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8771 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008772
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008773 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008774 case FK_ConstructorOverloadFailed: {
8775 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008776 if (Args.size())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008777 ArgsRange =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008778 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008779
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008780 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00008781 assert(Args.size() == 1 &&
8782 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008783 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008784 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008785 }
8786
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008787 // FIXME: Using "DestType" for the entity we're printing is probably
8788 // bad.
8789 switch (FailedOverloadResult) {
8790 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00008791 FailedCandidateSet.NoteCandidates(
8792 PartialDiagnosticAt(Kind.getLocation(),
8793 S.PDiag(diag::err_ovl_ambiguous_init)
8794 << DestType << ArgsRange),
8795 S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008796 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008797
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008798 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008799 if (Kind.getKind() == InitializationKind::IK_Default &&
8800 (Entity.getKind() == InitializedEntity::EK_Base ||
8801 Entity.getKind() == InitializedEntity::EK_Member) &&
8802 isa<CXXConstructorDecl>(S.CurContext)) {
8803 // This is implicit default initialization of a member or
8804 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00008805 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008806 // initialize this base/member.
8807 CXXConstructorDecl *Constructor
8808 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00008809 const CXXRecordDecl *InheritedFrom = nullptr;
8810 if (auto Inherited = Constructor->getInheritedConstructor())
8811 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008812 if (Entity.getKind() == InitializedEntity::EK_Base) {
8813 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008814 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008815 << S.Context.getTypeDeclType(Constructor->getParent())
8816 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00008817 << Entity.getType()
8818 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008819
8820 RecordDecl *BaseDecl
8821 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
8822 ->getDecl();
8823 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8824 << S.Context.getTagDeclType(BaseDecl);
8825 } else {
8826 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008827 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008828 << S.Context.getTypeDeclType(Constructor->getParent())
8829 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00008830 << Entity.getName()
8831 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00008832 S.Diag(Entity.getDecl()->getLocation(),
8833 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008834
8835 if (const RecordType *Record
8836 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008837 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008838 diag::note_previous_decl)
8839 << S.Context.getTagDeclType(Record->getDecl());
8840 }
8841 break;
8842 }
8843
David Blaikie5e328052019-05-03 00:44:50 +00008844 FailedCandidateSet.NoteCandidates(
8845 PartialDiagnosticAt(
8846 Kind.getLocation(),
8847 S.PDiag(diag::err_ovl_no_viable_function_in_init)
8848 << DestType << ArgsRange),
8849 S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008850 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008851
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008852 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008853 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008854 OverloadingResult Ovl
8855 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00008856 if (Ovl != OR_Deleted) {
8857 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
Erik Pilkington13ee62f2019-03-20 19:26:33 +00008858 << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008859 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00008860 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008861 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008862
Douglas Gregor74f7d502012-02-15 19:33:52 +00008863 // If this is a defaulted or implicitly-declared function, then
8864 // it was implicitly deleted. Make it clear that the deletion was
8865 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00008866 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008867 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00008868 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008869 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00008870 else
8871 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
Erik Pilkington13ee62f2019-03-20 19:26:33 +00008872 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00008873
8874 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008875 break;
8876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008877
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008878 case OR_Success:
8879 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008880 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008881 }
David Blaikie60deeee2012-01-17 08:24:58 +00008882 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008883
Douglas Gregor85dabae2009-12-16 01:38:02 +00008884 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008885 if (Entity.getKind() == InitializedEntity::EK_Member &&
8886 isa<CXXConstructorDecl>(S.CurContext)) {
8887 // This is implicit default-initialization of a const member in
8888 // a constructor. Complain that it needs to be explicitly
8889 // initialized.
8890 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
8891 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00008892 << (Constructor->getInheritedConstructor() ? 2 :
8893 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008894 << S.Context.getTypeDeclType(Constructor->getParent())
8895 << /*const=*/1
8896 << Entity.getName();
8897 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
8898 << Entity.getName();
8899 } else {
8900 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00008901 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008902 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00008903 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008904
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008905 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00008906 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008907 diag::err_init_incomplete_type);
8908 break;
8909
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008910 case FK_ListInitializationFailed: {
8911 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00008912 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8913 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008914 break;
8915 }
John McCall4124c492011-10-17 18:40:02 +00008916
8917 case FK_PlaceholderType: {
8918 // FIXME: Already diagnosed!
8919 break;
8920 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00008921
Sebastian Redl048a6d72012-04-01 19:54:59 +00008922 case FK_ExplicitConstructor: {
8923 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
8924 << Args[0]->getSourceRange();
8925 OverloadCandidateSet::iterator Best;
8926 OverloadingResult Ovl
8927 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00008928 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008929 assert(Ovl == OR_Success && "Inconsistent overload resolution");
8930 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00008931 S.Diag(CtorDecl->getLocation(),
8932 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008933 break;
8934 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008936
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008937 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008938 return true;
8939}
Douglas Gregore1314a62009-12-18 05:02:21 +00008940
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008941void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008942 switch (SequenceKind) {
8943 case FailedSequence: {
8944 OS << "Failed sequence: ";
8945 switch (Failure) {
8946 case FK_TooManyInitsForReference:
8947 OS << "too many initializers for reference";
8948 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008949
Richard Smith49a6b6e2017-03-24 01:14:25 +00008950 case FK_ParenthesizedListInitForReference:
8951 OS << "parenthesized list init for reference";
8952 break;
8953
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008954 case FK_ArrayNeedsInitList:
8955 OS << "array requires initializer list";
8956 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008957
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008958 case FK_AddressOfUnaddressableFunction:
8959 OS << "address of unaddressable function was taken";
8960 break;
8961
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008962 case FK_ArrayNeedsInitListOrStringLiteral:
8963 OS << "array requires initializer list or string literal";
8964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008965
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008966 case FK_ArrayNeedsInitListOrWideStringLiteral:
8967 OS << "array requires initializer list or wide string literal";
8968 break;
8969
8970 case FK_NarrowStringIntoWideCharArray:
8971 OS << "narrow string into wide char array";
8972 break;
8973
8974 case FK_WideStringIntoCharArray:
8975 OS << "wide string into char array";
8976 break;
8977
8978 case FK_IncompatWideStringIntoWideChar:
8979 OS << "incompatible wide string into wide char array";
8980 break;
8981
Richard Smith3a8244d2018-05-01 05:02:45 +00008982 case FK_PlainStringIntoUTF8Char:
8983 OS << "plain string literal into char8_t array";
8984 break;
8985
8986 case FK_UTF8StringIntoPlainChar:
8987 OS << "u8 string literal into char array";
8988 break;
8989
Douglas Gregore2f943b2011-02-22 18:29:51 +00008990 case FK_ArrayTypeMismatch:
8991 OS << "array type mismatch";
8992 break;
8993
8994 case FK_NonConstantArrayInit:
8995 OS << "non-constant array initializer";
8996 break;
8997
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008998 case FK_AddressOfOverloadFailed:
8999 OS << "address of overloaded function failed";
9000 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009001
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009002 case FK_ReferenceInitOverloadFailed:
9003 OS << "overload resolution for reference initialization failed";
9004 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009005
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009006 case FK_NonConstLValueReferenceBindingToTemporary:
9007 OS << "non-const lvalue reference bound to temporary";
9008 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009009
Richard Smithb8c0f552016-12-09 18:49:13 +00009010 case FK_NonConstLValueReferenceBindingToBitfield:
9011 OS << "non-const lvalue reference bound to bit-field";
9012 break;
9013
9014 case FK_NonConstLValueReferenceBindingToVectorElement:
9015 OS << "non-const lvalue reference bound to vector element";
9016 break;
9017
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009018 case FK_NonConstLValueReferenceBindingToUnrelated:
9019 OS << "non-const lvalue reference bound to unrelated type";
9020 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009021
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009022 case FK_RValueReferenceBindingToLValue:
9023 OS << "rvalue reference bound to an lvalue";
9024 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009025
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009026 case FK_ReferenceInitDropsQualifiers:
9027 OS << "reference initialization drops qualifiers";
9028 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009029
Anastasia Stulova5145b1e2019-06-05 14:03:34 +00009030 case FK_ReferenceAddrspaceMismatchTemporary:
9031 OS << "reference with mismatching address space bound to temporary";
9032 break;
9033
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009034 case FK_ReferenceInitFailed:
9035 OS << "reference initialization failed";
9036 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009037
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009038 case FK_ConversionFailed:
9039 OS << "conversion failed";
9040 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009041
John Wiegley01296292011-04-08 18:41:53 +00009042 case FK_ConversionFromPropertyFailed:
9043 OS << "conversion from property failed";
9044 break;
9045
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009046 case FK_TooManyInitsForScalar:
9047 OS << "too many initializers for scalar";
9048 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009049
Richard Smith49a6b6e2017-03-24 01:14:25 +00009050 case FK_ParenthesizedListInitForScalar:
9051 OS << "parenthesized list init for reference";
9052 break;
9053
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009054 case FK_ReferenceBindingToInitList:
9055 OS << "referencing binding to initializer list";
9056 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009057
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009058 case FK_InitListBadDestinationType:
9059 OS << "initializer list for non-aggregate, non-scalar type";
9060 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009061
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009062 case FK_UserConversionOverloadFailed:
9063 OS << "overloading failed for user-defined conversion";
9064 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009065
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009066 case FK_ConstructorOverloadFailed:
9067 OS << "constructor overloading failed";
9068 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009069
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009070 case FK_DefaultInitOfConst:
9071 OS << "default initialization of a const variable";
9072 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009073
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00009074 case FK_Incomplete:
9075 OS << "initialization of incomplete type";
9076 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00009077
9078 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009079 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00009080 break;
9081
John McCalla59dc2f2012-01-05 00:13:19 +00009082 case FK_VariableLengthArrayHasInitializer:
9083 OS << "variable length array has an initializer";
9084 break;
9085
John McCall4124c492011-10-17 18:40:02 +00009086 case FK_PlaceholderType:
9087 OS << "initializer expression isn't contextually valid";
9088 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00009089
9090 case FK_ListConstructorOverloadFailed:
9091 OS << "list constructor overloading failed";
9092 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00009093
Sebastian Redl048a6d72012-04-01 19:54:59 +00009094 case FK_ExplicitConstructor:
9095 OS << "list copy initialization chose explicit constructor";
9096 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009097 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009098 OS << '\n';
9099 return;
9100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009101
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009102 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00009103 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009104 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009105
Sebastian Redld201edf2011-06-05 13:59:11 +00009106 case NormalSequence:
9107 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009108 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009110
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009111 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9112 if (S != step_begin()) {
9113 OS << " -> ";
9114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009115
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009116 switch (S->Kind) {
9117 case SK_ResolveAddressOfOverloadedFunction:
9118 OS << "resolve address of overloaded function";
9119 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009120
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009121 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00009122 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009123 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009124
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009125 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00009126 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009127 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009128
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009129 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00009130 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009131 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009132
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009133 case SK_BindReference:
9134 OS << "bind reference to lvalue";
9135 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009136
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009137 case SK_BindReferenceToTemporary:
9138 OS << "bind reference to a temporary";
9139 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009140
Richard Smithb8c0f552016-12-09 18:49:13 +00009141 case SK_FinalCopy:
9142 OS << "final copy in class direct-initialization";
9143 break;
9144
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00009145 case SK_ExtraneousCopyToTemporary:
9146 OS << "extraneous C++03 copy to temporary";
9147 break;
9148
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009149 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00009150 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009151 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009152
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009153 case SK_QualificationConversionRValue:
9154 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00009155 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009156
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009157 case SK_QualificationConversionXValue:
9158 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00009159 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00009160
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009161 case SK_QualificationConversionLValue:
9162 OS << "qualification conversion (lvalue)";
9163 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009164
Richard Smith77be48a2014-07-31 06:31:19 +00009165 case SK_AtomicConversion:
9166 OS << "non-atomic-to-atomic conversion";
9167 break;
9168
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009169 case SK_ConversionSequence:
9170 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00009171 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009172 OS << ")";
9173 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009174
Richard Smithaaa0ec42013-09-21 21:19:19 +00009175 case SK_ConversionSequenceNoNarrowing:
9176 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00009177 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00009178 OS << ")";
9179 break;
9180
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009181 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00009182 OS << "list aggregate initialization";
9183 break;
9184
Sebastian Redl29526f02011-11-27 16:50:07 +00009185 case SK_UnwrapInitList:
9186 OS << "unwrap reference initializer list";
9187 break;
9188
9189 case SK_RewrapInitList:
9190 OS << "rewrap reference initializer list";
9191 break;
9192
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009193 case SK_ConstructorInitialization:
9194 OS << "constructor initialization";
9195 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009196
Richard Smith53324112014-07-16 21:33:43 +00009197 case SK_ConstructorInitializationFromList:
9198 OS << "list initialization via constructor";
9199 break;
9200
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009201 case SK_ZeroInitialization:
9202 OS << "zero initialization";
9203 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009204
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009205 case SK_CAssignment:
9206 OS << "C assignment";
9207 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009208
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009209 case SK_StringInit:
9210 OS << "string initialization";
9211 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00009212
9213 case SK_ObjCObjectConversion:
9214 OS << "Objective-C object conversion";
9215 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00009216
Richard Smith410306b2016-12-12 02:53:20 +00009217 case SK_ArrayLoopIndex:
9218 OS << "indexing for array initialization loop";
9219 break;
9220
9221 case SK_ArrayLoopInit:
9222 OS << "array initialization loop";
9223 break;
9224
Douglas Gregore2f943b2011-02-22 18:29:51 +00009225 case SK_ArrayInit:
9226 OS << "array initialization";
9227 break;
John McCall31168b02011-06-15 23:02:42 +00009228
Richard Smith378b8c82016-12-14 03:22:16 +00009229 case SK_GNUArrayInit:
9230 OS << "array initialization (GNU extension)";
9231 break;
9232
Richard Smithebeed412012-02-15 22:38:09 +00009233 case SK_ParenthesizedArrayInit:
9234 OS << "parenthesized array initialization";
9235 break;
9236
John McCall31168b02011-06-15 23:02:42 +00009237 case SK_PassByIndirectCopyRestore:
9238 OS << "pass by indirect copy and restore";
9239 break;
9240
9241 case SK_PassByIndirectRestore:
9242 OS << "pass by indirect restore";
9243 break;
9244
9245 case SK_ProduceObjCObject:
9246 OS << "Objective-C object retension";
9247 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00009248
9249 case SK_StdInitializerList:
9250 OS << "std::initializer_list from initializer list";
9251 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009252
Richard Smithf8adcdc2014-07-17 05:12:35 +00009253 case SK_StdInitializerListConstructorCall:
9254 OS << "list initialization from std::initializer_list";
9255 break;
9256
Guy Benyei61054192013-02-07 10:55:47 +00009257 case SK_OCLSamplerInit:
9258 OS << "OpenCL sampler_t from integer constant";
9259 break;
9260
Andrew Savonichevb555b762018-10-23 15:19:20 +00009261 case SK_OCLZeroOpaqueType:
9262 OS << "OpenCL opaque type from zero";
Egor Churaev89831422016-12-23 14:55:49 +00009263 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009264 }
Richard Smith6b216962013-02-05 05:52:24 +00009265
9266 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009267 }
Richard Smith6b216962013-02-05 05:52:24 +00009268
9269 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00009270}
9271
9272void InitializationSequence::dump() const {
9273 dump(llvm::errs());
9274}
9275
Nico Weber3d7f00d2018-06-19 23:19:34 +00009276static bool NarrowingErrs(const LangOptions &L) {
9277 return L.CPlusPlus11 &&
9278 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
9279}
9280
Richard Smithaaa0ec42013-09-21 21:19:19 +00009281static void DiagnoseNarrowingInInitList(Sema &S,
9282 const ImplicitConversionSequence &ICS,
9283 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00009284 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00009285 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009286 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00009287 switch (ICS.getKind()) {
9288 case ImplicitConversionSequence::StandardConversion:
9289 SCS = &ICS.Standard;
9290 break;
9291 case ImplicitConversionSequence::UserDefinedConversion:
9292 SCS = &ICS.UserDefined.After;
9293 break;
9294 case ImplicitConversionSequence::AmbiguousConversion:
9295 case ImplicitConversionSequence::EllipsisConversion:
9296 case ImplicitConversionSequence::BadConversion:
9297 return;
9298 }
9299
Richard Smith66e05fe2012-01-18 05:21:49 +00009300 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9301 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00009302 QualType ConstantType;
9303 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9304 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00009305 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00009306 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00009307 // No narrowing occurred.
9308 return;
9309
9310 case NK_Type_Narrowing:
9311 // This was a floating-to-integer conversion, which is always considered a
9312 // narrowing conversion even if the value is a constant and can be
9313 // represented exactly as an integer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009314 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
Nico Weber3d7f00d2018-06-19 23:19:34 +00009315 ? diag::ext_init_list_type_narrowing
9316 : diag::warn_init_list_type_narrowing)
9317 << PostInit->getSourceRange()
9318 << PreNarrowingType.getLocalUnqualifiedType()
9319 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009320 break;
9321
9322 case NK_Constant_Narrowing:
9323 // A constant value was narrowed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009324 S.Diag(PostInit->getBeginLoc(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00009325 NarrowingErrs(S.getLangOpts())
9326 ? diag::ext_init_list_constant_narrowing
9327 : diag::warn_init_list_constant_narrowing)
9328 << PostInit->getSourceRange()
9329 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9330 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009331 break;
9332
9333 case NK_Variable_Narrowing:
9334 // A variable's value may have been narrowed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009335 S.Diag(PostInit->getBeginLoc(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00009336 NarrowingErrs(S.getLangOpts())
9337 ? diag::ext_init_list_variable_narrowing
9338 : diag::warn_init_list_variable_narrowing)
9339 << PostInit->getSourceRange()
9340 << PreNarrowingType.getLocalUnqualifiedType()
9341 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00009342 break;
9343 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009344
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009345 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009346 llvm::raw_svector_ostream OS(StaticCast);
9347 OS << "static_cast<";
9348 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9349 // It's important to use the typedef's name if there is one so that the
9350 // fixit doesn't break code using types like int64_t.
9351 //
9352 // FIXME: This will break if the typedef requires qualification. But
9353 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00009354 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009355 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00009356 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009357 else {
9358 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9359 // with a broken cast.
9360 return;
9361 }
9362 OS << ">(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009363 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009364 << PostInit->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009365 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
Alp Tokerb6cc5922014-05-03 03:45:55 +00009366 << FixItHint::CreateInsertion(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009367 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009368}
9369
Douglas Gregore1314a62009-12-18 05:02:21 +00009370//===----------------------------------------------------------------------===//
9371// Initialization helper functions
9372//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00009373bool
9374Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
9375 ExprResult Init) {
9376 if (Init.isInvalid())
9377 return false;
9378
9379 Expr *InitE = Init.get();
9380 assert(InitE && "No initialization expression");
9381
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009382 InitializationKind Kind =
9383 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00009384 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00009385 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00009386}
9387
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009388ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00009389Sema::PerformCopyInitialization(const InitializedEntity &Entity,
9390 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009391 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00009392 bool TopLevelOfInitList,
9393 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00009394 if (Init.isInvalid())
9395 return ExprError();
9396
John McCall1f425642010-11-11 03:21:53 +00009397 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00009398 assert(InitE && "No initialization expression?");
9399
9400 if (EqualLoc.isInvalid())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009401 EqualLoc = InitE->getBeginLoc();
Douglas Gregore1314a62009-12-18 05:02:21 +00009402
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009403 InitializationKind Kind = InitializationKind::CreateCopy(
9404 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00009405 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00009406
Alex Lorenzde69ff92017-05-16 10:23:58 +00009407 // Prevent infinite recursion when performing parameter copy-initialization.
9408 const bool ShouldTrackCopy =
9409 Entity.isParameterKind() && Seq.isConstructorInitialization();
9410 if (ShouldTrackCopy) {
9411 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
9412 CurrentParameterCopyTypes.end()) {
9413 Seq.SetOverloadFailure(
9414 InitializationSequence::FK_ConstructorOverloadFailed,
9415 OR_No_Viable_Function);
9416
9417 // Try to give a meaningful diagnostic note for the problematic
9418 // constructor.
9419 const auto LastStep = Seq.step_end() - 1;
9420 assert(LastStep->Kind ==
9421 InitializationSequence::SK_ConstructorInitialization);
9422 const FunctionDecl *Function = LastStep->Function.Function;
9423 auto Candidate =
9424 llvm::find_if(Seq.getFailedCandidateSet(),
9425 [Function](const OverloadCandidate &Candidate) -> bool {
9426 return Candidate.Viable &&
9427 Candidate.Function == Function &&
9428 Candidate.Conversions.size() > 0;
9429 });
9430 if (Candidate != Seq.getFailedCandidateSet().end() &&
9431 Function->getNumParams() > 0) {
9432 Candidate->Viable = false;
9433 Candidate->FailureKind = ovl_fail_bad_conversion;
9434 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9435 InitE,
9436 Function->getParamDecl(0)->getType());
9437 }
9438 }
9439 CurrentParameterCopyTypes.push_back(Entity.getType());
9440 }
9441
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00009442 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00009443
Alex Lorenzde69ff92017-05-16 10:23:58 +00009444 if (ShouldTrackCopy)
9445 CurrentParameterCopyTypes.pop_back();
9446
Richard Smith66e05fe2012-01-18 05:21:49 +00009447 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00009448}
Richard Smith60437622017-02-09 19:17:44 +00009449
Richard Smith1363e8f2017-09-07 07:22:36 +00009450/// Determine whether RD is, or is derived from, a specialization of CTD.
9451static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
9452 ClassTemplateDecl *CTD) {
9453 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9454 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9455 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9456 };
9457 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9458}
9459
Richard Smith60437622017-02-09 19:17:44 +00009460QualType Sema::DeduceTemplateSpecializationFromInitializer(
9461 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9462 const InitializationKind &Kind, MultiExprArg Inits) {
9463 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9464 TSInfo->getType()->getContainedDeducedType());
9465 assert(DeducedTST && "not a deduced template specialization type");
9466
Richard Smith60437622017-02-09 19:17:44 +00009467 auto TemplateName = DeducedTST->getTemplateName();
Richard Smithcff42012018-09-28 03:18:53 +00009468 if (TemplateName.isDependent())
9469 return Context.DependentTy;
9470
9471 // We can only perform deduction for class templates.
Richard Smith60437622017-02-09 19:17:44 +00009472 auto *Template =
9473 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
9474 if (!Template) {
9475 Diag(Kind.getLocation(),
9476 diag::err_deduced_non_class_template_specialization_type)
9477 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
9478 if (auto *TD = TemplateName.getAsTemplateDecl())
9479 Diag(TD->getLocation(), diag::note_template_decl_here);
9480 return QualType();
9481 }
9482
Richard Smith32918772017-02-14 00:25:28 +00009483 // Can't deduce from dependent arguments.
Richard Smith8eeb16f2018-09-10 20:31:03 +00009484 if (Expr::hasAnyTypeDependentArguments(Inits)) {
9485 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9486 diag::warn_cxx14_compat_class_template_argument_deduction)
9487 << TSInfo->getTypeLoc().getSourceRange() << 0;
Richard Smith32918772017-02-14 00:25:28 +00009488 return Context.DependentTy;
Richard Smith8eeb16f2018-09-10 20:31:03 +00009489 }
Richard Smith32918772017-02-14 00:25:28 +00009490
Richard Smith60437622017-02-09 19:17:44 +00009491 // FIXME: Perform "exact type" matching first, per CWG discussion?
9492 // Or implement this via an implied 'T(T) -> T' deduction guide?
9493
9494 // FIXME: Do we need/want a std::initializer_list<T> special case?
9495
Richard Smith32918772017-02-14 00:25:28 +00009496 // Look up deduction guides, including those synthesized from constructors.
9497 //
Richard Smith60437622017-02-09 19:17:44 +00009498 // C++1z [over.match.class.deduct]p1:
9499 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00009500 // - For each constructor of the class template designated by the
9501 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00009502 // - For each deduction-guide, a function or function template [...]
9503 DeclarationNameInfo NameInfo(
9504 Context.DeclarationNames.getCXXDeductionGuideName(Template),
9505 TSInfo->getTypeLoc().getEndLoc());
9506 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
9507 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00009508
9509 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9510 // clear on this, but they're not found by name so access does not apply.
9511 Guides.suppressDiagnostics();
9512
9513 // Figure out if this is list-initialization.
9514 InitListExpr *ListInit =
9515 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
9516 ? dyn_cast<InitListExpr>(Inits[0])
9517 : nullptr;
9518
9519 // C++1z [over.match.class.deduct]p1:
9520 // Initialization and overload resolution are performed as described in
9521 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9522 // (as appropriate for the type of initialization performed) for an object
9523 // of a hypothetical class type, where the selected functions and function
9524 // templates are considered to be the constructors of that class type
9525 //
9526 // Since we know we're initializing a class type of a type unrelated to that
9527 // of the initializer, this reduces to something fairly reasonable.
9528 OverloadCandidateSet Candidates(Kind.getLocation(),
9529 OverloadCandidateSet::CSK_Normal);
9530 OverloadCandidateSet::iterator Best;
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009531
9532 bool HasAnyDeductionGuide = false;
Richard Smith76b90272019-05-09 03:59:21 +00009533 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009534
Richard Smith60437622017-02-09 19:17:44 +00009535 auto tryToResolveOverload =
9536 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00009537 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009538 HasAnyDeductionGuide = false;
9539
Richard Smith32918772017-02-14 00:25:28 +00009540 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
9541 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00009542 if (D->isInvalidDecl())
9543 continue;
9544
Richard Smithbc491202017-02-17 20:05:37 +00009545 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
9546 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
9547 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9548 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00009549 continue;
9550
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009551 if (!GD->isImplicit())
9552 HasAnyDeductionGuide = true;
9553
Richard Smith60437622017-02-09 19:17:44 +00009554 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9555 // For copy-initialization, the candidate functions are all the
9556 // converting constructors (12.3.1) of that class.
9557 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9558 // The converting constructors of T are candidate functions.
Richard Smith76b90272019-05-09 03:59:21 +00009559 if (!AllowExplicit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00009560 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00009561 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00009562 continue;
Richard Smith60437622017-02-09 19:17:44 +00009563
9564 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00009565 // could never be called with one argument are not interesting to
9566 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00009567 if (GD->getMinRequiredArguments() > 1 ||
9568 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00009569 continue;
9570 }
9571
9572 // C++ [over.match.list]p1.1: (first phase list initialization)
9573 // Initially, the candidate functions are the initializer-list
9574 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00009575 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00009576 continue;
9577
9578 // C++ [over.match.list]p1.2: (second phase list initialization)
9579 // the candidate functions are all the constructors of the class T
9580 // C++ [over.match.ctor]p1: (all other cases)
9581 // the candidate functions are all the constructors of the class of
9582 // the object being initialized
9583
9584 // C++ [over.best.ics]p4:
9585 // When [...] the constructor [...] is a candidate by
9586 // - [over.match.copy] (in all cases)
9587 // FIXME: The "second phase of [over.match.list] case can also
9588 // theoretically happen here, but it's not clear whether we can
9589 // ever have a parameter of the right type.
9590 bool SuppressUserConversions = Kind.isCopyInit();
9591
Richard Smith60437622017-02-09 19:17:44 +00009592 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00009593 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
Richard Smith76b90272019-05-09 03:59:21 +00009594 Inits, Candidates, SuppressUserConversions,
9595 /*PartialOverloading*/ false,
9596 AllowExplicit);
Richard Smith60437622017-02-09 19:17:44 +00009597 else
Richard Smithbc491202017-02-17 20:05:37 +00009598 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith76b90272019-05-09 03:59:21 +00009599 SuppressUserConversions,
9600 /*PartialOverloading*/ false, AllowExplicit);
Richard Smith60437622017-02-09 19:17:44 +00009601 }
9602 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
9603 };
9604
9605 OverloadingResult Result = OR_No_Viable_Function;
9606
9607 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9608 // try initializer-list constructors.
9609 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00009610 bool TryListConstructors = true;
9611
9612 // Try list constructors unless the list is empty and the class has one or
9613 // more default constructors, in which case those constructors win.
9614 if (!ListInit->getNumInits()) {
9615 for (NamedDecl *D : Guides) {
9616 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9617 if (FD && FD->getMinRequiredArguments() == 0) {
9618 TryListConstructors = false;
9619 break;
9620 }
9621 }
Richard Smith1363e8f2017-09-07 07:22:36 +00009622 } else if (ListInit->getNumInits() == 1) {
9623 // C++ [over.match.class.deduct]:
9624 // As an exception, the first phase in [over.match.list] (considering
9625 // initializer-list constructors) is omitted if the initializer list
9626 // consists of a single expression of type cv U, where U is a
9627 // specialization of C or a class derived from a specialization of C.
9628 Expr *E = ListInit->getInit(0);
9629 auto *RD = E->getType()->getAsCXXRecordDecl();
9630 if (!isa<InitListExpr>(E) && RD &&
Erik Pilkingtondd0b3442018-07-26 23:40:42 +00009631 isCompleteType(Kind.getLocation(), E->getType()) &&
Richard Smith1363e8f2017-09-07 07:22:36 +00009632 isOrIsDerivedFromSpecializationOf(RD, Template))
9633 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00009634 }
9635
9636 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00009637 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
9638 // Then unwrap the initializer list and try again considering all
9639 // constructors.
9640 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
9641 }
9642
9643 // If list-initialization fails, or if we're doing any other kind of
9644 // initialization, we (eventually) consider constructors.
9645 if (Result == OR_No_Viable_Function)
9646 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
9647
9648 switch (Result) {
9649 case OR_Ambiguous:
Richard Smith60437622017-02-09 19:17:44 +00009650 // FIXME: For list-initialization candidates, it'd usually be better to
9651 // list why they were not viable when given the initializer list itself as
9652 // an argument.
David Blaikie5e328052019-05-03 00:44:50 +00009653 Candidates.NoteCandidates(
9654 PartialDiagnosticAt(
9655 Kind.getLocation(),
9656 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
9657 << TemplateName),
9658 *this, OCD_ViableCandidates, Inits);
Richard Smith60437622017-02-09 19:17:44 +00009659 return QualType();
9660
Richard Smith32918772017-02-14 00:25:28 +00009661 case OR_No_Viable_Function: {
9662 CXXRecordDecl *Primary =
9663 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
9664 bool Complete =
9665 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
David Blaikie5e328052019-05-03 00:44:50 +00009666 Candidates.NoteCandidates(
9667 PartialDiagnosticAt(
9668 Kind.getLocation(),
9669 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
9670 : diag::err_deduced_class_template_incomplete)
9671 << TemplateName << !Guides.empty()),
9672 *this, OCD_AllCandidates, Inits);
Richard Smith60437622017-02-09 19:17:44 +00009673 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00009674 }
Richard Smith60437622017-02-09 19:17:44 +00009675
9676 case OR_Deleted: {
9677 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
9678 << TemplateName;
9679 NoteDeletedFunction(Best->Function);
9680 return QualType();
9681 }
9682
9683 case OR_Success:
9684 // C++ [over.match.list]p1:
9685 // In copy-list-initialization, if an explicit constructor is chosen, the
9686 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00009687 if (Kind.isCopyInit() && ListInit &&
9688 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00009689 bool IsDeductionGuide = !Best->Function->isImplicit();
9690 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
9691 << TemplateName << IsDeductionGuide;
9692 Diag(Best->Function->getLocation(),
9693 diag::note_explicit_ctor_deduction_guide_here)
9694 << IsDeductionGuide;
9695 return QualType();
9696 }
9697
9698 // Make sure we didn't select an unusable deduction guide, and mark it
9699 // as referenced.
9700 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
9701 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
9702 break;
9703 }
9704
9705 // C++ [dcl.type.class.deduct]p1:
9706 // The placeholder is replaced by the return type of the function selected
9707 // by overload resolution for class template deduction.
Richard Smith8eeb16f2018-09-10 20:31:03 +00009708 QualType DeducedType =
9709 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
9710 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9711 diag::warn_cxx14_compat_class_template_argument_deduction)
9712 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
Eric Fiselier73b51ae2019-01-17 21:44:24 +00009713
9714 // Warn if CTAD was used on a type that does not have any user-defined
9715 // deduction guides.
9716 if (!HasAnyDeductionGuide) {
9717 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9718 diag::warn_ctad_maybe_unsupported)
9719 << TemplateName;
9720 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
9721 }
9722
Richard Smith8eeb16f2018-09-10 20:31:03 +00009723 return DeducedType;
Richard Smith60437622017-02-09 19:17:44 +00009724}