1//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with code generation of C++ expressions
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCUDARuntime.h"
14#include "CGCXXABI.h"
15#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "ConstantEmitter.h"
19#include "TargetInfo.h"
20#include "clang/Basic/CodeGenOptions.h"
21#include "clang/CodeGen/CGFunctionInfo.h"
22#include "llvm/IR/Intrinsics.h"
23
24using namespace clang;
25using namespace CodeGen;
26
27namespace {
28struct MemberCallInfo {
29 RequiredArgs ReqArgs;
30 // Number of prefix arguments for the call. Ignores the `this` pointer.
31 unsigned PrefixSize;
32};
33} // namespace
34
35static MemberCallInfo
36commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, GlobalDecl GD,
37 llvm::Value *This, llvm::Value *ImplicitParam,
38 QualType ImplicitParamTy, const CallExpr *CE,
39 CallArgList &Args, CallArgList *RtlArgs) {
40 auto *MD = cast<CXXMethodDecl>(Val: GD.getDecl());
41
42 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
43 isa<CXXOperatorCallExpr>(CE));
44 assert(MD->isImplicitObjectMemberFunction() &&
45 "Trying to emit a member or operator call expr on a static method!");
46
47 // Push the this ptr.
48 const CXXRecordDecl *RD =
49 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(GD);
50 Args.add(rvalue: RValue::get(V: This), type: CGF.getTypes().DeriveThisType(RD, MD));
51
52 // If there is an implicit parameter (e.g. VTT), emit it.
53 if (ImplicitParam) {
54 Args.add(rvalue: RValue::get(V: ImplicitParam), type: ImplicitParamTy);
55 }
56
57 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
58 RequiredArgs required = RequiredArgs::forPrototypePlus(prototype: FPT, additional: Args.size());
59 unsigned PrefixSize = Args.size() - 1;
60
61 // And the rest of the call args.
62 if (RtlArgs) {
63 // Special case: if the caller emitted the arguments right-to-left already
64 // (prior to emitting the *this argument), we're done. This happens for
65 // assignment operators.
66 Args.addFrom(other: *RtlArgs);
67 } else if (CE) {
68 // Special case: skip first argument of CXXOperatorCall (it is "this").
69 unsigned ArgsToSkip = 0;
70 if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(Val: CE)) {
71 if (const auto *M = dyn_cast<CXXMethodDecl>(Val: Op->getCalleeDecl()))
72 ArgsToSkip =
73 static_cast<unsigned>(!M->isExplicitObjectMemberFunction());
74 }
75 CGF.EmitCallArgs(Args, Prototype: FPT, ArgRange: drop_begin(RangeOrContainer: CE->arguments(), N: ArgsToSkip),
76 AC: CE->getDirectCallee());
77 } else {
78 assert(
79 FPT->getNumParams() == 0 &&
80 "No CallExpr specified for function with non-zero number of arguments");
81 }
82 return {.ReqArgs: required, .PrefixSize: PrefixSize};
83}
84
85RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
86 const CXXMethodDecl *MD, const CGCallee &Callee,
87 ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
88 QualType ImplicitParamTy, const CallExpr *CE, CallArgList *RtlArgs,
89 llvm::CallBase **CallOrInvoke) {
90 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
91 CallArgList Args;
92 MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
93 CGF&: *this, GD: MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
94 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
95 args: Args, type: FPT, required: CallInfo.ReqArgs, numPrefixArgs: CallInfo.PrefixSize);
96 return EmitCall(CallInfo: FnInfo, Callee, ReturnValue, Args, CallOrInvoke,
97 IsMustTail: CE && CE == MustTailCall,
98 Loc: CE ? CE->getExprLoc() : SourceLocation());
99}
100
101RValue CodeGenFunction::EmitCXXDestructorCall(
102 GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
103 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
104 llvm::CallBase **CallOrInvoke) {
105 const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Val: Dtor.getDecl());
106
107 assert(!ThisTy.isNull());
108 assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
109 "Pointer/Object mixup");
110
111 LangAS SrcAS = ThisTy.getAddressSpace();
112 LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
113 if (SrcAS != DstAS) {
114 QualType DstTy = DtorDecl->getThisType();
115 llvm::Type *NewType = CGM.getTypes().ConvertType(T: DstTy);
116 This = performAddrSpaceCast(Src: This, DestTy: NewType);
117 }
118
119 CallArgList Args;
120 commonEmitCXXMemberOrOperatorCall(CGF&: *this, GD: Dtor, This, ImplicitParam,
121 ImplicitParamTy, CE, Args, RtlArgs: nullptr);
122 return EmitCall(CallInfo: CGM.getTypes().arrangeCXXStructorDeclaration(GD: Dtor), Callee,
123 ReturnValue: ReturnValueSlot(), Args, CallOrInvoke,
124 IsMustTail: CE && CE == MustTailCall,
125 Loc: CE ? CE->getExprLoc() : SourceLocation{});
126}
127
128RValue
129CodeGenFunction::EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
130 QualType DestroyedType = E->getDestroyedType();
131 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
132 // Automatic Reference Counting:
133 // If the pseudo-expression names a retainable object with weak or
134 // strong lifetime, the object shall be released.
135 Expr *BaseExpr = E->getBase();
136 Address BaseValue = Address::invalid();
137 Qualifiers BaseQuals;
138
139 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
140 if (E->isArrow()) {
141 BaseValue = EmitPointerWithAlignment(Addr: BaseExpr);
142 const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
143 BaseQuals = PTy->getPointeeType().getQualifiers();
144 } else {
145 LValue BaseLV = EmitLValue(E: BaseExpr);
146 BaseValue = BaseLV.getAddress();
147 QualType BaseTy = BaseExpr->getType();
148 BaseQuals = BaseTy.getQualifiers();
149 }
150
151 switch (DestroyedType.getObjCLifetime()) {
152 case Qualifiers::OCL_None:
153 case Qualifiers::OCL_ExplicitNone:
154 case Qualifiers::OCL_Autoreleasing:
155 break;
156
157 case Qualifiers::OCL_Strong:
158 EmitARCRelease(
159 value: Builder.CreateLoad(Addr: BaseValue, IsVolatile: DestroyedType.isVolatileQualified()),
160 precise: ARCPreciseLifetime);
161 break;
162
163 case Qualifiers::OCL_Weak:
164 EmitARCDestroyWeak(addr: BaseValue);
165 break;
166 }
167 } else {
168 // C++ [expr.pseudo]p1:
169 // The result shall only be used as the operand for the function call
170 // operator (), and the result of such a call has type void. The only
171 // effect is the evaluation of the postfix-expression before the dot or
172 // arrow.
173 EmitIgnoredExpr(E: E->getBase());
174 }
175
176 return RValue::get(V: nullptr);
177}
178
179static CXXRecordDecl *getCXXRecord(const Expr *E) {
180 QualType T = E->getType();
181 if (const PointerType *PTy = T->getAs<PointerType>())
182 T = PTy->getPointeeType();
183 return T->castAsCXXRecordDecl();
184}
185
186// Note: This function also emit constructor calls to support a MSVC
187// extensions allowing explicit constructor function call.
188RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
189 ReturnValueSlot ReturnValue,
190 llvm::CallBase **CallOrInvoke) {
191 const Expr *callee = CE->getCallee()->IgnoreParens();
192
193 if (isa<BinaryOperator>(Val: callee))
194 return EmitCXXMemberPointerCallExpr(E: CE, ReturnValue, CallOrInvoke);
195
196 const MemberExpr *ME = cast<MemberExpr>(Val: callee);
197 const CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: ME->getMemberDecl());
198
199 if (MD->isStatic()) {
200 // The method is static, emit it as we would a regular call.
201 CGCallee callee =
202 CGCallee::forDirect(functionPtr: CGM.GetAddrOfFunction(GD: MD), abstractInfo: GlobalDecl(MD));
203 return EmitCall(FnType: getContext().getPointerType(T: MD->getType()), Callee: callee, E: CE,
204 ReturnValue, /*Chain=*/nullptr, CallOrInvoke);
205 }
206
207 bool HasQualifier = ME->hasQualifier();
208 NestedNameSpecifier Qualifier = ME->getQualifier();
209 bool IsArrow = ME->isArrow();
210 const Expr *Base = ME->getBase();
211
212 return EmitCXXMemberOrOperatorMemberCallExpr(CE, MD, ReturnValue,
213 HasQualifier, Qualifier, IsArrow,
214 Base, CallOrInvoke);
215}
216
217RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
218 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
219 bool HasQualifier, NestedNameSpecifier Qualifier, bool IsArrow,
220 const Expr *Base, llvm::CallBase **CallOrInvoke) {
221 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
222
223 // Compute the object pointer.
224 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
225
226 const CXXMethodDecl *DevirtualizedMethod = nullptr;
227 if (CanUseVirtualCall &&
228 MD->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext)) {
229 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
230 DevirtualizedMethod = MD->getCorrespondingMethodInClass(RD: BestDynamicDecl);
231 assert(DevirtualizedMethod);
232 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
233 const Expr *Inner = Base->IgnoreParenBaseCasts();
234 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
235 MD->getReturnType().getCanonicalType())
236 // If the return types are not the same, this might be a case where more
237 // code needs to run to compensate for it. For example, the derived
238 // method might return a type that inherits form from the return
239 // type of MD and has a prefix.
240 // For now we just avoid devirtualizing these covariant cases.
241 DevirtualizedMethod = nullptr;
242 else if (getCXXRecord(E: Inner) == DevirtualizedClass)
243 // If the class of the Inner expression is where the dynamic method
244 // is defined, build the this pointer from it.
245 Base = Inner;
246 else if (getCXXRecord(E: Base) != DevirtualizedClass) {
247 // If the method is defined in a class that is not the best dynamic
248 // one or the one of the full expression, we would have to build
249 // a derived-to-base cast to compute the correct this pointer, but
250 // we don't have support for that yet, so do a virtual call.
251 DevirtualizedMethod = nullptr;
252 }
253 }
254
255 bool TrivialForCodegen =
256 MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
257 bool TrivialAssignment =
258 TrivialForCodegen &&
259 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
260 !MD->getParent()->mayInsertExtraPadding();
261
262 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
263 // operator before the LHS.
264 CallArgList RtlArgStorage;
265 CallArgList *RtlArgs = nullptr;
266 LValue TrivialAssignmentRHS;
267 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: CE)) {
268 if (OCE->isAssignmentOp()) {
269 if (TrivialAssignment) {
270 TrivialAssignmentRHS = EmitCheckedLValue(E: CE->getArg(Arg: 1), TCK: TCK_Load);
271 } else {
272 RtlArgs = &RtlArgStorage;
273 EmitCallArgs(Args&: *RtlArgs, Prototype: MD->getType()->castAs<FunctionProtoType>(),
274 ArgRange: drop_begin(RangeOrContainer: CE->arguments(), N: 1), AC: CE->getDirectCallee(),
275 /*ParamsToSkip*/ 0, Order: EvaluationOrder::ForceRightToLeft);
276 }
277 }
278 }
279
280 auto getLValueForThis = [this, IsArrow,
281 Base](bool EmitCheckedForStore = false) {
282 // FIXME: Respect EmitCheckedForStore for the IsArrow case.
283 if (IsArrow) {
284 LValueBaseInfo BaseInfo;
285 TBAAAccessInfo TBAAInfo;
286 Address ThisValue = EmitPointerWithAlignment(Addr: Base, BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo);
287 return MakeAddrLValue(Addr: ThisValue, T: Base->getType()->getPointeeType(),
288 BaseInfo, TBAAInfo);
289 }
290 if (EmitCheckedForStore)
291 return EmitCheckedLValue(E: Base, TCK: TCK_Store);
292 return EmitLValue(E: Base);
293 };
294
295 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD)) {
296 // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
297 // constructing a new complete object of type Ctor.
298 assert(!RtlArgs);
299 assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
300 LValue This = getLValueForThis();
301 CallArgList Args;
302 commonEmitCXXMemberOrOperatorCall(
303 CGF&: *this, GD: {Ctor, Ctor_Complete}, This: This.getPointer(CGF&: *this),
304 /*ImplicitParam=*/nullptr,
305 /*ImplicitParamTy=*/QualType(), CE, Args, RtlArgs: nullptr);
306
307 EmitCXXConstructorCall(D: Ctor, Type: Ctor_Complete, /*ForVirtualBase=*/false,
308 /*Delegating=*/false, This: This.getAddress(), Args,
309 Overlap: AggValueSlot::DoesNotOverlap, Loc: CE->getExprLoc(),
310 /*NewPointerIsChecked=*/false, CallOrInvoke);
311 return RValue::get(V: nullptr);
312 }
313
314 if (TrivialForCodegen) {
315 if (isa<CXXDestructorDecl>(Val: MD)) {
316 (void)getLValueForThis(); // Emit LHS for side effects.
317 return RValue::get(V: nullptr);
318 }
319
320 if (TrivialAssignment) {
321 // We don't like to generate the trivial copy/move assignment operator
322 // when it isn't necessary; just produce the proper effect here.
323 LValue This = getLValueForThis(/*EmitCheckedForStore=*/true);
324
325 // It's important that we use the result of EmitCheckedLValue here rather
326 // than emitting call arguments, in order to preserve TBAA information
327 // from the RHS.
328 LValue RHS = isa<CXXOperatorCallExpr>(Val: CE)
329 ? TrivialAssignmentRHS
330 : EmitCheckedLValue(E: *CE->arg_begin(), TCK: TCK_Load);
331 EmitAggregateAssign(Dest: This, Src: RHS, EltTy: CE->getType());
332 return RValue::get(V: This.getPointer(CGF&: *this));
333 }
334
335 assert(MD->getParent()->mayInsertExtraPadding() &&
336 "unknown trivial member function");
337 }
338
339 // Compute the function type we're calling.
340 const CXXMethodDecl *CalleeDecl =
341 DevirtualizedMethod ? DevirtualizedMethod : MD;
342 const CGFunctionInfo *FInfo = nullptr;
343 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: CalleeDecl))
344 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
345 GD: GlobalDecl(Dtor, Dtor_Complete));
346 else
347 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD: CalleeDecl);
348
349 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(Info: *FInfo);
350
351 // C++11 [class.mfct.non-static]p2:
352 // If a non-static member function of a class X is called for an object that
353 // is not of type X, or of a type derived from X, the behavior is undefined.
354 SourceLocation CallLoc;
355 ASTContext &C = getContext();
356 if (CE)
357 CallLoc = CE->getExprLoc();
358
359 SanitizerSet SkippedChecks;
360 if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(Val: CE)) {
361 auto *IOA = CMCE->getImplicitObjectArgument();
362 bool IsImplicitObjectCXXThis = IsWrappedCXXThis(E: IOA);
363 if (IsImplicitObjectCXXThis)
364 SkippedChecks.set(K: SanitizerKind::Alignment, Value: true);
365 if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(Val: IOA))
366 SkippedChecks.set(K: SanitizerKind::Null, Value: true);
367 }
368
369 LValue This = getLValueForThis();
370 if (sanitizePerformTypeCheck())
371 EmitTypeCheck(TCK: CodeGenFunction::TCK_MemberCall, Loc: CallLoc,
372 V: This.emitRawPointer(CGF&: *this),
373 Type: C.getCanonicalTagType(TD: CalleeDecl->getParent()),
374 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
375
376 // C++ [class.virtual]p12:
377 // Explicit qualification with the scope operator (5.1) suppresses the
378 // virtual call mechanism.
379 //
380 // We also don't emit a virtual call if the base expression has a record type
381 // because then we know what the type is.
382 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
383
384 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(Val: CalleeDecl)) {
385 assert(CE->arguments().empty() &&
386 "Destructor shouldn't have explicit parameters");
387 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
388 if (UseVirtualCall) {
389 CGM.getCXXABI().EmitVirtualDestructorCall(
390 CGF&: *this, Dtor, DtorType: Dtor_Complete, This: This.getAddress(),
391 E: cast<CXXMemberCallExpr>(Val: CE), CallOrInvoke);
392 } else {
393 GlobalDecl GD(Dtor, Dtor_Complete);
394 CGCallee Callee;
395 if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
396 Callee = BuildAppleKextVirtualCall(MD: Dtor, Qual: Qualifier, Ty);
397 else if (!DevirtualizedMethod)
398 Callee =
399 CGCallee::forDirect(functionPtr: CGM.getAddrOfCXXStructor(GD, FnInfo: FInfo, FnType: Ty), abstractInfo: GD);
400 else {
401 Callee = CGCallee::forDirect(functionPtr: CGM.GetAddrOfFunction(GD, Ty), abstractInfo: GD);
402 }
403
404 QualType ThisTy =
405 IsArrow ? Base->getType()->getPointeeType() : Base->getType();
406 EmitCXXDestructorCall(Dtor: GD, Callee, This: This.getPointer(CGF&: *this), ThisTy,
407 /*ImplicitParam=*/nullptr,
408 /*ImplicitParamTy=*/QualType(), CE, CallOrInvoke);
409 }
410 return RValue::get(V: nullptr);
411 }
412
413 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
414 // 'CalleeDecl' instead.
415
416 CGCallee Callee;
417 if (UseVirtualCall) {
418 Callee = CGCallee::forVirtual(CE, MD, Addr: This.getAddress(), FTy: Ty);
419 } else {
420 if (SanOpts.has(K: SanitizerKind::CFINVCall) &&
421 MD->getParent()->isDynamicClass()) {
422 llvm::Value *VTable;
423 const CXXRecordDecl *RD;
424 std::tie(args&: VTable, args&: RD) = CGM.getCXXABI().LoadVTablePtr(
425 CGF&: *this, This: This.getAddress(), RD: CalleeDecl->getParent());
426 EmitVTablePtrCheckForCall(RD, VTable, TCK: CFITCK_NVCall, Loc: CE->getBeginLoc());
427 }
428
429 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
430 Callee = BuildAppleKextVirtualCall(MD, Qual: Qualifier, Ty);
431 else if (!DevirtualizedMethod)
432 Callee =
433 CGCallee::forDirect(functionPtr: CGM.GetAddrOfFunction(GD: MD, Ty), abstractInfo: GlobalDecl(MD));
434 else {
435 Callee =
436 CGCallee::forDirect(functionPtr: CGM.GetAddrOfFunction(GD: DevirtualizedMethod, Ty),
437 abstractInfo: GlobalDecl(DevirtualizedMethod));
438 }
439 }
440
441 if (MD->isVirtual()) {
442 Address NewThisAddr =
443 CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
444 CGF&: *this, GD: CalleeDecl, This: This.getAddress(), VirtualCall: UseVirtualCall);
445 This.setAddress(NewThisAddr);
446 }
447
448 return EmitCXXMemberOrOperatorCall(
449 MD: CalleeDecl, Callee, ReturnValue, This: This.getPointer(CGF&: *this),
450 /*ImplicitParam=*/nullptr, ImplicitParamTy: QualType(), CE, RtlArgs, CallOrInvoke);
451}
452
453RValue
454CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
455 ReturnValueSlot ReturnValue,
456 llvm::CallBase **CallOrInvoke) {
457 const BinaryOperator *BO =
458 cast<BinaryOperator>(Val: E->getCallee()->IgnoreParens());
459 const Expr *BaseExpr = BO->getLHS();
460 const Expr *MemFnExpr = BO->getRHS();
461
462 const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
463 const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
464 const auto *RD = MPT->getMostRecentCXXRecordDecl();
465
466 // Emit the 'this' pointer.
467 Address This = Address::invalid();
468 if (BO->getOpcode() == BO_PtrMemI)
469 This = EmitPointerWithAlignment(Addr: BaseExpr, BaseInfo: nullptr, TBAAInfo: nullptr, IsKnownNonNull: KnownNonNull);
470 else
471 This = EmitLValue(E: BaseExpr, IsKnownNonNull: KnownNonNull).getAddress();
472
473 CanQualType ClassType = CGM.getContext().getCanonicalTagType(TD: RD);
474 EmitTypeCheck(TCK: TCK_MemberCall, Loc: E->getExprLoc(), V: This.emitRawPointer(CGF&: *this),
475 Type: ClassType);
476
477 // Get the member function pointer.
478 llvm::Value *MemFnPtr = EmitScalarExpr(E: MemFnExpr);
479
480 // Ask the ABI to load the callee. Note that This is modified.
481 llvm::Value *ThisPtrForCall = nullptr;
482 CGCallee Callee = CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(
483 CGF&: *this, E: BO, This, ThisPtrForCall, MemPtr: MemFnPtr, MPT);
484
485 CallArgList Args;
486
487 QualType ThisType = getContext().getPointerType(T: ClassType);
488
489 // Push the this ptr.
490 Args.add(rvalue: RValue::get(V: ThisPtrForCall), type: ThisType);
491
492 RequiredArgs required = RequiredArgs::forPrototypePlus(prototype: FPT, additional: 1);
493
494 // And the rest of the call args
495 EmitCallArgs(Args, Prototype: FPT, ArgRange: E->arguments());
496 return EmitCall(CallInfo: CGM.getTypes().arrangeCXXMethodCall(args: Args, type: FPT, required,
497 /*PrefixSize=*/numPrefixArgs: 0),
498 Callee, ReturnValue, Args, CallOrInvoke, IsMustTail: E == MustTailCall,
499 Loc: E->getExprLoc());
500}
501
502RValue CodeGenFunction::EmitCXXOperatorMemberCallExpr(
503 const CXXOperatorCallExpr *E, const CXXMethodDecl *MD,
504 ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke) {
505 assert(MD->isImplicitObjectMemberFunction() &&
506 "Trying to emit a member call expr on a static method!");
507 return EmitCXXMemberOrOperatorMemberCallExpr(
508 CE: E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/std::nullopt,
509 /*IsArrow=*/false, Base: E->getArg(Arg: 0), CallOrInvoke);
510}
511
512RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
513 ReturnValueSlot ReturnValue,
514 llvm::CallBase **CallOrInvoke) {
515 // Emit as a device kernel call if CUDA device code is to be generated.
516 // TODO: implement for HIP
517 if (!getLangOpts().HIP && getLangOpts().CUDAIsDevice)
518 return CGM.getCUDARuntime().EmitCUDADeviceKernelCallExpr(
519 CGF&: *this, E, ReturnValue, CallOrInvoke);
520 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(CGF&: *this, E, ReturnValue,
521 CallOrInvoke);
522}
523
524static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
525 Address DestPtr,
526 const CXXRecordDecl *Base) {
527 if (Base->isEmpty())
528 return;
529
530 DestPtr = DestPtr.withElementType(ElemTy: CGF.Int8Ty);
531
532 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(D: Base);
533 CharUnits NVSize = Layout.getNonVirtualSize();
534
535 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
536 // present, they are initialized by the most derived class before calling the
537 // constructor.
538 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
539 Stores.emplace_back(Args: CharUnits::Zero(), Args&: NVSize);
540
541 // Each store is split by the existence of a vbptr.
542 CharUnits VBPtrWidth = CGF.getPointerSize();
543 std::vector<CharUnits> VBPtrOffsets =
544 CGF.CGM.getCXXABI().getVBPtrOffsets(RD: Base);
545 for (CharUnits VBPtrOffset : VBPtrOffsets) {
546 // Stop before we hit any virtual base pointers located in virtual bases.
547 if (VBPtrOffset >= NVSize)
548 break;
549 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
550 CharUnits LastStoreOffset = LastStore.first;
551
552 CharUnits SplitBeforeOffset = LastStoreOffset;
553 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
554 assert(!SplitBeforeSize.isNegative() && "negative store size!");
555 if (!SplitBeforeSize.isZero())
556 Stores.emplace_back(Args&: SplitBeforeOffset, Args&: SplitBeforeSize);
557
558 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
559 CharUnits SplitAfterSize = NVSize - SplitAfterOffset;
560 assert(!SplitAfterSize.isNegative() && "negative store size!");
561 if (!SplitAfterSize.isZero())
562 Stores.emplace_back(Args&: SplitAfterOffset, Args&: SplitAfterSize);
563 }
564
565 // If the type contains a pointer to data member we can't memset it to zero.
566 // Instead, create a null constant and copy it to the destination.
567 // TODO: there are other patterns besides zero that we can usefully memset,
568 // like -1, which happens to be the pattern used by member-pointers.
569 // TODO: isZeroInitializable can be over-conservative in the case where a
570 // virtual base contains a member pointer.
571 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Record: Base);
572 if (!NullConstantForBase->isNullValue()) {
573 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
574 CGF.CGM.getModule(), NullConstantForBase->getType(),
575 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
576 NullConstantForBase, Twine());
577
578 CharUnits Align =
579 std::max(a: Layout.getNonVirtualAlignment(), b: DestPtr.getAlignment());
580 NullVariable->setAlignment(Align.getAsAlign());
581
582 Address SrcPtr(NullVariable, CGF.Int8Ty, Align);
583
584 // Get and call the appropriate llvm.memcpy overload.
585 for (std::pair<CharUnits, CharUnits> Store : Stores) {
586 CharUnits StoreOffset = Store.first;
587 CharUnits StoreSize = Store.second;
588 llvm::Value *StoreSizeVal = CGF.CGM.getSize(numChars: StoreSize);
589 CGF.Builder.CreateMemCpy(
590 Dest: CGF.Builder.CreateConstInBoundsByteGEP(Addr: DestPtr, Offset: StoreOffset),
591 Src: CGF.Builder.CreateConstInBoundsByteGEP(Addr: SrcPtr, Offset: StoreOffset),
592 Size: StoreSizeVal);
593 }
594
595 // Otherwise, just memset the whole thing to zero. This is legal
596 // because in LLVM, all default initializers (other than the ones we just
597 // handled above) are guaranteed to have a bit pattern of all zeros.
598 } else {
599 for (std::pair<CharUnits, CharUnits> Store : Stores) {
600 CharUnits StoreOffset = Store.first;
601 CharUnits StoreSize = Store.second;
602 llvm::Value *StoreSizeVal = CGF.CGM.getSize(numChars: StoreSize);
603 CGF.Builder.CreateMemSet(
604 Dest: CGF.Builder.CreateConstInBoundsByteGEP(Addr: DestPtr, Offset: StoreOffset),
605 Value: CGF.Builder.getInt8(C: 0), Size: StoreSizeVal);
606 }
607 }
608}
609
610void CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
611 AggValueSlot Dest) {
612 assert(!Dest.isIgnored() && "Must have a destination!");
613 const CXXConstructorDecl *CD = E->getConstructor();
614
615 // If we require zero initialization before (or instead of) calling the
616 // constructor, as can be the case with a non-user-provided default
617 // constructor, emit the zero initialization now, unless destination is
618 // already zeroed.
619 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
620 switch (E->getConstructionKind()) {
621 case CXXConstructionKind::Delegating:
622 case CXXConstructionKind::Complete:
623 EmitNullInitialization(DestPtr: Dest.getAddress(), Ty: E->getType());
624 break;
625 case CXXConstructionKind::VirtualBase:
626 case CXXConstructionKind::NonVirtualBase:
627 EmitNullBaseClassInitialization(CGF&: *this, DestPtr: Dest.getAddress(),
628 Base: CD->getParent());
629 break;
630 }
631 }
632
633 // If this is a call to a trivial default constructor, do nothing.
634 if (CD->isTrivial() && CD->isDefaultConstructor())
635 return;
636
637 // Elide the constructor if we're constructing from a temporary.
638 if (getLangOpts().ElideConstructors && E->isElidable()) {
639 // FIXME: This only handles the simplest case, where the source object
640 // is passed directly as the first argument to the constructor.
641 // This should also handle stepping though implicit casts and
642 // conversion sequences which involve two steps, with a
643 // conversion operator followed by a converting constructor.
644 const Expr *SrcObj = E->getArg(Arg: 0);
645 assert(SrcObj->isTemporaryObject(getContext(), CD->getParent()));
646 assert(
647 getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
648 EmitAggExpr(E: SrcObj, AS: Dest);
649 return;
650 }
651
652 if (const ArrayType *arrayType = getContext().getAsArrayType(T: E->getType())) {
653 EmitCXXAggrConstructorCall(D: CD, ArrayTy: arrayType, ArrayPtr: Dest.getAddress(), E,
654 NewPointerIsChecked: Dest.isSanitizerChecked());
655 } else {
656 CXXCtorType Type = Ctor_Complete;
657 bool ForVirtualBase = false;
658 bool Delegating = false;
659
660 switch (E->getConstructionKind()) {
661 case CXXConstructionKind::Delegating:
662 // We should be emitting a constructor; GlobalDecl will assert this
663 Type = CurGD.getCtorType();
664 Delegating = true;
665 break;
666
667 case CXXConstructionKind::Complete:
668 Type = Ctor_Complete;
669 break;
670
671 case CXXConstructionKind::VirtualBase:
672 ForVirtualBase = true;
673 [[fallthrough]];
674
675 case CXXConstructionKind::NonVirtualBase:
676 Type = Ctor_Base;
677 }
678
679 // Call the constructor.
680 EmitCXXConstructorCall(D: CD, Type, ForVirtualBase, Delegating, ThisAVS: Dest, E);
681 }
682}
683
684void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
685 const Expr *Exp) {
686 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Val: Exp))
687 Exp = E->getSubExpr();
688 assert(isa<CXXConstructExpr>(Exp) &&
689 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
690 const CXXConstructExpr *E = cast<CXXConstructExpr>(Val: Exp);
691 const CXXConstructorDecl *CD = E->getConstructor();
692 RunCleanupsScope Scope(*this);
693
694 // If we require zero initialization before (or instead of) calling the
695 // constructor, as can be the case with a non-user-provided default
696 // constructor, emit the zero initialization now.
697 // FIXME. Do I still need this for a copy ctor synthesis?
698 if (E->requiresZeroInitialization())
699 EmitNullInitialization(DestPtr: Dest, Ty: E->getType());
700
701 assert(!getContext().getAsConstantArrayType(E->getType()) &&
702 "EmitSynthesizedCXXCopyCtor - Copied-in Array");
703 EmitSynthesizedCXXCopyCtorCall(D: CD, This: Dest, Src, E);
704}
705
706static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
707 const CXXNewExpr *E) {
708 if (!E->isArray())
709 return CharUnits::Zero();
710
711 // No cookie is required if the operator new[] being used is the
712 // reserved placement operator new[].
713 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
714 return CharUnits::Zero();
715
716 return CGF.CGM.getCXXABI().GetArrayCookieSize(expr: E);
717}
718
719static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
720 const CXXNewExpr *e,
721 unsigned minElements,
722 llvm::Value *&numElements,
723 llvm::Value *&sizeWithoutCookie) {
724 QualType type = e->getAllocatedType();
725
726 if (!e->isArray()) {
727 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(T: type);
728 sizeWithoutCookie =
729 llvm::ConstantInt::get(Ty: CGF.SizeTy, V: typeSize.getQuantity());
730 return sizeWithoutCookie;
731 }
732
733 // The width of size_t.
734 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
735
736 // Figure out the cookie size.
737 llvm::APInt cookieSize(sizeWidth,
738 CalculateCookiePadding(CGF, E: e).getQuantity());
739
740 // Emit the array size expression.
741 // We multiply the size of all dimensions for NumElements.
742 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
743 numElements = ConstantEmitter(CGF).tryEmitAbstract(
744 E: *e->getArraySize(), T: (*e->getArraySize())->getType());
745 if (!numElements)
746 numElements = CGF.EmitScalarExpr(E: *e->getArraySize());
747 assert(isa<llvm::IntegerType>(numElements->getType()));
748
749 // The number of elements can be have an arbitrary integer type;
750 // essentially, we need to multiply it by a constant factor, add a
751 // cookie size, and verify that the result is representable as a
752 // size_t. That's just a gloss, though, and it's wrong in one
753 // important way: if the count is negative, it's an error even if
754 // the cookie size would bring the total size >= 0.
755 bool isSigned =
756 (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
757 llvm::IntegerType *numElementsType =
758 cast<llvm::IntegerType>(Val: numElements->getType());
759 unsigned numElementsWidth = numElementsType->getBitWidth();
760
761 // Compute the constant factor.
762 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
763 while (const ConstantArrayType *CAT =
764 CGF.getContext().getAsConstantArrayType(T: type)) {
765 type = CAT->getElementType();
766 arraySizeMultiplier *= CAT->getSize();
767 }
768
769 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(T: type);
770 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
771 typeSizeMultiplier *= arraySizeMultiplier;
772
773 // This will be a size_t.
774 llvm::Value *size;
775
776 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
777 // Don't bloat the -O0 code.
778 if (llvm::ConstantInt *numElementsC =
779 dyn_cast<llvm::ConstantInt>(Val: numElements)) {
780 const llvm::APInt &count = numElementsC->getValue();
781
782 bool hasAnyOverflow = false;
783
784 // If 'count' was a negative number, it's an overflow.
785 if (isSigned && count.isNegative())
786 hasAnyOverflow = true;
787
788 // We want to do all this arithmetic in size_t. If numElements is
789 // wider than that, check whether it's already too big, and if so,
790 // overflow.
791 else if (numElementsWidth > sizeWidth &&
792 numElementsWidth - sizeWidth > count.countl_zero())
793 hasAnyOverflow = true;
794
795 // Okay, compute a count at the right width.
796 llvm::APInt adjustedCount = count.zextOrTrunc(width: sizeWidth);
797
798 // If there is a brace-initializer, we cannot allocate fewer elements than
799 // there are initializers. If we do, that's treated like an overflow.
800 if (adjustedCount.ult(RHS: minElements))
801 hasAnyOverflow = true;
802
803 // Scale numElements by that. This might overflow, but we don't
804 // care because it only overflows if allocationSize does, too, and
805 // if that overflows then we shouldn't use this.
806 numElements =
807 llvm::ConstantInt::get(Ty: CGF.SizeTy, V: adjustedCount * arraySizeMultiplier);
808
809 // Compute the size before cookie, and track whether it overflowed.
810 bool overflow;
811 llvm::APInt allocationSize =
812 adjustedCount.umul_ov(RHS: typeSizeMultiplier, Overflow&: overflow);
813 hasAnyOverflow |= overflow;
814
815 // Add in the cookie, and check whether it's overflowed.
816 if (cookieSize != 0) {
817 // Save the current size without a cookie. This shouldn't be
818 // used if there was overflow.
819 sizeWithoutCookie = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: allocationSize);
820
821 allocationSize = allocationSize.uadd_ov(RHS: cookieSize, Overflow&: overflow);
822 hasAnyOverflow |= overflow;
823 }
824
825 // On overflow, produce a -1 so operator new will fail.
826 if (hasAnyOverflow) {
827 size = llvm::Constant::getAllOnesValue(Ty: CGF.SizeTy);
828 } else {
829 size = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: allocationSize);
830 }
831
832 // Otherwise, we might need to use the overflow intrinsics.
833 } else {
834 // There are up to five conditions we need to test for:
835 // 1) if isSigned, we need to check whether numElements is negative;
836 // 2) if numElementsWidth > sizeWidth, we need to check whether
837 // numElements is larger than something representable in size_t;
838 // 3) if minElements > 0, we need to check whether numElements is smaller
839 // than that.
840 // 4) we need to compute
841 // sizeWithoutCookie := numElements * typeSizeMultiplier
842 // and check whether it overflows; and
843 // 5) if we need a cookie, we need to compute
844 // size := sizeWithoutCookie + cookieSize
845 // and check whether it overflows.
846
847 llvm::Value *hasOverflow = nullptr;
848
849 // If numElementsWidth > sizeWidth, then one way or another, we're
850 // going to have to do a comparison for (2), and this happens to
851 // take care of (1), too.
852 if (numElementsWidth > sizeWidth) {
853 llvm::APInt threshold =
854 llvm::APInt::getOneBitSet(numBits: numElementsWidth, BitNo: sizeWidth);
855
856 llvm::Value *thresholdV =
857 llvm::ConstantInt::get(Ty: numElementsType, V: threshold);
858
859 hasOverflow = CGF.Builder.CreateICmpUGE(LHS: numElements, RHS: thresholdV);
860 numElements = CGF.Builder.CreateTrunc(V: numElements, DestTy: CGF.SizeTy);
861
862 // Otherwise, if we're signed, we want to sext up to size_t.
863 } else if (isSigned) {
864 if (numElementsWidth < sizeWidth)
865 numElements = CGF.Builder.CreateSExt(V: numElements, DestTy: CGF.SizeTy);
866
867 // If there's a non-1 type size multiplier, then we can do the
868 // signedness check at the same time as we do the multiply
869 // because a negative number times anything will cause an
870 // unsigned overflow. Otherwise, we have to do it here. But at least
871 // in this case, we can subsume the >= minElements check.
872 if (typeSizeMultiplier == 1)
873 hasOverflow = CGF.Builder.CreateICmpSLT(
874 LHS: numElements, RHS: llvm::ConstantInt::get(Ty: CGF.SizeTy, V: minElements));
875
876 // Otherwise, zext up to size_t if necessary.
877 } else if (numElementsWidth < sizeWidth) {
878 numElements = CGF.Builder.CreateZExt(V: numElements, DestTy: CGF.SizeTy);
879 }
880
881 assert(numElements->getType() == CGF.SizeTy);
882
883 if (minElements) {
884 // Don't allow allocation of fewer elements than we have initializers.
885 if (!hasOverflow) {
886 hasOverflow = CGF.Builder.CreateICmpULT(
887 LHS: numElements, RHS: llvm::ConstantInt::get(Ty: CGF.SizeTy, V: minElements));
888 } else if (numElementsWidth > sizeWidth) {
889 // The other existing overflow subsumes this check.
890 // We do an unsigned comparison, since any signed value < -1 is
891 // taken care of either above or below.
892 hasOverflow = CGF.Builder.CreateOr(
893 LHS: hasOverflow,
894 RHS: CGF.Builder.CreateICmpULT(
895 LHS: numElements, RHS: llvm::ConstantInt::get(Ty: CGF.SizeTy, V: minElements)));
896 }
897 }
898
899 size = numElements;
900
901 // Multiply by the type size if necessary. This multiplier
902 // includes all the factors for nested arrays.
903 //
904 // This step also causes numElements to be scaled up by the
905 // nested-array factor if necessary. Overflow on this computation
906 // can be ignored because the result shouldn't be used if
907 // allocation fails.
908 if (typeSizeMultiplier != 1) {
909 llvm::Function *umul_with_overflow =
910 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::umul_with_overflow, Tys: CGF.SizeTy);
911
912 llvm::Value *tsmV =
913 llvm::ConstantInt::get(Ty: CGF.SizeTy, V: typeSizeMultiplier);
914 llvm::Value *result =
915 CGF.Builder.CreateCall(Callee: umul_with_overflow, Args: {size, tsmV});
916
917 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(Agg: result, Idxs: 1);
918 if (hasOverflow)
919 hasOverflow = CGF.Builder.CreateOr(LHS: hasOverflow, RHS: overflowed);
920 else
921 hasOverflow = overflowed;
922
923 size = CGF.Builder.CreateExtractValue(Agg: result, Idxs: 0);
924
925 // Also scale up numElements by the array size multiplier.
926 if (arraySizeMultiplier != 1) {
927 // If the base element type size is 1, then we can re-use the
928 // multiply we just did.
929 if (typeSize.isOne()) {
930 assert(arraySizeMultiplier == typeSizeMultiplier);
931 numElements = size;
932
933 // Otherwise we need a separate multiply.
934 } else {
935 llvm::Value *asmV =
936 llvm::ConstantInt::get(Ty: CGF.SizeTy, V: arraySizeMultiplier);
937 numElements = CGF.Builder.CreateMul(LHS: numElements, RHS: asmV);
938 }
939 }
940 } else {
941 // numElements doesn't need to be scaled.
942 assert(arraySizeMultiplier == 1);
943 }
944
945 // Add in the cookie size if necessary.
946 if (cookieSize != 0) {
947 sizeWithoutCookie = size;
948
949 llvm::Function *uadd_with_overflow =
950 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::uadd_with_overflow, Tys: CGF.SizeTy);
951
952 llvm::Value *cookieSizeV = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: cookieSize);
953 llvm::Value *result =
954 CGF.Builder.CreateCall(Callee: uadd_with_overflow, Args: {size, cookieSizeV});
955
956 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(Agg: result, Idxs: 1);
957 if (hasOverflow)
958 hasOverflow = CGF.Builder.CreateOr(LHS: hasOverflow, RHS: overflowed);
959 else
960 hasOverflow = overflowed;
961
962 size = CGF.Builder.CreateExtractValue(Agg: result, Idxs: 0);
963 }
964
965 // If we had any possibility of dynamic overflow, make a select to
966 // overwrite 'size' with an all-ones value, which should cause
967 // operator new to throw.
968 if (hasOverflow)
969 size = CGF.Builder.CreateSelect(
970 C: hasOverflow, True: llvm::Constant::getAllOnesValue(Ty: CGF.SizeTy), False: size);
971 }
972
973 if (cookieSize == 0)
974 sizeWithoutCookie = size;
975 else
976 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
977
978 return size;
979}
980
981static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
982 QualType AllocType, Address NewPtr,
983 AggValueSlot::Overlap_t MayOverlap) {
984 // FIXME: Refactor with EmitExprAsInit.
985 switch (CGF.getEvaluationKind(T: AllocType)) {
986 case TEK_Scalar:
987 CGF.EmitScalarInit(init: Init, D: nullptr, lvalue: CGF.MakeAddrLValue(Addr: NewPtr, T: AllocType),
988 capturedByInit: false);
989 return;
990 case TEK_Complex:
991 CGF.EmitComplexExprIntoLValue(E: Init, dest: CGF.MakeAddrLValue(Addr: NewPtr, T: AllocType),
992 /*isInit*/ true);
993 return;
994 case TEK_Aggregate: {
995 AggValueSlot Slot = AggValueSlot::forAddr(
996 addr: NewPtr, quals: AllocType.getQualifiers(), isDestructed: AggValueSlot::IsDestructed,
997 needsGC: AggValueSlot::DoesNotNeedGCBarriers, isAliased: AggValueSlot::IsNotAliased,
998 mayOverlap: MayOverlap, isZeroed: AggValueSlot::IsNotZeroed,
999 isChecked: AggValueSlot::IsSanitizerChecked);
1000 CGF.EmitAggExpr(E: Init, AS: Slot);
1001 return;
1002 }
1003 }
1004 llvm_unreachable("bad evaluation kind");
1005}
1006
1007void CodeGenFunction::EmitNewArrayInitializer(
1008 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
1009 Address BeginPtr, llvm::Value *NumElements,
1010 llvm::Value *AllocSizeWithoutCookie) {
1011 // If we have a type with trivial initialization and no initializer,
1012 // there's nothing to do.
1013 if (!E->hasInitializer())
1014 return;
1015
1016 Address CurPtr = BeginPtr;
1017
1018 unsigned InitListElements = 0;
1019
1020 const Expr *Init = E->getInitializer();
1021 Address EndOfInit = Address::invalid();
1022 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
1023 CleanupDeactivationScope deactivation(*this);
1024 bool pushedCleanup = false;
1025
1026 CharUnits ElementSize = getContext().getTypeSizeInChars(T: ElementType);
1027 CharUnits ElementAlign =
1028 BeginPtr.getAlignment().alignmentOfArrayElement(elementSize: ElementSize);
1029
1030 // Attempt to perform zero-initialization using memset.
1031 auto TryMemsetInitialization = [&]() -> bool {
1032 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
1033 // we can initialize with a memset to -1.
1034 if (!CGM.getTypes().isZeroInitializable(T: ElementType))
1035 return false;
1036
1037 // Optimization: since zero initialization will just set the memory
1038 // to all zeroes, generate a single memset to do it in one shot.
1039
1040 // Subtract out the size of any elements we've already initialized.
1041 auto *RemainingSize = AllocSizeWithoutCookie;
1042 if (InitListElements) {
1043 // We know this can't overflow; we check this when doing the allocation.
1044 auto *InitializedSize = llvm::ConstantInt::get(
1045 Ty: RemainingSize->getType(),
1046 V: getContext().getTypeSizeInChars(T: ElementType).getQuantity() *
1047 InitListElements);
1048 RemainingSize = Builder.CreateSub(LHS: RemainingSize, RHS: InitializedSize);
1049 }
1050
1051 // Create the memset.
1052 Builder.CreateMemSet(Dest: CurPtr, Value: Builder.getInt8(C: 0), Size: RemainingSize, IsVolatile: false);
1053 return true;
1054 };
1055
1056 const InitListExpr *ILE = dyn_cast<InitListExpr>(Val: Init);
1057 const CXXParenListInitExpr *CPLIE = nullptr;
1058 const StringLiteral *SL = nullptr;
1059 const ObjCEncodeExpr *OCEE = nullptr;
1060 const Expr *IgnoreParen = nullptr;
1061 if (!ILE) {
1062 IgnoreParen = Init->IgnoreParenImpCasts();
1063 CPLIE = dyn_cast<CXXParenListInitExpr>(Val: IgnoreParen);
1064 SL = dyn_cast<StringLiteral>(Val: IgnoreParen);
1065 OCEE = dyn_cast<ObjCEncodeExpr>(Val: IgnoreParen);
1066 }
1067
1068 // If the initializer is an initializer list, first do the explicit elements.
1069 if (ILE || CPLIE || SL || OCEE) {
1070 // Initializing from a (braced) string literal is a special case; the init
1071 // list element does not initialize a (single) array element.
1072 if ((ILE && ILE->isStringLiteralInit()) || SL || OCEE) {
1073 if (!ILE)
1074 Init = IgnoreParen;
1075 // Initialize the initial portion of length equal to that of the string
1076 // literal. The allocation must be for at least this much; we emitted a
1077 // check for that earlier.
1078 AggValueSlot Slot = AggValueSlot::forAddr(
1079 addr: CurPtr, quals: ElementType.getQualifiers(), isDestructed: AggValueSlot::IsDestructed,
1080 needsGC: AggValueSlot::DoesNotNeedGCBarriers, isAliased: AggValueSlot::IsNotAliased,
1081 mayOverlap: AggValueSlot::DoesNotOverlap, isZeroed: AggValueSlot::IsNotZeroed,
1082 isChecked: AggValueSlot::IsSanitizerChecked);
1083 EmitAggExpr(E: ILE ? ILE->getInit(Init: 0) : Init, AS: Slot);
1084
1085 // Move past these elements.
1086 InitListElements =
1087 cast<ConstantArrayType>(Val: Init->getType()->getAsArrayTypeUnsafe())
1088 ->getZExtSize();
1089 CurPtr = Builder.CreateConstInBoundsGEP(Addr: CurPtr, Index: InitListElements,
1090 Name: "string.init.end");
1091
1092 // Zero out the rest, if any remain.
1093 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(Val: NumElements);
1094 if (!ConstNum || !ConstNum->equalsInt(V: InitListElements)) {
1095 bool OK = TryMemsetInitialization();
1096 (void)OK;
1097 assert(OK && "couldn't memset character type?");
1098 }
1099 return;
1100 }
1101
1102 ArrayRef<const Expr *> InitExprs =
1103 ILE ? ILE->inits() : CPLIE->getInitExprs();
1104 InitListElements = InitExprs.size();
1105
1106 // If this is a multi-dimensional array new, we will initialize multiple
1107 // elements with each init list element.
1108 QualType AllocType = E->getAllocatedType();
1109 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1110 Val: AllocType->getAsArrayTypeUnsafe())) {
1111 ElementTy = ConvertTypeForMem(T: AllocType);
1112 CurPtr = CurPtr.withElementType(ElemTy: ElementTy);
1113 InitListElements *= getContext().getConstantArrayElementCount(CA: CAT);
1114 }
1115
1116 // Enter a partial-destruction Cleanup if necessary.
1117 if (DtorKind) {
1118 AllocaTrackerRAII AllocaTracker(*this);
1119 // In principle we could tell the Cleanup where we are more
1120 // directly, but the control flow can get so varied here that it
1121 // would actually be quite complex. Therefore we go through an
1122 // alloca.
1123 llvm::Instruction *DominatingIP =
1124 Builder.CreateFlagLoad(Addr: llvm::ConstantInt::getNullValue(Ty: Int8PtrTy));
1125 EndOfInit = CreateTempAlloca(Ty: BeginPtr.getType(), align: getPointerAlign(),
1126 Name: "array.init.end");
1127 pushIrregularPartialArrayCleanup(arrayBegin: BeginPtr.emitRawPointer(CGF&: *this),
1128 arrayEndPointer: EndOfInit, elementType: ElementType, elementAlignment: ElementAlign,
1129 destroyer: getDestroyer(destructionKind: DtorKind));
1130 cast<EHCleanupScope>(Val&: *EHStack.find(sp: EHStack.stable_begin()))
1131 .AddAuxAllocas(Allocas: AllocaTracker.Take());
1132 DeferredDeactivationCleanupStack.push_back(
1133 Elt: {.Cleanup: EHStack.stable_begin(), .DominatingIP: DominatingIP});
1134 pushedCleanup = true;
1135 }
1136
1137 CharUnits StartAlign = CurPtr.getAlignment();
1138 unsigned i = 0;
1139 for (const Expr *IE : InitExprs) {
1140 // Tell the cleanup that it needs to destroy up to this
1141 // element. TODO: some of these stores can be trivially
1142 // observed to be unnecessary.
1143 if (EndOfInit.isValid()) {
1144 Builder.CreateStore(Val: CurPtr.emitRawPointer(CGF&: *this), Addr: EndOfInit);
1145 }
1146 // FIXME: If the last initializer is an incomplete initializer list for
1147 // an array, and we have an array filler, we can fold together the two
1148 // initialization loops.
1149 StoreAnyExprIntoOneUnit(CGF&: *this, Init: IE, AllocType: IE->getType(), NewPtr: CurPtr,
1150 MayOverlap: AggValueSlot::DoesNotOverlap);
1151 CurPtr = Address(Builder.CreateInBoundsGEP(Ty: CurPtr.getElementType(),
1152 Ptr: CurPtr.emitRawPointer(CGF&: *this),
1153 IdxList: Builder.getSize(N: 1),
1154 Name: "array.exp.next"),
1155 CurPtr.getElementType(),
1156 StartAlign.alignmentAtOffset(offset: (++i) * ElementSize));
1157 }
1158
1159 // The remaining elements are filled with the array filler expression.
1160 Init = ILE ? ILE->getArrayFiller() : CPLIE->getArrayFiller();
1161
1162 // Extract the initializer for the individual array elements by pulling
1163 // out the array filler from all the nested initializer lists. This avoids
1164 // generating a nested loop for the initialization.
1165 while (Init && Init->getType()->isConstantArrayType()) {
1166 auto *SubILE = dyn_cast<InitListExpr>(Val: Init);
1167 if (!SubILE)
1168 break;
1169 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1170 Init = SubILE->getArrayFiller();
1171 }
1172
1173 // Switch back to initializing one base element at a time.
1174 CurPtr = CurPtr.withElementType(ElemTy: BeginPtr.getElementType());
1175 }
1176
1177 // If all elements have already been initialized, skip any further
1178 // initialization.
1179 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(Val: NumElements);
1180 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1181 return;
1182 }
1183
1184 assert(Init && "have trailing elements to initialize but no initializer");
1185
1186 // If this is a constructor call, try to optimize it out, and failing that
1187 // emit a single loop to initialize all remaining elements.
1188 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) {
1189 CXXConstructorDecl *Ctor = CCE->getConstructor();
1190 if (Ctor->isTrivial()) {
1191 // If new expression did not specify value-initialization, then there
1192 // is no initialization.
1193 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1194 return;
1195
1196 if (TryMemsetInitialization())
1197 return;
1198 }
1199
1200 // Store the new Cleanup position for irregular Cleanups.
1201 //
1202 // FIXME: Share this cleanup with the constructor call emission rather than
1203 // having it create a cleanup of its own.
1204 if (EndOfInit.isValid())
1205 Builder.CreateStore(Val: CurPtr.emitRawPointer(CGF&: *this), Addr: EndOfInit);
1206
1207 // Emit a constructor call loop to initialize the remaining elements.
1208 if (InitListElements)
1209 NumElements = Builder.CreateSub(
1210 LHS: NumElements,
1211 RHS: llvm::ConstantInt::get(Ty: NumElements->getType(), V: InitListElements));
1212 EmitCXXAggrConstructorCall(D: Ctor, NumElements, ArrayPtr: CurPtr, E: CCE,
1213 /*NewPointerIsChecked*/ true,
1214 ZeroInitialization: CCE->requiresZeroInitialization());
1215 if (getContext().getTargetInfo().emitVectorDeletingDtors(
1216 getContext().getLangOpts())) {
1217 CXXDestructorDecl *Dtor = Ctor->getParent()->getDestructor();
1218 if (Dtor && Dtor->isVirtual())
1219 CGM.requireVectorDestructorDefinition(RD: Ctor->getParent());
1220 }
1221 return;
1222 }
1223
1224 // If this is value-initialization, we can usually use memset.
1225 ImplicitValueInitExpr IVIE(ElementType);
1226 if (isa<ImplicitValueInitExpr>(Val: Init)) {
1227 if (TryMemsetInitialization())
1228 return;
1229
1230 // Switch to an ImplicitValueInitExpr for the element type. This handles
1231 // only one case: multidimensional array new of pointers to members. In
1232 // all other cases, we already have an initializer for the array element.
1233 Init = &IVIE;
1234 }
1235
1236 // At this point we should have found an initializer for the individual
1237 // elements of the array.
1238 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1239 "got wrong type of element to initialize");
1240
1241 // If we have an empty initializer list, we can usually use memset.
1242 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init))
1243 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1244 return;
1245
1246 // If we have a struct whose every field is value-initialized, we can
1247 // usually use memset.
1248 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
1249 if (const RecordType *RType =
1250 ILE->getType()->getAsCanonical<RecordType>()) {
1251 if (RType->getDecl()->isStruct()) {
1252 const RecordDecl *RD = RType->getDecl()->getDefinitionOrSelf();
1253 unsigned NumElements = 0;
1254 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
1255 NumElements = CXXRD->getNumBases();
1256 for (auto *Field : RD->fields())
1257 if (!Field->isUnnamedBitField())
1258 ++NumElements;
1259 // FIXME: Recurse into nested InitListExprs.
1260 if (ILE->getNumInits() == NumElements)
1261 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1262 if (!isa<ImplicitValueInitExpr>(Val: ILE->getInit(Init: i)))
1263 --NumElements;
1264 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1265 return;
1266 }
1267 }
1268 }
1269
1270 // Create the loop blocks.
1271 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1272 llvm::BasicBlock *LoopBB = createBasicBlock(name: "new.loop");
1273 llvm::BasicBlock *ContBB = createBasicBlock(name: "new.loop.end");
1274
1275 // Find the end of the array, hoisted out of the loop.
1276 llvm::Value *EndPtr = Builder.CreateInBoundsGEP(
1277 Ty: BeginPtr.getElementType(), Ptr: BeginPtr.emitRawPointer(CGF&: *this), IdxList: NumElements,
1278 Name: "array.end");
1279
1280 // If the number of elements isn't constant, we have to now check if there is
1281 // anything left to initialize.
1282 if (!ConstNum) {
1283 llvm::Value *IsEmpty = Builder.CreateICmpEQ(LHS: CurPtr.emitRawPointer(CGF&: *this),
1284 RHS: EndPtr, Name: "array.isempty");
1285 Builder.CreateCondBr(Cond: IsEmpty, True: ContBB, False: LoopBB);
1286 }
1287
1288 // Enter the loop.
1289 EmitBlock(BB: LoopBB);
1290
1291 // Set up the current-element phi.
1292 llvm::PHINode *CurPtrPhi =
1293 Builder.CreatePHI(Ty: CurPtr.getType(), NumReservedValues: 2, Name: "array.cur");
1294 CurPtrPhi->addIncoming(V: CurPtr.emitRawPointer(CGF&: *this), BB: EntryBB);
1295
1296 CurPtr = Address(CurPtrPhi, CurPtr.getElementType(), ElementAlign);
1297
1298 // Store the new Cleanup position for irregular Cleanups.
1299 if (EndOfInit.isValid())
1300 Builder.CreateStore(Val: CurPtr.emitRawPointer(CGF&: *this), Addr: EndOfInit);
1301
1302 // Enter a partial-destruction Cleanup if necessary.
1303 if (!pushedCleanup && needsEHCleanup(kind: DtorKind)) {
1304 llvm::Instruction *DominatingIP =
1305 Builder.CreateFlagLoad(Addr: llvm::ConstantInt::getNullValue(Ty: Int8PtrTy));
1306 pushRegularPartialArrayCleanup(arrayBegin: BeginPtr.emitRawPointer(CGF&: *this),
1307 arrayEnd: CurPtr.emitRawPointer(CGF&: *this), elementType: ElementType,
1308 elementAlignment: ElementAlign, destroyer: getDestroyer(destructionKind: DtorKind));
1309 DeferredDeactivationCleanupStack.push_back(
1310 Elt: {.Cleanup: EHStack.stable_begin(), .DominatingIP: DominatingIP});
1311 }
1312
1313 // Emit the initializer into this element.
1314 StoreAnyExprIntoOneUnit(CGF&: *this, Init, AllocType: Init->getType(), NewPtr: CurPtr,
1315 MayOverlap: AggValueSlot::DoesNotOverlap);
1316
1317 // Leave the Cleanup if we entered one.
1318 deactivation.ForceDeactivate();
1319
1320 // Advance to the next element by adjusting the pointer type as necessary.
1321 llvm::Value *NextPtr = Builder.CreateConstInBoundsGEP1_32(
1322 Ty: ElementTy, Ptr: CurPtr.emitRawPointer(CGF&: *this), Idx0: 1, Name: "array.next");
1323
1324 // Check whether we've gotten to the end of the array and, if so,
1325 // exit the loop.
1326 llvm::Value *IsEnd = Builder.CreateICmpEQ(LHS: NextPtr, RHS: EndPtr, Name: "array.atend");
1327 Builder.CreateCondBr(Cond: IsEnd, True: ContBB, False: LoopBB);
1328 CurPtrPhi->addIncoming(V: NextPtr, BB: Builder.GetInsertBlock());
1329
1330 EmitBlock(BB: ContBB);
1331}
1332
1333static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1334 QualType ElementType, llvm::Type *ElementTy,
1335 Address NewPtr, llvm::Value *NumElements,
1336 llvm::Value *AllocSizeWithoutCookie) {
1337 ApplyDebugLocation DL(CGF, E);
1338 if (E->isArray())
1339 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, BeginPtr: NewPtr, NumElements,
1340 AllocSizeWithoutCookie);
1341 else if (const Expr *Init = E->getInitializer())
1342 StoreAnyExprIntoOneUnit(CGF, Init, AllocType: E->getAllocatedType(), NewPtr,
1343 MayOverlap: AggValueSlot::DoesNotOverlap);
1344}
1345
1346/// Emit a call to an operator new or operator delete function, as implicitly
1347/// created by new-expressions and delete-expressions.
1348static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1349 const FunctionDecl *CalleeDecl,
1350 const FunctionProtoType *CalleeType,
1351 const CallArgList &Args) {
1352 llvm::CallBase *CallOrInvoke;
1353 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(GD: CalleeDecl);
1354 CGCallee Callee = CGCallee::forDirect(functionPtr: CalleePtr, abstractInfo: GlobalDecl(CalleeDecl));
1355 RValue RV = CGF.EmitCall(CallInfo: CGF.CGM.getTypes().arrangeFreeFunctionCall(
1356 Args, Ty: CalleeType, /*ChainCall=*/false),
1357 Callee, ReturnValue: ReturnValueSlot(), Args, CallOrInvoke: &CallOrInvoke);
1358
1359 /// C++1y [expr.new]p10:
1360 /// [In a new-expression,] an implementation is allowed to omit a call
1361 /// to a replaceable global allocation function.
1362 ///
1363 /// We model such elidable calls with the 'builtin' attribute.
1364 llvm::Function *Fn = dyn_cast<llvm::Function>(Val: CalleePtr);
1365 if (CalleeDecl->isReplaceableGlobalAllocationFunction() && Fn &&
1366 Fn->hasFnAttribute(Kind: llvm::Attribute::NoBuiltin)) {
1367 CallOrInvoke->addFnAttr(Kind: llvm::Attribute::Builtin);
1368 }
1369
1370 return RV;
1371}
1372
1373RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1374 const CallExpr *TheCall,
1375 bool IsDelete) {
1376 CallArgList Args;
1377 EmitCallArgs(Args, Prototype: Type, ArgRange: TheCall->arguments());
1378 // Find the allocation or deallocation function that we're calling.
1379 ASTContext &Ctx = getContext();
1380 DeclarationName Name =
1381 Ctx.DeclarationNames.getCXXOperatorName(Op: IsDelete ? OO_Delete : OO_New);
1382
1383 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1384 if (auto *FD = dyn_cast<FunctionDecl>(Val: Decl))
1385 if (Ctx.hasSameType(T1: FD->getType(), T2: QualType(Type, 0))) {
1386 RValue RV = EmitNewDeleteCall(CGF&: *this, CalleeDecl: FD, CalleeType: Type, Args);
1387 if (auto *CB = dyn_cast_if_present<llvm::CallBase>(Val: RV.getScalarVal())) {
1388 if (SanOpts.has(K: SanitizerKind::AllocToken)) {
1389 // Set !alloc_token metadata.
1390 EmitAllocToken(CB, E: TheCall);
1391 }
1392 }
1393 return RV;
1394 }
1395 llvm_unreachable("predeclared global operator new/delete is missing");
1396}
1397
1398namespace {
1399/// A cleanup to call the given 'operator delete' function upon abnormal
1400/// exit from a new expression. Templated on a traits type that deals with
1401/// ensuring that the arguments dominate the cleanup if necessary.
1402template <typename Traits>
1403class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1404 /// Type used to hold llvm::Value*s.
1405 typedef typename Traits::ValueTy ValueTy;
1406 /// Type used to hold RValues.
1407 typedef typename Traits::RValueTy RValueTy;
1408 struct PlacementArg {
1409 RValueTy ArgValue;
1410 QualType ArgType;
1411 };
1412
1413 unsigned NumPlacementArgs : 30;
1414 LLVM_PREFERRED_TYPE(AlignedAllocationMode)
1415 unsigned PassAlignmentToPlacementDelete : 1;
1416 const FunctionDecl *OperatorDelete;
1417 RValueTy TypeIdentity;
1418 ValueTy Ptr;
1419 ValueTy AllocSize;
1420 CharUnits AllocAlign;
1421
1422 PlacementArg *getPlacementArgs() {
1423 return reinterpret_cast<PlacementArg *>(this + 1);
1424 }
1425
1426public:
1427 static size_t getExtraSize(size_t NumPlacementArgs) {
1428 return NumPlacementArgs * sizeof(PlacementArg);
1429 }
1430
1431 CallDeleteDuringNew(size_t NumPlacementArgs,
1432 const FunctionDecl *OperatorDelete, RValueTy TypeIdentity,
1433 ValueTy Ptr, ValueTy AllocSize,
1434 const ImplicitAllocationParameters &IAP,
1435 CharUnits AllocAlign)
1436 : NumPlacementArgs(NumPlacementArgs),
1437 PassAlignmentToPlacementDelete(isAlignedAllocation(Mode: IAP.PassAlignment)),
1438 OperatorDelete(OperatorDelete), TypeIdentity(TypeIdentity), Ptr(Ptr),
1439 AllocSize(AllocSize), AllocAlign(AllocAlign) {}
1440
1441 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1442 assert(I < NumPlacementArgs && "index out of range");
1443 getPlacementArgs()[I] = {Arg, Type};
1444 }
1445
1446 void Emit(CodeGenFunction &CGF, Flags flags) override {
1447 const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
1448 CallArgList DeleteArgs;
1449 unsigned FirstNonTypeArg = 0;
1450 TypeAwareAllocationMode TypeAwareDeallocation = TypeAwareAllocationMode::No;
1451 if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) {
1452 TypeAwareDeallocation = TypeAwareAllocationMode::Yes;
1453 QualType SpecializedTypeIdentity = FPT->getParamType(i: 0);
1454 ++FirstNonTypeArg;
1455 DeleteArgs.add(rvalue: Traits::get(CGF, TypeIdentity), type: SpecializedTypeIdentity);
1456 }
1457 // The first argument after type-identity parameter (if any) is always
1458 // a void* (or C* for a destroying operator delete for class type C).
1459 DeleteArgs.add(rvalue: Traits::get(CGF, Ptr), type: FPT->getParamType(i: FirstNonTypeArg));
1460
1461 // Figure out what other parameters we should be implicitly passing.
1462 UsualDeleteParams Params;
1463 if (NumPlacementArgs) {
1464 // A placement deallocation function is implicitly passed an alignment
1465 // if the placement allocation function was, but is never passed a size.
1466 Params.Alignment =
1467 alignedAllocationModeFromBool(IsAligned: PassAlignmentToPlacementDelete);
1468 Params.TypeAwareDelete = TypeAwareDeallocation;
1469 Params.Size = isTypeAwareAllocation(Mode: Params.TypeAwareDelete);
1470 } else {
1471 // For a non-placement new-expression, 'operator delete' can take a
1472 // size and/or an alignment if it has the right parameters.
1473 Params = OperatorDelete->getUsualDeleteParams();
1474 }
1475
1476 assert(!Params.DestroyingDelete &&
1477 "should not call destroying delete in a new-expression");
1478
1479 // The second argument can be a std::size_t (for non-placement delete).
1480 if (Params.Size)
1481 DeleteArgs.add(rvalue: Traits::get(CGF, AllocSize),
1482 type: CGF.getContext().getSizeType());
1483
1484 // The next (second or third) argument can be a std::align_val_t, which
1485 // is an enum whose underlying type is std::size_t.
1486 // FIXME: Use the right type as the parameter type. Note that in a call
1487 // to operator delete(size_t, ...), we may not have it available.
1488 if (isAlignedAllocation(Mode: Params.Alignment))
1489 DeleteArgs.add(rvalue: RValue::get(V: llvm::ConstantInt::get(
1490 Ty: CGF.SizeTy, V: AllocAlign.getQuantity())),
1491 type: CGF.getContext().getSizeType());
1492
1493 // Pass the rest of the arguments, which must match exactly.
1494 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1495 auto Arg = getPlacementArgs()[I];
1496 DeleteArgs.add(rvalue: Traits::get(CGF, Arg.ArgValue), type: Arg.ArgType);
1497 }
1498
1499 // Call 'operator delete'.
1500 EmitNewDeleteCall(CGF, CalleeDecl: OperatorDelete, CalleeType: FPT, Args: DeleteArgs);
1501 }
1502};
1503} // namespace
1504
1505/// Enter a cleanup to call 'operator delete' if the initializer in a
1506/// new-expression throws.
1507static void EnterNewDeleteCleanup(CodeGenFunction &CGF, const CXXNewExpr *E,
1508 RValue TypeIdentity, Address NewPtr,
1509 llvm::Value *AllocSize, CharUnits AllocAlign,
1510 const CallArgList &NewArgs) {
1511 unsigned NumNonPlacementArgs = E->getNumImplicitArgs();
1512
1513 // If we're not inside a conditional branch, then the cleanup will
1514 // dominate and we can do the easier (and more efficient) thing.
1515 if (!CGF.isInConditionalBranch()) {
1516 struct DirectCleanupTraits {
1517 typedef llvm::Value *ValueTy;
1518 typedef RValue RValueTy;
1519 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1520 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1521 };
1522
1523 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1524
1525 DirectCleanup *Cleanup = CGF.EHStack.pushCleanupWithExtra<DirectCleanup>(
1526 Kind: EHCleanup, N: E->getNumPlacementArgs(), A: E->getOperatorDelete(),
1527 A: TypeIdentity, A: NewPtr.emitRawPointer(CGF), A: AllocSize,
1528 A: E->implicitAllocationParameters(), A: AllocAlign);
1529 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1530 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1531 Cleanup->setPlacementArg(I, Arg: Arg.getRValue(CGF), Type: Arg.Ty);
1532 }
1533
1534 return;
1535 }
1536
1537 // Otherwise, we need to save all this stuff.
1538 DominatingValue<RValue>::saved_type SavedNewPtr =
1539 DominatingValue<RValue>::save(CGF, value: RValue::get(Addr: NewPtr, CGF));
1540 DominatingValue<RValue>::saved_type SavedAllocSize =
1541 DominatingValue<RValue>::save(CGF, value: RValue::get(V: AllocSize));
1542 DominatingValue<RValue>::saved_type SavedTypeIdentity =
1543 DominatingValue<RValue>::save(CGF, value: TypeIdentity);
1544 struct ConditionalCleanupTraits {
1545 typedef DominatingValue<RValue>::saved_type ValueTy;
1546 typedef DominatingValue<RValue>::saved_type RValueTy;
1547 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1548 return V.restore(CGF);
1549 }
1550 };
1551 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1552
1553 ConditionalCleanup *Cleanup =
1554 CGF.EHStack.pushCleanupWithExtra<ConditionalCleanup>(
1555 Kind: EHCleanup, N: E->getNumPlacementArgs(), A: E->getOperatorDelete(),
1556 A: SavedTypeIdentity, A: SavedNewPtr, A: SavedAllocSize,
1557 A: E->implicitAllocationParameters(), A: AllocAlign);
1558 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1559 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1560 Cleanup->setPlacementArg(
1561 I, Arg: DominatingValue<RValue>::save(CGF, value: Arg.getRValue(CGF)), Type: Arg.Ty);
1562 }
1563
1564 CGF.initFullExprCleanup();
1565}
1566
1567llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1568 // The element type being allocated.
1569 QualType allocType = getContext().getBaseElementType(QT: E->getAllocatedType());
1570
1571 // 1. Build a call to the allocation function.
1572 FunctionDecl *allocator = E->getOperatorNew();
1573
1574 // If there is a brace-initializer or C++20 parenthesized initializer, cannot
1575 // allocate fewer elements than inits.
1576 unsigned minElements = 0;
1577 unsigned IndexOfAlignArg = 1;
1578 if (E->isArray() && E->hasInitializer()) {
1579 const Expr *Init = E->getInitializer();
1580 const InitListExpr *ILE = dyn_cast<InitListExpr>(Val: Init);
1581 const CXXParenListInitExpr *CPLIE = dyn_cast<CXXParenListInitExpr>(Val: Init);
1582 const Expr *IgnoreParen = Init->IgnoreParenImpCasts();
1583 if ((ILE && ILE->isStringLiteralInit()) ||
1584 isa<StringLiteral>(Val: IgnoreParen) || isa<ObjCEncodeExpr>(Val: IgnoreParen)) {
1585 minElements =
1586 cast<ConstantArrayType>(Val: Init->getType()->getAsArrayTypeUnsafe())
1587 ->getZExtSize();
1588 } else if (ILE || CPLIE) {
1589 minElements = ILE ? ILE->getNumInits() : CPLIE->getInitExprs().size();
1590 }
1591 }
1592
1593 llvm::Value *numElements = nullptr;
1594 llvm::Value *allocSizeWithoutCookie = nullptr;
1595 llvm::Value *allocSize = EmitCXXNewAllocSize(
1596 CGF&: *this, e: E, minElements, numElements, sizeWithoutCookie&: allocSizeWithoutCookie);
1597 CharUnits allocAlign = getContext().getTypeAlignInChars(T: allocType);
1598
1599 // Emit the allocation call. If the allocator is a global placement
1600 // operator, just "inline" it directly.
1601 Address allocation = Address::invalid();
1602 CallArgList allocatorArgs;
1603 RValue TypeIdentityArg;
1604 if (allocator->isReservedGlobalPlacementOperator()) {
1605 assert(E->getNumPlacementArgs() == 1);
1606 const Expr *arg = *E->placement_arguments().begin();
1607
1608 LValueBaseInfo BaseInfo;
1609 allocation = EmitPointerWithAlignment(Addr: arg, BaseInfo: &BaseInfo);
1610
1611 // The pointer expression will, in many cases, be an opaque void*.
1612 // In these cases, discard the computed alignment and use the
1613 // formal alignment of the allocated type.
1614 if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1615 allocation.setAlignment(allocAlign);
1616
1617 // Set up allocatorArgs for the call to operator delete if it's not
1618 // the reserved global operator.
1619 if (E->getOperatorDelete() &&
1620 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1621 allocatorArgs.add(rvalue: RValue::get(V: allocSize), type: getContext().getSizeType());
1622 allocatorArgs.add(rvalue: RValue::get(Addr: allocation, CGF&: *this), type: arg->getType());
1623 }
1624
1625 } else {
1626 const FunctionProtoType *allocatorType =
1627 allocator->getType()->castAs<FunctionProtoType>();
1628 ImplicitAllocationParameters IAP = E->implicitAllocationParameters();
1629 unsigned ParamsToSkip = 0;
1630 if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) {
1631 QualType SpecializedTypeIdentity = allocatorType->getParamType(i: 0);
1632 CXXScalarValueInitExpr TypeIdentityParam(SpecializedTypeIdentity, nullptr,
1633 SourceLocation());
1634 TypeIdentityArg = EmitAnyExprToTemp(E: &TypeIdentityParam);
1635 allocatorArgs.add(rvalue: TypeIdentityArg, type: SpecializedTypeIdentity);
1636 ++ParamsToSkip;
1637 ++IndexOfAlignArg;
1638 }
1639 // The allocation size is the first argument.
1640 QualType sizeType = getContext().getSizeType();
1641 allocatorArgs.add(rvalue: RValue::get(V: allocSize), type: sizeType);
1642 ++ParamsToSkip;
1643
1644 if (allocSize != allocSizeWithoutCookie) {
1645 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1646 allocAlign = std::max(a: allocAlign, b: cookieAlign);
1647 }
1648
1649 // The allocation alignment may be passed as the second argument.
1650 if (isAlignedAllocation(Mode: IAP.PassAlignment)) {
1651 QualType AlignValT = sizeType;
1652 if (allocatorType->getNumParams() > IndexOfAlignArg) {
1653 AlignValT = allocatorType->getParamType(i: IndexOfAlignArg);
1654 assert(getContext().hasSameUnqualifiedType(
1655 AlignValT->castAsEnumDecl()->getIntegerType(), sizeType) &&
1656 "wrong type for alignment parameter");
1657 ++ParamsToSkip;
1658 } else {
1659 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1660 assert(allocator->isVariadic() && "can't pass alignment to allocator");
1661 }
1662 allocatorArgs.add(
1663 rvalue: RValue::get(V: llvm::ConstantInt::get(Ty: SizeTy, V: allocAlign.getQuantity())),
1664 type: AlignValT);
1665 }
1666
1667 // FIXME: Why do we not pass a CalleeDecl here?
1668 EmitCallArgs(Args&: allocatorArgs, Prototype: allocatorType, ArgRange: E->placement_arguments(),
1669 /*AC*/ AbstractCallee(), /*ParamsToSkip*/ ParamsToSkip);
1670
1671 RValue RV =
1672 EmitNewDeleteCall(CGF&: *this, CalleeDecl: allocator, CalleeType: allocatorType, Args: allocatorArgs);
1673
1674 if (auto *newCall = dyn_cast<llvm::CallBase>(Val: RV.getScalarVal())) {
1675 if (auto *CGDI = getDebugInfo()) {
1676 // Set !heapallocsite metadata on the call to operator new.
1677 CGDI->addHeapAllocSiteMetadata(CallSite: newCall, AllocatedTy: allocType, Loc: E->getExprLoc());
1678 }
1679 if (SanOpts.has(K: SanitizerKind::AllocToken)) {
1680 // Set !alloc_token metadata.
1681 EmitAllocToken(CB: newCall, AllocType: allocType);
1682 }
1683 }
1684
1685 // If this was a call to a global replaceable allocation function that does
1686 // not take an alignment argument, the allocator is known to produce
1687 // storage that's suitably aligned for any object that fits, up to a known
1688 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1689 CharUnits allocationAlign = allocAlign;
1690 if (!E->passAlignment() &&
1691 allocator->isReplaceableGlobalAllocationFunction()) {
1692 unsigned AllocatorAlign = llvm::bit_floor(Value: std::min<uint64_t>(
1693 a: Target.getNewAlign(), b: getContext().getTypeSize(T: allocType)));
1694 allocationAlign = std::max(
1695 a: allocationAlign, b: getContext().toCharUnitsFromBits(BitSize: AllocatorAlign));
1696 }
1697
1698 allocation = Address(RV.getScalarVal(), Int8Ty, allocationAlign);
1699 }
1700
1701 // Emit a null check on the allocation result if the allocation
1702 // function is allowed to return null (because it has a non-throwing
1703 // exception spec or is the reserved placement new) and we have an
1704 // interesting initializer will be running sanitizers on the initialization.
1705 bool nullCheck = E->shouldNullCheckAllocation() &&
1706 (!allocType.isPODType(Context: getContext()) || E->hasInitializer() ||
1707 sanitizePerformTypeCheck());
1708
1709 llvm::BasicBlock *nullCheckBB = nullptr;
1710 llvm::BasicBlock *contBB = nullptr;
1711
1712 // The null-check means that the initializer is conditionally
1713 // evaluated.
1714 ConditionalEvaluation conditional(*this);
1715
1716 if (nullCheck) {
1717 conditional.begin(CGF&: *this);
1718
1719 nullCheckBB = Builder.GetInsertBlock();
1720 llvm::BasicBlock *notNullBB = createBasicBlock(name: "new.notnull");
1721 contBB = createBasicBlock(name: "new.cont");
1722
1723 llvm::Value *isNull = Builder.CreateIsNull(Addr: allocation, Name: "new.isnull");
1724 Builder.CreateCondBr(Cond: isNull, True: contBB, False: notNullBB);
1725 EmitBlock(BB: notNullBB);
1726 }
1727
1728 // If there's an operator delete, enter a cleanup to call it if an
1729 // exception is thrown.
1730 EHScopeStack::stable_iterator operatorDeleteCleanup;
1731 llvm::Instruction *cleanupDominator = nullptr;
1732 if (E->getOperatorDelete() &&
1733 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1734 // A potentially-throwing constructor inside __try requires C++ object
1735 // unwinding, which is incompatible with SEH.
1736 if (getLangOpts().CXXExceptions && currentFunctionUsesSEHTry()) {
1737 if (const auto *ConstructExpr = E->getConstructExpr()) {
1738 const auto *FPT = ConstructExpr->getConstructor()
1739 ->getType()
1740 ->castAs<FunctionProtoType>();
1741 if (!FPT->isNothrow())
1742 getContext().getDiagnostics().Report(Loc: E->getBeginLoc(),
1743 DiagID: diag::err_seh_object_unwinding);
1744 }
1745 }
1746 EnterNewDeleteCleanup(CGF&: *this, E, TypeIdentity: TypeIdentityArg, NewPtr: allocation, AllocSize: allocSize,
1747 AllocAlign: allocAlign, NewArgs: allocatorArgs);
1748 operatorDeleteCleanup = EHStack.stable_begin();
1749 cleanupDominator = Builder.CreateUnreachable();
1750 }
1751
1752 assert((allocSize == allocSizeWithoutCookie) ==
1753 CalculateCookiePadding(*this, E).isZero());
1754 if (allocSize != allocSizeWithoutCookie) {
1755 assert(E->isArray());
1756 allocation = CGM.getCXXABI().InitializeArrayCookie(
1757 CGF&: *this, NewPtr: allocation, NumElements: numElements, expr: E, ElementType: allocType);
1758 }
1759
1760 llvm::Type *elementTy = ConvertTypeForMem(T: allocType);
1761 Address result = allocation.withElementType(ElemTy: elementTy);
1762
1763 // Passing pointer through launder.invariant.group to avoid propagation of
1764 // vptrs information which may be included in previous type.
1765 // To not break LTO with different optimizations levels, we do it regardless
1766 // of optimization level.
1767 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1768 allocator->isReservedGlobalPlacementOperator())
1769 result = Builder.CreateLaunderInvariantGroup(Addr: result);
1770
1771 // Emit sanitizer checks for pointer value now, so that in the case of an
1772 // array it was checked only once and not at each constructor call. We may
1773 // have already checked that the pointer is non-null.
1774 // FIXME: If we have an array cookie and a potentially-throwing allocator,
1775 // we'll null check the wrong pointer here.
1776 SanitizerSet SkippedChecks;
1777 SkippedChecks.set(K: SanitizerKind::Null, Value: nullCheck);
1778 EmitTypeCheck(TCK: CodeGenFunction::TCK_ConstructorCall,
1779 Loc: E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1780 Addr: result, Type: allocType, Alignment: result.getAlignment(), SkippedChecks,
1781 ArraySize: numElements);
1782
1783 EmitNewInitializer(CGF&: *this, E, ElementType: allocType, ElementTy: elementTy, NewPtr: result, NumElements: numElements,
1784 AllocSizeWithoutCookie: allocSizeWithoutCookie);
1785 llvm::Value *resultPtr = result.emitRawPointer(CGF&: *this);
1786
1787 // Deactivate the 'operator delete' cleanup if we finished
1788 // initialization.
1789 if (operatorDeleteCleanup.isValid()) {
1790 DeactivateCleanupBlock(Cleanup: operatorDeleteCleanup, DominatingIP: cleanupDominator);
1791 cleanupDominator->eraseFromParent();
1792 }
1793
1794 if (nullCheck) {
1795 conditional.end(CGF&: *this);
1796
1797 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1798 EmitBlock(BB: contBB);
1799
1800 llvm::PHINode *PHI = Builder.CreatePHI(Ty: resultPtr->getType(), NumReservedValues: 2);
1801 PHI->addIncoming(V: resultPtr, BB: notNullBB);
1802 PHI->addIncoming(V: llvm::Constant::getNullValue(Ty: resultPtr->getType()),
1803 BB: nullCheckBB);
1804
1805 resultPtr = PHI;
1806 }
1807
1808 return resultPtr;
1809}
1810
1811void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1812 llvm::Value *DeletePtr, QualType DeleteTy,
1813 llvm::Value *NumElements,
1814 CharUnits CookieSize) {
1815 assert((!NumElements && CookieSize.isZero()) ||
1816 DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1817
1818 const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
1819 CallArgList DeleteArgs;
1820
1821 auto Params = DeleteFD->getUsualDeleteParams();
1822 auto ParamTypeIt = DeleteFTy->param_type_begin();
1823
1824 std::optional<llvm::AllocaInst *> TagAlloca;
1825 auto EmitTag = [&](QualType TagType, const char *TagName) {
1826 assert(!TagAlloca);
1827 llvm::Type *Ty = getTypes().ConvertType(T: TagType);
1828 CharUnits Align = CGM.getNaturalTypeAlignment(T: TagType);
1829 llvm::AllocaInst *TagAllocation = CreateTempAlloca(Ty, Name: TagName);
1830 TagAllocation->setAlignment(Align.getAsAlign());
1831 DeleteArgs.add(rvalue: RValue::getAggregate(addr: Address(TagAllocation, Ty, Align)),
1832 type: TagType);
1833 TagAlloca = TagAllocation;
1834 };
1835
1836 // Pass std::type_identity tag if present
1837 if (isTypeAwareAllocation(Mode: Params.TypeAwareDelete))
1838 EmitTag(*ParamTypeIt++, "typeaware.delete.tag");
1839
1840 // Pass the pointer itself.
1841 QualType ArgTy = *ParamTypeIt++;
1842 DeleteArgs.add(rvalue: RValue::get(V: DeletePtr), type: ArgTy);
1843
1844 // Pass the std::destroying_delete tag if present.
1845 if (Params.DestroyingDelete)
1846 EmitTag(*ParamTypeIt++, "destroying.delete.tag");
1847
1848 // Pass the size if the delete function has a size_t parameter.
1849 if (Params.Size) {
1850 QualType SizeType = *ParamTypeIt++;
1851 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(T: DeleteTy);
1852 llvm::Value *Size = llvm::ConstantInt::get(Ty: ConvertType(T: SizeType),
1853 V: DeleteTypeSize.getQuantity());
1854
1855 // For array new, multiply by the number of elements.
1856 if (NumElements)
1857 Size = Builder.CreateMul(LHS: Size, RHS: NumElements);
1858
1859 // If there is a cookie, add the cookie size.
1860 if (!CookieSize.isZero())
1861 Size = Builder.CreateAdd(
1862 LHS: Size, RHS: llvm::ConstantInt::get(Ty: SizeTy, V: CookieSize.getQuantity()));
1863
1864 DeleteArgs.add(rvalue: RValue::get(V: Size), type: SizeType);
1865 }
1866
1867 // Pass the alignment if the delete function has an align_val_t parameter.
1868 if (isAlignedAllocation(Mode: Params.Alignment)) {
1869 QualType AlignValType = *ParamTypeIt++;
1870 CharUnits DeleteTypeAlign =
1871 getContext().toCharUnitsFromBits(BitSize: getContext().getTypeAlignIfKnown(
1872 T: DeleteTy, NeedsPreferredAlignment: true /* NeedsPreferredAlignment */));
1873 llvm::Value *Align = llvm::ConstantInt::get(Ty: ConvertType(T: AlignValType),
1874 V: DeleteTypeAlign.getQuantity());
1875 DeleteArgs.add(rvalue: RValue::get(V: Align), type: AlignValType);
1876 }
1877
1878 assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1879 "unknown parameter to usual delete function");
1880
1881 // Emit the call to delete.
1882 EmitNewDeleteCall(CGF&: *this, CalleeDecl: DeleteFD, CalleeType: DeleteFTy, Args: DeleteArgs);
1883
1884 // If call argument lowering didn't use a generated tag argument alloca we
1885 // remove them
1886 if (TagAlloca && (*TagAlloca)->use_empty())
1887 (*TagAlloca)->eraseFromParent();
1888}
1889namespace {
1890/// Calls the given 'operator delete' on a single object.
1891struct CallObjectDelete final : EHScopeStack::Cleanup {
1892 llvm::Value *Ptr;
1893 const FunctionDecl *OperatorDelete;
1894 QualType ElementType;
1895
1896 CallObjectDelete(llvm::Value *Ptr, const FunctionDecl *OperatorDelete,
1897 QualType ElementType)
1898 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1899
1900 void Emit(CodeGenFunction &CGF, Flags flags) override {
1901 CGF.EmitDeleteCall(DeleteFD: OperatorDelete, DeletePtr: Ptr, DeleteTy: ElementType);
1902 }
1903};
1904} // namespace
1905
1906void CodeGenFunction::pushCallObjectDeleteCleanup(
1907 const FunctionDecl *OperatorDelete, llvm::Value *CompletePtr,
1908 QualType ElementType) {
1909 EHStack.pushCleanup<CallObjectDelete>(Kind: NormalAndEHCleanup, A: CompletePtr,
1910 A: OperatorDelete, A: ElementType);
1911}
1912
1913/// Emit the code for deleting a single object with a destroying operator
1914/// delete. If the element type has a non-virtual destructor, Ptr has already
1915/// been converted to the type of the parameter of 'operator delete'. Otherwise
1916/// Ptr points to an object of the static type.
1917static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1918 const CXXDeleteExpr *DE, Address Ptr,
1919 QualType ElementType) {
1920 auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1921 if (Dtor && Dtor->isVirtual())
1922 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1923 Dtor);
1924 else
1925 CGF.EmitDeleteCall(DeleteFD: DE->getOperatorDelete(), DeletePtr: Ptr.emitRawPointer(CGF),
1926 DeleteTy: ElementType);
1927}
1928
1929static CXXDestructorDecl *TryDevirtualizeDtorCall(const CXXDeleteExpr *E,
1930 CXXDestructorDecl *Dtor,
1931 const LangOptions &LO) {
1932 assert(Dtor && Dtor->isVirtual() && "virtual dtor is expected");
1933 const Expr *DBase = E->getArgument();
1934 if (auto *MaybeDevirtualizedDtor = dyn_cast_or_null<CXXDestructorDecl>(
1935 Val: Dtor->getDevirtualizedMethod(Base: DBase, IsAppleKext: LO.AppleKext))) {
1936 const CXXRecordDecl *DevirtualizedClass =
1937 MaybeDevirtualizedDtor->getParent();
1938 if (declaresSameEntity(D1: getCXXRecord(E: DBase), D2: DevirtualizedClass)) {
1939 // Devirtualized to the class of the base type (the type of the
1940 // whole expression).
1941 return MaybeDevirtualizedDtor;
1942 }
1943 // Devirtualized to some other type. Would need to cast the this
1944 // pointer to that type but we don't have support for that yet, so
1945 // do a virtual call. FIXME: handle the case where it is
1946 // devirtualized to the derived type (the type of the inner
1947 // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1948 }
1949 return nullptr;
1950}
1951
1952/// Emit the code for deleting a single object.
1953/// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
1954/// if not.
1955static bool EmitObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
1956 Address Ptr, QualType ElementType,
1957 llvm::BasicBlock *UnconditionalDeleteBlock) {
1958 // C++11 [expr.delete]p3:
1959 // If the static type of the object to be deleted is different from its
1960 // dynamic type, the static type shall be a base class of the dynamic type
1961 // of the object to be deleted and the static type shall have a virtual
1962 // destructor or the behavior is undefined.
1963 CGF.EmitTypeCheck(TCK: CodeGenFunction::TCK_MemberCall, Loc: DE->getExprLoc(), Addr: Ptr,
1964 Type: ElementType);
1965
1966 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1967 assert(!OperatorDelete->isDestroyingOperatorDelete());
1968
1969 // Find the destructor for the type, if applicable. If the
1970 // destructor is virtual, we'll just emit the vcall and return.
1971 CXXDestructorDecl *Dtor = nullptr;
1972 if (const auto *RD = ElementType->getAsCXXRecordDecl()) {
1973 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1974 Dtor = RD->getDestructor();
1975
1976 if (Dtor->isVirtual()) {
1977 if (auto *DevirtualizedDtor =
1978 TryDevirtualizeDtorCall(E: DE, Dtor, LO: CGF.CGM.getLangOpts())) {
1979 Dtor = DevirtualizedDtor;
1980 } else {
1981 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1982 Dtor);
1983 return false;
1984 }
1985 }
1986 }
1987 }
1988
1989 // Make sure that we call delete even if the dtor throws.
1990 // This doesn't have to a conditional cleanup because we're going
1991 // to pop it off in a second.
1992 CGF.EHStack.pushCleanup<CallObjectDelete>(
1993 Kind: NormalAndEHCleanup, A: Ptr.emitRawPointer(CGF), A: OperatorDelete, A: ElementType);
1994
1995 if (Dtor)
1996 CGF.EmitCXXDestructorCall(D: Dtor, Type: Dtor_Complete,
1997 /*ForVirtualBase=*/false,
1998 /*Delegating=*/false, This: Ptr, ThisTy: ElementType);
1999 else if (auto Lifetime = ElementType.getObjCLifetime()) {
2000 switch (Lifetime) {
2001 case Qualifiers::OCL_None:
2002 case Qualifiers::OCL_ExplicitNone:
2003 case Qualifiers::OCL_Autoreleasing:
2004 break;
2005
2006 case Qualifiers::OCL_Strong:
2007 CGF.EmitARCDestroyStrong(addr: Ptr, precise: ARCPreciseLifetime);
2008 break;
2009
2010 case Qualifiers::OCL_Weak:
2011 CGF.EmitARCDestroyWeak(addr: Ptr);
2012 break;
2013 }
2014 }
2015
2016 // When optimizing for size, call 'operator delete' unconditionally.
2017 if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
2018 CGF.EmitBlock(BB: UnconditionalDeleteBlock);
2019 CGF.PopCleanupBlock();
2020 return true;
2021 }
2022
2023 CGF.PopCleanupBlock();
2024 return false;
2025}
2026
2027namespace {
2028/// Calls the given 'operator delete' on an array of objects.
2029struct CallArrayDelete final : EHScopeStack::Cleanup {
2030 llvm::Value *Ptr;
2031 const FunctionDecl *OperatorDelete;
2032 llvm::Value *NumElements;
2033 QualType ElementType;
2034 CharUnits CookieSize;
2035
2036 CallArrayDelete(llvm::Value *Ptr, const FunctionDecl *OperatorDelete,
2037 llvm::Value *NumElements, QualType ElementType,
2038 CharUnits CookieSize)
2039 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
2040 ElementType(ElementType), CookieSize(CookieSize) {}
2041
2042 void Emit(CodeGenFunction &CGF, Flags flags) override {
2043 CGF.EmitDeleteCall(DeleteFD: OperatorDelete, DeletePtr: Ptr, DeleteTy: ElementType, NumElements,
2044 CookieSize);
2045 }
2046};
2047} // namespace
2048
2049/// Emit the code for deleting an array of objects.
2050static void EmitArrayDelete(CodeGenFunction &CGF, const CXXDeleteExpr *E,
2051 Address deletedPtr, QualType elementType) {
2052 llvm::Value *numElements = nullptr;
2053 llvm::Value *allocatedPtr = nullptr;
2054 CharUnits cookieSize;
2055 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr: deletedPtr, expr: E, ElementType: elementType,
2056 NumElements&: numElements, AllocPtr&: allocatedPtr, CookieSize&: cookieSize);
2057
2058 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
2059
2060 // Make sure that we call delete even if one of the dtors throws.
2061 const FunctionDecl *operatorDelete = E->getOperatorDelete();
2062 CGF.EHStack.pushCleanup<CallArrayDelete>(Kind: NormalAndEHCleanup, A: allocatedPtr,
2063 A: operatorDelete, A: numElements,
2064 A: elementType, A: cookieSize);
2065
2066 // Destroy the elements.
2067 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
2068 assert(numElements && "no element count for a type with a destructor!");
2069
2070 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(T: elementType);
2071 CharUnits elementAlign =
2072 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
2073
2074 llvm::Value *arrayBegin = deletedPtr.emitRawPointer(CGF);
2075 llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
2076 Ty: deletedPtr.getElementType(), Ptr: arrayBegin, IdxList: numElements, Name: "delete.end");
2077
2078 // Note that it is legal to allocate a zero-length array, and we
2079 // can never fold the check away because the length should always
2080 // come from a cookie.
2081 CGF.emitArrayDestroy(begin: arrayBegin, end: arrayEnd, elementType, elementAlign,
2082 destroyer: CGF.getDestroyer(destructionKind: dtorKind),
2083 /*checkZeroLength*/ true,
2084 useEHCleanup: CGF.needsEHCleanup(kind: dtorKind));
2085 }
2086
2087 // Pop the cleanup block.
2088 CGF.PopCleanupBlock();
2089}
2090
2091void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
2092 const Expr *Arg = E->getArgument();
2093 Address Ptr = EmitPointerWithAlignment(Addr: Arg);
2094
2095 // Null check the pointer.
2096 //
2097 // We could avoid this null check if we can determine that the object
2098 // destruction is trivial and doesn't require an array cookie; we can
2099 // unconditionally perform the operator delete call in that case. For now, we
2100 // assume that deleted pointers are null rarely enough that it's better to
2101 // keep the branch. This might be worth revisiting for a -O0 code size win.
2102 llvm::BasicBlock *DeleteNotNull = createBasicBlock(name: "delete.notnull");
2103 llvm::BasicBlock *DeleteEnd = createBasicBlock(name: "delete.end");
2104
2105 llvm::Value *IsNull = Builder.CreateIsNull(Addr: Ptr, Name: "isnull");
2106
2107 Builder.CreateCondBr(Cond: IsNull, True: DeleteEnd, False: DeleteNotNull);
2108 EmitBlock(BB: DeleteNotNull);
2109 Ptr.setKnownNonNull();
2110
2111 QualType DeleteTy = E->getDestroyedType();
2112
2113 // A destroying operator delete overrides the entire operation of the
2114 // delete expression.
2115 if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
2116 EmitDestroyingObjectDelete(CGF&: *this, DE: E, Ptr, ElementType: DeleteTy);
2117 EmitBlock(BB: DeleteEnd);
2118 return;
2119 }
2120
2121 // We might be deleting a pointer to array.
2122 DeleteTy = getContext().getBaseElementType(QT: DeleteTy);
2123 Ptr = Ptr.withElementType(ElemTy: ConvertTypeForMem(T: DeleteTy));
2124
2125 if (E->isArrayForm() &&
2126 CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
2127 CGM.getContext().getLangOpts())) {
2128 if (auto *RD = DeleteTy->getAsCXXRecordDecl()) {
2129 auto *Dtor = RD->getDestructor();
2130 if (Dtor && Dtor->isVirtual()) {
2131 // Emit normal loop over the array elements if we can easily
2132 // devirtualize destructor call.
2133 // Emit virtual call to vector deleting destructor otherwise.
2134 if (!TryDevirtualizeDtorCall(E, Dtor, LO: CGM.getLangOpts())) {
2135 llvm::Value *NumElements = nullptr;
2136 llvm::Value *AllocatedPtr = nullptr;
2137 CharUnits CookieSize;
2138 llvm::BasicBlock *BodyBB = createBasicBlock(name: "vdtor.call");
2139 llvm::BasicBlock *DoneBB = createBasicBlock(name: "vdtor.nocall");
2140 // Check array cookie to see if the array has length 0. Don't call
2141 // the destructor in that case.
2142 CGM.getCXXABI().ReadArrayCookie(CGF&: *this, Ptr, expr: E, ElementType: DeleteTy, NumElements,
2143 AllocPtr&: AllocatedPtr, CookieSize);
2144
2145 auto *CondTy = cast<llvm::IntegerType>(Val: NumElements->getType());
2146 llvm::Value *IsEmpty = Builder.CreateICmpEQ(
2147 LHS: NumElements, RHS: llvm::ConstantInt::get(Ty: CondTy, V: 0));
2148 Builder.CreateCondBr(Cond: IsEmpty, True: DoneBB, False: BodyBB);
2149
2150 // Delete cookie for empty array.
2151 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
2152 EmitBlock(BB: DoneBB);
2153 EmitDeleteCall(DeleteFD: OperatorDelete, DeletePtr: AllocatedPtr, DeleteTy, NumElements,
2154 CookieSize);
2155 EmitBranch(Block: DeleteEnd);
2156
2157 EmitBlock(BB: BodyBB);
2158 CGM.getCXXABI().emitVirtualObjectDelete(CGF&: *this, DE: E, Ptr, ElementType: DeleteTy,
2159 Dtor);
2160 EmitBlock(BB: DeleteEnd);
2161 return;
2162 }
2163 }
2164 }
2165 }
2166
2167 if (E->isArrayForm()) {
2168 EmitArrayDelete(CGF&: *this, E, deletedPtr: Ptr, elementType: DeleteTy);
2169 EmitBlock(BB: DeleteEnd);
2170 } else {
2171 if (!EmitObjectDelete(CGF&: *this, DE: E, Ptr, ElementType: DeleteTy, UnconditionalDeleteBlock: DeleteEnd))
2172 EmitBlock(BB: DeleteEnd);
2173 }
2174}
2175
2176static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2177 llvm::Type *StdTypeInfoPtrTy,
2178 bool HasNullCheck) {
2179 // Get the vtable pointer.
2180 Address ThisPtr = CGF.EmitLValue(E).getAddress();
2181
2182 QualType SrcRecordTy = E->getType();
2183
2184 // C++ [class.cdtor]p4:
2185 // If the operand of typeid refers to the object under construction or
2186 // destruction and the static type of the operand is neither the constructor
2187 // or destructor’s class nor one of its bases, the behavior is undefined.
2188 CGF.EmitTypeCheck(TCK: CodeGenFunction::TCK_DynamicOperation, Loc: E->getExprLoc(),
2189 Addr: ThisPtr, Type: SrcRecordTy);
2190
2191 // Whether we need an explicit null pointer check. For example, with the
2192 // Microsoft ABI, if this is a call to __RTtypeid, the null pointer check and
2193 // exception throw is inside the __RTtypeid(nullptr) call
2194 if (HasNullCheck &&
2195 CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(SrcRecordTy)) {
2196 llvm::BasicBlock *BadTypeidBlock =
2197 CGF.createBasicBlock(name: "typeid.bad_typeid");
2198 llvm::BasicBlock *EndBlock = CGF.createBasicBlock(name: "typeid.end");
2199
2200 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Addr: ThisPtr);
2201 CGF.Builder.CreateCondBr(Cond: IsNull, True: BadTypeidBlock, False: EndBlock);
2202
2203 CGF.EmitBlock(BB: BadTypeidBlock);
2204 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2205 CGF.EmitBlock(BB: EndBlock);
2206 }
2207
2208 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2209 StdTypeInfoPtrTy);
2210}
2211
2212llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2213 // Ideally, we would like to use GlobalsInt8PtrTy here, however, we cannot,
2214 // primarily because the result of applying typeid is a value of type
2215 // type_info, which is declared & defined by the standard library
2216 // implementation and expects to operate on the generic (default) AS.
2217 // https://reviews.llvm.org/D157452 has more context, and a possible solution.
2218 llvm::Type *PtrTy = Int8PtrTy;
2219 LangAS GlobAS = CGM.GetGlobalVarAddressSpace(D: nullptr);
2220
2221 auto MaybeASCast = [=](llvm::Constant *TypeInfo) {
2222 if (GlobAS == LangAS::Default)
2223 return TypeInfo;
2224 return CGM.performAddrSpaceCast(Src: TypeInfo, DestTy: PtrTy);
2225 };
2226
2227 if (E->isTypeOperand()) {
2228 llvm::Constant *TypeInfo =
2229 CGM.GetAddrOfRTTIDescriptor(Ty: E->getTypeOperand(Context: getContext()));
2230 return MaybeASCast(TypeInfo);
2231 }
2232
2233 // C++ [expr.typeid]p2:
2234 // When typeid is applied to a glvalue expression whose type is a
2235 // polymorphic class type, the result refers to a std::type_info object
2236 // representing the type of the most derived object (that is, the dynamic
2237 // type) to which the glvalue refers.
2238 // If the operand is already most derived object, no need to look up vtable.
2239 if (E->isPotentiallyEvaluated() && !E->isMostDerived(Context: getContext()))
2240 return EmitTypeidFromVTable(CGF&: *this, E: E->getExprOperand(), StdTypeInfoPtrTy: PtrTy,
2241 HasNullCheck: E->hasNullCheck());
2242
2243 QualType OperandTy = E->getExprOperand()->getType();
2244 return MaybeASCast(CGM.GetAddrOfRTTIDescriptor(Ty: OperandTy));
2245}
2246
2247static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2248 QualType DestTy) {
2249 llvm::Type *DestLTy = CGF.ConvertType(T: DestTy);
2250 if (DestTy->isPointerType())
2251 return llvm::Constant::getNullValue(Ty: DestLTy);
2252
2253 /// C++ [expr.dynamic.cast]p9:
2254 /// A failed cast to reference type throws std::bad_cast
2255 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2256 return nullptr;
2257
2258 CGF.Builder.ClearInsertionPoint();
2259 return llvm::PoisonValue::get(T: DestLTy);
2260}
2261
2262llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2263 const CXXDynamicCastExpr *DCE) {
2264 CGM.EmitExplicitCastExprType(E: DCE, CGF: this);
2265 QualType DestTy = DCE->getTypeAsWritten();
2266
2267 QualType SrcTy = DCE->getSubExpr()->getType();
2268
2269 // C++ [expr.dynamic.cast]p7:
2270 // If T is "pointer to cv void," then the result is a pointer to the most
2271 // derived object pointed to by v.
2272 bool IsDynamicCastToVoid = DestTy->isVoidPointerType();
2273 QualType SrcRecordTy;
2274 QualType DestRecordTy;
2275 if (IsDynamicCastToVoid) {
2276 SrcRecordTy = SrcTy->getPointeeType();
2277 // No DestRecordTy.
2278 } else if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
2279 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2280 DestRecordTy = DestPTy->getPointeeType();
2281 } else {
2282 SrcRecordTy = SrcTy;
2283 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2284 }
2285
2286 // C++ [class.cdtor]p5:
2287 // If the operand of the dynamic_cast refers to the object under
2288 // construction or destruction and the static type of the operand is not a
2289 // pointer to or object of the constructor or destructor’s own class or one
2290 // of its bases, the dynamic_cast results in undefined behavior.
2291 EmitTypeCheck(TCK: TCK_DynamicOperation, Loc: DCE->getExprLoc(), Addr: ThisAddr, Type: SrcRecordTy);
2292
2293 if (DCE->isAlwaysNull()) {
2294 if (llvm::Value *T = EmitDynamicCastToNull(CGF&: *this, DestTy)) {
2295 // Expression emission is expected to retain a valid insertion point.
2296 if (!Builder.GetInsertBlock())
2297 EmitBlock(BB: createBasicBlock(name: "dynamic_cast.unreachable"));
2298 return T;
2299 }
2300 }
2301
2302 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2303
2304 // If the destination is effectively final, the cast succeeds if and only
2305 // if the dynamic type of the pointer is exactly the destination type.
2306 bool IsExact = !IsDynamicCastToVoid &&
2307 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2308 DestRecordTy->getAsCXXRecordDecl()->isEffectivelyFinal() &&
2309 CGM.getCXXABI().shouldEmitExactDynamicCast(DestRecordTy);
2310
2311 std::optional<CGCXXABI::ExactDynamicCastInfo> ExactCastInfo;
2312 if (IsExact) {
2313 ExactCastInfo = CGM.getCXXABI().getExactDynamicCastInfo(SrcRecordTy, DestTy,
2314 DestRecordTy);
2315 if (!ExactCastInfo) {
2316 llvm::Value *NullValue = EmitDynamicCastToNull(CGF&: *this, DestTy);
2317 if (!Builder.GetInsertBlock())
2318 EmitBlock(BB: createBasicBlock(name: "dynamic_cast.unreachable"));
2319 return NullValue;
2320 }
2321 }
2322
2323 // C++ [expr.dynamic.cast]p4:
2324 // If the value of v is a null pointer value in the pointer case, the result
2325 // is the null pointer value of type T.
2326 bool ShouldNullCheckSrcValue =
2327 IsExact || CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(
2328 SrcIsPtr: SrcTy->isPointerType(), SrcRecordTy);
2329
2330 llvm::BasicBlock *CastNull = nullptr;
2331 llvm::BasicBlock *CastNotNull = nullptr;
2332 llvm::BasicBlock *CastEnd = createBasicBlock(name: "dynamic_cast.end");
2333
2334 if (ShouldNullCheckSrcValue) {
2335 CastNull = createBasicBlock(name: "dynamic_cast.null");
2336 CastNotNull = createBasicBlock(name: "dynamic_cast.notnull");
2337
2338 llvm::Value *IsNull = Builder.CreateIsNull(Addr: ThisAddr);
2339 Builder.CreateCondBr(Cond: IsNull, True: CastNull, False: CastNotNull);
2340 EmitBlock(BB: CastNotNull);
2341 }
2342
2343 llvm::Value *Value;
2344 if (IsDynamicCastToVoid) {
2345 Value = CGM.getCXXABI().emitDynamicCastToVoid(CGF&: *this, Value: ThisAddr, SrcRecordTy);
2346 } else if (IsExact) {
2347 // If the destination type is effectively final, this pointer points to the
2348 // right type if and only if its vptr has the right value.
2349 Value = CGM.getCXXABI().emitExactDynamicCast(
2350 CGF&: *this, Value: ThisAddr, SrcRecordTy, DestTy, DestRecordTy, CastInfo: *ExactCastInfo,
2351 CastSuccess: CastEnd, CastFail: CastNull);
2352 } else {
2353 assert(DestRecordTy->isRecordType() &&
2354 "destination type must be a record type!");
2355 Value = CGM.getCXXABI().emitDynamicCastCall(CGF&: *this, Value: ThisAddr, SrcRecordTy,
2356 DestTy, DestRecordTy, CastEnd);
2357 }
2358 CastNotNull = Builder.GetInsertBlock();
2359
2360 llvm::Value *NullValue = nullptr;
2361 if (ShouldNullCheckSrcValue) {
2362 EmitBranch(Block: CastEnd);
2363
2364 EmitBlock(BB: CastNull);
2365 NullValue = EmitDynamicCastToNull(CGF&: *this, DestTy);
2366 CastNull = Builder.GetInsertBlock();
2367
2368 EmitBranch(Block: CastEnd);
2369 }
2370
2371 EmitBlock(BB: CastEnd);
2372
2373 if (CastNull) {
2374 llvm::PHINode *PHI = Builder.CreatePHI(Ty: Value->getType(), NumReservedValues: 2);
2375 PHI->addIncoming(V: Value, BB: CastNotNull);
2376 PHI->addIncoming(V: NullValue, BB: CastNull);
2377
2378 Value = PHI;
2379 }
2380
2381 return Value;
2382}
2383