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