blob: 3fc86136c5295c7444c22230e5274232db95e261 [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
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
Anders Carlssoncc52f652009-09-22 22:53:17 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with code generation of C++ expressions
10//
11//===----------------------------------------------------------------------===//
12
Peter Collingbournefe883422011-10-06 18:29:37 +000013#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Devang Patel91bbb552010-09-30 19:05:55 +000015#include "CGDebugInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGObjCRuntime.h"
Marco Antognini88559632019-07-22 09:39:13 +000017#include "CodeGenFunction.h"
John McCallde0fe072017-08-15 21:42:52 +000018#include "ConstantEmitter.h"
Marco Antognini88559632019-07-22 09:39:13 +000019#include "TargetInfo.h"
Richard Trieu63688182018-12-11 03:18:39 +000020#include "clang/Basic/CodeGenOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000023
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
George Burgess IVd0a9e802017-02-23 22:07:35 +000027namespace {
28struct MemberCallInfo {
29 RequiredArgs ReqArgs;
30 // Number of prefix arguments for the call. Ignores the `this` pointer.
31 unsigned PrefixSize;
32};
33}
34
35static MemberCallInfo
Alexey Samsonovefa956c2016-03-10 00:20:33 +000036commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
37 llvm::Value *This, llvm::Value *ImplicitParam,
38 QualType ImplicitParamTy, const CallExpr *CE,
Richard Smith762672a2016-09-28 19:09:10 +000039 CallArgList &Args, CallArgList *RtlArgs) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000040 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
41 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000042 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000043 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson27da15b2010-01-01 20:29:01 +000044
Anders Carlsson27da15b2010-01-01 20:29:01 +000045 // Push the this ptr.
Reid Kleckner034e7272016-09-07 15:15:51 +000046 const CXXRecordDecl *RD =
47 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
James Y Knightb92d2902019-02-05 16:05:50 +000048 Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
Anders Carlsson27da15b2010-01-01 20:29:01 +000049
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000050 // If there is an implicit parameter (e.g. VTT), emit it.
51 if (ImplicitParam) {
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssone36a6b32010-01-02 01:01:18 +000053 }
John McCalla729c622012-02-17 03:33:10 +000054
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
James Y Knight916db652019-02-02 01:48:23 +000056 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
George Burgess IVd0a9e802017-02-23 22:07:35 +000057 unsigned PrefixSize = Args.size() - 1;
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000058
John McCalla729c622012-02-17 03:33:10 +000059 // And the rest of the call args.
Richard Smith762672a2016-09-28 19:09:10 +000060 if (RtlArgs) {
61 // Special case: if the caller emitted the arguments right-to-left already
62 // (prior to emitting the *this argument), we're done. This happens for
63 // assignment operators.
64 Args.addFrom(*RtlArgs);
65 } else if (CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000066 // Special case: skip first argument of CXXOperatorCall (it is "this").
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000067 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
David Blaikief05779e2015-07-21 18:37:18 +000068 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
David Majnemer0c0b6d92014-10-31 20:09:12 +000069 CE->getDirectCallee());
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000070 } else {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000071 assert(
72 FPT->getNumParams() == 0 &&
73 "No CallExpr specified for function with non-zero number of arguments");
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000074 }
George Burgess IVd0a9e802017-02-23 22:07:35 +000075 return {required, PrefixSize};
David Majnemer0c0b6d92014-10-31 20:09:12 +000076}
Anders Carlsson27da15b2010-01-01 20:29:01 +000077
David Majnemer0c0b6d92014-10-31 20:09:12 +000078RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
John McCallb92ab1a2016-10-26 23:46:34 +000079 const CXXMethodDecl *MD, const CGCallee &Callee,
80 ReturnValueSlot ReturnValue,
David Majnemer0c0b6d92014-10-31 20:09:12 +000081 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
Richard Smith762672a2016-09-28 19:09:10 +000082 const CallExpr *CE, CallArgList *RtlArgs) {
David Majnemer0c0b6d92014-10-31 20:09:12 +000083 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
84 CallArgList Args;
George Burgess IVd0a9e802017-02-23 22:07:35 +000085 MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
Richard Smith762672a2016-09-28 19:09:10 +000086 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
George Burgess IVd0a9e802017-02-23 22:07:35 +000087 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
88 Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
Vedant Kumar09b5bfd2017-12-21 00:10:25 +000089 return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
90 CE ? CE->getExprLoc() : SourceLocation());
Anders Carlsson27da15b2010-01-01 20:29:01 +000091}
92
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000093RValue CodeGenFunction::EmitCXXDestructorCall(
Marco Antognini88559632019-07-22 09:39:13 +000094 GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
Peter Collingbourned1c5b282019-03-22 23:05:10 +000095 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
Marco Antognini88559632019-07-22 09:39:13 +000096 const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
97
98 assert(!ThisTy.isNull());
99 assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
100 "Pointer/Object mixup");
101
102 LangAS SrcAS = ThisTy.getAddressSpace();
103 LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
104 if (SrcAS != DstAS) {
105 QualType DstTy = DtorDecl->getThisType();
106 llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
107 This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
108 NewType);
109 }
110
David Majnemer0c0b6d92014-10-31 20:09:12 +0000111 CallArgList Args;
Marco Antognini88559632019-07-22 09:39:13 +0000112 commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam,
113 ImplicitParamTy, CE, Args, nullptr);
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000114 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
115 ReturnValueSlot(), Args);
John McCallb92ab1a2016-10-26 23:46:34 +0000116}
117
118RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
119 const CXXPseudoDestructorExpr *E) {
120 QualType DestroyedType = E->getDestroyedType();
121 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
122 // Automatic Reference Counting:
123 // If the pseudo-expression names a retainable object with weak or
124 // strong lifetime, the object shall be released.
125 Expr *BaseExpr = E->getBase();
126 Address BaseValue = Address::invalid();
127 Qualifiers BaseQuals;
128
129 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
130 if (E->isArrow()) {
131 BaseValue = EmitPointerWithAlignment(BaseExpr);
132 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
133 BaseQuals = PTy->getPointeeType().getQualifiers();
134 } else {
135 LValue BaseLV = EmitLValue(BaseExpr);
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800136 BaseValue = BaseLV.getAddress(*this);
John McCallb92ab1a2016-10-26 23:46:34 +0000137 QualType BaseTy = BaseExpr->getType();
138 BaseQuals = BaseTy.getQualifiers();
139 }
140
141 switch (DestroyedType.getObjCLifetime()) {
142 case Qualifiers::OCL_None:
143 case Qualifiers::OCL_ExplicitNone:
144 case Qualifiers::OCL_Autoreleasing:
145 break;
146
147 case Qualifiers::OCL_Strong:
148 EmitARCRelease(Builder.CreateLoad(BaseValue,
149 DestroyedType.isVolatileQualified()),
150 ARCPreciseLifetime);
151 break;
152
153 case Qualifiers::OCL_Weak:
154 EmitARCDestroyWeak(BaseValue);
155 break;
156 }
157 } else {
158 // C++ [expr.pseudo]p1:
159 // The result shall only be used as the operand for the function call
160 // operator (), and the result of such a call has type void. The only
161 // effect is the evaluation of the postfix-expression before the dot or
162 // arrow.
163 EmitIgnoredExpr(E->getBase());
164 }
165
166 return RValue::get(nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000167}
168
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000169static CXXRecordDecl *getCXXRecord(const Expr *E) {
170 QualType T = E->getType();
171 if (const PointerType *PTy = T->getAs<PointerType>())
172 T = PTy->getPointeeType();
173 const RecordType *Ty = T->castAs<RecordType>();
174 return cast<CXXRecordDecl>(Ty->getDecl());
175}
176
Francois Pichet64225792011-01-18 05:04:39 +0000177// Note: This function also emit constructor calls to support a MSVC
178// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000179RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
180 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000181 const Expr *callee = CE->getCallee()->IgnoreParens();
182
183 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000184 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000185
186 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000187 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
188
189 if (MD->isStatic()) {
190 // The method is static, emit it as we would a regular call.
Erich Keanede6480a32018-11-13 15:48:08 +0000191 CGCallee callee =
192 CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
John McCallb92ab1a2016-10-26 23:46:34 +0000193 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000194 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000195 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000196
Nico Weberaad4af62014-12-03 01:21:41 +0000197 bool HasQualifier = ME->hasQualifier();
198 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
199 bool IsArrow = ME->isArrow();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000200 const Expr *Base = ME->getBase();
Nico Weberaad4af62014-12-03 01:21:41 +0000201
202 return EmitCXXMemberOrOperatorMemberCallExpr(
203 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
204}
205
206RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
207 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
208 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
209 const Expr *Base) {
210 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
211
212 // Compute the object pointer.
213 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000214
Craig Topper8a13c412014-05-21 05:09:00 +0000215 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Akira Hatanaka22461672017-07-13 06:08:27 +0000216 if (CanUseVirtualCall &&
217 MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000218 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
219 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
220 assert(DevirtualizedMethod);
221 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
222 const Expr *Inner = Base->ignoreParenBaseCasts();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000223 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
224 MD->getReturnType().getCanonicalType())
225 // If the return types are not the same, this might be a case where more
226 // code needs to run to compensate for it. For example, the derived
227 // method might return a type that inherits form from the return
228 // type of MD and has a prefix.
229 // For now we just avoid devirtualizing these covariant cases.
230 DevirtualizedMethod = nullptr;
231 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000232 // If the class of the Inner expression is where the dynamic method
233 // is defined, build the this pointer from it.
234 Base = Inner;
235 else if (getCXXRecord(Base) != DevirtualizedClass) {
236 // If the method is defined in a class that is not the best dynamic
237 // one or the one of the full expression, we would have to build
238 // a derived-to-base cast to compute the correct this pointer, but
239 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000240 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000241 }
242 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000243
Richard Smith3ced2392019-12-18 14:01:40 -0800244 bool TrivialForCodegen =
245 MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
246 bool TrivialAssignment =
247 TrivialForCodegen &&
248 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
249 !MD->getParent()->mayInsertExtraPadding();
250
Richard Smith762672a2016-09-28 19:09:10 +0000251 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
252 // operator before the LHS.
253 CallArgList RtlArgStorage;
254 CallArgList *RtlArgs = nullptr;
Richard Smith3ced2392019-12-18 14:01:40 -0800255 LValue TrivialAssignmentRHS;
Richard Smith762672a2016-09-28 19:09:10 +0000256 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
257 if (OCE->isAssignmentOp()) {
Richard Smith3ced2392019-12-18 14:01:40 -0800258 if (TrivialAssignment) {
259 TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
260 } else {
261 RtlArgs = &RtlArgStorage;
262 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
263 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
264 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
265 }
Richard Smith762672a2016-09-28 19:09:10 +0000266 }
267 }
268
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000269 LValue This;
270 if (IsArrow) {
271 LValueBaseInfo BaseInfo;
272 TBAAAccessInfo TBAAInfo;
273 Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
274 This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
275 } else {
276 This = EmitLValue(Base);
277 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000278
James Y Knightab4f7f12019-02-06 00:06:03 +0000279 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
280 // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
281 // constructing a new complete object of type Ctor.
282 assert(!RtlArgs);
283 assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
284 CallArgList Args;
285 commonEmitCXXMemberOrOperatorCall(
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800286 *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr,
James Y Knightab4f7f12019-02-06 00:06:03 +0000287 /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
288
289 EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800290 /*Delegating=*/false, This.getAddress(*this), Args,
James Y Knightab4f7f12019-02-06 00:06:03 +0000291 AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
292 /*NewPointerIsChecked=*/false);
293 return RValue::get(nullptr);
294 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295
Richard Smith3ced2392019-12-18 14:01:40 -0800296 if (TrivialForCodegen) {
297 if (isa<CXXDestructorDecl>(MD))
298 return RValue::get(nullptr);
299
300 if (TrivialAssignment) {
301 // We don't like to generate the trivial copy/move assignment operator
302 // when it isn't necessary; just produce the proper effect here.
303 // It's important that we use the result of EmitLValue here rather than
304 // emitting call arguments, in order to preserve TBAA information from
305 // the RHS.
306 LValue RHS = isa<CXXOperatorCallExpr>(CE)
307 ? TrivialAssignmentRHS
308 : EmitLValue(*CE->arg_begin());
309 EmitAggregateAssign(This, RHS, CE->getType());
310 return RValue::get(This.getPointer(*this));
Francois Pichet64225792011-01-18 05:04:39 +0000311 }
Richard Smith3ced2392019-12-18 14:01:40 -0800312
313 assert(MD->getParent()->mayInsertExtraPadding() &&
314 "unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000315 }
316
John McCall0d635f52010-09-03 01:26:39 +0000317 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000318 const CXXMethodDecl *CalleeDecl =
319 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000320 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000321 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000322 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000323 GlobalDecl(Dtor, Dtor_Complete));
Francois Pichet64225792011-01-18 05:04:39 +0000324 else
Eli Friedmanade60972012-10-25 00:12:49 +0000325 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000326
Reid Klecknere7de47e2013-07-22 13:51:44 +0000327 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000328
Ivan Krasind98f5d72016-11-17 00:39:48 +0000329 // C++11 [class.mfct.non-static]p2:
330 // If a non-static member function of a class X is called for an object that
331 // is not of type X, or of a type derived from X, the behavior is undefined.
332 SourceLocation CallLoc;
333 ASTContext &C = getContext();
334 if (CE)
335 CallLoc = CE->getExprLoc();
336
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000337 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +0000338 if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
339 auto *IOA = CMCE->getImplicitObjectArgument();
340 bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
341 if (IsImplicitObjectCXXThis)
342 SkippedChecks.set(SanitizerKind::Alignment, true);
343 if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000344 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +0000345 }
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800346 EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
347 This.getPointer(*this),
James Y Knightab4f7f12019-02-06 00:06:03 +0000348 C.getRecordType(CalleeDecl->getParent()),
349 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan Krasind98f5d72016-11-17 00:39:48 +0000350
Anders Carlsson27da15b2010-01-01 20:29:01 +0000351 // C++ [class.virtual]p12:
352 // Explicit qualification with the scope operator (5.1) suppresses the
353 // virtual call mechanism.
354 //
355 // We also don't emit a virtual call if the base expression has a record type
356 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000357 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Fangrui Song6907ce22018-07-30 19:24:48 +0000358
James Y Knightb92d2902019-02-05 16:05:50 +0000359 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000360 assert(CE->arg_begin() == CE->arg_end() &&
361 "Destructor shouldn't have explicit parameters");
362 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000363 if (UseVirtualCall) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800364 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
365 This.getAddress(*this),
366 cast<CXXMemberCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000367 } else {
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000368 GlobalDecl GD(Dtor, Dtor_Complete);
John McCallb92ab1a2016-10-26 23:46:34 +0000369 CGCallee Callee;
James Y Knightb92d2902019-02-05 16:05:50 +0000370 if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
371 Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000372 else if (!DevirtualizedMethod)
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000373 Callee =
374 CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000375 else {
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000376 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000377 }
James Y Knightb92d2902019-02-05 16:05:50 +0000378
Marco Antognini88559632019-07-22 09:39:13 +0000379 QualType ThisTy =
380 IsArrow ? Base->getType()->getPointeeType() : Base->getType();
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800381 EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
James Y Knightb92d2902019-02-05 16:05:50 +0000382 /*ImplicitParam=*/nullptr,
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000383 /*ImplicitParamTy=*/QualType(), nullptr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000384 }
Craig Topper8a13c412014-05-21 05:09:00 +0000385 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000386 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000387
James Y Knightb92d2902019-02-05 16:05:50 +0000388 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
389 // 'CalleeDecl' instead.
390
John McCallb92ab1a2016-10-26 23:46:34 +0000391 CGCallee Callee;
James Y Knightab4f7f12019-02-06 00:06:03 +0000392 if (UseVirtualCall) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800393 Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000394 } else {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000395 if (SanOpts.has(SanitizerKind::CFINVCall) &&
396 MD->getParent()->isDynamicClass()) {
Peter Collingbourne60108802017-12-13 21:53:04 +0000397 llvm::Value *VTable;
398 const CXXRecordDecl *RD;
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800399 std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
400 *this, This.getAddress(*this), CalleeDecl->getParent());
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000401 EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000402 }
403
Nico Weberaad4af62014-12-03 01:21:41 +0000404 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
405 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000406 else if (!DevirtualizedMethod)
Erich Keanede6480a32018-11-13 15:48:08 +0000407 Callee =
408 CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
Rafael Espindola49e860b2012-06-26 17:45:31 +0000409 else {
Erich Keanede6480a32018-11-13 15:48:08 +0000410 Callee =
411 CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
412 GlobalDecl(DevirtualizedMethod));
Rafael Espindola49e860b2012-06-26 17:45:31 +0000413 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000414 }
415
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000416 if (MD->isVirtual()) {
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000417 Address NewThisAddr =
418 CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800419 *this, CalleeDecl, This.getAddress(*this), UseVirtualCall);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000420 This.setAddress(NewThisAddr);
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000421 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000422
Vedant Kumar018f2662016-10-19 20:21:16 +0000423 return EmitCXXMemberOrOperatorCall(
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800424 CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
Vedant Kumar018f2662016-10-19 20:21:16 +0000425 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000426}
427
428RValue
429CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
430 ReturnValueSlot ReturnValue) {
431 const BinaryOperator *BO =
432 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
433 const Expr *BaseExpr = BO->getLHS();
434 const Expr *MemFnExpr = BO->getRHS();
Fangrui Song6907ce22018-07-30 19:24:48 +0000435
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000436 const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
437 const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
438 const auto *RD =
439 cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000440
Anders Carlsson27da15b2010-01-01 20:29:01 +0000441 // Emit the 'this' pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000442 Address This = Address::invalid();
John McCalle3027922010-08-25 11:45:40 +0000443 if (BO->getOpcode() == BO_PtrMemI)
John McCall7f416cc2015-09-08 08:05:57 +0000444 This = EmitPointerWithAlignment(BaseExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +0000445 else
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800446 This = EmitLValue(BaseExpr).getAddress(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000447
John McCall7f416cc2015-09-08 08:05:57 +0000448 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000449 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000450
Richard Smithbde62d72016-09-26 23:56:57 +0000451 // Get the member function pointer.
452 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
453
John McCall475999d2010-08-22 00:05:51 +0000454 // Ask the ABI to load the callee. Note that This is modified.
John McCall7f416cc2015-09-08 08:05:57 +0000455 llvm::Value *ThisPtrForCall = nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +0000456 CGCallee Callee =
John McCall7f416cc2015-09-08 08:05:57 +0000457 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
458 ThisPtrForCall, MemFnPtr, MPT);
Fangrui Song6907ce22018-07-30 19:24:48 +0000459
Anders Carlsson27da15b2010-01-01 20:29:01 +0000460 CallArgList Args;
461
Fangrui Song6907ce22018-07-30 19:24:48 +0000462 QualType ThisType =
Anders Carlsson27da15b2010-01-01 20:29:01 +0000463 getContext().getPointerType(getContext().getTagDeclType(RD));
464
465 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +0000466 Args.add(RValue::get(ThisPtrForCall), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000467
James Y Knight916db652019-02-02 01:48:23 +0000468 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
George Burgess IV419996c2016-06-16 23:06:04 +0000469
Anders Carlsson27da15b2010-01-01 20:29:01 +0000470 // And the rest of the call args
George Burgess IV419996c2016-06-16 23:06:04 +0000471 EmitCallArgs(Args, FPT, E->arguments());
George Burgess IVd0a9e802017-02-23 22:07:35 +0000472 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
473 /*PrefixSize=*/0),
Vedant Kumar09b5bfd2017-12-21 00:10:25 +0000474 Callee, ReturnValue, Args, nullptr, E->getExprLoc());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000475}
476
477RValue
478CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
479 const CXXMethodDecl *MD,
480 ReturnValueSlot ReturnValue) {
481 assert(MD->isInstance() &&
482 "Trying to emit a member call expr on a static method!");
Nico Weberaad4af62014-12-03 01:21:41 +0000483 return EmitCXXMemberOrOperatorMemberCallExpr(
484 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
485 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000486}
487
Peter Collingbournefe883422011-10-06 18:29:37 +0000488RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
489 ReturnValueSlot ReturnValue) {
490 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
491}
492
Eli Friedmanfde961d2011-10-14 02:27:24 +0000493static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000494 Address DestPtr,
Eli Friedmanfde961d2011-10-14 02:27:24 +0000495 const CXXRecordDecl *Base) {
496 if (Base->isEmpty())
497 return;
498
John McCall7f416cc2015-09-08 08:05:57 +0000499 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000500
501 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
David Majnemer8671c6e2015-11-02 09:01:44 +0000502 CharUnits NVSize = Layout.getNonVirtualSize();
503
504 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
505 // present, they are initialized by the most derived class before calling the
506 // constructor.
507 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
508 Stores.emplace_back(CharUnits::Zero(), NVSize);
509
510 // Each store is split by the existence of a vbptr.
511 CharUnits VBPtrWidth = CGF.getPointerSize();
512 std::vector<CharUnits> VBPtrOffsets =
513 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
514 for (CharUnits VBPtrOffset : VBPtrOffsets) {
David Majnemer7f980d82016-05-12 03:51:52 +0000515 // Stop before we hit any virtual base pointers located in virtual bases.
516 if (VBPtrOffset >= NVSize)
517 break;
David Majnemer8671c6e2015-11-02 09:01:44 +0000518 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
519 CharUnits LastStoreOffset = LastStore.first;
520 CharUnits LastStoreSize = LastStore.second;
521
522 CharUnits SplitBeforeOffset = LastStoreOffset;
523 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
524 assert(!SplitBeforeSize.isNegative() && "negative store size!");
525 if (!SplitBeforeSize.isZero())
526 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
527
528 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
529 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
530 assert(!SplitAfterSize.isNegative() && "negative store size!");
531 if (!SplitAfterSize.isZero())
532 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
533 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000534
535 // If the type contains a pointer to data member we can't memset it to zero.
536 // Instead, create a null constant and copy it to the destination.
537 // TODO: there are other patterns besides zero that we can usefully memset,
538 // like -1, which happens to be the pattern used by member-pointers.
539 // TODO: isZeroInitializable can be over-conservative in the case where a
540 // virtual base contains a member pointer.
David Majnemer8671c6e2015-11-02 09:01:44 +0000541 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
542 if (!NullConstantForBase->isNullValue()) {
543 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
544 CGF.CGM.getModule(), NullConstantForBase->getType(),
545 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
546 NullConstantForBase, Twine());
John McCall7f416cc2015-09-08 08:05:57 +0000547
548 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
549 DestPtr.getAlignment());
Guillaume Chateletc79099e2019-10-03 13:00:29 +0000550 NullVariable->setAlignment(Align.getAsAlign());
John McCall7f416cc2015-09-08 08:05:57 +0000551
552 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000553
554 // Get and call the appropriate llvm.memcpy overload.
David Majnemer8671c6e2015-11-02 09:01:44 +0000555 for (std::pair<CharUnits, CharUnits> Store : Stores) {
556 CharUnits StoreOffset = Store.first;
557 CharUnits StoreSize = Store.second;
558 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
559 CGF.Builder.CreateMemCpy(
560 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
561 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
562 StoreSizeVal);
563 }
564
Eli Friedmanfde961d2011-10-14 02:27:24 +0000565 // Otherwise, just memset the whole thing to zero. This is legal
566 // because in LLVM, all default initializers (other than the ones we just
567 // handled above) are guaranteed to have a bit pattern of all zeros.
David Majnemer8671c6e2015-11-02 09:01:44 +0000568 } else {
569 for (std::pair<CharUnits, CharUnits> Store : Stores) {
570 CharUnits StoreOffset = Store.first;
571 CharUnits StoreSize = Store.second;
572 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
573 CGF.Builder.CreateMemSet(
574 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
575 CGF.Builder.getInt8(0), StoreSizeVal);
576 }
577 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000578}
579
Anders Carlsson27da15b2010-01-01 20:29:01 +0000580void
John McCall7a626f62010-09-15 10:14:12 +0000581CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
582 AggValueSlot Dest) {
583 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000584 const CXXConstructorDecl *CD = E->getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +0000585
Douglas Gregor630c76e2010-08-22 16:15:35 +0000586 // If we require zero initialization before (or instead of) calling the
587 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000588 // constructor, emit the zero initialization now, unless destination is
589 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000590 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
591 switch (E->getConstructionKind()) {
592 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000593 case CXXConstructExpr::CK_Complete:
John McCall7f416cc2015-09-08 08:05:57 +0000594 EmitNullInitialization(Dest.getAddress(), E->getType());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000595 break;
596 case CXXConstructExpr::CK_VirtualBase:
597 case CXXConstructExpr::CK_NonVirtualBase:
John McCall7f416cc2015-09-08 08:05:57 +0000598 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
599 CD->getParent());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000600 break;
601 }
602 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000603
Douglas Gregor630c76e2010-08-22 16:15:35 +0000604 // If this is a call to a trivial default constructor, do nothing.
605 if (CD->isTrivial() && CD->isDefaultConstructor())
606 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000607
John McCall8ea46b62010-09-18 00:58:34 +0000608 // Elide the constructor if we're constructing from a temporary.
609 // The temporary check is required because Sema sets this on NRVO
610 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000611 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000612 assert(getContext().hasSameUnqualifiedType(E->getType(),
613 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000614 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
615 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000616 return;
617 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000618 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000619
Alexey Bataeve7545b32016-04-29 09:39:50 +0000620 if (const ArrayType *arrayType
621 = getContext().getAsArrayType(E->getType())) {
Serge Pavlov37605182018-07-28 15:33:03 +0000622 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
623 Dest.isSanitizerChecked());
John McCallf677a8e2011-07-13 06:10:41 +0000624 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000625 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000626 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000627 bool Delegating = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000628
Alexis Hunt271c3682011-05-03 20:19:28 +0000629 switch (E->getConstructionKind()) {
630 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000631 // We should be emitting a constructor; GlobalDecl will assert this
632 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000633 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000634 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000635
Alexis Hunt271c3682011-05-03 20:19:28 +0000636 case CXXConstructExpr::CK_Complete:
637 Type = Ctor_Complete;
638 break;
639
640 case CXXConstructExpr::CK_VirtualBase:
641 ForVirtualBase = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000642 LLVM_FALLTHROUGH;
Alexis Hunt271c3682011-05-03 20:19:28 +0000643
644 case CXXConstructExpr::CK_NonVirtualBase:
645 Type = Ctor_Base;
Anastasia Stulova094c7262019-04-04 10:48:36 +0000646 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000647
Anastasia Stulova094c7262019-04-04 10:48:36 +0000648 // Call the constructor.
649 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000650 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000651}
652
John McCall7f416cc2015-09-08 08:05:57 +0000653void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
654 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000655 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000656 Exp = E->getSubExpr();
Fangrui Song6907ce22018-07-30 19:24:48 +0000657 assert(isa<CXXConstructExpr>(Exp) &&
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000658 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
659 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
660 const CXXConstructorDecl *CD = E->getConstructor();
661 RunCleanupsScope Scope(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000662
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000663 // If we require zero initialization before (or instead of) calling the
664 // constructor, as can be the case with a non-user-provided default
665 // constructor, emit the zero initialization now.
666 // FIXME. Do I still need this for a copy ctor synthesis?
667 if (E->requiresZeroInitialization())
668 EmitNullInitialization(Dest, E->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +0000669
Chandler Carruth99da11c2010-11-15 13:54:43 +0000670 assert(!getContext().getAsConstantArrayType(E->getType())
671 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000672 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000673}
674
John McCall8ed55a52010-09-02 09:58:18 +0000675static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
676 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000677 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000678 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000679
John McCall7ec4b432011-05-16 01:05:12 +0000680 // No cookie is required if the operator new[] being used is the
681 // reserved placement operator new[].
682 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000683 return CharUnits::Zero();
684
John McCall284c48f2011-01-27 09:37:56 +0000685 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000686}
687
John McCall036f2f62011-05-15 07:14:44 +0000688static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
689 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000690 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000691 llvm::Value *&numElements,
692 llvm::Value *&sizeWithoutCookie) {
693 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000694
John McCall036f2f62011-05-15 07:14:44 +0000695 if (!e->isArray()) {
696 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
697 sizeWithoutCookie
698 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
699 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000700 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000701
John McCall036f2f62011-05-15 07:14:44 +0000702 // The width of size_t.
703 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
704
John McCall8ed55a52010-09-02 09:58:18 +0000705 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000706 llvm::APInt cookieSize(sizeWidth,
707 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000708
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000709 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000710 // We multiply the size of all dimensions for NumElements.
711 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCallde0fe072017-08-15 21:42:52 +0000712 numElements =
Richard Smithb9fb1212019-05-06 03:47:15 +0000713 ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
Nick Lewycky07527622017-02-13 23:49:55 +0000714 if (!numElements)
Richard Smithb9fb1212019-05-06 03:47:15 +0000715 numElements = CGF.EmitScalarExpr(*e->getArraySize());
John McCall036f2f62011-05-15 07:14:44 +0000716 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000717
John McCall036f2f62011-05-15 07:14:44 +0000718 // The number of elements can be have an arbitrary integer type;
719 // essentially, we need to multiply it by a constant factor, add a
720 // cookie size, and verify that the result is representable as a
721 // size_t. That's just a gloss, though, and it's wrong in one
722 // important way: if the count is negative, it's an error even if
723 // the cookie size would bring the total size >= 0.
Fangrui Song6907ce22018-07-30 19:24:48 +0000724 bool isSigned
Richard Smithb9fb1212019-05-06 03:47:15 +0000725 = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000726 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000727 = cast<llvm::IntegerType>(numElements->getType());
728 unsigned numElementsWidth = numElementsType->getBitWidth();
729
730 // Compute the constant factor.
731 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000732 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000733 = CGF.getContext().getAsConstantArrayType(type)) {
734 type = CAT->getElementType();
735 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000736 }
737
John McCall036f2f62011-05-15 07:14:44 +0000738 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
739 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
740 typeSizeMultiplier *= arraySizeMultiplier;
741
742 // This will be a size_t.
743 llvm::Value *size;
Fangrui Song6907ce22018-07-30 19:24:48 +0000744
Chris Lattner32ac5832010-07-20 21:55:52 +0000745 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
746 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000747 if (llvm::ConstantInt *numElementsC =
748 dyn_cast<llvm::ConstantInt>(numElements)) {
749 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000750
John McCall036f2f62011-05-15 07:14:44 +0000751 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000752
John McCall036f2f62011-05-15 07:14:44 +0000753 // If 'count' was a negative number, it's an overflow.
754 if (isSigned && count.isNegative())
755 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000756
John McCall036f2f62011-05-15 07:14:44 +0000757 // We want to do all this arithmetic in size_t. If numElements is
758 // wider than that, check whether it's already too big, and if so,
759 // overflow.
760 else if (numElementsWidth > sizeWidth &&
761 numElementsWidth - sizeWidth > count.countLeadingZeros())
762 hasAnyOverflow = true;
763
764 // Okay, compute a count at the right width.
765 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
766
Sebastian Redlf862eb62012-02-22 17:37:52 +0000767 // If there is a brace-initializer, we cannot allocate fewer elements than
768 // there are initializers. If we do, that's treated like an overflow.
769 if (adjustedCount.ult(minElements))
770 hasAnyOverflow = true;
771
John McCall036f2f62011-05-15 07:14:44 +0000772 // Scale numElements by that. This might overflow, but we don't
773 // care because it only overflows if allocationSize does, too, and
774 // if that overflows then we shouldn't use this.
775 numElements = llvm::ConstantInt::get(CGF.SizeTy,
776 adjustedCount * arraySizeMultiplier);
777
778 // Compute the size before cookie, and track whether it overflowed.
779 bool overflow;
780 llvm::APInt allocationSize
781 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
782 hasAnyOverflow |= overflow;
783
784 // Add in the cookie, and check whether it's overflowed.
785 if (cookieSize != 0) {
786 // Save the current size without a cookie. This shouldn't be
787 // used if there was overflow.
788 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
789
790 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
791 hasAnyOverflow |= overflow;
792 }
793
794 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000795 if (hasAnyOverflow) {
796 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
797 } else {
John McCall036f2f62011-05-15 07:14:44 +0000798 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000799 }
John McCall036f2f62011-05-15 07:14:44 +0000800
801 // Otherwise, we might need to use the overflow intrinsics.
802 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000803 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000804 // 1) if isSigned, we need to check whether numElements is negative;
805 // 2) if numElementsWidth > sizeWidth, we need to check whether
806 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000807 // 3) if minElements > 0, we need to check whether numElements is smaller
808 // than that.
809 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000810 // sizeWithoutCookie := numElements * typeSizeMultiplier
811 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000812 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000813 // size := sizeWithoutCookie + cookieSize
814 // and check whether it overflows.
815
Craig Topper8a13c412014-05-21 05:09:00 +0000816 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000817
818 // If numElementsWidth > sizeWidth, then one way or another, we're
819 // going to have to do a comparison for (2), and this happens to
820 // take care of (1), too.
821 if (numElementsWidth > sizeWidth) {
822 llvm::APInt threshold(numElementsWidth, 1);
823 threshold <<= sizeWidth;
824
825 llvm::Value *thresholdV
826 = llvm::ConstantInt::get(numElementsType, threshold);
827
828 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
829 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
830
831 // Otherwise, if we're signed, we want to sext up to size_t.
832 } else if (isSigned) {
833 if (numElementsWidth < sizeWidth)
834 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000835
John McCall036f2f62011-05-15 07:14:44 +0000836 // If there's a non-1 type size multiplier, then we can do the
837 // signedness check at the same time as we do the multiply
838 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000839 // unsigned overflow. Otherwise, we have to do it here. But at least
840 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000841 if (typeSizeMultiplier == 1)
842 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000843 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000844
845 // Otherwise, zext up to size_t if necessary.
846 } else if (numElementsWidth < sizeWidth) {
847 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
848 }
849
850 assert(numElements->getType() == CGF.SizeTy);
851
Sebastian Redlf862eb62012-02-22 17:37:52 +0000852 if (minElements) {
853 // Don't allow allocation of fewer elements than we have initializers.
854 if (!hasOverflow) {
855 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
856 llvm::ConstantInt::get(CGF.SizeTy, minElements));
857 } else if (numElementsWidth > sizeWidth) {
858 // The other existing overflow subsumes this check.
859 // We do an unsigned comparison, since any signed value < -1 is
860 // taken care of either above or below.
861 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
862 CGF.Builder.CreateICmpULT(numElements,
863 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
864 }
865 }
866
John McCall036f2f62011-05-15 07:14:44 +0000867 size = numElements;
868
869 // Multiply by the type size if necessary. This multiplier
870 // includes all the factors for nested arrays.
871 //
872 // This step also causes numElements to be scaled up by the
873 // nested-array factor if necessary. Overflow on this computation
874 // can be ignored because the result shouldn't be used if
875 // allocation fails.
876 if (typeSizeMultiplier != 1) {
James Y Knight8799cae2019-02-03 21:53:49 +0000877 llvm::Function *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000878 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000879
880 llvm::Value *tsmV =
881 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
882 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000883 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
John McCall036f2f62011-05-15 07:14:44 +0000884
885 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
886 if (hasOverflow)
887 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
888 else
889 hasOverflow = overflowed;
890
891 size = CGF.Builder.CreateExtractValue(result, 0);
892
893 // Also scale up numElements by the array size multiplier.
894 if (arraySizeMultiplier != 1) {
895 // If the base element type size is 1, then we can re-use the
896 // multiply we just did.
897 if (typeSize.isOne()) {
898 assert(arraySizeMultiplier == typeSizeMultiplier);
899 numElements = size;
900
901 // Otherwise we need a separate multiply.
902 } else {
903 llvm::Value *asmV =
904 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
905 numElements = CGF.Builder.CreateMul(numElements, asmV);
906 }
907 }
908 } else {
909 // numElements doesn't need to be scaled.
910 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000911 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000912
John McCall036f2f62011-05-15 07:14:44 +0000913 // Add in the cookie size if necessary.
914 if (cookieSize != 0) {
915 sizeWithoutCookie = size;
916
James Y Knight8799cae2019-02-03 21:53:49 +0000917 llvm::Function *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000918 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000919
920 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
921 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000922 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
John McCall036f2f62011-05-15 07:14:44 +0000923
924 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
925 if (hasOverflow)
926 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
927 else
928 hasOverflow = overflowed;
929
930 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000931 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000932
John McCall036f2f62011-05-15 07:14:44 +0000933 // If we had any possibility of dynamic overflow, make a select to
934 // overwrite 'size' with an all-ones value, which should cause
935 // operator new to throw.
936 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000937 size = CGF.Builder.CreateSelect(hasOverflow,
938 llvm::Constant::getAllOnesValue(CGF.SizeTy),
939 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000940 }
John McCall8ed55a52010-09-02 09:58:18 +0000941
John McCall036f2f62011-05-15 07:14:44 +0000942 if (cookieSize == 0)
943 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000944 else
John McCall036f2f62011-05-15 07:14:44 +0000945 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000946
John McCall036f2f62011-05-15 07:14:44 +0000947 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000948}
949
Sebastian Redlf862eb62012-02-22 17:37:52 +0000950static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
Richard Smithe78fac52018-04-05 20:52:58 +0000951 QualType AllocType, Address NewPtr,
952 AggValueSlot::Overlap_t MayOverlap) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000953 // FIXME: Refactor with EmitExprAsInit.
John McCall47fb9502013-03-07 21:37:08 +0000954 switch (CGF.getEvaluationKind(AllocType)) {
955 case TEK_Scalar:
David Blaikiea2c11242014-12-10 19:04:09 +0000956 CGF.EmitScalarInit(Init, nullptr,
John McCall7f416cc2015-09-08 08:05:57 +0000957 CGF.MakeAddrLValue(NewPtr, AllocType), false);
John McCall47fb9502013-03-07 21:37:08 +0000958 return;
959 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000960 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
John McCall47fb9502013-03-07 21:37:08 +0000961 /*isInit*/ true);
962 return;
963 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000964 AggValueSlot Slot
John McCall7f416cc2015-09-08 08:05:57 +0000965 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000966 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000967 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000968 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +0000969 MayOverlap, AggValueSlot::IsNotZeroed,
970 AggValueSlot::IsSanitizerChecked);
John McCall7a626f62010-09-15 10:14:12 +0000971 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000972 return;
John McCall7a626f62010-09-15 10:14:12 +0000973 }
John McCall47fb9502013-03-07 21:37:08 +0000974 }
975 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000976}
977
David Blaikiefb901c7a2015-04-04 15:12:29 +0000978void CodeGenFunction::EmitNewArrayInitializer(
979 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +0000980 Address BeginPtr, llvm::Value *NumElements,
David Blaikiefb901c7a2015-04-04 15:12:29 +0000981 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000982 // If we have a type with trivial initialization and no initializer,
983 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000984 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000985 return;
John McCall99210dc2011-09-15 06:49:18 +0000986
John McCall7f416cc2015-09-08 08:05:57 +0000987 Address CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000988
Richard Smith06a67e22014-06-03 06:58:52 +0000989 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000990
991 const Expr *Init = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +0000992 Address EndOfInit = Address::invalid();
Richard Smith06a67e22014-06-03 06:58:52 +0000993 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
994 EHScopeStack::stable_iterator Cleanup;
995 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000996
John McCall7f416cc2015-09-08 08:05:57 +0000997 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
998 CharUnits ElementAlign =
999 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
1000
Richard Smith0511d232016-10-05 22:41:02 +00001001 // Attempt to perform zero-initialization using memset.
1002 auto TryMemsetInitialization = [&]() -> bool {
1003 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
1004 // we can initialize with a memset to -1.
1005 if (!CGM.getTypes().isZeroInitializable(ElementType))
1006 return false;
1007
1008 // Optimization: since zero initialization will just set the memory
1009 // to all zeroes, generate a single memset to do it in one shot.
1010
1011 // Subtract out the size of any elements we've already initialized.
1012 auto *RemainingSize = AllocSizeWithoutCookie;
1013 if (InitListElements) {
1014 // We know this can't overflow; we check this when doing the allocation.
1015 auto *InitializedSize = llvm::ConstantInt::get(
1016 RemainingSize->getType(),
1017 getContext().getTypeSizeInChars(ElementType).getQuantity() *
1018 InitListElements);
1019 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
1020 }
1021
1022 // Create the memset.
1023 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1024 return true;
1025 };
1026
Sebastian Redlf862eb62012-02-22 17:37:52 +00001027 // If the initializer is an initializer list, first do the explicit elements.
1028 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith0511d232016-10-05 22:41:02 +00001029 // Initializing from a (braced) string literal is a special case; the init
1030 // list element does not initialize a (single) array element.
1031 if (ILE->isStringLiteralInit()) {
1032 // Initialize the initial portion of length equal to that of the string
1033 // literal. The allocation must be for at least this much; we emitted a
1034 // check for that earlier.
1035 AggValueSlot Slot =
1036 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1037 AggValueSlot::IsDestructed,
1038 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001039 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +00001040 AggValueSlot::DoesNotOverlap,
1041 AggValueSlot::IsNotZeroed,
1042 AggValueSlot::IsSanitizerChecked);
Richard Smith0511d232016-10-05 22:41:02 +00001043 EmitAggExpr(ILE->getInit(0), Slot);
1044
1045 // Move past these elements.
1046 InitListElements =
1047 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1048 ->getSize().getZExtValue();
1049 CurPtr =
1050 Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1051 Builder.getSize(InitListElements),
1052 "string.init.end"),
1053 CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1054 ElementSize));
1055
1056 // Zero out the rest, if any remain.
1057 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1058 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1059 bool OK = TryMemsetInitialization();
1060 (void)OK;
1061 assert(OK && "couldn't memset character type?");
1062 }
1063 return;
1064 }
1065
Richard Smith06a67e22014-06-03 06:58:52 +00001066 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +00001067
Richard Smith1c96bc52013-12-11 01:40:16 +00001068 // If this is a multi-dimensional array new, we will initialize multiple
1069 // elements with each init list element.
1070 QualType AllocType = E->getAllocatedType();
1071 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1072 AllocType->getAsArrayTypeUnsafe())) {
David Blaikiefb901c7a2015-04-04 15:12:29 +00001073 ElementTy = ConvertTypeForMem(AllocType);
John McCall7f416cc2015-09-08 08:05:57 +00001074 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
Richard Smith06a67e22014-06-03 06:58:52 +00001075 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +00001076 }
1077
Richard Smith06a67e22014-06-03 06:58:52 +00001078 // Enter a partial-destruction Cleanup if necessary.
1079 if (needsEHCleanup(DtorKind)) {
1080 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +00001081 // directly, but the control flow can get so varied here that it
1082 // would actually be quite complex. Therefore we go through an
1083 // alloca.
John McCall7f416cc2015-09-08 08:05:57 +00001084 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1085 "array.init.end");
1086 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1087 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1088 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001089 getDestroyer(DtorKind));
1090 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +00001091 }
1092
John McCall7f416cc2015-09-08 08:05:57 +00001093 CharUnits StartAlign = CurPtr.getAlignment();
Sebastian Redlf862eb62012-02-22 17:37:52 +00001094 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +00001095 // Tell the cleanup that it needs to destroy up to this
1096 // element. TODO: some of these stores can be trivially
1097 // observed to be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00001098 if (EndOfInit.isValid()) {
1099 auto FinishedPtr =
1100 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1101 Builder.CreateStore(FinishedPtr, EndOfInit);
1102 }
Richard Smith06a67e22014-06-03 06:58:52 +00001103 // FIXME: If the last initializer is an incomplete initializer list for
1104 // an array, and we have an array filler, we can fold together the two
1105 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +00001106 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smithe78fac52018-04-05 20:52:58 +00001107 ILE->getInit(i)->getType(), CurPtr,
1108 AggValueSlot::DoesNotOverlap);
John McCall7f416cc2015-09-08 08:05:57 +00001109 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1110 Builder.getSize(1),
1111 "array.exp.next"),
1112 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
Sebastian Redlf862eb62012-02-22 17:37:52 +00001113 }
1114
1115 // The remaining elements are filled with the array filler expression.
1116 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +00001117
Richard Smith06a67e22014-06-03 06:58:52 +00001118 // Extract the initializer for the individual array elements by pulling
1119 // out the array filler from all the nested initializer lists. This avoids
1120 // generating a nested loop for the initialization.
1121 while (Init && Init->getType()->isConstantArrayType()) {
1122 auto *SubILE = dyn_cast<InitListExpr>(Init);
1123 if (!SubILE)
1124 break;
1125 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1126 Init = SubILE->getArrayFiller();
1127 }
1128
1129 // Switch back to initializing one base element at a time.
John McCall7f416cc2015-09-08 08:05:57 +00001130 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +00001131 }
1132
Richard Smith454a7cd2014-06-03 08:26:00 +00001133 // If all elements have already been initialized, skip any further
1134 // initialization.
1135 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1136 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1137 // If there was a Cleanup, deactivate it.
1138 if (CleanupDominator)
1139 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1140 return;
1141 }
1142
1143 assert(Init && "have trailing elements to initialize but no initializer");
1144
Richard Smith06a67e22014-06-03 06:58:52 +00001145 // If this is a constructor call, try to optimize it out, and failing that
1146 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +00001147 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001148 CXXConstructorDecl *Ctor = CCE->getConstructor();
1149 if (Ctor->isTrivial()) {
1150 // If new expression did not specify value-initialization, then there
1151 // is no initialization.
1152 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1153 return;
1154
1155 if (TryMemsetInitialization())
1156 return;
1157 }
1158
1159 // Store the new Cleanup position for irregular Cleanups.
1160 //
1161 // FIXME: Share this cleanup with the constructor call emission rather than
1162 // having it create a cleanup of its own.
John McCall7f416cc2015-09-08 08:05:57 +00001163 if (EndOfInit.isValid())
1164 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Richard Smith06a67e22014-06-03 06:58:52 +00001165
1166 // Emit a constructor call loop to initialize the remaining elements.
1167 if (InitListElements)
1168 NumElements = Builder.CreateSub(
1169 NumElements,
1170 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001171 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Serge Pavlov37605182018-07-28 15:33:03 +00001172 /*NewPointerIsChecked*/true,
Richard Smith06a67e22014-06-03 06:58:52 +00001173 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +00001174 return;
1175 }
1176
Richard Smith06a67e22014-06-03 06:58:52 +00001177 // If this is value-initialization, we can usually use memset.
1178 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +00001179 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001180 if (TryMemsetInitialization())
1181 return;
1182
1183 // Switch to an ImplicitValueInitExpr for the element type. This handles
1184 // only one case: multidimensional array new of pointers to members. In
1185 // all other cases, we already have an initializer for the array element.
1186 Init = &IVIE;
1187 }
1188
1189 // At this point we should have found an initializer for the individual
1190 // elements of the array.
1191 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1192 "got wrong type of element to initialize");
1193
Richard Smith454a7cd2014-06-03 08:26:00 +00001194 // If we have an empty initializer list, we can usually use memset.
1195 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1196 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1197 return;
Richard Smith06a67e22014-06-03 06:58:52 +00001198
Yunzhong Gaocb779302015-06-10 00:27:52 +00001199 // If we have a struct whose every field is value-initialized, we can
1200 // usually use memset.
1201 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1202 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1203 if (RType->getDecl()->isStruct()) {
Richard Smith872307e2016-03-08 22:17:41 +00001204 unsigned NumElements = 0;
1205 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1206 NumElements = CXXRD->getNumBases();
Yunzhong Gaocb779302015-06-10 00:27:52 +00001207 for (auto *Field : RType->getDecl()->fields())
1208 if (!Field->isUnnamedBitfield())
Richard Smith872307e2016-03-08 22:17:41 +00001209 ++NumElements;
1210 // FIXME: Recurse into nested InitListExprs.
1211 if (ILE->getNumInits() == NumElements)
Yunzhong Gaocb779302015-06-10 00:27:52 +00001212 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1213 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
Richard Smith872307e2016-03-08 22:17:41 +00001214 --NumElements;
1215 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
Yunzhong Gaocb779302015-06-10 00:27:52 +00001216 return;
1217 }
1218 }
1219 }
1220
Richard Smith06a67e22014-06-03 06:58:52 +00001221 // Create the loop blocks.
1222 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1223 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1224 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1225
1226 // Find the end of the array, hoisted out of the loop.
1227 llvm::Value *EndPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001228 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +00001229
Sebastian Redlf862eb62012-02-22 17:37:52 +00001230 // If the number of elements isn't constant, we have to now check if there is
1231 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +00001232 if (!ConstNum) {
John McCall7f416cc2015-09-08 08:05:57 +00001233 llvm::Value *IsEmpty =
1234 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +00001235 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001236 }
1237
1238 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001239 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001240
1241 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +00001242 llvm::PHINode *CurPtrPhi =
John McCall7f416cc2015-09-08 08:05:57 +00001243 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1244 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1245
1246 CurPtr = Address(CurPtrPhi, ElementAlign);
John McCall99210dc2011-09-15 06:49:18 +00001247
Richard Smith06a67e22014-06-03 06:58:52 +00001248 // Store the new Cleanup position for irregular Cleanups.
Fangrui Song6907ce22018-07-30 19:24:48 +00001249 if (EndOfInit.isValid())
John McCall7f416cc2015-09-08 08:05:57 +00001250 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +00001251
Richard Smith06a67e22014-06-03 06:58:52 +00001252 // Enter a partial-destruction Cleanup if necessary.
1253 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
John McCall7f416cc2015-09-08 08:05:57 +00001254 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1255 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001256 getDestroyer(DtorKind));
1257 Cleanup = EHStack.stable_begin();
1258 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +00001259 }
1260
1261 // Emit the initializer into this element.
Richard Smithe78fac52018-04-05 20:52:58 +00001262 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
1263 AggValueSlot::DoesNotOverlap);
John McCall99210dc2011-09-15 06:49:18 +00001264
Richard Smith06a67e22014-06-03 06:58:52 +00001265 // Leave the Cleanup if we entered one.
1266 if (CleanupDominator) {
1267 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1268 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +00001269 }
John McCall99210dc2011-09-15 06:49:18 +00001270
Faisal Vali57ae0562013-12-14 00:40:05 +00001271 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +00001272 llvm::Value *NextPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001273 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1274 "array.next");
Richard Smith06a67e22014-06-03 06:58:52 +00001275
John McCall99210dc2011-09-15 06:49:18 +00001276 // Check whether we've gotten to the end of the array and, if so,
1277 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001278 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1279 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1280 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001281
Richard Smith06a67e22014-06-03 06:58:52 +00001282 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001283}
1284
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001285static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
David Blaikiefb901c7a2015-04-04 15:12:29 +00001286 QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +00001287 Address NewPtr, llvm::Value *NumElements,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001288 llvm::Value *AllocSizeWithoutCookie) {
David Blaikie9b479662015-01-25 01:19:10 +00001289 ApplyDebugLocation DL(CGF, E);
Richard Smith06a67e22014-06-03 06:58:52 +00001290 if (E->isArray())
David Blaikiefb901c7a2015-04-04 15:12:29 +00001291 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
Richard Smith06a67e22014-06-03 06:58:52 +00001292 AllocSizeWithoutCookie);
1293 else if (const Expr *Init = E->getInitializer())
Richard Smithe78fac52018-04-05 20:52:58 +00001294 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
1295 AggValueSlot::DoesNotOverlap);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001296}
1297
Richard Smith8d0dc312013-07-21 23:12:18 +00001298/// Emit a call to an operator new or operator delete function, as implicitly
1299/// created by new-expressions and delete-expressions.
1300static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
John McCallb92ab1a2016-10-26 23:46:34 +00001301 const FunctionDecl *CalleeDecl,
Richard Smith8d0dc312013-07-21 23:12:18 +00001302 const FunctionProtoType *CalleeType,
1303 const CallArgList &Args) {
James Y Knight3933add2019-01-30 02:54:28 +00001304 llvm::CallBase *CallOrInvoke;
John McCallb92ab1a2016-10-26 23:46:34 +00001305 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
Erich Keanede6480a32018-11-13 15:48:08 +00001306 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
Richard Smith8d0dc312013-07-21 23:12:18 +00001307 RValue RV =
Peter Collingbournef7706832014-12-12 23:41:25 +00001308 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001309 Args, CalleeType, /*ChainCall=*/false),
John McCallb92ab1a2016-10-26 23:46:34 +00001310 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
Richard Smith8d0dc312013-07-21 23:12:18 +00001311
1312 /// C++1y [expr.new]p10:
1313 /// [In a new-expression,] an implementation is allowed to omit a call
1314 /// to a replaceable global allocation function.
1315 ///
1316 /// We model such elidable calls with the 'builtin' attribute.
John McCallb92ab1a2016-10-26 23:46:34 +00001317 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1318 if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001319 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
James Y Knight3933add2019-01-30 02:54:28 +00001320 CallOrInvoke->addAttribute(llvm::AttributeList::FunctionIndex,
1321 llvm::Attribute::Builtin);
Richard Smith8d0dc312013-07-21 23:12:18 +00001322 }
1323
1324 return RV;
1325}
1326
Richard Smith760520b2014-06-03 23:27:44 +00001327RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
Eric Fiselierfa752f22018-03-21 19:19:48 +00001328 const CallExpr *TheCall,
Richard Smith760520b2014-06-03 23:27:44 +00001329 bool IsDelete) {
1330 CallArgList Args;
Eric Fiselierfa752f22018-03-21 19:19:48 +00001331 EmitCallArgs(Args, Type->getParamTypes(), TheCall->arguments());
Richard Smith760520b2014-06-03 23:27:44 +00001332 // Find the allocation or deallocation function that we're calling.
1333 ASTContext &Ctx = getContext();
1334 DeclarationName Name = Ctx.DeclarationNames
1335 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
Eric Fiselierfa752f22018-03-21 19:19:48 +00001336
Richard Smith760520b2014-06-03 23:27:44 +00001337 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001338 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1339 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
Eric Fiselierfa752f22018-03-21 19:19:48 +00001340 return EmitNewDeleteCall(*this, FD, Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001341 llvm_unreachable("predeclared global operator new/delete is missing");
1342}
1343
Richard Smith5b349582017-10-13 01:55:36 +00001344namespace {
1345/// The parameters to pass to a usual operator delete.
1346struct UsualDeleteParams {
1347 bool DestroyingDelete = false;
1348 bool Size = false;
1349 bool Alignment = false;
1350};
1351}
1352
1353static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1354 UsualDeleteParams Params;
1355
1356 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00001357 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
Richard Smith189e52f2016-10-10 06:42:31 +00001358
Richard Smithb2f0f052016-10-10 18:54:32 +00001359 // The first argument is always a void*.
1360 ++AI;
1361
Richard Smith5b349582017-10-13 01:55:36 +00001362 // The next parameter may be a std::destroying_delete_t.
1363 if (FD->isDestroyingOperatorDelete()) {
1364 Params.DestroyingDelete = true;
1365 assert(AI != AE);
1366 ++AI;
1367 }
Richard Smithb2f0f052016-10-10 18:54:32 +00001368
Richard Smith5b349582017-10-13 01:55:36 +00001369 // Figure out what other parameters we should be implicitly passing.
Richard Smithb2f0f052016-10-10 18:54:32 +00001370 if (AI != AE && (*AI)->isIntegerType()) {
Richard Smith5b349582017-10-13 01:55:36 +00001371 Params.Size = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001372 ++AI;
1373 }
1374
1375 if (AI != AE && (*AI)->isAlignValT()) {
Richard Smith5b349582017-10-13 01:55:36 +00001376 Params.Alignment = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001377 ++AI;
1378 }
1379
1380 assert(AI == AE && "unexpected usual deallocation function parameter");
Richard Smith5b349582017-10-13 01:55:36 +00001381 return Params;
Richard Smithb2f0f052016-10-10 18:54:32 +00001382}
1383
1384namespace {
1385 /// A cleanup to call the given 'operator delete' function upon abnormal
1386 /// exit from a new expression. Templated on a traits type that deals with
1387 /// ensuring that the arguments dominate the cleanup if necessary.
1388 template<typename Traits>
1389 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1390 /// Type used to hold llvm::Value*s.
1391 typedef typename Traits::ValueTy ValueTy;
1392 /// Type used to hold RValues.
1393 typedef typename Traits::RValueTy RValueTy;
1394 struct PlacementArg {
1395 RValueTy ArgValue;
1396 QualType ArgType;
1397 };
1398
1399 unsigned NumPlacementArgs : 31;
1400 unsigned PassAlignmentToPlacementDelete : 1;
1401 const FunctionDecl *OperatorDelete;
1402 ValueTy Ptr;
1403 ValueTy AllocSize;
1404 CharUnits AllocAlign;
1405
1406 PlacementArg *getPlacementArgs() {
1407 return reinterpret_cast<PlacementArg *>(this + 1);
1408 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00001409
1410 public:
1411 static size_t getExtraSize(size_t NumPlacementArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001412 return NumPlacementArgs * sizeof(PlacementArg);
Daniel Jaspere9abe642016-10-10 14:13:55 +00001413 }
1414
1415 CallDeleteDuringNew(size_t NumPlacementArgs,
Richard Smithb2f0f052016-10-10 18:54:32 +00001416 const FunctionDecl *OperatorDelete, ValueTy Ptr,
1417 ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1418 CharUnits AllocAlign)
1419 : NumPlacementArgs(NumPlacementArgs),
1420 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1421 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1422 AllocAlign(AllocAlign) {}
Daniel Jaspere9abe642016-10-10 14:13:55 +00001423
Richard Smithb2f0f052016-10-10 18:54:32 +00001424 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
Daniel Jaspere9abe642016-10-10 14:13:55 +00001425 assert(I < NumPlacementArgs && "index out of range");
Richard Smithb2f0f052016-10-10 18:54:32 +00001426 getPlacementArgs()[I] = {Arg, Type};
Daniel Jaspere9abe642016-10-10 14:13:55 +00001427 }
1428
1429 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001430 const FunctionProtoType *FPT =
1431 OperatorDelete->getType()->getAs<FunctionProtoType>();
Daniel Jaspere9abe642016-10-10 14:13:55 +00001432 CallArgList DeleteArgs;
1433
Richard Smith5b349582017-10-13 01:55:36 +00001434 // The first argument is always a void* (or C* for a destroying operator
1435 // delete for class type C).
Richard Smithb2f0f052016-10-10 18:54:32 +00001436 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
Daniel Jaspere9abe642016-10-10 14:13:55 +00001437
Richard Smithb2f0f052016-10-10 18:54:32 +00001438 // Figure out what other parameters we should be implicitly passing.
Richard Smith5b349582017-10-13 01:55:36 +00001439 UsualDeleteParams Params;
Richard Smithb2f0f052016-10-10 18:54:32 +00001440 if (NumPlacementArgs) {
1441 // A placement deallocation function is implicitly passed an alignment
1442 // if the placement allocation function was, but is never passed a size.
Richard Smith5b349582017-10-13 01:55:36 +00001443 Params.Alignment = PassAlignmentToPlacementDelete;
Richard Smithb2f0f052016-10-10 18:54:32 +00001444 } else {
1445 // For a non-placement new-expression, 'operator delete' can take a
1446 // size and/or an alignment if it has the right parameters.
Richard Smith5b349582017-10-13 01:55:36 +00001447 Params = getUsualDeleteParams(OperatorDelete);
John McCall7f9c92a2010-09-17 00:50:28 +00001448 }
1449
Richard Smith5b349582017-10-13 01:55:36 +00001450 assert(!Params.DestroyingDelete &&
1451 "should not call destroying delete in a new-expression");
1452
Richard Smithb2f0f052016-10-10 18:54:32 +00001453 // The second argument can be a std::size_t (for non-placement delete).
Richard Smith5b349582017-10-13 01:55:36 +00001454 if (Params.Size)
Richard Smithb2f0f052016-10-10 18:54:32 +00001455 DeleteArgs.add(Traits::get(CGF, AllocSize),
1456 CGF.getContext().getSizeType());
1457
1458 // The next (second or third) argument can be a std::align_val_t, which
1459 // is an enum whose underlying type is std::size_t.
1460 // FIXME: Use the right type as the parameter type. Note that in a call
1461 // to operator delete(size_t, ...), we may not have it available.
Richard Smith5b349582017-10-13 01:55:36 +00001462 if (Params.Alignment)
Richard Smithb2f0f052016-10-10 18:54:32 +00001463 DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1464 CGF.SizeTy, AllocAlign.getQuantity())),
1465 CGF.getContext().getSizeType());
1466
John McCall7f9c92a2010-09-17 00:50:28 +00001467 // Pass the rest of the arguments, which must match exactly.
1468 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001469 auto Arg = getPlacementArgs()[I];
1470 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
John McCall7f9c92a2010-09-17 00:50:28 +00001471 }
1472
1473 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001474 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001475 }
1476 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001477}
John McCall7f9c92a2010-09-17 00:50:28 +00001478
1479/// Enter a cleanup to call 'operator delete' if the initializer in a
1480/// new-expression throws.
1481static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1482 const CXXNewExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001483 Address NewPtr,
John McCall7f9c92a2010-09-17 00:50:28 +00001484 llvm::Value *AllocSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00001485 CharUnits AllocAlign,
John McCall7f9c92a2010-09-17 00:50:28 +00001486 const CallArgList &NewArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001487 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1488
John McCall7f9c92a2010-09-17 00:50:28 +00001489 // If we're not inside a conditional branch, then the cleanup will
1490 // dominate and we can do the easier (and more efficient) thing.
1491 if (!CGF.isInConditionalBranch()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001492 struct DirectCleanupTraits {
1493 typedef llvm::Value *ValueTy;
1494 typedef RValue RValueTy;
1495 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1496 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1497 };
1498
1499 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1500
1501 DirectCleanup *Cleanup = CGF.EHStack
1502 .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1503 E->getNumPlacementArgs(),
1504 E->getOperatorDelete(),
1505 NewPtr.getPointer(),
1506 AllocSize,
1507 E->passAlignment(),
1508 AllocAlign);
1509 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1510 auto &Arg = NewArgs[I + NumNonPlacementArgs];
Yaxun Liu5b330e82018-03-15 15:25:19 +00001511 Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
Richard Smithb2f0f052016-10-10 18:54:32 +00001512 }
John McCall7f9c92a2010-09-17 00:50:28 +00001513
1514 return;
1515 }
1516
1517 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001518 DominatingValue<RValue>::saved_type SavedNewPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001519 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
John McCallcb5f77f2011-01-28 10:53:53 +00001520 DominatingValue<RValue>::saved_type SavedAllocSize =
1521 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001522
Richard Smithb2f0f052016-10-10 18:54:32 +00001523 struct ConditionalCleanupTraits {
1524 typedef DominatingValue<RValue>::saved_type ValueTy;
1525 typedef DominatingValue<RValue>::saved_type RValueTy;
1526 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1527 return V.restore(CGF);
1528 }
1529 };
1530 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1531
1532 ConditionalCleanup *Cleanup = CGF.EHStack
1533 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1534 E->getNumPlacementArgs(),
1535 E->getOperatorDelete(),
1536 SavedNewPtr,
1537 SavedAllocSize,
1538 E->passAlignment(),
1539 AllocAlign);
1540 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1541 auto &Arg = NewArgs[I + NumNonPlacementArgs];
Yaxun Liu5b330e82018-03-15 15:25:19 +00001542 Cleanup->setPlacementArg(
1543 I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
Richard Smithb2f0f052016-10-10 18:54:32 +00001544 }
John McCall7f9c92a2010-09-17 00:50:28 +00001545
John McCallf4beacd2011-11-10 10:43:54 +00001546 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001547}
1548
Anders Carlssoncc52f652009-09-22 22:53:17 +00001549llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001550 // The element type being allocated.
1551 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001552
John McCall75f94982011-03-07 03:12:35 +00001553 // 1. Build a call to the allocation function.
1554 FunctionDecl *allocator = E->getOperatorNew();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001555
Sebastian Redlf862eb62012-02-22 17:37:52 +00001556 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1557 unsigned minElements = 0;
1558 if (E->isArray() && E->hasInitializer()) {
Richard Smith0511d232016-10-05 22:41:02 +00001559 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1560 if (ILE && ILE->isStringLiteralInit())
1561 minElements =
1562 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1563 ->getSize().getZExtValue();
1564 else if (ILE)
Sebastian Redlf862eb62012-02-22 17:37:52 +00001565 minElements = ILE->getNumInits();
1566 }
1567
Craig Topper8a13c412014-05-21 05:09:00 +00001568 llvm::Value *numElements = nullptr;
1569 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001570 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001571 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1572 allocSizeWithoutCookie);
Richard Smithb2f0f052016-10-10 18:54:32 +00001573 CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001574
John McCall7ec4b432011-05-16 01:05:12 +00001575 // Emit the allocation call. If the allocator is a global placement
1576 // operator, just "inline" it directly.
John McCall7f416cc2015-09-08 08:05:57 +00001577 Address allocation = Address::invalid();
1578 CallArgList allocatorArgs;
John McCall7ec4b432011-05-16 01:05:12 +00001579 if (allocator->isReservedGlobalPlacementOperator()) {
John McCall53dcf942015-09-29 23:55:17 +00001580 assert(E->getNumPlacementArgs() == 1);
1581 const Expr *arg = *E->placement_arguments().begin();
1582
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001583 LValueBaseInfo BaseInfo;
1584 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001585
1586 // The pointer expression will, in many cases, be an opaque void*.
1587 // In these cases, discard the computed alignment and use the
1588 // formal alignment of the allocated type.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001589 if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
Richard Smithb2f0f052016-10-10 18:54:32 +00001590 allocation = Address(allocation.getPointer(), allocAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001591
John McCall53dcf942015-09-29 23:55:17 +00001592 // Set up allocatorArgs for the call to operator delete if it's not
1593 // the reserved global operator.
1594 if (E->getOperatorDelete() &&
1595 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1596 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1597 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1598 }
1599
John McCall7ec4b432011-05-16 01:05:12 +00001600 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001601 const FunctionProtoType *allocatorType =
1602 allocator->getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00001603 unsigned ParamsToSkip = 0;
John McCall7f416cc2015-09-08 08:05:57 +00001604
1605 // The allocation size is the first argument.
1606 QualType sizeType = getContext().getSizeType();
1607 allocatorArgs.add(RValue::get(allocSize), sizeType);
Richard Smithb2f0f052016-10-10 18:54:32 +00001608 ++ParamsToSkip;
John McCall7f416cc2015-09-08 08:05:57 +00001609
Richard Smithb2f0f052016-10-10 18:54:32 +00001610 if (allocSize != allocSizeWithoutCookie) {
1611 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1612 allocAlign = std::max(allocAlign, cookieAlign);
1613 }
1614
1615 // The allocation alignment may be passed as the second argument.
1616 if (E->passAlignment()) {
1617 QualType AlignValT = sizeType;
1618 if (allocatorType->getNumParams() > 1) {
1619 AlignValT = allocatorType->getParamType(1);
1620 assert(getContext().hasSameUnqualifiedType(
1621 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1622 sizeType) &&
1623 "wrong type for alignment parameter");
1624 ++ParamsToSkip;
1625 } else {
1626 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1627 assert(allocator->isVariadic() && "can't pass alignment to allocator");
1628 }
1629 allocatorArgs.add(
1630 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1631 AlignValT);
1632 }
1633
1634 // FIXME: Why do we not pass a CalleeDecl here?
John McCall7f416cc2015-09-08 08:05:57 +00001635 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
Vedant Kumared00ea02017-03-06 05:28:22 +00001636 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
John McCall7f416cc2015-09-08 08:05:57 +00001637
1638 RValue RV =
1639 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1640
Richard Smithb2f0f052016-10-10 18:54:32 +00001641 // If this was a call to a global replaceable allocation function that does
1642 // not take an alignment argument, the allocator is known to produce
1643 // storage that's suitably aligned for any object that fits, up to a known
1644 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1645 CharUnits allocationAlign = allocAlign;
1646 if (!E->passAlignment() &&
1647 allocator->isReplaceableGlobalAllocationFunction()) {
1648 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1649 Target.getNewAlign(), getContext().getTypeSize(allocType)));
1650 allocationAlign = std::max(
1651 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
John McCall7f416cc2015-09-08 08:05:57 +00001652 }
1653
1654 allocation = Address(RV.getScalarVal(), allocationAlign);
John McCall7ec4b432011-05-16 01:05:12 +00001655 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001656
John McCall75f94982011-03-07 03:12:35 +00001657 // Emit a null check on the allocation result if the allocation
1658 // function is allowed to return null (because it has a non-throwing
Richard Smith902a0232015-02-14 01:52:20 +00001659 // exception spec or is the reserved placement new) and we have an
Richard Smith2f72a752019-01-10 00:03:29 +00001660 // interesting initializer will be running sanitizers on the initialization.
Bruno Ricci9b6dfac2019-01-07 15:04:45 +00001661 bool nullCheck = E->shouldNullCheckAllocation() &&
Richard Smith2f72a752019-01-10 00:03:29 +00001662 (!allocType.isPODType(getContext()) || E->hasInitializer() ||
1663 sanitizePerformTypeCheck());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001664
Craig Topper8a13c412014-05-21 05:09:00 +00001665 llvm::BasicBlock *nullCheckBB = nullptr;
1666 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001667
John McCallf7dcf322011-03-07 01:52:56 +00001668 // The null-check means that the initializer is conditionally
1669 // evaluated.
1670 ConditionalEvaluation conditional(*this);
1671
John McCall75f94982011-03-07 03:12:35 +00001672 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001673 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001674
1675 nullCheckBB = Builder.GetInsertBlock();
1676 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1677 contBB = createBasicBlock("new.cont");
1678
John McCall7f416cc2015-09-08 08:05:57 +00001679 llvm::Value *isNull =
1680 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
John McCall75f94982011-03-07 03:12:35 +00001681 Builder.CreateCondBr(isNull, contBB, notNullBB);
1682 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001683 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001684
John McCall824c2f52010-09-14 07:57:04 +00001685 // If there's an operator delete, enter a cleanup to call it if an
1686 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001687 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001688 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001689 if (E->getOperatorDelete() &&
1690 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001691 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1692 allocatorArgs);
John McCall75f94982011-03-07 03:12:35 +00001693 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001694 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001695 }
1696
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001697 assert((allocSize == allocSizeWithoutCookie) ==
1698 CalculateCookiePadding(*this, E).isZero());
1699 if (allocSize != allocSizeWithoutCookie) {
1700 assert(E->isArray());
1701 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1702 numElements,
1703 E, allocType);
1704 }
1705
David Blaikiefb901c7a2015-04-04 15:12:29 +00001706 llvm::Type *elementTy = ConvertTypeForMem(allocType);
John McCall7f416cc2015-09-08 08:05:57 +00001707 Address result = Builder.CreateElementBitCast(allocation, elementTy);
John McCall824c2f52010-09-14 07:57:04 +00001708
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001709 // Passing pointer through launder.invariant.group to avoid propagation of
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001710 // vptrs information which may be included in previous type.
Piotr Padlewski31fd99c2017-05-20 08:56:18 +00001711 // To not break LTO with different optimizations levels, we do it regardless
1712 // of optimization level.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001713 if (CGM.getCodeGenOpts().StrictVTablePointers &&
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001714 allocator->isReservedGlobalPlacementOperator())
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001715 result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()),
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001716 result.getAlignment());
1717
Serge Pavlov37605182018-07-28 15:33:03 +00001718 // Emit sanitizer checks for pointer value now, so that in the case of an
Richard Smithcfa79b22019-01-23 03:37:29 +00001719 // array it was checked only once and not at each constructor call. We may
1720 // have already checked that the pointer is non-null.
1721 // FIXME: If we have an array cookie and a potentially-throwing allocator,
1722 // we'll null check the wrong pointer here.
1723 SanitizerSet SkippedChecks;
1724 SkippedChecks.set(SanitizerKind::Null, nullCheck);
Serge Pavlov37605182018-07-28 15:33:03 +00001725 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
Richard Smithcfa79b22019-01-23 03:37:29 +00001726 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1727 result.getPointer(), allocType, result.getAlignment(),
1728 SkippedChecks, numElements);
Serge Pavlov37605182018-07-28 15:33:03 +00001729
David Blaikiefb901c7a2015-04-04 15:12:29 +00001730 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
John McCall99210dc2011-09-15 06:49:18 +00001731 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001732 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001733 // NewPtr is a pointer to the base element type. If we're
1734 // allocating an array of arrays, we'll need to cast back to the
1735 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001736 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001737 if (result.getType() != resultType)
John McCall75f94982011-03-07 03:12:35 +00001738 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001739 }
John McCall824c2f52010-09-14 07:57:04 +00001740
1741 // Deactivate the 'operator delete' cleanup if we finished
1742 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001743 if (operatorDeleteCleanup.isValid()) {
1744 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1745 cleanupDominator->eraseFromParent();
1746 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001747
John McCall7f416cc2015-09-08 08:05:57 +00001748 llvm::Value *resultPtr = result.getPointer();
John McCall75f94982011-03-07 03:12:35 +00001749 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001750 conditional.end(*this);
1751
John McCall75f94982011-03-07 03:12:35 +00001752 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1753 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001754
John McCall7f416cc2015-09-08 08:05:57 +00001755 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1756 PHI->addIncoming(resultPtr, notNullBB);
1757 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
John McCall75f94982011-03-07 03:12:35 +00001758 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001759
John McCall7f416cc2015-09-08 08:05:57 +00001760 resultPtr = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001761 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001762
John McCall7f416cc2015-09-08 08:05:57 +00001763 return resultPtr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001764}
1765
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001766void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
Richard Smithb2f0f052016-10-10 18:54:32 +00001767 llvm::Value *Ptr, QualType DeleteTy,
1768 llvm::Value *NumElements,
1769 CharUnits CookieSize) {
1770 assert((!NumElements && CookieSize.isZero()) ||
1771 DeleteFD->getOverloadedOperator() == OO_Array_Delete);
John McCall8ed55a52010-09-02 09:58:18 +00001772
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001773 const FunctionProtoType *DeleteFTy =
1774 DeleteFD->getType()->getAs<FunctionProtoType>();
1775
1776 CallArgList DeleteArgs;
1777
Richard Smith5b349582017-10-13 01:55:36 +00001778 auto Params = getUsualDeleteParams(DeleteFD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001779 auto ParamTypeIt = DeleteFTy->param_type_begin();
1780
1781 // Pass the pointer itself.
1782 QualType ArgTy = *ParamTypeIt++;
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001783 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001784 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001785
Richard Smith5b349582017-10-13 01:55:36 +00001786 // Pass the std::destroying_delete tag if present.
1787 if (Params.DestroyingDelete) {
1788 QualType DDTag = *ParamTypeIt++;
1789 // Just pass an 'undef'. We expect the tag type to be an empty struct.
1790 auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
1791 DeleteArgs.add(RValue::get(V), DDTag);
1792 }
1793
Richard Smithb2f0f052016-10-10 18:54:32 +00001794 // Pass the size if the delete function has a size_t parameter.
Richard Smith5b349582017-10-13 01:55:36 +00001795 if (Params.Size) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001796 QualType SizeType = *ParamTypeIt++;
1797 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1798 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1799 DeleteTypeSize.getQuantity());
1800
1801 // For array new, multiply by the number of elements.
1802 if (NumElements)
1803 Size = Builder.CreateMul(Size, NumElements);
1804
1805 // If there is a cookie, add the cookie size.
1806 if (!CookieSize.isZero())
1807 Size = Builder.CreateAdd(
1808 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1809
1810 DeleteArgs.add(RValue::get(Size), SizeType);
1811 }
1812
1813 // Pass the alignment if the delete function has an align_val_t parameter.
Richard Smith5b349582017-10-13 01:55:36 +00001814 if (Params.Alignment) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001815 QualType AlignValType = *ParamTypeIt++;
1816 CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1817 getContext().getTypeAlignIfKnown(DeleteTy));
1818 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1819 DeleteTypeAlign.getQuantity());
1820 DeleteArgs.add(RValue::get(Align), AlignValType);
1821 }
1822
1823 assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1824 "unknown parameter to usual delete function");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001825
1826 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001827 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001828}
1829
John McCall8ed55a52010-09-02 09:58:18 +00001830namespace {
1831 /// Calls the given 'operator delete' on a single object.
David Blaikie7e70d682015-08-18 22:40:54 +00001832 struct CallObjectDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001833 llvm::Value *Ptr;
1834 const FunctionDecl *OperatorDelete;
1835 QualType ElementType;
1836
1837 CallObjectDelete(llvm::Value *Ptr,
1838 const FunctionDecl *OperatorDelete,
1839 QualType ElementType)
1840 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1841
Craig Topper4f12f102014-03-12 06:41:41 +00001842 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001843 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1844 }
1845 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001846}
John McCall8ed55a52010-09-02 09:58:18 +00001847
David Majnemer0c0b6d92014-10-31 20:09:12 +00001848void
1849CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1850 llvm::Value *CompletePtr,
1851 QualType ElementType) {
1852 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1853 OperatorDelete, ElementType);
1854}
1855
Richard Smith5b349582017-10-13 01:55:36 +00001856/// Emit the code for deleting a single object with a destroying operator
1857/// delete. If the element type has a non-virtual destructor, Ptr has already
1858/// been converted to the type of the parameter of 'operator delete'. Otherwise
1859/// Ptr points to an object of the static type.
1860static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1861 const CXXDeleteExpr *DE, Address Ptr,
1862 QualType ElementType) {
1863 auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1864 if (Dtor && Dtor->isVirtual())
1865 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1866 Dtor);
1867 else
1868 CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1869}
1870
John McCall8ed55a52010-09-02 09:58:18 +00001871/// Emit the code for deleting a single object.
1872static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001873 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001874 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001875 QualType ElementType) {
Ivan Krasind98f5d72016-11-17 00:39:48 +00001876 // C++11 [expr.delete]p3:
1877 // If the static type of the object to be deleted is different from its
1878 // dynamic type, the static type shall be a base class of the dynamic type
1879 // of the object to be deleted and the static type shall have a virtual
1880 // destructor or the behavior is undefined.
1881 CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1882 DE->getExprLoc(), Ptr.getPointer(),
1883 ElementType);
1884
Richard Smith5b349582017-10-13 01:55:36 +00001885 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1886 assert(!OperatorDelete->isDestroyingOperatorDelete());
1887
John McCall8ed55a52010-09-02 09:58:18 +00001888 // Find the destructor for the type, if applicable. If the
1889 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001890 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001891 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1892 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001893 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001894 Dtor = RD->getDestructor();
1895
1896 if (Dtor->isVirtual()) {
Hiroshi Yamauchicb305902019-08-08 18:00:49 +00001897 bool UseVirtualCall = true;
1898 const Expr *Base = DE->getArgument();
1899 if (auto *DevirtualizedDtor =
1900 dyn_cast_or_null<const CXXDestructorDecl>(
1901 Dtor->getDevirtualizedMethod(
1902 Base, CGF.CGM.getLangOpts().AppleKext))) {
1903 UseVirtualCall = false;
1904 const CXXRecordDecl *DevirtualizedClass =
1905 DevirtualizedDtor->getParent();
1906 if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1907 // Devirtualized to the class of the base type (the type of the
1908 // whole expression).
1909 Dtor = DevirtualizedDtor;
1910 } else {
1911 // Devirtualized to some other type. Would need to cast the this
1912 // pointer to that type but we don't have support for that yet, so
1913 // do a virtual call. FIXME: handle the case where it is
1914 // devirtualized to the derived type (the type of the inner
1915 // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1916 UseVirtualCall = true;
1917 }
1918 }
1919 if (UseVirtualCall) {
1920 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1921 Dtor);
1922 return;
1923 }
John McCall8ed55a52010-09-02 09:58:18 +00001924 }
1925 }
1926 }
1927
1928 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001929 // This doesn't have to a conditional cleanup because we're going
1930 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001931 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall7f416cc2015-09-08 08:05:57 +00001932 Ptr.getPointer(),
1933 OperatorDelete, ElementType);
John McCall8ed55a52010-09-02 09:58:18 +00001934
1935 if (Dtor)
1936 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001937 /*ForVirtualBase=*/false,
1938 /*Delegating=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00001939 Ptr, ElementType);
John McCall460ce582015-10-22 18:38:17 +00001940 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1941 switch (Lifetime) {
John McCall31168b02011-06-15 23:02:42 +00001942 case Qualifiers::OCL_None:
1943 case Qualifiers::OCL_ExplicitNone:
1944 case Qualifiers::OCL_Autoreleasing:
1945 break;
John McCall8ed55a52010-09-02 09:58:18 +00001946
John McCall7f416cc2015-09-08 08:05:57 +00001947 case Qualifiers::OCL_Strong:
1948 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001949 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001950
John McCall31168b02011-06-15 23:02:42 +00001951 case Qualifiers::OCL_Weak:
1952 CGF.EmitARCDestroyWeak(Ptr);
1953 break;
1954 }
1955 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001956
John McCall8ed55a52010-09-02 09:58:18 +00001957 CGF.PopCleanupBlock();
1958}
1959
1960namespace {
1961 /// Calls the given 'operator delete' on an array of objects.
David Blaikie7e70d682015-08-18 22:40:54 +00001962 struct CallArrayDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001963 llvm::Value *Ptr;
1964 const FunctionDecl *OperatorDelete;
1965 llvm::Value *NumElements;
1966 QualType ElementType;
1967 CharUnits CookieSize;
1968
1969 CallArrayDelete(llvm::Value *Ptr,
1970 const FunctionDecl *OperatorDelete,
1971 llvm::Value *NumElements,
1972 QualType ElementType,
1973 CharUnits CookieSize)
1974 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1975 ElementType(ElementType), CookieSize(CookieSize) {}
1976
Craig Topper4f12f102014-03-12 06:41:41 +00001977 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001978 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1979 CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001980 }
1981 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001982}
John McCall8ed55a52010-09-02 09:58:18 +00001983
1984/// Emit the code for deleting an array of objects.
1985static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001986 const CXXDeleteExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001987 Address deletedPtr,
John McCallca2c56f2011-07-13 01:41:37 +00001988 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001989 llvm::Value *numElements = nullptr;
1990 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001991 CharUnits cookieSize;
1992 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1993 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001994
John McCallca2c56f2011-07-13 01:41:37 +00001995 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001996
1997 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001998 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001999 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00002000 allocatedPtr, operatorDelete,
2001 numElements, elementType,
2002 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00002003
John McCallca2c56f2011-07-13 01:41:37 +00002004 // Destroy the elements.
2005 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
2006 assert(numElements && "no element count for a type with a destructor!");
2007
John McCall7f416cc2015-09-08 08:05:57 +00002008 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2009 CharUnits elementAlign =
2010 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
2011
2012 llvm::Value *arrayBegin = deletedPtr.getPointer();
John McCallca2c56f2011-07-13 01:41:37 +00002013 llvm::Value *arrayEnd =
John McCall7f416cc2015-09-08 08:05:57 +00002014 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00002015
2016 // Note that it is legal to allocate a zero-length array, and we
2017 // can never fold the check away because the length should always
2018 // come from a cookie.
John McCall7f416cc2015-09-08 08:05:57 +00002019 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
John McCallca2c56f2011-07-13 01:41:37 +00002020 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00002021 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00002022 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00002023 }
2024
John McCallca2c56f2011-07-13 01:41:37 +00002025 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00002026 CGF.PopCleanupBlock();
2027}
2028
Anders Carlssoncc52f652009-09-22 22:53:17 +00002029void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00002030 const Expr *Arg = E->getArgument();
John McCall7f416cc2015-09-08 08:05:57 +00002031 Address Ptr = EmitPointerWithAlignment(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00002032
2033 // Null check the pointer.
2034 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
2035 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
2036
John McCall7f416cc2015-09-08 08:05:57 +00002037 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00002038
2039 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
2040 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00002041
Richard Smith5b349582017-10-13 01:55:36 +00002042 QualType DeleteTy = E->getDestroyedType();
2043
2044 // A destroying operator delete overrides the entire operation of the
2045 // delete expression.
2046 if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
2047 EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
2048 EmitBlock(DeleteEnd);
2049 return;
2050 }
2051
John McCall8ed55a52010-09-02 09:58:18 +00002052 // We might be deleting a pointer to array. If so, GEP down to the
2053 // first non-array element.
2054 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
John McCall8ed55a52010-09-02 09:58:18 +00002055 if (DeleteTy->isConstantArrayType()) {
2056 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002057 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00002058
2059 GEP.push_back(Zero); // point at the outermost array
2060
2061 // For each layer of array type we're pointing at:
2062 while (const ConstantArrayType *Arr
2063 = getContext().getAsConstantArrayType(DeleteTy)) {
2064 // 1. Unpeel the array type.
2065 DeleteTy = Arr->getElementType();
2066
2067 // 2. GEP to the first element of the array.
2068 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00002069 }
John McCall8ed55a52010-09-02 09:58:18 +00002070
John McCall7f416cc2015-09-08 08:05:57 +00002071 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
2072 Ptr.getAlignment());
Anders Carlssoncc52f652009-09-22 22:53:17 +00002073 }
2074
John McCall7f416cc2015-09-08 08:05:57 +00002075 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00002076
Reid Kleckner7270ef52015-03-19 17:03:58 +00002077 if (E->isArrayForm()) {
2078 EmitArrayDelete(*this, E, Ptr, DeleteTy);
2079 } else {
2080 EmitObjectDelete(*this, E, Ptr, DeleteTy);
2081 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00002082
Anders Carlssoncc52f652009-09-22 22:53:17 +00002083 EmitBlock(DeleteEnd);
2084}
Mike Stumpc9b231c2009-11-15 08:09:41 +00002085
David Majnemer1c3d95e2014-07-19 00:17:06 +00002086static bool isGLValueFromPointerDeref(const Expr *E) {
2087 E = E->IgnoreParens();
2088
2089 if (const auto *CE = dyn_cast<CastExpr>(E)) {
2090 if (!CE->getSubExpr()->isGLValue())
2091 return false;
2092 return isGLValueFromPointerDeref(CE->getSubExpr());
2093 }
2094
2095 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2096 return isGLValueFromPointerDeref(OVE->getSourceExpr());
2097
2098 if (const auto *BO = dyn_cast<BinaryOperator>(E))
2099 if (BO->getOpcode() == BO_Comma)
2100 return isGLValueFromPointerDeref(BO->getRHS());
2101
2102 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2103 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2104 isGLValueFromPointerDeref(ACO->getFalseExpr());
2105
2106 // C++11 [expr.sub]p1:
2107 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2108 if (isa<ArraySubscriptExpr>(E))
2109 return true;
2110
2111 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2112 if (UO->getOpcode() == UO_Deref)
2113 return true;
2114
2115 return false;
2116}
2117
Warren Hunt747e3012014-06-18 21:15:55 +00002118static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00002119 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00002120 // Get the vtable pointer.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002121 Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002122
Stephan Bergmannd71ad172017-12-28 12:45:41 +00002123 QualType SrcRecordTy = E->getType();
2124
2125 // C++ [class.cdtor]p4:
2126 // If the operand of typeid refers to the object under construction or
2127 // destruction and the static type of the operand is neither the constructor
2128 // or destructor’s class nor one of its bases, the behavior is undefined.
2129 CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2130 ThisPtr.getPointer(), SrcRecordTy);
2131
Anders Carlsson940f02d2011-04-18 00:57:03 +00002132 // C++ [expr.typeid]p2:
2133 // If the glvalue expression is obtained by applying the unary * operator to
2134 // a pointer and the pointer is a null pointer value, the typeid expression
2135 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00002136 //
2137 // However, this paragraph's intent is not clear. We choose a very generous
2138 // interpretation which implores us to consider comma operators, conditional
2139 // operators, parentheses and other such constructs.
David Majnemer1c3d95e2014-07-19 00:17:06 +00002140 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2141 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00002142 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00002143 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00002144 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00002145
John McCall7f416cc2015-09-08 08:05:57 +00002146 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
David Majnemer1162d252014-06-22 19:05:33 +00002147 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002148
David Majnemer1162d252014-06-22 19:05:33 +00002149 CGF.EmitBlock(BadTypeidBlock);
2150 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2151 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002152 }
2153
David Majnemer1162d252014-06-22 19:05:33 +00002154 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2155 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002156}
2157
John McCalle4df6c82011-01-28 08:37:24 +00002158llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002159 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00002160 ConvertType(E->getType())->getPointerTo();
Fangrui Song6907ce22018-07-30 19:24:48 +00002161
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002162 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00002163 llvm::Constant *TypeInfo =
2164 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00002165 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002166 }
Anders Carlsson0c633502011-04-11 14:13:40 +00002167
Anders Carlsson940f02d2011-04-18 00:57:03 +00002168 // C++ [expr.typeid]p2:
2169 // When typeid is applied to a glvalue expression whose type is a
2170 // polymorphic class type, the result refers to a std::type_info object
2171 // representing the type of the most derived object (that is, the dynamic
2172 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00002173 if (E->isPotentiallyEvaluated())
Fangrui Song6907ce22018-07-30 19:24:48 +00002174 return EmitTypeidFromVTable(*this, E->getExprOperand(),
Richard Smithef8bf432012-08-13 20:08:14 +00002175 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002176
2177 QualType OperandTy = E->getExprOperand()->getType();
2178 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2179 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00002180}
Mike Stump65511702009-11-16 06:50:58 +00002181
Anders Carlssonc1c99712011-04-11 01:45:29 +00002182static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2183 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002184 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00002185 if (DestTy->isPointerType())
2186 return llvm::Constant::getNullValue(DestLTy);
2187
2188 /// C++ [expr.dynamic.cast]p9:
2189 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00002190 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2191 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00002192
2193 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2194 return llvm::UndefValue::get(DestLTy);
2195}
2196
John McCall7f416cc2015-09-08 08:05:57 +00002197llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
Mike Stump65511702009-11-16 06:50:58 +00002198 const CXXDynamicCastExpr *DCE) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00002199 CGM.EmitExplicitCastExprType(DCE, this);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002200 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00002201
Anders Carlssonc1c99712011-04-11 01:45:29 +00002202 QualType SrcTy = DCE->getSubExpr()->getType();
2203
David Majnemer1162d252014-06-22 19:05:33 +00002204 // C++ [expr.dynamic.cast]p7:
2205 // If T is "pointer to cv void," then the result is a pointer to the most
2206 // derived object pointed to by v.
2207 const PointerType *DestPTy = DestTy->getAs<PointerType>();
2208
2209 bool isDynamicCastToVoid;
2210 QualType SrcRecordTy;
2211 QualType DestRecordTy;
2212 if (DestPTy) {
2213 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2214 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2215 DestRecordTy = DestPTy->getPointeeType();
2216 } else {
2217 isDynamicCastToVoid = false;
2218 SrcRecordTy = SrcTy;
2219 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2220 }
2221
Stephan Bergmannd71ad172017-12-28 12:45:41 +00002222 // C++ [class.cdtor]p5:
2223 // If the operand of the dynamic_cast refers to the object under
2224 // construction or destruction and the static type of the operand is not a
2225 // pointer to or object of the constructor or destructor’s own class or one
2226 // of its bases, the dynamic_cast results in undefined behavior.
2227 EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2228 SrcRecordTy);
2229
2230 if (DCE->isAlwaysNull())
2231 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2232 return T;
2233
David Majnemer1162d252014-06-22 19:05:33 +00002234 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2235
Fangrui Song6907ce22018-07-30 19:24:48 +00002236 // C++ [expr.dynamic.cast]p4:
Anders Carlsson882d7902011-04-11 00:46:40 +00002237 // If the value of v is a null pointer value in the pointer case, the result
2238 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00002239 bool ShouldNullCheckSrcValue =
2240 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2241 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00002242
2243 llvm::BasicBlock *CastNull = nullptr;
2244 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00002245 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Fangrui Song6907ce22018-07-30 19:24:48 +00002246
Anders Carlsson882d7902011-04-11 00:46:40 +00002247 if (ShouldNullCheckSrcValue) {
2248 CastNull = createBasicBlock("dynamic_cast.null");
2249 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2250
John McCall7f416cc2015-09-08 08:05:57 +00002251 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
Anders Carlsson882d7902011-04-11 00:46:40 +00002252 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2253 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00002254 }
2255
John McCall7f416cc2015-09-08 08:05:57 +00002256 llvm::Value *Value;
David Majnemer1162d252014-06-22 19:05:33 +00002257 if (isDynamicCastToVoid) {
John McCall7f416cc2015-09-08 08:05:57 +00002258 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002259 DestTy);
2260 } else {
2261 assert(DestRecordTy->isRecordType() &&
2262 "destination type must be a record type!");
John McCall7f416cc2015-09-08 08:05:57 +00002263 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002264 DestTy, DestRecordTy, CastEnd);
David Majnemer67528ea2015-11-23 03:01:14 +00002265 CastNotNull = Builder.GetInsertBlock();
David Majnemer1162d252014-06-22 19:05:33 +00002266 }
Anders Carlsson882d7902011-04-11 00:46:40 +00002267
2268 if (ShouldNullCheckSrcValue) {
2269 EmitBranch(CastEnd);
2270
2271 EmitBlock(CastNull);
2272 EmitBranch(CastEnd);
2273 }
2274
2275 EmitBlock(CastEnd);
2276
2277 if (ShouldNullCheckSrcValue) {
2278 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2279 PHI->addIncoming(Value, CastNotNull);
2280 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2281
2282 Value = PHI;
2283 }
2284
2285 return Value;
Mike Stump65511702009-11-16 06:50:58 +00002286}