1//===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
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 C++ code generation of classes
10//
11//===----------------------------------------------------------------------===//
12
13#include "ABIInfoImpl.h"
14#include "CGBlocks.h"
15#include "CGCXXABI.h"
16#include "CGDebugInfo.h"
17#include "CGRecordLayout.h"
18#include "CodeGenFunction.h"
19#include "TargetInfo.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/CXXInheritance.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/Basic/CodeGenOptions.h"
28#include "clang/CodeGen/CGFunctionInfo.h"
29#include "clang/CodeGenUtils/CodeGenUtils.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/Support/SaveAndRestore.h"
33#include "llvm/Transforms/Utils/ModuleUtils.h"
34#include "llvm/Transforms/Utils/SanitizerStats.h"
35#include <optional>
36
37using namespace clang;
38using namespace CodeGen;
39
40/// Return the best known alignment for an unknown pointer to a
41/// particular class.
42CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
43 if (!RD->hasDefinition())
44 return CharUnits::One(); // Hopefully won't be used anywhere.
45
46 auto &layout = getContext().getASTRecordLayout(D: RD);
47
48 // If the class is final, then we know that the pointer points to an
49 // object of that type and can use the full alignment.
50 if (RD->isEffectivelyFinal())
51 return layout.getAlignment();
52
53 // Otherwise, we have to assume it could be a subclass.
54 return layout.getNonVirtualAlignment();
55}
56
57/// Return the smallest possible amount of storage that might be allocated
58/// starting from the beginning of an object of a particular class.
59///
60/// This may be smaller than sizeof(RD) if RD has virtual base classes.
61CharUnits CodeGenModule::getMinimumClassObjectSize(const CXXRecordDecl *RD) {
62 if (!RD->hasDefinition())
63 return CharUnits::One();
64
65 auto &layout = getContext().getASTRecordLayout(D: RD);
66
67 // If the class is final, then we know that the pointer points to an
68 // object of that type and can use the full alignment.
69 if (RD->isEffectivelyFinal())
70 return layout.getSize();
71
72 // Otherwise, we have to assume it could be a subclass.
73 return std::max(a: layout.getNonVirtualSize(), b: CharUnits::One());
74}
75
76/// Return the best known alignment for a pointer to a virtual base,
77/// given the alignment of a pointer to the derived class.
78CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
79 const CXXRecordDecl *derivedClass,
80 const CXXRecordDecl *vbaseClass) {
81 // The basic idea here is that an underaligned derived pointer might
82 // indicate an underaligned base pointer.
83
84 assert(vbaseClass->isCompleteDefinition());
85 auto &baseLayout = getContext().getASTRecordLayout(D: vbaseClass);
86 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
87
88 return getDynamicOffsetAlignment(ActualAlign: actualDerivedAlign, Class: derivedClass,
89 ExpectedTargetAlign: expectedVBaseAlign);
90}
91
92CharUnits
93CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
94 const CXXRecordDecl *baseDecl,
95 CharUnits expectedTargetAlign) {
96 // If the base is an incomplete type (which is, alas, possible with
97 // member pointers), be pessimistic.
98 if (!baseDecl->isCompleteDefinition())
99 return std::min(a: actualBaseAlign, b: expectedTargetAlign);
100
101 auto &baseLayout = getContext().getASTRecordLayout(D: baseDecl);
102 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
103
104 // If the class is properly aligned, assume the target offset is, too.
105 //
106 // This actually isn't necessarily the right thing to do --- if the
107 // class is a complete object, but it's only properly aligned for a
108 // base subobject, then the alignments of things relative to it are
109 // probably off as well. (Note that this requires the alignment of
110 // the target to be greater than the NV alignment of the derived
111 // class.)
112 //
113 // However, our approach to this kind of under-alignment can only
114 // ever be best effort; after all, we're never going to propagate
115 // alignments through variables or parameters. Note, in particular,
116 // that constructing a polymorphic type in an address that's less
117 // than pointer-aligned will generally trap in the constructor,
118 // unless we someday add some sort of attribute to change the
119 // assumed alignment of 'this'. So our goal here is pretty much
120 // just to allow the user to explicitly say that a pointer is
121 // under-aligned and then safely access its fields and vtables.
122 if (actualBaseAlign >= expectedBaseAlign) {
123 return expectedTargetAlign;
124 }
125
126 // Otherwise, we might be offset by an arbitrary multiple of the
127 // actual alignment. The correct adjustment is to take the min of
128 // the two alignments.
129 return std::min(a: actualBaseAlign, b: expectedTargetAlign);
130}
131
132Address CodeGenFunction::LoadCXXThisAddress() {
133 assert(CurFuncDecl && "loading 'this' without a func declaration?");
134 auto *MD = cast<CXXMethodDecl>(Val: CurFuncDecl);
135
136 // Lazily compute CXXThisAlignment.
137 if (CXXThisAlignment.isZero()) {
138 // Just use the best known alignment for the parent.
139 // TODO: if we're currently emitting a complete-object ctor/dtor,
140 // we can always use the complete-object alignment.
141 CXXThisAlignment = CGM.getClassPointerAlignment(RD: MD->getParent());
142 }
143
144 return makeNaturalAddressForPointer(
145 Ptr: LoadCXXThis(), T: MD->getFunctionObjectParameterType(), Alignment: CXXThisAlignment,
146 ForPointeeType: false, BaseInfo: nullptr, TBAAInfo: nullptr, IsKnownNonNull: KnownNonNull);
147}
148
149/// Emit the address of a field using a member data pointer.
150///
151/// \param E Only used for emergency diagnostics
152Address CodeGenFunction::EmitCXXMemberDataPointerAddress(
153 const Expr *E, Address base, llvm::Value *memberPtr,
154 const MemberPointerType *memberPtrType, bool IsInBounds,
155 LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
156 // Ask the ABI to compute the actual address.
157 llvm::Value *ptr = CGM.getCXXABI().EmitMemberDataPointerAddress(
158 CGF&: *this, E, Base: base, MemPtr: memberPtr, MPT: memberPtrType, IsInBounds);
159
160 QualType memberType = memberPtrType->getPointeeType();
161 CharUnits memberAlign =
162 CGM.getNaturalTypeAlignment(T: memberType, BaseInfo, TBAAInfo);
163 memberAlign = CGM.getDynamicOffsetAlignment(
164 actualBaseAlign: base.getAlignment(), baseDecl: memberPtrType->getMostRecentCXXRecordDecl(),
165 expectedTargetAlign: memberAlign);
166 return Address(ptr, ConvertTypeForMem(T: memberPtrType->getPointeeType()),
167 memberAlign);
168}
169
170CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
171 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
172 CastExpr::path_const_iterator End) {
173 CharUnits Offset = CharUnits::Zero();
174
175 const ASTContext &Context = getContext();
176 const CXXRecordDecl *RD = DerivedClass;
177
178 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
179 const CXXBaseSpecifier *Base = *I;
180 assert(!Base->isVirtual() && "Should not see virtual bases here!");
181
182 // Get the layout.
183 const ASTRecordLayout &Layout = Context.getASTRecordLayout(D: RD);
184
185 const auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
186 // Add the offset.
187 Offset += Layout.getBaseClassOffset(Base: BaseDecl);
188
189 RD = BaseDecl;
190 }
191
192 return Offset;
193}
194
195llvm::Constant *CodeGenModule::GetNonVirtualBaseClassOffset(
196 const CXXRecordDecl *ClassDecl, CastExpr::path_const_iterator PathBegin,
197 CastExpr::path_const_iterator PathEnd) {
198 assert(PathBegin != PathEnd && "Base path should not be empty!");
199
200 CharUnits Offset =
201 computeNonVirtualBaseClassOffset(DerivedClass: ClassDecl, Start: PathBegin, End: PathEnd);
202 if (Offset.isZero())
203 return nullptr;
204
205 llvm::Type *PtrDiffTy =
206 getTypes().ConvertType(T: getContext().getPointerDiffType());
207
208 return llvm::ConstantInt::get(Ty: PtrDiffTy, V: Offset.getQuantity());
209}
210
211/// Gets the address of a direct base class within a complete object.
212/// This should only be used for (1) non-virtual bases or (2) virtual bases
213/// when the type is known to be complete (e.g. in complete destructors).
214///
215/// The object pointed to by 'This' is assumed to be non-null.
216Address CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(
217 Address This, const CXXRecordDecl *Derived, const CXXRecordDecl *Base,
218 bool BaseIsVirtual) {
219 // 'this' must be a pointer (in some address space) to Derived.
220 assert(This.getElementType() == ConvertType(Derived));
221
222 // Compute the offset of the virtual base.
223 CharUnits Offset;
224 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D: Derived);
225 if (BaseIsVirtual)
226 Offset = Layout.getVBaseClassOffset(VBase: Base);
227 else
228 Offset = Layout.getBaseClassOffset(Base);
229
230 // Shift and cast down to the base type.
231 // TODO: for complete types, this should be possible with a GEP.
232 Address V = This;
233 if (!Offset.isZero()) {
234 V = V.withElementType(ElemTy: Int8Ty);
235 V = Builder.CreateConstInBoundsByteGEP(Addr: V, Offset);
236 }
237 return V.withElementType(ElemTy: ConvertType(T: Base));
238}
239
240static Address ApplyNonVirtualAndVirtualOffset(
241 CodeGenFunction &CGF, Address addr, CharUnits nonVirtualOffset,
242 llvm::Value *virtualOffset, const CXXRecordDecl *derivedClass,
243 const CXXRecordDecl *nearestVBase) {
244 // Assert that we have something to do.
245 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
246
247 // Compute the offset from the static and dynamic components.
248 llvm::Value *baseOffset;
249 if (!nonVirtualOffset.isZero()) {
250 llvm::Type *OffsetType =
251 (CGF.CGM.getTarget().getCXXABI().isItaniumFamily() &&
252 CGF.CGM.getLangOpts().RelativeCXXABIVTables)
253 ? CGF.Int32Ty
254 : CGF.PtrDiffTy;
255 baseOffset =
256 llvm::ConstantInt::get(Ty: OffsetType, V: nonVirtualOffset.getQuantity());
257 if (virtualOffset) {
258 baseOffset = CGF.Builder.CreateAdd(LHS: virtualOffset, RHS: baseOffset);
259 }
260 } else {
261 baseOffset = virtualOffset;
262 }
263
264 // Apply the base offset.
265 llvm::Value *ptr = addr.emitRawPointer(CGF);
266 ptr = CGF.Builder.CreateInBoundsGEP(Ty: CGF.Int8Ty, Ptr: ptr, IdxList: baseOffset, Name: "add.ptr");
267
268 // If we have a virtual component, the alignment of the result will
269 // be relative only to the known alignment of that vbase.
270 CharUnits alignment;
271 if (virtualOffset) {
272 assert(nearestVBase && "virtual offset without vbase?");
273 alignment = CGF.CGM.getVBaseAlignment(actualDerivedAlign: addr.getAlignment(), derivedClass,
274 vbaseClass: nearestVBase);
275 } else {
276 alignment = addr.getAlignment();
277 }
278 alignment = alignment.alignmentAtOffset(offset: nonVirtualOffset);
279
280 return Address(ptr, CGF.Int8Ty, alignment);
281}
282
283Address CodeGenFunction::GetAddressOfBaseClass(
284 Address Value, const CXXRecordDecl *Derived,
285 CastExpr::path_const_iterator PathBegin,
286 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
287 SourceLocation Loc) {
288 assert(PathBegin != PathEnd && "Base path should not be empty!");
289
290 CastExpr::path_const_iterator Start = PathBegin;
291 const CXXRecordDecl *VBase = nullptr;
292
293 // Sema has done some convenient canonicalization here: if the
294 // access path involved any virtual steps, the conversion path will
295 // *start* with a step down to the correct virtual base subobject,
296 // and hence will not require any further steps.
297 if ((*Start)->isVirtual()) {
298 VBase = (*Start)->getType()->castAsCXXRecordDecl();
299 ++Start;
300 }
301
302 // Compute the static offset of the ultimate destination within its
303 // allocating subobject (the virtual base, if there is one, or else
304 // the "complete" object that we see).
305 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
306 DerivedClass: VBase ? VBase : Derived, Start, End: PathEnd);
307
308 // If there's a virtual step, we can sometimes "devirtualize" it.
309 // For now, that's limited to when the derived type is final.
310 // TODO: "devirtualize" this for accesses to known-complete objects.
311 if (VBase && Derived->hasAttr<FinalAttr>()) {
312 const ASTRecordLayout &layout = getContext().getASTRecordLayout(D: Derived);
313 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
314 NonVirtualOffset += vBaseOffset;
315 VBase = nullptr; // we no longer have a virtual step
316 }
317
318 // Get the base pointer type.
319 llvm::Type *BaseValueTy = ConvertType(T: (PathEnd[-1])->getType());
320 llvm::Type *PtrTy = llvm::PointerType::get(
321 C&: CGM.getLLVMContext(), AddressSpace: Value.getType()->getPointerAddressSpace());
322
323 CanQualType DerivedTy = getContext().getCanonicalTagType(TD: Derived);
324 CharUnits DerivedAlign = CGM.getClassPointerAlignment(RD: Derived);
325
326 // If the static offset is zero and we don't have a virtual step,
327 // just do a bitcast; null checks are unnecessary.
328 if (NonVirtualOffset.isZero() && !VBase) {
329 if (sanitizePerformTypeCheck()) {
330 SanitizerSet SkippedChecks;
331 SkippedChecks.set(K: SanitizerKind::Null, Value: !NullCheckValue);
332 EmitTypeCheck(TCK: TCK_Upcast, Loc, V: Value.emitRawPointer(CGF&: *this), Type: DerivedTy,
333 Alignment: DerivedAlign, SkippedChecks);
334 }
335 return Value.withElementType(ElemTy: BaseValueTy);
336 }
337
338 llvm::BasicBlock *origBB = nullptr;
339 llvm::BasicBlock *endBB = nullptr;
340
341 // Skip over the offset (and the vtable load) if we're supposed to
342 // null-check the pointer.
343 if (NullCheckValue) {
344 origBB = Builder.GetInsertBlock();
345 llvm::BasicBlock *notNullBB = createBasicBlock(name: "cast.notnull");
346 endBB = createBasicBlock(name: "cast.end");
347
348 llvm::Value *isNull = Builder.CreateIsNull(Addr: Value);
349 Builder.CreateCondBr(Cond: isNull, True: endBB, False: notNullBB);
350 EmitBlock(BB: notNullBB);
351 }
352
353 if (sanitizePerformTypeCheck()) {
354 SanitizerSet SkippedChecks;
355 SkippedChecks.set(K: SanitizerKind::Null, Value: true);
356 EmitTypeCheck(TCK: VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
357 V: Value.emitRawPointer(CGF&: *this), Type: DerivedTy, Alignment: DerivedAlign,
358 SkippedChecks);
359 }
360
361 // Compute the virtual offset.
362 llvm::Value *VirtualOffset = nullptr;
363 if (VBase) {
364 VirtualOffset =
365 CGM.getCXXABI().GetVirtualBaseClassOffset(CGF&: *this, This: Value, ClassDecl: Derived, BaseClassDecl: VBase);
366 }
367
368 // Apply both offsets.
369 Value = ApplyNonVirtualAndVirtualOffset(CGF&: *this, addr: Value, nonVirtualOffset: NonVirtualOffset,
370 virtualOffset: VirtualOffset, derivedClass: Derived, nearestVBase: VBase);
371
372 // Cast to the destination type.
373 Value = Value.withElementType(ElemTy: BaseValueTy);
374
375 // Build a phi if we needed a null check.
376 if (NullCheckValue) {
377 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
378 Builder.CreateBr(Dest: endBB);
379 EmitBlock(BB: endBB);
380
381 llvm::PHINode *PHI = Builder.CreatePHI(Ty: PtrTy, NumReservedValues: 2, Name: "cast.result");
382 PHI->addIncoming(V: Value.emitRawPointer(CGF&: *this), BB: notNullBB);
383 PHI->addIncoming(V: llvm::Constant::getNullValue(Ty: PtrTy), BB: origBB);
384 Value = Value.withPointer(NewPointer: PHI, IsKnownNonNull: NotKnownNonNull);
385 }
386
387 return Value;
388}
389
390Address CodeGenFunction::GetAddressOfDerivedClass(
391 Address BaseAddr, const CXXRecordDecl *Derived,
392 CastExpr::path_const_iterator PathBegin,
393 CastExpr::path_const_iterator PathEnd, bool NullCheckValue) {
394 assert(PathBegin != PathEnd && "Base path should not be empty!");
395
396 CanQualType DerivedTy = getContext().getCanonicalTagType(TD: Derived);
397 llvm::Type *DerivedValueTy = ConvertType(T: DerivedTy);
398
399 llvm::Value *NonVirtualOffset =
400 CGM.GetNonVirtualBaseClassOffset(ClassDecl: Derived, PathBegin, PathEnd);
401
402 if (!NonVirtualOffset) {
403 // No offset, we can just cast back.
404 return BaseAddr.withElementType(ElemTy: DerivedValueTy);
405 }
406
407 llvm::BasicBlock *CastNull = nullptr;
408 llvm::BasicBlock *CastNotNull = nullptr;
409 llvm::BasicBlock *CastEnd = nullptr;
410
411 if (NullCheckValue) {
412 CastNull = createBasicBlock(name: "cast.null");
413 CastNotNull = createBasicBlock(name: "cast.notnull");
414 CastEnd = createBasicBlock(name: "cast.end");
415
416 llvm::Value *IsNull = Builder.CreateIsNull(Addr: BaseAddr);
417 Builder.CreateCondBr(Cond: IsNull, True: CastNull, False: CastNotNull);
418 EmitBlock(BB: CastNotNull);
419 }
420
421 // Apply the offset.
422 Address Addr = BaseAddr.withElementType(ElemTy: Int8Ty);
423 Addr = Builder.CreateInBoundsGEP(
424 Addr, IdxList: Builder.CreateNeg(V: NonVirtualOffset), ElementType: Int8Ty,
425 Align: CGM.getClassPointerAlignment(RD: Derived), Name: "sub.ptr");
426
427 // Just cast.
428 Addr = Addr.withElementType(ElemTy: DerivedValueTy);
429
430 // Produce a PHI if we had a null-check.
431 if (NullCheckValue) {
432 Builder.CreateBr(Dest: CastEnd);
433 EmitBlock(BB: CastNull);
434 Builder.CreateBr(Dest: CastEnd);
435 EmitBlock(BB: CastEnd);
436
437 llvm::Value *Value = Addr.emitRawPointer(CGF&: *this);
438 llvm::PHINode *PHI = Builder.CreatePHI(Ty: Value->getType(), NumReservedValues: 2);
439 PHI->addIncoming(V: Value, BB: CastNotNull);
440 PHI->addIncoming(V: llvm::Constant::getNullValue(Ty: Value->getType()), BB: CastNull);
441 return Address(PHI, Addr.getElementType(),
442 CGM.getClassPointerAlignment(RD: Derived));
443 }
444
445 return Addr;
446}
447
448llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
449 bool ForVirtualBase,
450 bool Delegating) {
451 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
452 // This constructor/destructor does not need a VTT parameter.
453 return nullptr;
454 }
455
456 const CXXRecordDecl *RD = cast<CXXMethodDecl>(Val: CurCodeDecl)->getParent();
457 const CXXRecordDecl *Base = cast<CXXMethodDecl>(Val: GD.getDecl())->getParent();
458
459 uint64_t SubVTTIndex;
460
461 if (Delegating) {
462 // If this is a delegating constructor call, just load the VTT.
463 return LoadCXXVTT();
464 } else if (RD == Base) {
465 // If the record matches the base, this is the complete ctor/dtor
466 // variant calling the base variant in a class with virtual bases.
467 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
468 "doing no-op VTT offset in base dtor/ctor?");
469 assert(!ForVirtualBase && "Can't have same class as virtual base!");
470 SubVTTIndex = 0;
471 } else {
472 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D: RD);
473 CharUnits BaseOffset = ForVirtualBase ? Layout.getVBaseClassOffset(VBase: Base)
474 : Layout.getBaseClassOffset(Base);
475
476 SubVTTIndex =
477 CGM.getVTables().getSubVTTIndex(RD, Base: BaseSubobject(Base, BaseOffset));
478 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
479 }
480
481 llvm::Value *VTT;
482 if (CGM.getCXXABI().NeedsVTTParameter(GD: CurGD)) {
483 // A VTT parameter was passed to the constructor, use it.
484 VTT = LoadCXXVTT();
485 } else {
486 // We're the complete constructor, so get the VTT by name.
487 VTT = CGM.getVTables().GetAddrOfVTT(RD);
488 }
489 return Builder.CreateConstInBoundsGEP1_64(Ty: CGM.GlobalsInt8PtrTy, Ptr: VTT,
490 Idx0: SubVTTIndex);
491}
492
493namespace {
494/// Call the destructor for a direct base class.
495struct CallBaseDtor final : EHScopeStack::Cleanup {
496 const CXXRecordDecl *BaseClass;
497 bool BaseIsVirtual;
498 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
499 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
500
501 void Emit(CodeGenFunction &CGF, Flags flags) override {
502 const CXXRecordDecl *DerivedClass =
503 cast<CXXMethodDecl>(Val: CGF.CurCodeDecl)->getParent();
504
505 const CXXDestructorDecl *D = BaseClass->getDestructor();
506 // We are already inside a destructor, so presumably the object being
507 // destroyed should have the expected type.
508 QualType ThisTy = D->getFunctionObjectParameterType();
509 Address Addr = CGF.GetAddressOfDirectBaseInCompleteClass(
510 This: CGF.LoadCXXThisAddress(), Derived: DerivedClass, Base: BaseClass, BaseIsVirtual);
511 CGF.EmitCXXDestructorCall(D, Type: Dtor_Base, ForVirtualBase: BaseIsVirtual,
512 /*Delegating=*/false, This: Addr, ThisTy);
513 }
514};
515
516/// A visitor which checks whether an initializer uses 'this' in a
517/// way which requires the vtable to be properly set.
518struct DynamicThisUseChecker
519 : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
520 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
521
522 bool UsesThis;
523
524 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
525
526 // Black-list all explicit and implicit references to 'this'.
527 //
528 // Do we need to worry about external references to 'this' derived
529 // from arbitrary code? If so, then anything which runs arbitrary
530 // external code might potentially access the vtable.
531 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
532};
533} // end anonymous namespace
534
535static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
536 DynamicThisUseChecker Checker(C);
537 Checker.Visit(S: Init);
538 return Checker.UsesThis;
539}
540
541static void EmitBaseInitializer(CodeGenFunction &CGF,
542 const CXXRecordDecl *ClassDecl,
543 CXXCtorInitializer *BaseInit) {
544 assert(BaseInit->isBaseInitializer() && "Must have base initializer!");
545
546 Address ThisPtr = CGF.LoadCXXThisAddress();
547
548 const auto *BaseClassDecl = BaseInit->getBaseClass()->castAsCXXRecordDecl();
549
550 bool isBaseVirtual = BaseInit->isBaseVirtual();
551
552 // If the initializer for the base (other than the constructor
553 // itself) accesses 'this' in any way, we need to initialize the
554 // vtables.
555 if (BaseInitializerUsesThis(C&: CGF.getContext(), Init: BaseInit->getInit()))
556 CGF.InitializeVTablePointers(ClassDecl);
557
558 // We can pretend to be a complete class because it only matters for
559 // virtual bases, and we only do virtual bases for complete ctors.
560 Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
561 This: ThisPtr, Derived: ClassDecl, Base: BaseClassDecl, BaseIsVirtual: isBaseVirtual);
562 AggValueSlot AggSlot = AggValueSlot::forAddr(
563 addr: V, quals: Qualifiers(), isDestructed: AggValueSlot::IsDestructed,
564 needsGC: AggValueSlot::DoesNotNeedGCBarriers, isAliased: AggValueSlot::IsNotAliased,
565 mayOverlap: CGF.getOverlapForBaseInit(RD: ClassDecl, BaseRD: BaseClassDecl, IsVirtual: isBaseVirtual));
566
567 CGF.EmitAggExpr(E: BaseInit->getInit(), AS: AggSlot);
568
569 if (CGF.CGM.getLangOpts().Exceptions &&
570 !BaseClassDecl->hasTrivialDestructor())
571 CGF.EHStack.pushCleanup<CallBaseDtor>(Kind: EHCleanup, A: BaseClassDecl,
572 A: isBaseVirtual);
573}
574
575static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
576 CXXCtorInitializer *MemberInit,
577 LValue &LHS) {
578 FieldDecl *Field = MemberInit->getAnyMember();
579 if (MemberInit->isIndirectMemberInitializer()) {
580 // If we are initializing an anonymous union field, drill down to the field.
581 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
582 for (const auto *I : IndirectField->chain())
583 LHS = CGF.EmitLValueForFieldInitialization(Base: LHS, Field: cast<FieldDecl>(Val: I));
584 } else {
585 LHS = CGF.EmitLValueForFieldInitialization(Base: LHS, Field);
586 }
587}
588
589static void EmitMemberInitializer(CodeGenFunction &CGF,
590 const CXXRecordDecl *ClassDecl,
591 CXXCtorInitializer *MemberInit,
592 const CXXConstructorDecl *Constructor,
593 FunctionArgList &Args) {
594 ApplyAtomGroup Grp(CGF.getDebugInfo());
595 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
596 assert(MemberInit->isAnyMemberInitializer() &&
597 "Must have member initializer!");
598 assert(MemberInit->getInit() && "Must have initializer!");
599
600 // non-static data member initializers.
601 FieldDecl *Field = MemberInit->getAnyMember();
602 QualType FieldType = Field->getType();
603
604 llvm::Value *ThisPtr = CGF.LoadCXXThis();
605 CanQualType RecordTy = CGF.getContext().getCanonicalTagType(TD: ClassDecl);
606 LValue LHS;
607
608 // If a base constructor is being emitted, create an LValue that has the
609 // non-virtual alignment.
610 if (CGF.CurGD.getCtorType() == Ctor_Base)
611 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(V: ThisPtr, T: RecordTy);
612 else
613 LHS = CGF.MakeNaturalAlignAddrLValue(V: ThisPtr, T: RecordTy);
614
615 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
616
617 // Special case: if we are in a copy or move constructor, and we are copying
618 // an array of PODs or classes with trivial copy constructors, ignore the
619 // AST and perform the copy we know is equivalent.
620 // FIXME: This is hacky at best... if we had a bit more explicit information
621 // in the AST, we could generalize it more easily.
622 const ConstantArrayType *Array =
623 CGF.getContext().getAsConstantArrayType(T: FieldType);
624 if (Array && Constructor->isDefaulted() &&
625 Constructor->isCopyOrMoveConstructor()) {
626 QualType BaseElementTy = CGF.getContext().getBaseElementType(VAT: Array);
627 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Val: MemberInit->getInit());
628 if (BaseElementTy.isPODType(Context: CGF.getContext()) ||
629 (CE && CE->getConstructor()->isMemcpyEquivalentSpecialMember(
630 Ctx: CGF.getContext()))) {
631 unsigned SrcArgIndex =
632 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
633 llvm::Value *SrcPtr =
634 CGF.Builder.CreateLoad(Addr: CGF.GetAddrOfLocalVar(VD: Args[SrcArgIndex]));
635 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(V: SrcPtr, T: RecordTy);
636 LValue Src = CGF.EmitLValueForFieldInitialization(Base: ThisRHSLV, Field);
637
638 // Copy the aggregate.
639 CGF.EmitAggregateCopy(Dest: LHS, Src, EltTy: FieldType,
640 MayOverlap: CGF.getOverlapForFieldInit(FD: Field),
641 isVolatile: LHS.isVolatileQualified());
642 // Ensure that we destroy the objects if an exception is thrown later in
643 // the constructor.
644 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
645 if (CGF.needsEHCleanup(kind: dtorKind))
646 CGF.pushEHDestroy(dtorKind, addr: LHS.getAddress(), type: FieldType);
647 return;
648 }
649 }
650
651 CGF.EmitInitializerForField(Field, LHS, Init: MemberInit->getInit());
652}
653
654void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
655 Expr *Init) {
656 QualType FieldType = Field->getType();
657 switch (getEvaluationKind(T: FieldType)) {
658 case TEK_Scalar:
659 if (LHS.isSimple()) {
660 EmitExprAsInit(init: Init, D: Field, lvalue: LHS, capturedByInit: false);
661 } else {
662 RValue RHS = RValue::get(V: EmitScalarExpr(E: Init));
663 EmitStoreThroughLValue(Src: RHS, Dst: LHS);
664 }
665 break;
666 case TEK_Complex:
667 EmitComplexExprIntoLValue(E: Init, dest: LHS, /*isInit*/ true);
668 break;
669 case TEK_Aggregate: {
670 AggValueSlot Slot = AggValueSlot::forLValue(
671 LV: LHS, isDestructed: AggValueSlot::IsDestructed, needsGC: AggValueSlot::DoesNotNeedGCBarriers,
672 isAliased: AggValueSlot::IsNotAliased, mayOverlap: getOverlapForFieldInit(FD: Field),
673 isZeroed: AggValueSlot::IsNotZeroed,
674 // Checks are made by the code that calls constructor.
675 isChecked: AggValueSlot::IsSanitizerChecked);
676 EmitAggExpr(E: Init, AS: Slot);
677 break;
678 }
679 }
680
681 // Ensure that we destroy this object if an exception is thrown
682 // later in the constructor.
683 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
684 if (needsEHCleanup(kind: dtorKind))
685 pushEHDestroy(dtorKind, addr: LHS.getAddress(), type: FieldType);
686}
687
688/// Checks whether the given constructor is a valid subject for the
689/// complete-to-base constructor delegation optimization, i.e.
690/// emitting the complete constructor as a simple call to the base
691/// constructor.
692bool CodeGenFunction::IsConstructorDelegationValid(
693 const CXXConstructorDecl *Ctor) {
694
695 // Currently we disable the optimization for classes with virtual
696 // bases because (1) the addresses of parameter variables need to be
697 // consistent across all initializers but (2) the delegate function
698 // call necessarily creates a second copy of the parameter variable.
699 //
700 // The limiting example (purely theoretical AFAIK):
701 // struct A { A(int &c) { c++; } };
702 // struct B : virtual A {
703 // B(int count) : A(count) { printf("%d\n", count); }
704 // };
705 // ...although even this example could in principle be emitted as a
706 // delegation since the address of the parameter doesn't escape.
707 if (Ctor->getParent()->getNumVBases()) {
708 // TODO: white-list trivial vbase initializers. This case wouldn't
709 // be subject to the restrictions below.
710
711 // TODO: white-list cases where:
712 // - there are no non-reference parameters to the constructor
713 // - the initializers don't access any non-reference parameters
714 // - the initializers don't take the address of non-reference
715 // parameters
716 // - etc.
717 // If we ever add any of the above cases, remember that:
718 // - function-try-blocks will always exclude this optimization
719 // - we need to perform the constructor prologue and cleanup in
720 // EmitConstructorBody.
721
722 return false;
723 }
724
725 // We also disable the optimization for variadic functions because
726 // it's impossible to "re-pass" varargs.
727 if (Ctor->getType()->castAs<FunctionProtoType>()->isVariadic())
728 return false;
729
730 // FIXME: Decide if we can do a delegation of a delegating constructor.
731 if (Ctor->isDelegatingConstructor())
732 return false;
733
734 return true;
735}
736
737// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
738// to poison the extra field paddings inserted under
739// -fsanitize-address-field-padding=1|2.
740void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
741 ASTContext &Context = getContext();
742 const CXXRecordDecl *ClassDecl =
743 Prologue ? cast<CXXConstructorDecl>(Val: CurGD.getDecl())->getParent()
744 : cast<CXXDestructorDecl>(Val: CurGD.getDecl())->getParent();
745 if (!ClassDecl->mayInsertExtraPadding())
746 return;
747
748 struct SizeAndOffset {
749 uint64_t Size;
750 uint64_t Offset;
751 };
752
753 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
754 const ASTRecordLayout &Info = Context.getASTRecordLayout(D: ClassDecl);
755
756 // Populate sizes and offsets of fields.
757 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
758 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
759 SSV[i].Offset =
760 Context.toCharUnitsFromBits(BitSize: Info.getFieldOffset(FieldNo: i)).getQuantity();
761
762 size_t NumFields = 0;
763 for (const auto *Field : ClassDecl->fields()) {
764 const FieldDecl *D = Field;
765 auto FieldInfo = Context.getTypeInfoInChars(T: D->getType());
766 CharUnits FieldSize = FieldInfo.Width;
767 assert(NumFields < SSV.size());
768 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
769 NumFields++;
770 }
771 assert(NumFields == SSV.size());
772 if (SSV.size() <= 1)
773 return;
774
775 // We will insert calls to __asan_* run-time functions.
776 // LLVM AddressSanitizer pass may decide to inline them later.
777 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
778 llvm::FunctionType *FTy = llvm::FunctionType::get(Result: CGM.VoidTy, Params: Args, isVarArg: false);
779 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
780 Ty: FTy, Name: Prologue ? "__asan_poison_intra_object_redzone"
781 : "__asan_unpoison_intra_object_redzone");
782
783 llvm::Value *ThisPtr = LoadCXXThis();
784 ThisPtr = Builder.CreatePtrToInt(V: ThisPtr, DestTy: IntPtrTy);
785 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
786 // For each field check if it has sufficient padding,
787 // if so (un)poison it with a call.
788 for (size_t i = 0; i < SSV.size(); i++) {
789 uint64_t AsanAlignment = 8;
790 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
791 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
792 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
793 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
794 (NextField % AsanAlignment) != 0)
795 continue;
796 Builder.CreateCall(
797 Callee: F, Args: {Builder.CreateAdd(LHS: ThisPtr, RHS: Builder.getIntN(N: PtrSize, C: EndOffset)),
798 Builder.getIntN(N: PtrSize, C: PoisonSize)});
799 }
800}
801
802/// EmitConstructorBody - Emits the body of the current constructor.
803void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
804 EmitAsanPrologueOrEpilogue(Prologue: true);
805 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(Val: CurGD.getDecl());
806 CXXCtorType CtorType = CurGD.getCtorType();
807
808 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
809 CtorType == Ctor_Complete) &&
810 "can only generate complete ctor for this ABI");
811
812 // Before we go any further, try the complete->base constructor
813 // delegation optimization.
814 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
815 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
816 EmitDelegateCXXConstructorCall(Ctor, CtorType: Ctor_Base, Args, Loc: Ctor->getEndLoc());
817 return;
818 }
819
820 const FunctionDecl *Definition = nullptr;
821 Stmt *Body = Ctor->getBody(Definition);
822 assert(Definition == Ctor && "emitting wrong constructor body");
823
824 // Enter the function-try-block before the constructor prologue if
825 // applicable.
826 bool IsTryBody = isa_and_nonnull<CXXTryStmt>(Val: Body);
827 if (IsTryBody)
828 EnterCXXTryStmt(S: *cast<CXXTryStmt>(Val: Body), IsFnTryBlock: true);
829
830 incrementProfileCounter(S: Body);
831 maybeCreateMCDCCondBitmap();
832
833 RunCleanupsScope RunCleanups(*this);
834
835 // TODO: in restricted cases, we can emit the vbase initializers of
836 // a complete ctor and then delegate to the base ctor.
837
838 // Emit the constructor prologue, i.e. the base and member
839 // initializers.
840 EmitCtorPrologue(CD: Ctor, Type: CtorType, Args);
841
842 // Emit the body of the statement.
843 if (IsTryBody)
844 EmitStmt(S: cast<CXXTryStmt>(Val: Body)->getTryBlock());
845 else if (Body)
846 EmitStmt(S: Body);
847
848 // Emit any cleanup blocks associated with the member or base
849 // initializers, which includes (along the exceptional path) the
850 // destructors for those members and bases that were fully
851 // constructed.
852 RunCleanups.ForceCleanup();
853
854 if (IsTryBody)
855 ExitCXXTryStmt(S: *cast<CXXTryStmt>(Val: Body), IsFnTryBlock: true);
856}
857
858namespace {
859/// RAII object to indicate that codegen is copying the value representation
860/// instead of the object representation. Useful when copying a struct or
861/// class which has uninitialized members and we're only performing
862/// lvalue-to-rvalue conversion on the object but not its members.
863class CopyingValueRepresentation {
864public:
865 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
866 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
867 CGF.SanOpts.set(K: SanitizerKind::Bool, Value: false);
868 CGF.SanOpts.set(K: SanitizerKind::Enum, Value: false);
869 }
870 ~CopyingValueRepresentation() { CGF.SanOpts = OldSanOpts; }
871
872private:
873 CodeGenFunction &CGF;
874 SanitizerSet OldSanOpts;
875};
876} // end anonymous namespace
877
878namespace {
879class FieldMemcpyizer {
880public:
881 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
882 const VarDecl *SrcRec)
883 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
884 RecLayout(CGF.getContext().getASTRecordLayout(D: ClassDecl)),
885 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
886 LastFieldOffset(0), LastAddedFieldIndex(0) {}
887
888 bool isMemcpyableField(FieldDecl *F) const {
889 // Never memcpy fields when we are adding poisoned paddings.
890 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
891 return false;
892 Qualifiers Qual = F->getType().getQualifiers();
893 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
894 return false;
895 if (PointerAuthQualifier Q = F->getType().getPointerAuth();
896 Q && Q.isAddressDiscriminated())
897 return false;
898 // Non-trivially-copyable fields with pointer field protection need to be
899 // copied one by one.
900 if (!CGF.getContext().arePFPFieldsTriviallyCopyable(RD: ClassDecl) &&
901 CGF.getContext().isPFPField(Field: F))
902 return false;
903 return true;
904 }
905
906 void addMemcpyableField(FieldDecl *F) {
907 if (isEmptyFieldForLayout(Context: CGF.getContext(), FD: F))
908 return;
909 if (!FirstField)
910 addInitialField(F);
911 else
912 addNextField(F);
913 }
914
915 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
916 ASTContext &Ctx = CGF.getContext();
917 unsigned LastFieldSize =
918 LastField->isBitField()
919 ? LastField->getBitWidthValue()
920 : Ctx.toBits(
921 CharSize: Ctx.getTypeInfoDataSizeInChars(T: LastField->getType()).Width);
922 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
923 FirstByteOffset + Ctx.getCharWidth() - 1;
924 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(BitSize: MemcpySizeBits);
925 return MemcpySize;
926 }
927
928 void emitMemcpy() {
929 // Give the subclass a chance to bail out if it feels the memcpy isn't
930 // worth it (e.g. Hasn't aggregated enough data).
931 if (!FirstField) {
932 return;
933 }
934
935 uint64_t FirstByteOffset;
936 if (FirstField->isBitField()) {
937 const CGRecordLayout &RL =
938 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
939 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FD: FirstField);
940 // FirstFieldOffset is not appropriate for bitfields,
941 // we need to use the storage offset instead.
942 FirstByteOffset = CGF.getContext().toBits(CharSize: BFInfo.StorageOffset);
943 } else {
944 FirstByteOffset = FirstFieldOffset;
945 }
946
947 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
948 CanQualType RecordTy = CGF.getContext().getCanonicalTagType(TD: ClassDecl);
949 Address ThisPtr = CGF.LoadCXXThisAddress();
950 LValue DestLV = CGF.MakeAddrLValue(Addr: ThisPtr, T: RecordTy);
951 LValue Dest = CGF.EmitLValueForFieldInitialization(Base: DestLV, Field: FirstField);
952 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(Addr: CGF.GetAddrOfLocalVar(VD: SrcRec));
953 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(V: SrcPtr, T: RecordTy);
954 LValue Src = CGF.EmitLValueForFieldInitialization(Base: SrcLV, Field: FirstField);
955
956 emitMemcpyIR(DestPtr: Dest.isBitField() ? Dest.getBitFieldAddress()
957 : Dest.getAddress(),
958 SrcPtr: Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
959 Size: MemcpySize);
960 reset();
961 }
962
963 void reset() { FirstField = nullptr; }
964
965protected:
966 CodeGenFunction &CGF;
967 const CXXRecordDecl *ClassDecl;
968
969private:
970 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
971 DestPtr = DestPtr.withElementType(ElemTy: CGF.Int8Ty);
972 SrcPtr = SrcPtr.withElementType(ElemTy: CGF.Int8Ty);
973 auto *I = CGF.Builder.CreateMemCpy(Dest: DestPtr, Src: SrcPtr, Size: Size.getQuantity());
974 CGF.addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
975 }
976
977 void addInitialField(FieldDecl *F) {
978 FirstField = F;
979 LastField = F;
980 FirstFieldOffset = RecLayout.getFieldOffset(FieldNo: F->getFieldIndex());
981 LastFieldOffset = FirstFieldOffset;
982 LastAddedFieldIndex = F->getFieldIndex();
983 }
984
985 void addNextField(FieldDecl *F) {
986 // For the most part, the following invariant will hold:
987 // F->getFieldIndex() == LastAddedFieldIndex + 1
988 // The one exception is that Sema won't add a copy-initializer for an
989 // unnamed bitfield, which will show up here as a gap in the sequence.
990 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
991 "Cannot aggregate fields out of order.");
992 LastAddedFieldIndex = F->getFieldIndex();
993
994 // The 'first' and 'last' fields are chosen by offset, rather than field
995 // index. This allows the code to support bitfields, as well as regular
996 // fields.
997 uint64_t FOffset = RecLayout.getFieldOffset(FieldNo: F->getFieldIndex());
998 if (FOffset < FirstFieldOffset) {
999 FirstField = F;
1000 FirstFieldOffset = FOffset;
1001 } else if (FOffset >= LastFieldOffset) {
1002 LastField = F;
1003 LastFieldOffset = FOffset;
1004 }
1005 }
1006
1007 const VarDecl *SrcRec;
1008 const ASTRecordLayout &RecLayout;
1009 FieldDecl *FirstField;
1010 FieldDecl *LastField;
1011 uint64_t FirstFieldOffset, LastFieldOffset;
1012 unsigned LastAddedFieldIndex;
1013};
1014
1015class ConstructorMemcpyizer : public FieldMemcpyizer {
1016private:
1017 /// Get source argument for copy constructor. Returns null if not a copy
1018 /// constructor.
1019 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1020 const CXXConstructorDecl *CD,
1021 FunctionArgList &Args) {
1022 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1023 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1024 return nullptr;
1025 }
1026
1027 // Returns true if a CXXCtorInitializer represents a member initialization
1028 // that can be rolled into a memcpy.
1029 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1030 if (!MemcpyableCtor)
1031 return false;
1032 FieldDecl *Field = MemberInit->getMember();
1033 assert(Field && "No field for member init.");
1034 QualType FieldType = Field->getType();
1035 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Val: MemberInit->getInit());
1036
1037 // Bail out on non-memcpyable, not-trivially-copyable members.
1038 if (!(CE && CE->getConstructor()->isMemcpyEquivalentSpecialMember(
1039 Ctx: CGF.getContext())) &&
1040 !(FieldType.isTriviallyCopyableType(Context: CGF.getContext()) ||
1041 FieldType->isReferenceType()))
1042 return false;
1043
1044 // Bail out on volatile fields.
1045 if (!isMemcpyableField(F: Field))
1046 return false;
1047
1048 // Otherwise we're good.
1049 return true;
1050 }
1051
1052public:
1053 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1054 FunctionArgList &Args)
1055 : FieldMemcpyizer(CGF, CD->getParent(),
1056 getTrivialCopySource(CGF, CD, Args)),
1057 ConstructorDecl(CD),
1058 MemcpyableCtor(CD->isDefaulted() && CD->isCopyOrMoveConstructor() &&
1059 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1060 Args(Args) {}
1061
1062 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1063 if (isMemberInitMemcpyable(MemberInit)) {
1064 AggregatedInits.push_back(Elt: MemberInit);
1065 addMemcpyableField(F: MemberInit->getMember());
1066 } else {
1067 emitAggregatedInits();
1068 EmitMemberInitializer(CGF, ClassDecl: ConstructorDecl->getParent(), MemberInit,
1069 Constructor: ConstructorDecl, Args);
1070 }
1071 }
1072
1073 void emitAggregatedInits() {
1074 if (AggregatedInits.size() <= 1) {
1075 // This memcpy is too small to be worthwhile. Fall back on default
1076 // codegen.
1077 if (!AggregatedInits.empty()) {
1078 CopyingValueRepresentation CVR(CGF);
1079 EmitMemberInitializer(CGF, ClassDecl: ConstructorDecl->getParent(),
1080 MemberInit: AggregatedInits[0], Constructor: ConstructorDecl, Args);
1081 AggregatedInits.clear();
1082 }
1083 reset();
1084 return;
1085 }
1086
1087 pushEHDestructors();
1088 ApplyAtomGroup Grp(CGF.getDebugInfo());
1089 emitMemcpy();
1090 AggregatedInits.clear();
1091 }
1092
1093 void pushEHDestructors() {
1094 Address ThisPtr = CGF.LoadCXXThisAddress();
1095 CanQualType RecordTy = CGF.getContext().getCanonicalTagType(TD: ClassDecl);
1096 LValue LHS = CGF.MakeAddrLValue(Addr: ThisPtr, T: RecordTy);
1097
1098 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1099 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1100 QualType FieldType = MemberInit->getAnyMember()->getType();
1101 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1102 if (!CGF.needsEHCleanup(kind: dtorKind))
1103 continue;
1104 LValue FieldLHS = LHS;
1105 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS&: FieldLHS);
1106 CGF.pushEHDestroy(dtorKind, addr: FieldLHS.getAddress(), type: FieldType);
1107 }
1108 }
1109
1110 void finish() { emitAggregatedInits(); }
1111
1112private:
1113 const CXXConstructorDecl *ConstructorDecl;
1114 bool MemcpyableCtor;
1115 FunctionArgList &Args;
1116 SmallVector<CXXCtorInitializer *, 16> AggregatedInits;
1117};
1118
1119class AssignmentMemcpyizer : public FieldMemcpyizer {
1120private:
1121 // Returns the memcpyable field copied by the given statement, if one
1122 // exists. Otherwise returns null.
1123 FieldDecl *getMemcpyableField(Stmt *S) {
1124 if (!AssignmentsMemcpyable)
1125 return nullptr;
1126 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: S)) {
1127 // Recognise trivial assignments.
1128 if (BO->getOpcode() != BO_Assign)
1129 return nullptr;
1130 MemberExpr *ME = dyn_cast<MemberExpr>(Val: BO->getLHS());
1131 if (!ME)
1132 return nullptr;
1133 FieldDecl *Field = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
1134 if (!Field || !isMemcpyableField(F: Field))
1135 return nullptr;
1136 Stmt *RHS = BO->getRHS();
1137 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(Val: RHS))
1138 RHS = EC->getSubExpr();
1139 if (!RHS)
1140 return nullptr;
1141 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(Val: RHS)) {
1142 if (ME2->getMemberDecl() == Field)
1143 return Field;
1144 }
1145 return nullptr;
1146 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(Val: S)) {
1147 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: MCE->getCalleeDecl());
1148 if (!(MD && MD->isMemcpyEquivalentSpecialMember(Ctx: CGF.getContext())))
1149 return nullptr;
1150 MemberExpr *IOA = dyn_cast<MemberExpr>(Val: MCE->getImplicitObjectArgument());
1151 if (!IOA)
1152 return nullptr;
1153 FieldDecl *Field = dyn_cast<FieldDecl>(Val: IOA->getMemberDecl());
1154 if (!Field || !isMemcpyableField(F: Field))
1155 return nullptr;
1156 MemberExpr *Arg0 = dyn_cast<MemberExpr>(Val: MCE->getArg(Arg: 0));
1157 if (!Arg0 || Field != dyn_cast<FieldDecl>(Val: Arg0->getMemberDecl()))
1158 return nullptr;
1159 return Field;
1160 } else if (CallExpr *CE = dyn_cast<CallExpr>(Val: S)) {
1161 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CE->getCalleeDecl());
1162 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1163 return nullptr;
1164 Expr *DstPtr = CE->getArg(Arg: 0);
1165 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(Val: DstPtr))
1166 DstPtr = DC->getSubExpr();
1167 UnaryOperator *DUO = dyn_cast<UnaryOperator>(Val: DstPtr);
1168 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1169 return nullptr;
1170 MemberExpr *ME = dyn_cast<MemberExpr>(Val: DUO->getSubExpr());
1171 if (!ME)
1172 return nullptr;
1173 FieldDecl *Field = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
1174 if (!Field || !isMemcpyableField(F: Field))
1175 return nullptr;
1176 Expr *SrcPtr = CE->getArg(Arg: 1);
1177 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(Val: SrcPtr))
1178 SrcPtr = SC->getSubExpr();
1179 UnaryOperator *SUO = dyn_cast<UnaryOperator>(Val: SrcPtr);
1180 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1181 return nullptr;
1182 MemberExpr *ME2 = dyn_cast<MemberExpr>(Val: SUO->getSubExpr());
1183 if (!ME2 || Field != dyn_cast<FieldDecl>(Val: ME2->getMemberDecl()))
1184 return nullptr;
1185 return Field;
1186 }
1187
1188 return nullptr;
1189 }
1190
1191 bool AssignmentsMemcpyable;
1192 SmallVector<Stmt *, 16> AggregatedStmts;
1193
1194public:
1195 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1196 FunctionArgList &Args)
1197 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1198 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1199 assert(Args.size() == 2);
1200 }
1201
1202 void emitAssignment(Stmt *S) {
1203 FieldDecl *F = getMemcpyableField(S);
1204 if (F) {
1205 addMemcpyableField(F);
1206 AggregatedStmts.push_back(Elt: S);
1207 } else {
1208 emitAggregatedStmts();
1209 CGF.EmitStmt(S);
1210 }
1211 }
1212
1213 void emitAggregatedStmts() {
1214 if (AggregatedStmts.size() <= 1) {
1215 if (!AggregatedStmts.empty()) {
1216 CopyingValueRepresentation CVR(CGF);
1217 CGF.EmitStmt(S: AggregatedStmts[0]);
1218 }
1219 reset();
1220 }
1221
1222 ApplyAtomGroup Grp(CGF.getDebugInfo());
1223 emitMemcpy();
1224 AggregatedStmts.clear();
1225 }
1226
1227 void finish() { emitAggregatedStmts(); }
1228};
1229
1230} // end anonymous namespace
1231
1232/// EmitCtorPrologue - This routine generates necessary code to initialize
1233/// base classes and non-static data members belonging to this constructor.
1234void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1235 CXXCtorType CtorType,
1236 FunctionArgList &Args) {
1237 if (CD->isDelegatingConstructor())
1238 return EmitDelegatingCXXConstructorCall(Ctor: CD, Args);
1239
1240 const CXXRecordDecl *ClassDecl = CD->getParent();
1241
1242 // Virtual base initializers aren't needed if:
1243 // - This is a base ctor variant
1244 // - There are no vbases
1245 // - The class is abstract, so a complete object of it cannot be constructed
1246 //
1247 // The check for an abstract class is necessary because sema may not have
1248 // marked virtual base destructors referenced.
1249 bool ConstructVBases = CtorType != Ctor_Base &&
1250 ClassDecl->getNumVBases() != 0 &&
1251 !ClassDecl->isAbstract();
1252
1253 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1254 // constructor of a class with virtual bases takes an additional parameter to
1255 // conditionally construct the virtual bases. Emit that check here.
1256 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1257 if (ConstructVBases &&
1258 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1259 BaseCtorContinueBB =
1260 CGM.getCXXABI().EmitCtorCompleteObjectHandler(CGF&: *this, RD: ClassDecl);
1261 assert(BaseCtorContinueBB);
1262 }
1263
1264 // Create three separate ranges for the different types of initializers.
1265 auto AllInits = CD->inits();
1266
1267 // Find the boundaries between the three groups.
1268 auto VirtualBaseEnd = std::find_if(
1269 first: AllInits.begin(), last: AllInits.end(), pred: [](const CXXCtorInitializer *Init) {
1270 return !(Init->isBaseInitializer() && Init->isBaseVirtual());
1271 });
1272
1273 auto NonVirtualBaseEnd = std::find_if(first: VirtualBaseEnd, last: AllInits.end(),
1274 pred: [](const CXXCtorInitializer *Init) {
1275 return !Init->isBaseInitializer();
1276 });
1277
1278 // Create the three ranges.
1279 auto VirtualBaseInits = llvm::make_range(x: AllInits.begin(), y: VirtualBaseEnd);
1280 auto NonVirtualBaseInits =
1281 llvm::make_range(x: VirtualBaseEnd, y: NonVirtualBaseEnd);
1282 auto MemberInits = llvm::make_range(x: NonVirtualBaseEnd, y: AllInits.end());
1283
1284 // Process virtual base initializers, if necessary.
1285 if (ConstructVBases) {
1286 for (CXXCtorInitializer *Initializer : VirtualBaseInits) {
1287 SaveAndRestore ThisRAII(CXXThisValue);
1288 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1289 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1290 CodeGenUtils::isInitializerOfDynamicClass(BaseInit: Initializer))
1291 CXXThisValue = Builder.CreateLaunderInvariantGroup(Ptr: LoadCXXThis());
1292 EmitBaseInitializer(CGF&: *this, ClassDecl, BaseInit: Initializer);
1293 }
1294 }
1295
1296 if (BaseCtorContinueBB) {
1297 // Complete object handler should continue to the remaining initializers.
1298 Builder.CreateBr(Dest: BaseCtorContinueBB);
1299 EmitBlock(BB: BaseCtorContinueBB);
1300 }
1301
1302 // Then, non-virtual base initializers.
1303 for (CXXCtorInitializer *Initializer : NonVirtualBaseInits) {
1304 assert(!Initializer->isBaseVirtual());
1305 SaveAndRestore ThisRAII(CXXThisValue);
1306 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1307 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1308 CodeGenUtils::isInitializerOfDynamicClass(BaseInit: Initializer))
1309 CXXThisValue = Builder.CreateLaunderInvariantGroup(Ptr: LoadCXXThis());
1310 EmitBaseInitializer(CGF&: *this, ClassDecl, BaseInit: Initializer);
1311 }
1312
1313 InitializeVTablePointers(ClassDecl);
1314
1315 // And finally, initialize class members.
1316 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
1317 ConstructorMemcpyizer CM(*this, CD, Args);
1318 for (CXXCtorInitializer *Member : MemberInits) {
1319 assert(!Member->isBaseInitializer());
1320 assert(Member->isAnyMemberInitializer() &&
1321 "Delegating initializer on non-delegating constructor");
1322 CM.addMemberInitializer(MemberInit: Member);
1323 }
1324
1325 CM.finish();
1326}
1327
1328static void EmitConditionalArrayDtorCall(const CXXDestructorDecl *DD,
1329 CodeGenFunction &CGF,
1330 llvm::Value *ShouldDeleteCondition) {
1331 Address ThisPtr = CGF.LoadCXXThisAddress();
1332 llvm::BasicBlock *ScalarBB = CGF.createBasicBlock(name: "dtor.scalar");
1333 llvm::BasicBlock *callDeleteBB =
1334 CGF.createBasicBlock(name: "dtor.call_delete_after_array_destroy");
1335 llvm::BasicBlock *VectorBB = CGF.createBasicBlock(name: "dtor.vector");
1336 auto *CondTy = cast<llvm::IntegerType>(Val: ShouldDeleteCondition->getType());
1337 llvm::Value *CheckTheBitForArrayDestroy = CGF.Builder.CreateAnd(
1338 LHS: ShouldDeleteCondition, RHS: llvm::ConstantInt::get(Ty: CondTy, V: 2));
1339 llvm::Value *ShouldDestroyArray =
1340 CGF.Builder.CreateIsNull(Arg: CheckTheBitForArrayDestroy);
1341 CGF.Builder.CreateCondBr(Cond: ShouldDestroyArray, True: ScalarBB, False: VectorBB);
1342
1343 CGF.EmitBlock(BB: VectorBB);
1344
1345 llvm::Value *numElements = nullptr;
1346 llvm::Value *allocatedPtr = nullptr;
1347 CharUnits cookieSize;
1348 QualType EltTy = DD->getThisType()->getPointeeType();
1349 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr: ThisPtr, ElementType: EltTy, NumElements&: numElements,
1350 AllocPtr&: allocatedPtr, CookieSize&: cookieSize);
1351
1352 // Destroy the elements.
1353 QualType::DestructionKind dtorKind = EltTy.isDestructedType();
1354
1355 assert(dtorKind);
1356 assert(numElements && "no element count for a type with a destructor!");
1357
1358 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(T: EltTy);
1359 CharUnits elementAlign =
1360 ThisPtr.getAlignment().alignmentOfArrayElement(elementSize);
1361
1362 llvm::Value *arrayBegin = ThisPtr.emitRawPointer(CGF);
1363 llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
1364 Ty: ThisPtr.getElementType(), Ptr: arrayBegin, IdxList: numElements, Name: "delete.end");
1365
1366 // We already checked that the array is not 0-length before entering vector
1367 // deleting dtor.
1368 CGF.emitArrayDestroy(begin: arrayBegin, end: arrayEnd, elementType: EltTy, elementAlign,
1369 destroyer: CGF.getDestroyer(destructionKind: dtorKind),
1370 /*checkZeroLength*/ false, useEHCleanup: CGF.needsEHCleanup(kind: dtorKind));
1371
1372 llvm::BasicBlock *VectorBBCont = CGF.createBasicBlock(name: "dtor.vector.cont");
1373 CGF.EmitBlock(BB: VectorBBCont);
1374
1375 llvm::Value *CheckTheBitForDeleteCall = CGF.Builder.CreateAnd(
1376 LHS: ShouldDeleteCondition, RHS: llvm::ConstantInt::get(Ty: CondTy, V: 1));
1377
1378 llvm::Value *ShouldCallDelete =
1379 CGF.Builder.CreateIsNull(Arg: CheckTheBitForDeleteCall);
1380 CGF.Builder.CreateCondBr(Cond: ShouldCallDelete, True: CGF.ReturnBlock.getBlock(),
1381 False: callDeleteBB);
1382 CGF.EmitBlock(BB: callDeleteBB);
1383 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(Val: CGF.CurCodeDecl);
1384 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1385 if (Dtor->getArrayOperatorDelete()) {
1386 if (!Dtor->getGlobalArrayOperatorDelete()) {
1387 CGF.EmitDeleteCall(DeleteFD: Dtor->getArrayOperatorDelete(), Ptr: allocatedPtr,
1388 DeleteTy: CGF.getContext().getCanonicalTagType(TD: ClassDecl),
1389 NumElements: numElements, CookieSize: cookieSize);
1390 } else {
1391 // If global operator[] is set, the class had its own operator delete[].
1392 // In that case, check the 4th bit. If it is set, we need to call
1393 // ::delete[].
1394 llvm::Value *CheckTheBitForGlobDeleteCall = CGF.Builder.CreateAnd(
1395 LHS: ShouldDeleteCondition, RHS: llvm::ConstantInt::get(Ty: CondTy, V: 4));
1396
1397 llvm::Value *ShouldCallGlobDelete =
1398 CGF.Builder.CreateIsNull(Arg: CheckTheBitForGlobDeleteCall);
1399 llvm::BasicBlock *GlobDelete =
1400 CGF.createBasicBlock(name: "dtor.call_glob_delete_after_array_destroy");
1401 llvm::BasicBlock *ClassDelete =
1402 CGF.createBasicBlock(name: "dtor.call_class_delete_after_array_destroy");
1403 CGF.Builder.CreateCondBr(Cond: ShouldCallGlobDelete, True: ClassDelete, False: GlobDelete);
1404 CGF.EmitBlock(BB: ClassDelete);
1405 CGF.EmitDeleteCall(DeleteFD: Dtor->getArrayOperatorDelete(), Ptr: allocatedPtr,
1406 DeleteTy: CGF.getContext().getCanonicalTagType(TD: ClassDecl),
1407 NumElements: numElements, CookieSize: cookieSize);
1408 CGF.EmitBranchThroughCleanup(Dest: CGF.ReturnBlock);
1409
1410 CGF.EmitBlock(BB: GlobDelete);
1411 // Use __global_delete wrapper instead of directly calling
1412 // ::operator delete to match MSVC's behavior. See the doc comment on
1413 // getOrCreateMSVCGlobalDeleteWrapper for details.
1414 llvm::Constant *GlobalDeleteWrapper =
1415 CGF.CGM.getOrCreateMSVCGlobalDeleteWrapper(
1416 GlobOD: Dtor->getGlobalArrayOperatorDelete());
1417 // For dllexport classes, emit forwarding bodies since the dtor is
1418 // exported and another TU may not provide the forwarding body.
1419 if (Dtor->hasAttr<DLLExportAttr>())
1420 CGF.CGM.noteDirectGlobalDelete();
1421 CGF.EmitDeleteCall(DeleteFD: Dtor->getGlobalArrayOperatorDelete(), Ptr: allocatedPtr,
1422 DeleteTy: CGF.getContext().getCanonicalTagType(TD: ClassDecl),
1423 NumElements: numElements, CookieSize: cookieSize, CalleeOverride: GlobalDeleteWrapper);
1424 }
1425 } else {
1426 // No operators delete[] were found, so emit a trap.
1427 CGF.EmitTrapCallAndMakeUnreachable();
1428 }
1429
1430 CGF.EmitBranchThroughCleanup(Dest: CGF.ReturnBlock);
1431 CGF.EmitBlock(BB: ScalarBB);
1432}
1433
1434/// EmitDestructorBody - Emits the body of the current destructor.
1435void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1436 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(Val: CurGD.getDecl());
1437 CXXDtorType DtorType = CurGD.getDtorType();
1438
1439 // For an abstract class, non-base destructors are never used (and can't
1440 // be emitted in general, because vbase dtors may not have been validated
1441 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1442 // in fact emit references to them from other compilations, so emit them
1443 // as functions containing a trap instruction.
1444 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1445 EmitTrapCallAndMakeUnreachable();
1446 return;
1447 }
1448
1449 Stmt *Body = Dtor->getBody();
1450 if (Body) {
1451 incrementProfileCounter(S: Body);
1452 maybeCreateMCDCCondBitmap();
1453 }
1454
1455 // The call to operator delete in a deleting destructor happens
1456 // outside of the function-try-block, which means it's always
1457 // possible to delegate the destructor body to the complete
1458 // destructor. Do so.
1459 if (DtorType == Dtor_Deleting || DtorType == Dtor_VectorDeleting) {
1460 if (CXXStructorImplicitParamValue && DtorType == Dtor_VectorDeleting)
1461 EmitConditionalArrayDtorCall(DD: Dtor, CGF&: *this, ShouldDeleteCondition: CXXStructorImplicitParamValue);
1462 RunCleanupsScope DtorEpilogue(*this);
1463 EnterDtorCleanups(Dtor, Type: Dtor_Deleting);
1464 if (HaveInsertPoint()) {
1465 QualType ThisTy = Dtor->getFunctionObjectParameterType();
1466 EmitCXXDestructorCall(D: Dtor, Type: Dtor_Complete, /*ForVirtualBase=*/false,
1467 /*Delegating=*/false, This: LoadCXXThisAddress(), ThisTy);
1468 }
1469 return;
1470 }
1471
1472 // If the body is a function-try-block, enter the try before
1473 // anything else.
1474 bool isTryBody = isa_and_nonnull<CXXTryStmt>(Val: Body);
1475 if (isTryBody)
1476 EnterCXXTryStmt(S: *cast<CXXTryStmt>(Val: Body), IsFnTryBlock: true);
1477 EmitAsanPrologueOrEpilogue(Prologue: false);
1478
1479 // Enter the epilogue cleanups.
1480 RunCleanupsScope DtorEpilogue(*this);
1481
1482 // If this is the complete variant, just invoke the base variant;
1483 // the epilogue will destruct the virtual bases. But we can't do
1484 // this optimization if the body is a function-try-block, because
1485 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1486 // always delegate because we might not have a definition in this TU.
1487 switch (DtorType) {
1488 case Dtor_Unified:
1489 llvm_unreachable("not expecting a unified dtor");
1490 case Dtor_Comdat:
1491 llvm_unreachable("not expecting a COMDAT");
1492 case Dtor_Deleting:
1493 llvm_unreachable("already handled deleting case");
1494 case Dtor_VectorDeleting:
1495 llvm_unreachable("already handled vector deleting case");
1496
1497 case Dtor_Complete:
1498 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1499 "can't emit a dtor without a body for non-Microsoft ABIs");
1500
1501 // Enter the cleanup scopes for virtual bases.
1502 EnterDtorCleanups(Dtor, Type: Dtor_Complete);
1503
1504 if (!isTryBody) {
1505 QualType ThisTy = Dtor->getFunctionObjectParameterType();
1506 EmitCXXDestructorCall(D: Dtor, Type: Dtor_Base, /*ForVirtualBase=*/false,
1507 /*Delegating=*/false, This: LoadCXXThisAddress(), ThisTy);
1508 break;
1509 }
1510
1511 // Fallthrough: act like we're in the base variant.
1512 [[fallthrough]];
1513
1514 case Dtor_Base:
1515 assert(Body);
1516
1517 // Enter the cleanup scopes for fields and non-virtual bases.
1518 EnterDtorCleanups(Dtor, Type: Dtor_Base);
1519
1520 // Initialize the vtable pointers before entering the body.
1521 if (!CodeGenUtils::canSkipVTablePointerInitialization(Ctx&: getContext(), Dtor)) {
1522 // Insert the llvm.launder.invariant.group intrinsic before initializing
1523 // the vptrs to cancel any previous assumptions we might have made.
1524 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1525 CGM.getCodeGenOpts().OptimizationLevel > 0)
1526 CXXThisValue = Builder.CreateLaunderInvariantGroup(Ptr: LoadCXXThis());
1527 InitializeVTablePointers(ClassDecl: Dtor->getParent());
1528 }
1529
1530 if (isTryBody)
1531 EmitStmt(S: cast<CXXTryStmt>(Val: Body)->getTryBlock());
1532 else if (Body)
1533 EmitStmt(S: Body);
1534 else {
1535 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1536 // nothing to do besides what's in the epilogue
1537 }
1538 // -fapple-kext must inline any call to this dtor into
1539 // the caller's body.
1540 if (getLangOpts().AppleKext)
1541 CurFn->addFnAttr(Kind: llvm::Attribute::AlwaysInline);
1542
1543 break;
1544 }
1545
1546 // Jump out through the epilogue cleanups.
1547 DtorEpilogue.ForceCleanup();
1548
1549 // Exit the try if applicable.
1550 if (isTryBody)
1551 ExitCXXTryStmt(S: *cast<CXXTryStmt>(Val: Body), IsFnTryBlock: true);
1552}
1553
1554void CodeGenFunction::emitImplicitAssignmentOperatorBody(
1555 FunctionArgList &Args) {
1556 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(Val: CurGD.getDecl());
1557 const Stmt *RootS = AssignOp->getBody();
1558 assert(isa<CompoundStmt>(RootS) &&
1559 "Body of an implicit assignment operator should be compound stmt.");
1560 const CompoundStmt *RootCS = cast<CompoundStmt>(Val: RootS);
1561
1562 LexicalScope Scope(*this, RootCS->getSourceRange());
1563
1564 incrementProfileCounter(S: RootCS);
1565 maybeCreateMCDCCondBitmap();
1566 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1567 for (auto *I : RootCS->body())
1568 AM.emitAssignment(S: I);
1569
1570 AM.finish();
1571}
1572
1573namespace {
1574llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1575 const CXXDestructorDecl *DD) {
1576 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
1577 return CGF.EmitScalarExpr(E: ThisArg);
1578 return CGF.LoadCXXThis();
1579}
1580
1581/// Call the operator delete associated with the current destructor.
1582struct CallDtorDelete final : EHScopeStack::Cleanup {
1583 CallDtorDelete() {}
1584
1585 void Emit(CodeGenFunction &CGF, Flags flags) override {
1586 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(Val: CGF.CurCodeDecl);
1587 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1588 CGF.EmitDeleteCall(DeleteFD: Dtor->getOperatorDelete(),
1589 Ptr: LoadThisForDtorDelete(CGF, DD: Dtor),
1590 DeleteTy: CGF.getContext().getCanonicalTagType(TD: ClassDecl));
1591 }
1592};
1593
1594// This function implements generation of scalar deleting destructor body for
1595// the case when the destructor also accepts an implicit flag. Right now only
1596// Microsoft ABI requires deleting destructors to accept implicit flags.
1597// The flag indicates whether an operator delete should be called and whether
1598// it should be a class-specific operator delete or a global one.
1599void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1600 llvm::Value *ShouldDeleteCondition,
1601 bool ReturnAfterDelete) {
1602 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(Val: CGF.CurCodeDecl);
1603 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1604 const FunctionDecl *OD = Dtor->getOperatorDelete();
1605 assert(OD->isDestroyingOperatorDelete() == ReturnAfterDelete &&
1606 "unexpected value for ReturnAfterDelete");
1607 auto *CondTy = cast<llvm::IntegerType>(Val: ShouldDeleteCondition->getType());
1608 // MSVC calls global operator delete inside of the dtor body, but clang
1609 // aligned with this behavior only after a particular version. This is not
1610 // ABI-compatible with previous versions.
1611 ASTContext &Context = CGF.getContext();
1612 bool CallGlobDelete = Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
1613 Context.getLangOpts());
1614 if (CallGlobDelete && OD->isDestroyingOperatorDelete()) {
1615 llvm::BasicBlock *CallDtor = CGF.createBasicBlock(name: "dtor.call_dtor");
1616 llvm::BasicBlock *DontCallDtor = CGF.createBasicBlock(name: "dtor.entry_cont");
1617 // Third bit set signals that global operator delete is called. That means
1618 // despite class having destroying operator delete which is responsible
1619 // for calling dtor, we need to call dtor because global operator delete
1620 // won't do that.
1621 llvm::Value *Check3rdBit = CGF.Builder.CreateAnd(
1622 LHS: ShouldDeleteCondition, RHS: llvm::ConstantInt::get(Ty: CondTy, V: 4));
1623 llvm::Value *ShouldCallDtor = CGF.Builder.CreateIsNull(Arg: Check3rdBit);
1624 CGF.Builder.CreateCondBr(Cond: ShouldCallDtor, True: DontCallDtor, False: CallDtor);
1625 CGF.EmitBlock(BB: CallDtor);
1626 QualType ThisTy = Dtor->getFunctionObjectParameterType();
1627 CGF.EmitCXXDestructorCall(D: Dtor, Type: Dtor_Complete, /*ForVirtualBase=*/false,
1628 /*Delegating=*/false, This: CGF.LoadCXXThisAddress(),
1629 ThisTy);
1630 CGF.Builder.CreateBr(Dest: DontCallDtor);
1631 CGF.EmitBlock(BB: DontCallDtor);
1632 }
1633 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock(name: "dtor.call_delete");
1634 llvm::BasicBlock *continueBB = CGF.createBasicBlock(name: "dtor.continue");
1635 // First bit set signals that operator delete must be called.
1636 llvm::Value *Check1stBit = CGF.Builder.CreateAnd(
1637 LHS: ShouldDeleteCondition, RHS: llvm::ConstantInt::get(Ty: CondTy, V: 1));
1638 llvm::Value *ShouldCallDelete = CGF.Builder.CreateIsNull(Arg: Check1stBit);
1639 CGF.Builder.CreateCondBr(Cond: ShouldCallDelete, True: continueBB, False: callDeleteBB);
1640
1641 CGF.EmitBlock(BB: callDeleteBB);
1642 auto EmitDeleteAndGoToEnd = [&](const FunctionDecl *DeleteOp,
1643 llvm::Constant *CalleeOverride = nullptr) {
1644 CGF.EmitDeleteCall(DeleteFD: DeleteOp, Ptr: LoadThisForDtorDelete(CGF, DD: Dtor),
1645 DeleteTy: Context.getCanonicalTagType(TD: ClassDecl),
1646 /*NumElements=*/nullptr, /*CookieSize=*/CharUnits(),
1647 CalleeOverride);
1648 if (ReturnAfterDelete)
1649 CGF.EmitBranchThroughCleanup(Dest: CGF.ReturnBlock);
1650 else
1651 CGF.Builder.CreateBr(Dest: continueBB);
1652 };
1653 // If Sema only found a global operator delete previously, the dtor can
1654 // always call it. Otherwise we need to check the third bit and call the
1655 // appropriate operator delete, i.e. global or class-specific.
1656 if (const FunctionDecl *GlobOD = Dtor->getOperatorGlobalDelete();
1657 isa<CXXMethodDecl>(Val: OD) && GlobOD && CallGlobDelete) {
1658 // Third bit set signals that global operator delete is called, i.e.
1659 // ::delete appears on the callsite.
1660 llvm::Value *CheckTheBitForGlobDeleteCall = CGF.Builder.CreateAnd(
1661 LHS: ShouldDeleteCondition, RHS: llvm::ConstantInt::get(Ty: CondTy, V: 4));
1662 llvm::Value *ShouldCallGlobDelete =
1663 CGF.Builder.CreateIsNull(Arg: CheckTheBitForGlobDeleteCall);
1664 llvm::BasicBlock *GlobDelete =
1665 CGF.createBasicBlock(name: "dtor.call_glob_delete");
1666 llvm::BasicBlock *ClassDelete =
1667 CGF.createBasicBlock(name: "dtor.call_class_delete");
1668 CGF.Builder.CreateCondBr(Cond: ShouldCallGlobDelete, True: ClassDelete, False: GlobDelete);
1669 CGF.EmitBlock(BB: GlobDelete);
1670
1671 // Use __global_delete wrapper instead of directly calling
1672 // ::operator delete to match MSVC's behavior. See the doc comment on
1673 // getOrCreateMSVCGlobalDeleteWrapper for details.
1674 llvm::Constant *GlobalDeleteWrapper =
1675 CGF.CGM.getOrCreateMSVCGlobalDeleteWrapper(GlobOD);
1676 // For dllexport classes, emit forwarding bodies since the dtor is
1677 // exported and another TU may not provide the forwarding body.
1678 if (Dtor->hasAttr<DLLExportAttr>())
1679 CGF.CGM.noteDirectGlobalDelete();
1680 EmitDeleteAndGoToEnd(GlobOD, GlobalDeleteWrapper);
1681 CGF.EmitBlock(BB: ClassDelete);
1682 }
1683 EmitDeleteAndGoToEnd(OD);
1684 CGF.EmitBlock(BB: continueBB);
1685}
1686
1687struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
1688 llvm::Value *ShouldDeleteCondition;
1689
1690public:
1691 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1692 : ShouldDeleteCondition(ShouldDeleteCondition) {
1693 assert(ShouldDeleteCondition != nullptr);
1694 }
1695
1696 void Emit(CodeGenFunction &CGF, Flags flags) override {
1697 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1698 /*ReturnAfterDelete*/ false);
1699 }
1700};
1701
1702class DestroyField final : public EHScopeStack::Cleanup {
1703 const FieldDecl *field;
1704 CodeGenFunction::Destroyer *destroyer;
1705 bool useEHCleanupForArray;
1706
1707public:
1708 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1709 bool useEHCleanupForArray)
1710 : field(field), destroyer(destroyer),
1711 useEHCleanupForArray(useEHCleanupForArray) {}
1712
1713 void Emit(CodeGenFunction &CGF, Flags flags) override {
1714 // Find the address of the field.
1715 Address thisValue = CGF.LoadCXXThisAddress();
1716 CanQualType RecordTy =
1717 CGF.getContext().getCanonicalTagType(TD: field->getParent());
1718 LValue ThisLV = CGF.MakeAddrLValue(Addr: thisValue, T: RecordTy);
1719 LValue LV = CGF.EmitLValueForField(Base: ThisLV, Field: field);
1720 assert(LV.isSimple());
1721
1722 CGF.emitDestroy(addr: LV.getAddress(), type: field->getType(), destroyer,
1723 useEHCleanupForArray: flags.isForNormalCleanup() && useEHCleanupForArray);
1724 }
1725};
1726
1727class DeclAsInlineDebugLocation {
1728 CGDebugInfo *DI;
1729 llvm::DILocation *InlinedAt;
1730 std::optional<ApplyDebugLocation> Location;
1731
1732public:
1733 DeclAsInlineDebugLocation(CodeGenFunction &CGF, const NamedDecl &Decl)
1734 : DI(CGF.getDebugInfo()) {
1735 if (!DI)
1736 return;
1737 InlinedAt = DI->getInlinedAt();
1738 DI->setInlinedAt(CGF.Builder.getCurrentDebugLocation());
1739 Location.emplace(args&: CGF, args: Decl.getLocation());
1740 }
1741
1742 ~DeclAsInlineDebugLocation() {
1743 if (!DI)
1744 return;
1745 Location.reset();
1746 DI->setInlinedAt(InlinedAt);
1747 }
1748};
1749
1750static void EmitSanitizerDtorCallback(
1751 CodeGenFunction &CGF, StringRef Name, llvm::Value *Ptr,
1752 std::optional<CharUnits::QuantityType> PoisonSize = {}) {
1753 CodeGenFunction::SanitizerScope SanScope(&CGF);
1754 // Pass in void pointer and size of region as arguments to runtime
1755 // function
1756 SmallVector<llvm::Value *, 2> Args = {Ptr};
1757 SmallVector<llvm::Type *, 2> ArgTypes = {CGF.VoidPtrTy};
1758
1759 if (PoisonSize.has_value()) {
1760 Args.emplace_back(Args: llvm::ConstantInt::get(Ty: CGF.SizeTy, V: *PoisonSize));
1761 ArgTypes.emplace_back(Args&: CGF.SizeTy);
1762 }
1763
1764 llvm::FunctionType *FnType =
1765 llvm::FunctionType::get(Result: CGF.VoidTy, Params: ArgTypes, isVarArg: false);
1766 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(Ty: FnType, Name);
1767
1768 CGF.EmitNounwindRuntimeCall(callee: Fn, args: Args);
1769}
1770
1771static void
1772EmitSanitizerDtorFieldsCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1773 CharUnits::QuantityType PoisonSize) {
1774 EmitSanitizerDtorCallback(CGF, Name: "__sanitizer_dtor_callback_fields", Ptr,
1775 PoisonSize);
1776}
1777
1778/// Poison base class with a trivial destructor.
1779struct SanitizeDtorTrivialBase final : EHScopeStack::Cleanup {
1780 const CXXRecordDecl *BaseClass;
1781 bool BaseIsVirtual;
1782 SanitizeDtorTrivialBase(const CXXRecordDecl *Base, bool BaseIsVirtual)
1783 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
1784
1785 void Emit(CodeGenFunction &CGF, Flags flags) override {
1786 const CXXRecordDecl *DerivedClass =
1787 cast<CXXMethodDecl>(Val: CGF.CurCodeDecl)->getParent();
1788
1789 Address Addr = CGF.GetAddressOfDirectBaseInCompleteClass(
1790 This: CGF.LoadCXXThisAddress(), Derived: DerivedClass, Base: BaseClass, BaseIsVirtual);
1791
1792 const ASTRecordLayout &BaseLayout =
1793 CGF.getContext().getASTRecordLayout(D: BaseClass);
1794 CharUnits BaseSize = BaseLayout.getSize();
1795
1796 if (!BaseSize.isPositive())
1797 return;
1798
1799 // Use the base class declaration location as inline DebugLocation. All
1800 // fields of the class are destroyed.
1801 DeclAsInlineDebugLocation InlineHere(CGF, *BaseClass);
1802 EmitSanitizerDtorFieldsCallback(CGF, Ptr: Addr.emitRawPointer(CGF),
1803 PoisonSize: BaseSize.getQuantity());
1804
1805 // Prevent the current stack frame from disappearing from the stack trace.
1806 CGF.CurFn->addFnAttr(Kind: "disable-tail-calls", Val: "true");
1807 }
1808};
1809
1810class SanitizeDtorFieldRange final : public EHScopeStack::Cleanup {
1811 const CXXDestructorDecl *Dtor;
1812 unsigned StartIndex;
1813 unsigned EndIndex;
1814
1815public:
1816 SanitizeDtorFieldRange(const CXXDestructorDecl *Dtor, unsigned StartIndex,
1817 unsigned EndIndex)
1818 : Dtor(Dtor), StartIndex(StartIndex), EndIndex(EndIndex) {}
1819
1820 // Generate function call for handling object poisoning.
1821 // Disables tail call elimination, to prevent the current stack frame
1822 // from disappearing from the stack trace.
1823 void Emit(CodeGenFunction &CGF, Flags flags) override {
1824 const ASTContext &Context = CGF.getContext();
1825 const ASTRecordLayout &Layout =
1826 Context.getASTRecordLayout(D: Dtor->getParent());
1827
1828 // It's a first trivial field so it should be at the begining of a char,
1829 // still round up start offset just in case.
1830 CharUnits PoisonStart = Context.toCharUnitsFromBits(
1831 BitSize: Layout.getFieldOffset(FieldNo: StartIndex) + Context.getCharWidth() - 1);
1832 llvm::ConstantInt *OffsetSizePtr =
1833 llvm::ConstantInt::get(Ty: CGF.SizeTy, V: PoisonStart.getQuantity());
1834
1835 llvm::Value *OffsetPtr =
1836 CGF.Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: CGF.LoadCXXThis(), IdxList: OffsetSizePtr);
1837
1838 CharUnits PoisonEnd;
1839 if (EndIndex >= Layout.getFieldCount()) {
1840 PoisonEnd = Layout.getNonVirtualSize();
1841 } else {
1842 PoisonEnd = Context.toCharUnitsFromBits(BitSize: Layout.getFieldOffset(FieldNo: EndIndex));
1843 }
1844 CharUnits PoisonSize = PoisonEnd - PoisonStart;
1845 if (!PoisonSize.isPositive())
1846 return;
1847
1848 // Use the top field declaration location as inline DebugLocation.
1849 DeclAsInlineDebugLocation InlineHere(
1850 CGF, **std::next(x: Dtor->getParent()->field_begin(), n: StartIndex));
1851 EmitSanitizerDtorFieldsCallback(CGF, Ptr: OffsetPtr, PoisonSize: PoisonSize.getQuantity());
1852
1853 // Prevent the current stack frame from disappearing from the stack trace.
1854 CGF.CurFn->addFnAttr(Kind: "disable-tail-calls", Val: "true");
1855 }
1856};
1857
1858class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1859 const CXXDestructorDecl *Dtor;
1860
1861public:
1862 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1863
1864 // Generate function call for handling vtable pointer poisoning.
1865 void Emit(CodeGenFunction &CGF, Flags flags) override {
1866 assert(Dtor->getParent()->isDynamicClass());
1867 (void)Dtor;
1868 // Poison vtable and vtable ptr if they exist for this class.
1869 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1870
1871 // Pass in void pointer and size of region as arguments to runtime
1872 // function
1873 EmitSanitizerDtorCallback(CGF, Name: "__sanitizer_dtor_callback_vptr", Ptr: VTablePtr);
1874 }
1875};
1876
1877class SanitizeDtorCleanupBuilder {
1878 ASTContext &Context;
1879 EHScopeStack &EHStack;
1880 const CXXDestructorDecl *DD;
1881 std::optional<unsigned> StartIndex;
1882
1883public:
1884 SanitizeDtorCleanupBuilder(ASTContext &Context, EHScopeStack &EHStack,
1885 const CXXDestructorDecl *DD)
1886 : Context(Context), EHStack(EHStack), DD(DD), StartIndex(std::nullopt) {}
1887 void PushCleanupForField(const FieldDecl *Field) {
1888 if (isEmptyFieldForLayout(Context, FD: Field))
1889 return;
1890 unsigned FieldIndex = Field->getFieldIndex();
1891 if (CodeGenUtils::fieldHasTrivialDestructorBody(Context, Field)) {
1892 if (!StartIndex)
1893 StartIndex = FieldIndex;
1894 } else if (StartIndex) {
1895 EHStack.pushCleanup<SanitizeDtorFieldRange>(Kind: NormalAndEHCleanup, A: DD,
1896 A: *StartIndex, A: FieldIndex);
1897 StartIndex = std::nullopt;
1898 }
1899 }
1900 void End() {
1901 if (StartIndex)
1902 EHStack.pushCleanup<SanitizeDtorFieldRange>(Kind: NormalAndEHCleanup, A: DD,
1903 A: *StartIndex, A: -1);
1904 }
1905};
1906} // end anonymous namespace
1907
1908/// Emit all code that comes at the end of class's
1909/// destructor. This is to call destructors on members and base classes
1910/// in reverse order of their construction.
1911///
1912/// For a deleting destructor, this also handles the case where a destroying
1913/// operator delete completely overrides the definition.
1914void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1915 CXXDtorType DtorType) {
1916 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1917 "Should not emit dtor epilogue for non-exported trivial dtor!");
1918
1919 // The deleting-destructor phase just needs to call the appropriate
1920 // operator delete that Sema picked up.
1921 if (DtorType == Dtor_Deleting) {
1922 assert(DD->getOperatorDelete() &&
1923 "operator delete missing - EnterDtorCleanups");
1924 if (CXXStructorImplicitParamValue) {
1925 // If there is an implicit param to the deleting dtor, it's a boolean
1926 // telling whether this is a deleting destructor.
1927 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1928 EmitConditionalDtorDeleteCall(CGF&: *this, ShouldDeleteCondition: CXXStructorImplicitParamValue,
1929 /*ReturnAfterDelete*/ true);
1930 else
1931 EHStack.pushCleanup<CallDtorDeleteConditional>(
1932 Kind: NormalAndEHCleanup, A: CXXStructorImplicitParamValue);
1933 } else {
1934 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1935 const CXXRecordDecl *ClassDecl = DD->getParent();
1936 EmitDeleteCall(DeleteFD: DD->getOperatorDelete(),
1937 Ptr: LoadThisForDtorDelete(CGF&: *this, DD),
1938 DeleteTy: getContext().getCanonicalTagType(TD: ClassDecl));
1939 EmitBranchThroughCleanup(Dest: ReturnBlock);
1940 } else {
1941 EHStack.pushCleanup<CallDtorDelete>(Kind: NormalAndEHCleanup);
1942 }
1943 }
1944 return;
1945 }
1946
1947 const CXXRecordDecl *ClassDecl = DD->getParent();
1948
1949 // Unions have no bases and do not call field destructors.
1950 if (ClassDecl->isUnion())
1951 return;
1952
1953 // The complete-destructor phase just destructs all the virtual bases.
1954 if (DtorType == Dtor_Complete) {
1955 // Poison the vtable pointer such that access after the base
1956 // and member destructors are invoked is invalid.
1957 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1958 SanOpts.has(K: SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1959 ClassDecl->isPolymorphic())
1960 EHStack.pushCleanup<SanitizeDtorVTable>(Kind: NormalAndEHCleanup, A: DD);
1961
1962 // We push them in the forward order so that they'll be popped in
1963 // the reverse order.
1964 for (const auto &Base : ClassDecl->vbases()) {
1965 auto *BaseClassDecl = Base.getType()->castAsCXXRecordDecl();
1966 if (BaseClassDecl->hasTrivialDestructor()) {
1967 // Under SanitizeMemoryUseAfterDtor, poison the trivial base class
1968 // memory. For non-trival base classes the same is done in the class
1969 // destructor.
1970 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1971 SanOpts.has(K: SanitizerKind::Memory) && !BaseClassDecl->isEmpty())
1972 EHStack.pushCleanup<SanitizeDtorTrivialBase>(Kind: NormalAndEHCleanup,
1973 A: BaseClassDecl,
1974 /*BaseIsVirtual*/ A: true);
1975 } else {
1976 EHStack.pushCleanup<CallBaseDtor>(Kind: NormalAndEHCleanup, A: BaseClassDecl,
1977 /*BaseIsVirtual*/ A: true);
1978 }
1979 }
1980
1981 return;
1982 }
1983
1984 assert(DtorType == Dtor_Base);
1985 // Poison the vtable pointer if it has no virtual bases, but inherits
1986 // virtual functions.
1987 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1988 SanOpts.has(K: SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1989 ClassDecl->isPolymorphic())
1990 EHStack.pushCleanup<SanitizeDtorVTable>(Kind: NormalAndEHCleanup, A: DD);
1991
1992 // Destroy non-virtual bases.
1993 for (const auto &Base : ClassDecl->bases()) {
1994 // Ignore virtual bases.
1995 if (Base.isVirtual())
1996 continue;
1997
1998 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1999
2000 if (BaseClassDecl->hasTrivialDestructor()) {
2001 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
2002 SanOpts.has(K: SanitizerKind::Memory) && !BaseClassDecl->isEmpty())
2003 EHStack.pushCleanup<SanitizeDtorTrivialBase>(Kind: NormalAndEHCleanup,
2004 A: BaseClassDecl,
2005 /*BaseIsVirtual*/ A: false);
2006 } else {
2007 EHStack.pushCleanup<CallBaseDtor>(Kind: NormalAndEHCleanup, A: BaseClassDecl,
2008 /*BaseIsVirtual*/ A: false);
2009 }
2010 }
2011
2012 // Poison fields such that access after their destructors are
2013 // invoked, and before the base class destructor runs, is invalid.
2014 bool SanitizeFields = CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
2015 SanOpts.has(K: SanitizerKind::Memory);
2016 SanitizeDtorCleanupBuilder SanitizeBuilder(getContext(), EHStack, DD);
2017
2018 // Destroy direct fields.
2019 for (const auto *Field : ClassDecl->fields()) {
2020 if (SanitizeFields)
2021 SanitizeBuilder.PushCleanupForField(Field);
2022
2023 QualType type = Field->getType();
2024 QualType::DestructionKind dtorKind = type.isDestructedType();
2025 if (!dtorKind)
2026 continue;
2027
2028 // Anonymous union members do not have their destructors called.
2029 const RecordType *RT = type->getAsUnionType();
2030 if (RT && RT->getDecl()->isAnonymousStructOrUnion())
2031 continue;
2032
2033 CleanupKind cleanupKind = getCleanupKind(kind: dtorKind);
2034 EHStack.pushCleanup<DestroyField>(
2035 Kind: cleanupKind, A: Field, A: getDestroyer(destructionKind: dtorKind), A: cleanupKind & EHCleanup);
2036 }
2037
2038 if (SanitizeFields)
2039 SanitizeBuilder.End();
2040}
2041
2042/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
2043/// constructor for each of several members of an array.
2044///
2045/// \param ctor the constructor to call for each element
2046/// \param arrayType the type of the array to initialize
2047/// \param arrayBegin an arrayType*
2048/// \param zeroInitialize true if each element should be
2049/// zero-initialized before it is constructed
2050void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
2051 const ArrayType *arrayType,
2052 Address arrayBegin,
2053 const CXXConstructExpr *E,
2054 bool NewPointerIsChecked,
2055 bool zeroInitialize) {
2056 QualType elementType;
2057 llvm::Value *numElements =
2058 emitArrayLength(arrayType, baseType&: elementType, addr&: arrayBegin);
2059
2060 EmitCXXAggrConstructorCall(D: ctor, NumElements: numElements, ArrayPtr: arrayBegin, E,
2061 NewPointerIsChecked, ZeroInitialization: zeroInitialize);
2062}
2063
2064/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
2065/// constructor for each of several members of an array.
2066///
2067/// \param ctor the constructor to call for each element
2068/// \param numElements the number of elements in the array;
2069/// may be zero
2070/// \param arrayBase a T*, where T is the type constructed by ctor
2071/// \param zeroInitialize true if each element should be
2072/// zero-initialized before it is constructed
2073void CodeGenFunction::EmitCXXAggrConstructorCall(
2074 const CXXConstructorDecl *ctor, llvm::Value *numElements, Address arrayBase,
2075 const CXXConstructExpr *E, bool NewPointerIsChecked, bool zeroInitialize) {
2076 // It's legal for numElements to be zero. This can happen both
2077 // dynamically, because x can be zero in 'new A[x]', and statically,
2078 // because of GCC extensions that permit zero-length arrays. There
2079 // are probably legitimate places where we could assume that this
2080 // doesn't happen, but it's not clear that it's worth it.
2081 llvm::CondBrInst *zeroCheckBranch = nullptr;
2082
2083 // Optimize for a constant count.
2084 llvm::ConstantInt *constantCount = dyn_cast<llvm::ConstantInt>(Val: numElements);
2085 if (constantCount) {
2086 // Just skip out if the constant count is zero.
2087 if (constantCount->isZero())
2088 return;
2089
2090 // Otherwise, emit the check.
2091 } else {
2092 llvm::BasicBlock *loopBB = createBasicBlock(name: "new.ctorloop");
2093 llvm::Value *iszero = Builder.CreateIsNull(Arg: numElements, Name: "isempty");
2094 zeroCheckBranch = Builder.CreateCondBr(Cond: iszero, True: loopBB, False: loopBB);
2095 EmitBlock(BB: loopBB);
2096 }
2097
2098 // Find the end of the array.
2099 llvm::Type *elementType = arrayBase.getElementType();
2100 llvm::Value *arrayBegin = arrayBase.emitRawPointer(CGF&: *this);
2101 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(
2102 Ty: elementType, Ptr: arrayBegin, IdxList: numElements, Name: "arrayctor.end");
2103
2104 // Enter the loop, setting up a phi for the current location to initialize.
2105 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2106 llvm::BasicBlock *loopBB = createBasicBlock(name: "arrayctor.loop");
2107 EmitBlock(BB: loopBB);
2108 llvm::PHINode *cur =
2109 Builder.CreatePHI(Ty: arrayBegin->getType(), NumReservedValues: 2, Name: "arrayctor.cur");
2110 cur->addIncoming(V: arrayBegin, BB: entryBB);
2111
2112 // Inside the loop body, emit the constructor call on the array element.
2113 if (CGM.shouldEmitConvergenceTokens())
2114 ConvergenceTokenStack.push_back(Elt: emitConvergenceLoopToken(BB: loopBB));
2115
2116 // The alignment of the base, adjusted by the size of a single element,
2117 // provides a conservative estimate of the alignment of every element.
2118 // (This assumes we never start tracking offsetted alignments.)
2119 //
2120 // Note that these are complete objects and so we don't need to
2121 // use the non-virtual size or alignment.
2122 CanQualType type = getContext().getCanonicalTagType(TD: ctor->getParent());
2123 CharUnits eltAlignment = arrayBase.getAlignment().alignmentOfArrayElement(
2124 elementSize: getContext().getTypeSizeInChars(T: type));
2125 Address curAddr = Address(cur, elementType, eltAlignment);
2126
2127 // Zero initialize the storage, if requested.
2128 if (zeroInitialize)
2129 EmitNullInitialization(DestPtr: curAddr, Ty: type);
2130
2131 // C++ [class.temporary]p4:
2132 // There are two contexts in which temporaries are destroyed at a different
2133 // point than the end of the full-expression. The first context is when a
2134 // default constructor is called to initialize an element of an array.
2135 // If the constructor has one or more default arguments, the destruction of
2136 // every temporary created in a default argument expression is sequenced
2137 // before the construction of the next array element, if any.
2138
2139 {
2140 RunCleanupsScope Scope(*this);
2141
2142 // Evaluate the constructor and its arguments in a regular
2143 // partial-destroy cleanup.
2144 if (getLangOpts().Exceptions &&
2145 !ctor->getParent()->hasTrivialDestructor()) {
2146 Destroyer *destroyer = destroyCXXObject;
2147 pushRegularPartialArrayCleanup(arrayBegin, arrayEnd: cur, elementType: type, elementAlignment: eltAlignment,
2148 destroyer: *destroyer);
2149 }
2150 auto currAVS = AggValueSlot::forAddr(
2151 addr: curAddr, quals: type.getQualifiers(), isDestructed: AggValueSlot::IsDestructed,
2152 needsGC: AggValueSlot::DoesNotNeedGCBarriers, isAliased: AggValueSlot::IsNotAliased,
2153 mayOverlap: AggValueSlot::DoesNotOverlap, isZeroed: AggValueSlot::IsNotZeroed,
2154 isChecked: NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
2155 : AggValueSlot::IsNotSanitizerChecked);
2156 EmitCXXConstructorCall(D: ctor, Type: Ctor_Complete, /*ForVirtualBase=*/false,
2157 /*Delegating=*/false, ThisAVS: currAVS, E);
2158 }
2159
2160 // Go to the next element.
2161 llvm::Value *next = Builder.CreateInBoundsGEP(
2162 Ty: elementType, Ptr: cur, IdxList: llvm::ConstantInt::get(Ty: SizeTy, V: 1), Name: "arrayctor.next");
2163 cur->addIncoming(V: next, BB: Builder.GetInsertBlock());
2164
2165 // Check whether that's the end of the loop.
2166 llvm::Value *done = Builder.CreateICmpEQ(LHS: next, RHS: arrayEnd, Name: "arrayctor.done");
2167 llvm::BasicBlock *contBB = createBasicBlock(name: "arrayctor.cont");
2168 Builder.CreateCondBr(Cond: done, True: contBB, False: loopBB);
2169
2170 // Patch the earlier check to skip over the loop.
2171 if (zeroCheckBranch)
2172 zeroCheckBranch->setSuccessor(idx: 0, NewSucc: contBB);
2173
2174 if (CGM.shouldEmitConvergenceTokens())
2175 ConvergenceTokenStack.pop_back();
2176
2177 EmitBlock(BB: contBB);
2178}
2179
2180void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, Address addr,
2181 QualType type) {
2182 const CXXDestructorDecl *dtor = type->castAsCXXRecordDecl()->getDestructor();
2183 assert(!dtor->isTrivial());
2184 CGF.EmitCXXDestructorCall(D: dtor, Type: Dtor_Complete, /*for vbase*/ ForVirtualBase: false,
2185 /*Delegating=*/false, This: addr, ThisTy: type);
2186}
2187
2188void CodeGenFunction::EmitCXXConstructorCall(
2189 const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase,
2190 bool Delegating, AggValueSlot ThisAVS, const CXXConstructExpr *E) {
2191 CallArgList Args;
2192 Address This = ThisAVS.getAddress();
2193 LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
2194 LangAS ThisAS = D->getFunctionObjectParameterType().getAddressSpace();
2195 llvm::Value *ThisPtr =
2196 getAsNaturalPointerTo(Addr: This, PointeeType: D->getThisType()->getPointeeType());
2197
2198 if (SlotAS != ThisAS) {
2199 unsigned TargetThisAS = getContext().getTargetAddressSpace(AS: ThisAS);
2200 llvm::Type *NewType =
2201 llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: TargetThisAS);
2202 ThisPtr = performAddrSpaceCast(Src: ThisPtr, DestTy: NewType);
2203 }
2204
2205 // Push the this ptr.
2206 Args.add(rvalue: RValue::get(V: ThisPtr), type: D->getThisType());
2207
2208 // If this is a trivial constructor, emit a memcpy now before we lose
2209 // the alignment information on the argument.
2210 // FIXME: It would be better to preserve alignment information into CallArg.
2211 if (D->isMemcpyEquivalentSpecialMember(Ctx: getContext())) {
2212 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2213
2214 const Expr *Arg = E->getArg(Arg: 0);
2215 LValue Src = EmitCheckedLValue(E: Arg, TCK: TCK_Load);
2216 CanQualType DestTy = getContext().getCanonicalTagType(TD: D->getParent());
2217 LValue Dest = MakeAddrLValue(Addr: This, T: DestTy);
2218 EmitAggregateCopyCtor(Dest, Src, MayOverlap: ThisAVS.mayOverlap());
2219 return;
2220 }
2221
2222 // Add the rest of the user-supplied arguments.
2223 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2224 EvaluationOrder Order = E->isListInitialization()
2225 ? EvaluationOrder::ForceLeftToRight
2226 : EvaluationOrder::Default;
2227 EmitCallArgs(Args, Prototype: FPT, ArgRange: E->arguments(), AC: E->getConstructor(),
2228 /*ParamsToSkip*/ 0, Order);
2229
2230 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
2231 Overlap: ThisAVS.mayOverlap(), Loc: E->getExprLoc(),
2232 NewPointerIsChecked: ThisAVS.isSanitizerChecked());
2233}
2234
2235static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2236 const CXXConstructorDecl *Ctor,
2237 CXXCtorType Type, CallArgList &Args) {
2238 // We can't forward a variadic call.
2239 if (Ctor->isVariadic())
2240 return false;
2241
2242 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2243 // If the parameters are callee-cleanup, it's not safe to forward.
2244 for (auto *P : Ctor->parameters())
2245 if (P->needsDestruction(Ctx: CGF.getContext()))
2246 return false;
2247
2248 // Likewise if they're inalloca.
2249 const CGFunctionInfo &Info = CGF.CGM.getTypes().arrangeCXXConstructorCall(
2250 Args, D: Ctor, CtorKind: Type, ExtraPrefixArgs: 0, ExtraSuffixArgs: 0, ABIInfoFD: CGF.getCurrentFunctionDecl());
2251 if (Info.usesInAlloca())
2252 return false;
2253 }
2254
2255 // Anything else should be OK.
2256 return true;
2257}
2258
2259void CodeGenFunction::EmitCXXConstructorCall(
2260 const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase,
2261 bool Delegating, Address This, CallArgList &Args,
2262 AggValueSlot::Overlap_t Overlap, SourceLocation Loc,
2263 bool NewPointerIsChecked, llvm::CallBase **CallOrInvoke) {
2264 const CXXRecordDecl *ClassDecl = D->getParent();
2265
2266 if (!NewPointerIsChecked)
2267 EmitTypeCheck(TCK: CodeGenFunction::TCK_ConstructorCall, Loc, Addr: This,
2268 Type: getContext().getCanonicalTagType(TD: ClassDecl),
2269 Alignment: CharUnits::Zero());
2270
2271 if (D->isTrivial() && D->isDefaultConstructor()) {
2272 assert(Args.size() == 1 && "trivial default ctor with args");
2273 return;
2274 }
2275
2276 // If this is a trivial constructor, just emit what's needed. If this is a
2277 // union copy constructor, we must emit a memcpy, because the AST does not
2278 // model that copy.
2279 if (D->isMemcpyEquivalentSpecialMember(Ctx: getContext())) {
2280 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
2281 QualType SrcTy = D->getParamDecl(i: 0)->getType().getNonReferenceType();
2282 Address Src = makeNaturalAddressForPointer(
2283 Ptr: Args[1].getRValue(CGF&: *this).getScalarVal(), T: SrcTy);
2284 LValue SrcLVal = MakeAddrLValue(Addr: Src, T: SrcTy);
2285 CanQualType DestTy = getContext().getCanonicalTagType(TD: ClassDecl);
2286 LValue DestLVal = MakeAddrLValue(Addr: This, T: DestTy);
2287 EmitAggregateCopyCtor(Dest: DestLVal, Src: SrcLVal, MayOverlap: Overlap);
2288 return;
2289 }
2290
2291 bool PassPrototypeArgs = true;
2292 // Check whether we can actually emit the constructor before trying to do so.
2293 if (auto Inherited = D->getInheritedConstructor()) {
2294 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2295 if (PassPrototypeArgs && !canEmitDelegateCallArgs(CGF&: *this, Ctor: D, Type, Args)) {
2296 EmitInlinedInheritingCXXConstructorCall(Ctor: D, CtorType: Type, ForVirtualBase,
2297 Delegating, Args);
2298 return;
2299 }
2300 }
2301
2302 // Insert any ABI-specific implicit constructor arguments.
2303 CGCXXABI::AddedStructorArgCounts ExtraArgs =
2304 CGM.getCXXABI().addImplicitConstructorArgs(CGF&: *this, D, Type, ForVirtualBase,
2305 Delegating, Args);
2306
2307 // Emit the call.
2308 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GD: GlobalDecl(D, Type));
2309 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
2310 Args, D, CtorKind: Type, ExtraPrefixArgs: ExtraArgs.Prefix, ExtraSuffixArgs: ExtraArgs.Suffix,
2311 ABIInfoFD: getCurrentFunctionDecl(), PassProtoArgs: PassPrototypeArgs);
2312 CGCallee Callee = CGCallee::forDirect(functionPtr: CalleePtr, abstractInfo: GlobalDecl(D, Type));
2313 EmitCall(CallInfo: Info, Callee, ReturnValue: ReturnValueSlot(), Args, CallOrInvoke, IsMustTail: false, Loc);
2314
2315 // Generate vtable assumptions if we're constructing a complete object
2316 // with a vtable. We don't do this for base subobjects for two reasons:
2317 // first, it's incorrect for classes with virtual bases, and second, we're
2318 // about to overwrite the vptrs anyway.
2319 // We also have to make sure if we can refer to vtable:
2320 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2321 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2322 // sure that definition of vtable is not hidden,
2323 // then we are always safe to refer to it.
2324 // FIXME: It looks like InstCombine is very inefficient on dealing with
2325 // assumes. Make assumption loads require -fstrict-vtable-pointers
2326 // temporarily.
2327 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2328 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
2329 CGM.getCXXABI().canSpeculativelyEmitVTable(RD: ClassDecl) &&
2330 CGM.getCodeGenOpts().StrictVTablePointers)
2331 EmitVTableAssumptionLoads(ClassDecl, This);
2332}
2333
2334void CodeGenFunction::EmitInheritedCXXConstructorCall(
2335 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2336 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2337 CallArgList Args;
2338 CallArg ThisArg(RValue::get(V: getAsNaturalPointerTo(
2339 Addr: This, PointeeType: D->getThisType()->getPointeeType())),
2340 D->getThisType());
2341
2342 // Forward the parameters.
2343 if (InheritedFromVBase &&
2344 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2345 // Nothing to do; this construction is not responsible for constructing
2346 // the base class containing the inherited constructor.
2347 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2348 // have constructor variants?
2349 Args.push_back(Elt: ThisArg);
2350 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2351 // The inheriting constructor was inlined; just inject its arguments.
2352 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2353 "wrong number of parameters for inherited constructor call");
2354 Args = CXXInheritedCtorInitExprArgs;
2355 Args[0] = ThisArg;
2356 } else {
2357 // The inheriting constructor was not inlined. Emit delegating arguments.
2358 Args.push_back(Elt: ThisArg);
2359 const auto *OuterCtor = cast<CXXConstructorDecl>(Val: CurCodeDecl);
2360 assert(OuterCtor->getNumParams() == D->getNumParams());
2361 assert(!OuterCtor->isVariadic() && "should have been inlined");
2362
2363 for (const auto *Param : OuterCtor->parameters()) {
2364 assert(getContext().hasSameUnqualifiedType(
2365 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2366 Param->getType()));
2367 EmitDelegateCallArg(args&: Args, param: Param, loc: E->getLocation());
2368
2369 // Forward __attribute__(pass_object_size).
2370 if (Param->hasAttr<PassObjectSizeAttr>()) {
2371 auto *POSParam = SizeArguments[Param];
2372 assert(POSParam && "missing pass_object_size value for forwarding");
2373 EmitDelegateCallArg(args&: Args, param: POSParam, loc: E->getLocation());
2374 }
2375 }
2376 }
2377
2378 EmitCXXConstructorCall(D, Type: Ctor_Base, ForVirtualBase, /*Delegating*/ false,
2379 This, Args, Overlap: AggValueSlot::MayOverlap, Loc: E->getLocation(),
2380 /*NewPointerIsChecked*/ true);
2381}
2382
2383void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2384 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2385 bool Delegating, CallArgList &Args) {
2386 GlobalDecl GD(Ctor, CtorType);
2387 InlinedInheritingConstructorScope Scope(*this, GD);
2388 ApplyInlineDebugLocation DebugScope(*this, GD);
2389 RunCleanupsScope RunCleanups(*this);
2390
2391 // Save the arguments to be passed to the inherited constructor.
2392 CXXInheritedCtorInitExprArgs = Args;
2393
2394 FunctionArgList Params;
2395 QualType RetType = BuildFunctionArgList(GD: CurGD, Args&: Params);
2396 FnRetTy = RetType;
2397
2398 // Insert any ABI-specific implicit constructor arguments.
2399 CGM.getCXXABI().addImplicitConstructorArgs(CGF&: *this, D: Ctor, Type: CtorType,
2400 ForVirtualBase, Delegating, Args);
2401
2402 // Emit a simplified prolog. We only need to emit the implicit params.
2403 assert(Args.size() >= Params.size() && "too few arguments for call");
2404 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2405 if (I < Params.size() && isa<ImplicitParamDecl>(Val: Params[I])) {
2406 const RValue &RV = Args[I].getRValue(CGF&: *this);
2407 assert(!RV.isComplex() && "complex indirect params not supported");
2408 ParamValue Val = RV.isScalar()
2409 ? ParamValue::forDirect(value: RV.getScalarVal())
2410 : ParamValue::forIndirect(addr: RV.getAggregateAddress());
2411 EmitParmDecl(D: *Params[I], Arg: Val, ArgNo: I + 1);
2412 }
2413 }
2414
2415 // Create a return value slot if the ABI implementation wants one.
2416 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2417 // value instead.
2418 if (!RetType->isVoidType())
2419 ReturnValue = CreateIRTempWithoutCast(T: RetType, Name: "retval.inhctor");
2420
2421 CGM.getCXXABI().EmitInstanceFunctionProlog(CGF&: *this);
2422 CXXThisValue = CXXABIThisValue;
2423
2424 // Directly emit the constructor initializers.
2425 EmitCtorPrologue(CD: Ctor, CtorType, Args&: Params);
2426}
2427
2428void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2429 llvm::Value *VTableGlobal =
2430 CGM.getCXXABI().getVTableAddressPoint(Base: Vptr.Base, VTableClass: Vptr.VTableClass);
2431 if (!VTableGlobal)
2432 return;
2433
2434 // We can just use the base offset in the complete class.
2435 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2436
2437 if (!NonVirtualOffset.isZero())
2438 This =
2439 ApplyNonVirtualAndVirtualOffset(CGF&: *this, addr: This, nonVirtualOffset: NonVirtualOffset, virtualOffset: nullptr,
2440 derivedClass: Vptr.VTableClass, nearestVBase: Vptr.NearestVBase);
2441
2442 llvm::Value *VPtrValue =
2443 GetVTablePtr(This, VTableTy: VTableGlobal->getType(), VTableClass: Vptr.VTableClass);
2444 llvm::Value *Cmp =
2445 Builder.CreateICmpEQ(LHS: VPtrValue, RHS: VTableGlobal, Name: "cmp.vtables");
2446 Builder.CreateAssumption(Cond: Cmp);
2447}
2448
2449void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2450 Address This) {
2451 if (CGM.getCXXABI().doStructorsInitializeVPtrs(VTableClass: ClassDecl))
2452 for (const VPtr &Vptr : getVTablePointers(VTableClass: ClassDecl))
2453 EmitVTableAssumptionLoad(Vptr, This);
2454}
2455
2456void CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(
2457 const CXXConstructorDecl *D, Address This, Address Src,
2458 const CXXConstructExpr *E) {
2459 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2460
2461 CallArgList Args;
2462
2463 // Push the this ptr.
2464 Args.add(rvalue: RValue::get(V: getAsNaturalPointerTo(Addr: This, PointeeType: D->getThisType())),
2465 type: D->getThisType());
2466
2467 // Push the src ptr.
2468 QualType QT = *(FPT->param_type_begin());
2469 llvm::Type *t = CGM.getTypes().ConvertType(T: QT);
2470 llvm::Value *Val = getAsNaturalPointerTo(Addr: Src, PointeeType: D->getThisType());
2471 llvm::Value *SrcVal = Builder.CreateBitCast(V: Val, DestTy: t);
2472 Args.add(rvalue: RValue::get(V: SrcVal), type: QT);
2473
2474 // Skip over first argument (Src).
2475 EmitCallArgs(Args, Prototype: FPT, ArgRange: drop_begin(RangeOrContainer: E->arguments(), N: 1), AC: E->getConstructor(),
2476 /*ParamsToSkip*/ 1);
2477
2478 EmitCXXConstructorCall(D, Type: Ctor_Complete, /*ForVirtualBase*/ false,
2479 /*Delegating*/ false, This, Args,
2480 Overlap: AggValueSlot::MayOverlap, Loc: E->getExprLoc(),
2481 /*NewPointerIsChecked*/ false);
2482}
2483
2484void CodeGenFunction::EmitDelegateCXXConstructorCall(
2485 const CXXConstructorDecl *Ctor, CXXCtorType CtorType,
2486 const FunctionArgList &Args, SourceLocation Loc) {
2487 CallArgList DelegateArgs;
2488
2489 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2490 assert(I != E && "no parameters to constructor");
2491
2492 // this
2493 Address This = LoadCXXThisAddress();
2494 DelegateArgs.add(rvalue: RValue::get(V: getAsNaturalPointerTo(
2495 Addr: This, PointeeType: (*I)->getType()->getPointeeType())),
2496 type: (*I)->getType());
2497 ++I;
2498
2499 // FIXME: The location of the VTT parameter in the parameter list is
2500 // specific to the Itanium ABI and shouldn't be hardcoded here.
2501 if (CGM.getCXXABI().NeedsVTTParameter(GD: CurGD)) {
2502 assert(I != E && "cannot skip vtt parameter, already done with args");
2503 assert((*I)->getType()->isPointerType() &&
2504 "skipping parameter not of vtt type");
2505 ++I;
2506 }
2507
2508 // Explicit arguments.
2509 for (; I != E; ++I) {
2510 const VarDecl *param = *I;
2511 // FIXME: per-argument source location
2512 EmitDelegateCallArg(args&: DelegateArgs, param, loc: Loc);
2513 }
2514
2515 EmitCXXConstructorCall(D: Ctor, Type: CtorType, /*ForVirtualBase=*/false,
2516 /*Delegating=*/true, This, Args&: DelegateArgs,
2517 Overlap: AggValueSlot::MayOverlap, Loc,
2518 /*NewPointerIsChecked=*/true);
2519}
2520
2521namespace {
2522struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
2523 const CXXDestructorDecl *Dtor;
2524 Address Addr;
2525 CXXDtorType Type;
2526
2527 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
2528 CXXDtorType Type)
2529 : Dtor(D), Addr(Addr), Type(Type) {}
2530
2531 void Emit(CodeGenFunction &CGF, Flags flags) override {
2532 // We are calling the destructor from within the constructor.
2533 // Therefore, "this" should have the expected type.
2534 QualType ThisTy = Dtor->getFunctionObjectParameterType();
2535 CGF.EmitCXXDestructorCall(D: Dtor, Type, /*ForVirtualBase=*/false,
2536 /*Delegating=*/true, This: Addr, ThisTy);
2537 }
2538};
2539} // end anonymous namespace
2540
2541void CodeGenFunction::EmitDelegatingCXXConstructorCall(
2542 const CXXConstructorDecl *Ctor, const FunctionArgList &Args) {
2543 assert(Ctor->isDelegatingConstructor());
2544
2545 Address ThisPtr = LoadCXXThisAddress();
2546
2547 AggValueSlot AggSlot = AggValueSlot::forAddr(
2548 addr: ThisPtr, quals: Qualifiers(), isDestructed: AggValueSlot::IsDestructed,
2549 needsGC: AggValueSlot::DoesNotNeedGCBarriers, isAliased: AggValueSlot::IsNotAliased,
2550 mayOverlap: AggValueSlot::MayOverlap, isZeroed: AggValueSlot::IsNotZeroed,
2551 // Checks are made by the code that calls constructor.
2552 isChecked: AggValueSlot::IsSanitizerChecked);
2553
2554 EmitAggExpr(E: Ctor->init_begin()[0]->getInit(), AS: AggSlot);
2555
2556 const CXXRecordDecl *ClassDecl = Ctor->getParent();
2557 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
2558 CXXDtorType Type =
2559 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2560
2561 EHStack.pushCleanup<CallDelegatingCtorDtor>(
2562 Kind: EHCleanup, A: ClassDecl->getDestructor(), A: ThisPtr, A: Type);
2563 }
2564}
2565
2566void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2567 CXXDtorType Type,
2568 bool ForVirtualBase,
2569 bool Delegating, Address This,
2570 QualType ThisTy) {
2571 CGM.getCXXABI().EmitDestructorCall(CGF&: *this, DD, Type, ForVirtualBase,
2572 Delegating, This, ThisTy);
2573}
2574
2575namespace {
2576struct CallLocalDtor final : EHScopeStack::Cleanup {
2577 const CXXDestructorDecl *Dtor;
2578 Address Addr;
2579 QualType Ty;
2580
2581 CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
2582 : Dtor(D), Addr(Addr), Ty(Ty) {}
2583
2584 void Emit(CodeGenFunction &CGF, Flags flags) override {
2585 CGF.EmitCXXDestructorCall(DD: Dtor, Type: Dtor_Complete,
2586 /*ForVirtualBase=*/false,
2587 /*Delegating=*/false, This: Addr, ThisTy: Ty);
2588 }
2589};
2590} // end anonymous namespace
2591
2592void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
2593 QualType T, Address Addr) {
2594 EHStack.pushCleanup<CallLocalDtor>(Kind: NormalAndEHCleanup, A: D, A: Addr, A: T);
2595}
2596
2597void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
2598 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2599 if (!ClassDecl)
2600 return;
2601 if (ClassDecl->hasTrivialDestructor())
2602 return;
2603
2604 const CXXDestructorDecl *D = ClassDecl->getDestructor();
2605 assert(D && D->isUsed() && "destructor not marked as used!");
2606 PushDestructorCleanup(D, T, Addr);
2607}
2608
2609void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
2610 // Compute the address point.
2611 llvm::Value *VTableAddressPoint =
2612 CGM.getCXXABI().getVTableAddressPointInStructor(
2613 CGF&: *this, RD: Vptr.VTableClass, Base: Vptr.Base, NearestVBase: Vptr.NearestVBase);
2614
2615 if (!VTableAddressPoint)
2616 return;
2617
2618 // Compute where to store the address point.
2619 llvm::Value *VirtualOffset = nullptr;
2620 CharUnits NonVirtualOffset = CharUnits::Zero();
2621
2622 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(CGF&: *this, Vptr)) {
2623 // We need to use the virtual base offset offset because the virtual base
2624 // might have a different offset in the most derived class.
2625
2626 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2627 CGF&: *this, This: LoadCXXThisAddress(), ClassDecl: Vptr.VTableClass, BaseClassDecl: Vptr.NearestVBase);
2628 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
2629 } else {
2630 // We can just use the base offset in the complete class.
2631 NonVirtualOffset = Vptr.Base.getBaseOffset();
2632 }
2633
2634 // Apply the offsets.
2635 Address VTableField = LoadCXXThisAddress();
2636 if (!NonVirtualOffset.isZero() || VirtualOffset)
2637 VTableField = ApplyNonVirtualAndVirtualOffset(
2638 CGF&: *this, addr: VTableField, nonVirtualOffset: NonVirtualOffset, virtualOffset: VirtualOffset, derivedClass: Vptr.VTableClass,
2639 nearestVBase: Vptr.NearestVBase);
2640
2641 // Finally, store the address point. Use the same LLVM types as the field to
2642 // support optimization.
2643 unsigned GlobalsAS = CGM.getDataLayout().getDefaultGlobalsAddressSpace();
2644 llvm::Type *PtrTy = llvm::PointerType::get(C&: CGM.getLLVMContext(), AddressSpace: GlobalsAS);
2645 // vtable field is derived from `this` pointer, therefore they should be in
2646 // the same addr space. Note that this might not be LLVM address space 0.
2647 VTableField = VTableField.withElementType(ElemTy: PtrTy);
2648
2649 if (auto AuthenticationInfo = CGM.getVTablePointerAuthInfo(
2650 Context: this, Record: Vptr.Base.getBase(), StorageAddress: VTableField.emitRawPointer(CGF&: *this)))
2651 VTableAddressPoint =
2652 EmitPointerAuthSign(Info: *AuthenticationInfo, Pointer: VTableAddressPoint);
2653
2654 llvm::StoreInst *Store = Builder.CreateStore(Val: VTableAddressPoint, Addr: VTableField);
2655 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrType: PtrTy);
2656 CGM.DecorateInstructionWithTBAA(Inst: Store, TBAAInfo);
2657 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2658 CGM.getCodeGenOpts().StrictVTablePointers)
2659 CGM.DecorateInstructionWithInvariantGroup(I: Store, RD: Vptr.VTableClass);
2660}
2661
2662CodeGenFunction::VPtrsVector
2663CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2664 CodeGenFunction::VPtrsVector VPtrsResult;
2665 VisitedVirtualBasesSetTy VBases;
2666 getVTablePointers(Base: BaseSubobject(VTableClass, CharUnits::Zero()),
2667 /*NearestVBase=*/nullptr,
2668 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2669 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2670 vptrs&: VPtrsResult);
2671 return VPtrsResult;
2672}
2673
2674void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2675 const CXXRecordDecl *NearestVBase,
2676 CharUnits OffsetFromNearestVBase,
2677 bool BaseIsNonVirtualPrimaryBase,
2678 const CXXRecordDecl *VTableClass,
2679 VisitedVirtualBasesSetTy &VBases,
2680 VPtrsVector &Vptrs) {
2681 // If this base is a non-virtual primary base the address point has already
2682 // been set.
2683 if (!BaseIsNonVirtualPrimaryBase) {
2684 // Initialize the vtable pointer for this base.
2685 VPtr Vptr = {.Base: Base, .NearestVBase: NearestVBase, .OffsetFromNearestVBase: OffsetFromNearestVBase, .VTableClass: VTableClass};
2686 Vptrs.push_back(Elt: Vptr);
2687 }
2688
2689 const CXXRecordDecl *RD = Base.getBase();
2690
2691 // Traverse bases.
2692 for (const auto &I : RD->bases()) {
2693 auto *BaseDecl = I.getType()->castAsCXXRecordDecl();
2694 // Ignore classes without a vtable.
2695 if (!BaseDecl->isDynamicClass())
2696 continue;
2697
2698 CharUnits BaseOffset;
2699 CharUnits BaseOffsetFromNearestVBase;
2700 bool BaseDeclIsNonVirtualPrimaryBase;
2701
2702 if (I.isVirtual()) {
2703 // Check if we've visited this virtual base before.
2704 if (!VBases.insert(Ptr: BaseDecl).second)
2705 continue;
2706
2707 const ASTRecordLayout &Layout =
2708 getContext().getASTRecordLayout(D: VTableClass);
2709
2710 BaseOffset = Layout.getVBaseClassOffset(VBase: BaseDecl);
2711 BaseOffsetFromNearestVBase = CharUnits::Zero();
2712 BaseDeclIsNonVirtualPrimaryBase = false;
2713 } else {
2714 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D: RD);
2715
2716 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(Base: BaseDecl);
2717 BaseOffsetFromNearestVBase =
2718 OffsetFromNearestVBase + Layout.getBaseClassOffset(Base: BaseDecl);
2719 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2720 }
2721
2722 getVTablePointers(
2723 Base: BaseSubobject(BaseDecl, BaseOffset),
2724 NearestVBase: I.isVirtual() ? BaseDecl : NearestVBase, OffsetFromNearestVBase: BaseOffsetFromNearestVBase,
2725 BaseIsNonVirtualPrimaryBase: BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
2726 }
2727}
2728
2729void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2730 // Ignore classes without a vtable.
2731 if (!RD->isDynamicClass())
2732 return;
2733
2734 // Initialize the vtable pointers for this class and all of its bases.
2735 if (CGM.getCXXABI().doStructorsInitializeVPtrs(VTableClass: RD))
2736 for (const VPtr &Vptr : getVTablePointers(VTableClass: RD))
2737 InitializeVTablePointer(Vptr);
2738
2739 if (RD->getNumVBases())
2740 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(CGF&: *this, RD);
2741}
2742
2743llvm::Value *CodeGenFunction::GetVTablePtr(Address This, llvm::Type *VTableTy,
2744 const CXXRecordDecl *RD,
2745 VTableAuthMode AuthMode) {
2746 Address VTablePtrSrc = This.withElementType(ElemTy: VTableTy);
2747 llvm::Instruction *VTable = Builder.CreateLoad(Addr: VTablePtrSrc, Name: "vtable");
2748 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrType: VTableTy);
2749 CGM.DecorateInstructionWithTBAA(Inst: VTable, TBAAInfo);
2750
2751 if (auto AuthenticationInfo =
2752 CGM.getVTablePointerAuthInfo(Context: this, Record: RD, StorageAddress: This.emitRawPointer(CGF&: *this))) {
2753 if (AuthMode != VTableAuthMode::UnsafeUbsanStrip) {
2754 VTable = cast<llvm::Instruction>(
2755 Val: EmitPointerAuthAuth(Info: *AuthenticationInfo, Pointer: VTable));
2756 if (AuthMode == VTableAuthMode::MustTrap) {
2757 // This is clearly suboptimal but until we have an ability
2758 // to rely on the authentication intrinsic trapping and force
2759 // an authentication to occur we don't really have a choice.
2760 VTable =
2761 cast<llvm::Instruction>(Val: Builder.CreateBitCast(V: VTable, DestTy: Int8PtrTy));
2762 Builder.CreateLoad(Addr: RawAddress(VTable, Int8Ty, CGM.getPointerAlign()),
2763 /* IsVolatile */ true);
2764 }
2765 } else {
2766 VTable = cast<llvm::Instruction>(Val: EmitPointerAuthAuth(
2767 Info: CGPointerAuthInfo(0, PointerAuthenticationMode::Strip, false, false,
2768 nullptr),
2769 Pointer: VTable));
2770 }
2771 }
2772
2773 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2774 CGM.getCodeGenOpts().StrictVTablePointers)
2775 CGM.DecorateInstructionWithInvariantGroup(I: VTable, RD);
2776
2777 return VTable;
2778}
2779
2780// If a class has a single non-virtual base and does not introduce or override
2781// virtual member functions or fields, it will have the same layout as its base.
2782// This function returns the least derived such class.
2783//
2784// Casting an instance of a base class to such a derived class is technically
2785// undefined behavior, but it is a relatively common hack for introducing member
2786// functions on class instances with specific properties (e.g. llvm::Operator)
2787// that works under most compilers and should not have security implications, so
2788// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2789static const CXXRecordDecl *
2790LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2791 if (!RD->field_empty())
2792 return RD;
2793
2794 if (RD->getNumVBases() != 0)
2795 return RD;
2796
2797 if (RD->getNumBases() != 1)
2798 return RD;
2799
2800 for (const CXXMethodDecl *MD : RD->methods()) {
2801 if (MD->isVirtual()) {
2802 // Virtual member functions are only ok if they are implicit destructors
2803 // because the implicit destructor will have the same semantics as the
2804 // base class's destructor if no fields are added.
2805 if (isa<CXXDestructorDecl>(Val: MD) && MD->isImplicit())
2806 continue;
2807 return RD;
2808 }
2809 }
2810
2811 return LeastDerivedClassWithSameLayout(
2812 RD: RD->bases_begin()->getType()->getAsCXXRecordDecl());
2813}
2814
2815void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2816 llvm::Value *VTable,
2817 SourceLocation Loc) {
2818 if (SanOpts.has(K: SanitizerKind::CFIVCall))
2819 EmitVTablePtrCheckForCall(RD, VTable, TCK: CodeGenFunction::CFITCK_VCall, Loc);
2820 // Emit the intrinsics of (type_test and assume) for the features of WPD and
2821 // speculative devirtualization. For WPD, emit the intrinsics only for the
2822 // case of non_public LTO visibility.
2823 // TODO: refactor this condition and similar ones into a function (e.g.,
2824 // ShouldEmitDevirtualizationMD) to encapsulate the details of the different
2825 // types of devirtualization.
2826 else if ((CGM.getCodeGenOpts().WholeProgramVTables &&
2827 !CGM.AlwaysHasLTOVisibilityPublic(RD)) ||
2828 CGM.getCodeGenOpts().DevirtualizeSpeculatively) {
2829 CanQualType Ty = CGM.getContext().getCanonicalTagType(TD: RD);
2830 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(T: Ty);
2831 llvm::Value *TypeId = llvm::MetadataAsValue::get(Context&: CGM.getLLVMContext(), MD);
2832
2833 // If we already know that the call has hidden LTO visibility, emit
2834 // @llvm.type.test(). Otherwise emit @llvm.public.type.test(), which WPD
2835 // will convert to @llvm.type.test() if we assert at link time that we have
2836 // whole program visibility.
2837 llvm::Intrinsic::ID IID = CGM.HasHiddenLTOVisibility(RD)
2838 ? llvm::Intrinsic::type_test
2839 : llvm::Intrinsic::public_type_test;
2840 llvm::Value *TypeTest =
2841 Builder.CreateCall(Callee: CGM.getIntrinsic(IID), Args: {VTable, TypeId});
2842 Builder.CreateCall(Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::assume), Args: TypeTest);
2843 }
2844}
2845
2846/// Converts the CFITypeCheckKind into SanitizerKind::SanitizerOrdinal and
2847/// llvm::SanitizerStatKind.
2848static std::pair<SanitizerKind::SanitizerOrdinal, llvm::SanitizerStatKind>
2849SanitizerInfoFromCFICheckKind(CodeGenFunction::CFITypeCheckKind TCK) {
2850 switch (TCK) {
2851 case CodeGenFunction::CFITCK_VCall:
2852 return std::make_pair(x: SanitizerKind::SO_CFIVCall, y: llvm::SanStat_CFI_VCall);
2853 case CodeGenFunction::CFITCK_NVCall:
2854 return std::make_pair(x: SanitizerKind::SO_CFINVCall,
2855 y: llvm::SanStat_CFI_NVCall);
2856 case CodeGenFunction::CFITCK_DerivedCast:
2857 return std::make_pair(x: SanitizerKind::SO_CFIDerivedCast,
2858 y: llvm::SanStat_CFI_DerivedCast);
2859 case CodeGenFunction::CFITCK_UnrelatedCast:
2860 return std::make_pair(x: SanitizerKind::SO_CFIUnrelatedCast,
2861 y: llvm::SanStat_CFI_UnrelatedCast);
2862 case CodeGenFunction::CFITCK_ICall:
2863 case CodeGenFunction::CFITCK_NVMFCall:
2864 case CodeGenFunction::CFITCK_VMFCall:
2865 llvm_unreachable("unexpected sanitizer kind");
2866 }
2867 llvm_unreachable("Unknown CFITypeCheckKind enum");
2868}
2869
2870void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
2871 llvm::Value *VTable,
2872 CFITypeCheckKind TCK,
2873 SourceLocation Loc) {
2874 if (!SanOpts.has(K: SanitizerKind::CFICastStrict))
2875 RD = LeastDerivedClassWithSameLayout(RD);
2876
2877 auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
2878 SanitizerDebugLocation SanScope(this, {Ordinal},
2879 SanitizerHandler::CFICheckFail);
2880
2881 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
2882}
2883
2884void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T, Address Derived,
2885 bool MayBeNull,
2886 CFITypeCheckKind TCK,
2887 SourceLocation Loc) {
2888 if (!getLangOpts().CPlusPlus)
2889 return;
2890
2891 const auto *ClassDecl = T->getAsCXXRecordDecl();
2892 if (!ClassDecl)
2893 return;
2894
2895 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2896 return;
2897
2898 if (!SanOpts.has(K: SanitizerKind::CFICastStrict))
2899 ClassDecl = LeastDerivedClassWithSameLayout(RD: ClassDecl);
2900
2901 auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
2902 SanitizerDebugLocation SanScope(this, {Ordinal},
2903 SanitizerHandler::CFICheckFail);
2904
2905 llvm::BasicBlock *ContBlock = nullptr;
2906
2907 if (MayBeNull) {
2908 llvm::Value *DerivedNotNull =
2909 Builder.CreateIsNotNull(Arg: Derived.emitRawPointer(CGF&: *this), Name: "cast.nonnull");
2910
2911 llvm::BasicBlock *CheckBlock = createBasicBlock(name: "cast.check");
2912 ContBlock = createBasicBlock(name: "cast.cont");
2913
2914 Builder.CreateCondBr(Cond: DerivedNotNull, True: CheckBlock, False: ContBlock);
2915
2916 EmitBlock(BB: CheckBlock);
2917 }
2918
2919 llvm::Value *VTable;
2920 std::tie(args&: VTable, args&: ClassDecl) =
2921 CGM.getCXXABI().LoadVTablePtr(CGF&: *this, This: Derived, RD: ClassDecl);
2922
2923 EmitVTablePtrCheck(RD: ClassDecl, VTable, TCK, Loc);
2924
2925 if (MayBeNull) {
2926 Builder.CreateBr(Dest: ContBlock);
2927 EmitBlock(BB: ContBlock);
2928 }
2929}
2930
2931void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
2932 llvm::Value *VTable,
2933 CFITypeCheckKind TCK,
2934 SourceLocation Loc) {
2935 assert(IsSanitizerScope);
2936
2937 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2938 !CGM.HasHiddenLTOVisibility(RD))
2939 return;
2940
2941 auto [M, SSK] = SanitizerInfoFromCFICheckKind(TCK);
2942
2943 std::string TypeName = RD->getQualifiedNameAsString();
2944 if (getContext().getNoSanitizeList().containsType(
2945 Mask: SanitizerMask::bitPosToMask(Pos: M), MangledTypeName: TypeName))
2946 return;
2947
2948 EmitSanitizerStatReport(SSK);
2949
2950 CanQualType T = CGM.getContext().getCanonicalTagType(TD: RD);
2951 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(T);
2952 llvm::Value *TypeId = llvm::MetadataAsValue::get(Context&: getLLVMContext(), MD);
2953
2954 llvm::Value *TypeTest = Builder.CreateCall(
2955 Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::type_test), Args: {VTable, TypeId});
2956
2957 llvm::Constant *StaticData[] = {
2958 llvm::ConstantInt::get(Ty: Int8Ty, V: TCK),
2959 EmitCheckSourceLocation(Loc),
2960 EmitCheckTypeDescriptor(T),
2961 };
2962
2963 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2964 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2965 EmitCfiSlowPathCheck(Ordinal: M, Cond: TypeTest, TypeId: CrossDsoTypeId, Ptr: VTable, StaticArgs: StaticData);
2966 return;
2967 }
2968
2969 if (CGM.getCodeGenOpts().SanitizeTrap.has(O: M)) {
2970 bool NoMerge = !CGM.getCodeGenOpts().SanitizeMergeHandlers.has(O: M);
2971 EmitTrapCheck(Checked: TypeTest, CheckHandlerID: SanitizerHandler::CFICheckFail, NoMerge);
2972 return;
2973 }
2974
2975 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2976 Context&: CGM.getLLVMContext(),
2977 MD: llvm::MDString::get(Context&: CGM.getLLVMContext(), Str: "all-vtables"));
2978 llvm::Value *ValidVtable = Builder.CreateCall(
2979 Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::type_test), Args: {VTable, AllVtables});
2980 EmitCheck(Checked: std::make_pair(x&: TypeTest, y&: M), Check: SanitizerHandler::CFICheckFail,
2981 StaticArgs: StaticData, DynamicArgs: {VTable, ValidVtable});
2982}
2983
2984bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2985 if ((!CGM.getCodeGenOpts().WholeProgramVTables ||
2986 !CGM.HasHiddenLTOVisibility(RD)) &&
2987 !CGM.getCodeGenOpts().DevirtualizeSpeculatively)
2988 return false;
2989
2990 if (CGM.getCodeGenOpts().VirtualFunctionElimination)
2991 return true;
2992
2993 if (!SanOpts.has(K: SanitizerKind::CFIVCall) ||
2994 !CGM.getCodeGenOpts().SanitizeTrap.has(K: SanitizerKind::CFIVCall))
2995 return false;
2996
2997 std::string TypeName = RD->getQualifiedNameAsString();
2998 return !getContext().getNoSanitizeList().containsType(Mask: SanitizerKind::CFIVCall,
2999 MangledTypeName: TypeName);
3000}
3001
3002llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
3003 const CXXRecordDecl *RD, llvm::Value *VTable, llvm::Type *VTableTy,
3004 uint64_t VTableByteOffset) {
3005 auto CheckOrdinal = SanitizerKind::SO_CFIVCall;
3006 auto CheckHandler = SanitizerHandler::CFICheckFail;
3007 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
3008
3009 EmitSanitizerStatReport(SSK: llvm::SanStat_CFI_VCall);
3010
3011 CanQualType T = CGM.getContext().getCanonicalTagType(TD: RD);
3012 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(T);
3013 llvm::Value *TypeId = llvm::MetadataAsValue::get(Context&: CGM.getLLVMContext(), MD);
3014
3015 auto CheckedLoadIntrinsic = CGM.getLangOpts().RelativeCXXABIVTables
3016 ? llvm::Intrinsic::type_checked_load_relative
3017 : llvm::Intrinsic::type_checked_load;
3018 llvm::Value *CheckedLoad = Builder.CreateCall(
3019 Callee: CGM.getIntrinsic(IID: CheckedLoadIntrinsic),
3020 Args: {VTable, llvm::ConstantInt::get(Ty: Int32Ty, V: VTableByteOffset), TypeId});
3021
3022 llvm::Value *CheckResult = Builder.CreateExtractValue(Agg: CheckedLoad, Idxs: 1);
3023
3024 std::string TypeName = RD->getQualifiedNameAsString();
3025 if (SanOpts.has(K: SanitizerKind::CFIVCall) &&
3026 !getContext().getNoSanitizeList().containsType(Mask: SanitizerKind::CFIVCall,
3027 MangledTypeName: TypeName)) {
3028 EmitCheck(Checked: std::make_pair(x&: CheckResult, y&: CheckOrdinal), Check: CheckHandler, StaticArgs: {}, DynamicArgs: {});
3029 }
3030
3031 return Builder.CreateBitCast(V: Builder.CreateExtractValue(Agg: CheckedLoad, Idxs: 0),
3032 DestTy: VTableTy);
3033}
3034
3035void CodeGenFunction::EmitForwardingCallToLambda(
3036 const CXXMethodDecl *callOperator, CallArgList &callArgs,
3037 const CGFunctionInfo *calleeFnInfo, llvm::Constant *calleePtr) {
3038 // Get the address of the call operator.
3039 if (!calleeFnInfo)
3040 calleeFnInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD: callOperator);
3041
3042 if (!calleePtr)
3043 calleePtr =
3044 CGM.GetAddrOfFunction(GD: GlobalDecl(callOperator),
3045 Ty: CGM.getTypes().GetFunctionType(Info: *calleeFnInfo));
3046
3047 // Prepare the return slot.
3048 const FunctionProtoType *FPT =
3049 callOperator->getType()->castAs<FunctionProtoType>();
3050 QualType resultType = FPT->getReturnType();
3051 ReturnValueSlot returnSlot;
3052 if (!resultType->isVoidType() &&
3053 calleeFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
3054 !hasScalarEvaluationKind(T: calleeFnInfo->getReturnType()))
3055 returnSlot =
3056 ReturnValueSlot(ReturnValue, resultType.isVolatileQualified(),
3057 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
3058
3059 // We don't need to separately arrange the call arguments because
3060 // the call can't be variadic anyway --- it's impossible to forward
3061 // variadic arguments.
3062
3063 // Now emit our call.
3064 auto callee = CGCallee::forDirect(functionPtr: calleePtr, abstractInfo: GlobalDecl(callOperator));
3065 RValue RV = EmitCall(CallInfo: *calleeFnInfo, Callee: callee, ReturnValue: returnSlot, Args: callArgs);
3066
3067 // If necessary, copy the returned value into the slot.
3068 if (!resultType->isVoidType() && returnSlot.isNull()) {
3069 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
3070 RV = RValue::get(V: EmitARCRetainAutoreleasedReturnValue(value: RV.getScalarVal()));
3071 }
3072 EmitReturnOfRValue(RV, Ty: resultType);
3073 } else
3074 EmitBranchThroughCleanup(Dest: ReturnBlock);
3075}
3076
3077void CodeGenFunction::EmitLambdaBlockInvokeBody() {
3078 const BlockDecl *BD = BlockInfo->getBlockDecl();
3079 const VarDecl *variable = BD->capture_begin()->getVariable();
3080 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
3081 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
3082
3083 if (CallOp->isVariadic()) {
3084 // FIXME: Making this work correctly is nasty because it requires either
3085 // cloning the body of the call operator or making the call operator
3086 // forward.
3087 CGM.ErrorUnsupported(D: CurCodeDecl, Type: "lambda conversion to variadic function");
3088 return;
3089 }
3090
3091 // Start building arguments for forwarding call
3092 CallArgList CallArgs;
3093
3094 CanQualType ThisType =
3095 getContext().getPointerType(T: getContext().getCanonicalTagType(TD: Lambda));
3096 Address ThisPtr = GetAddrOfBlockDecl(var: variable);
3097 CallArgs.add(rvalue: RValue::get(V: getAsNaturalPointerTo(Addr: ThisPtr, PointeeType: ThisType)), type: ThisType);
3098
3099 // Add the rest of the parameters.
3100 for (auto *param : BD->parameters())
3101 EmitDelegateCallArg(args&: CallArgs, param, loc: param->getBeginLoc());
3102
3103 assert(!Lambda->isGenericLambda() &&
3104 "generic lambda interconversion to block not implemented");
3105 EmitForwardingCallToLambda(callOperator: CallOp, callArgs&: CallArgs);
3106}
3107
3108void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
3109 if (MD->isVariadic()) {
3110 // FIXME: Making this work correctly is nasty because it requires either
3111 // cloning the body of the call operator or making the call operator
3112 // forward.
3113 CGM.ErrorUnsupported(D: MD, Type: "lambda conversion to variadic function");
3114 return;
3115 }
3116
3117 const CXXRecordDecl *Lambda = MD->getParent();
3118
3119 // Start building arguments for forwarding call
3120 CallArgList CallArgs;
3121
3122 CanQualType LambdaType = getContext().getCanonicalTagType(TD: Lambda);
3123 CanQualType ThisType = getContext().getPointerType(T: LambdaType);
3124 Address ThisPtr = CreateMemTempWithoutCast(T: LambdaType, Name: "unused.capture");
3125 CallArgs.add(rvalue: RValue::get(V: ThisPtr.emitRawPointer(CGF&: *this)), type: ThisType);
3126
3127 EmitLambdaDelegatingInvokeBody(MD, CallArgs);
3128}
3129
3130void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD,
3131 CallArgList &CallArgs) {
3132 // Add the rest of the forwarded parameters.
3133 for (auto *Param : MD->parameters())
3134 EmitDelegateCallArg(args&: CallArgs, param: Param, loc: Param->getBeginLoc());
3135
3136 const CXXRecordDecl *Lambda = MD->getParent();
3137 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
3138 // For a generic lambda, find the corresponding call operator specialization
3139 // to which the call to the static-invoker shall be forwarded.
3140 if (Lambda->isGenericLambda()) {
3141 assert(MD->isFunctionTemplateSpecialization());
3142 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
3143 FunctionTemplateDecl *CallOpTemplate =
3144 CallOp->getDescribedFunctionTemplate();
3145 llvm::FoldingSetInsertToken InsertToken;
3146 FunctionDecl *CorrespondingCallOpSpecialization =
3147 CallOpTemplate->findSpecialization(Args: TAL->asArray(), InsertToken);
3148 assert(CorrespondingCallOpSpecialization);
3149 CallOp = cast<CXXMethodDecl>(Val: CorrespondingCallOpSpecialization);
3150 }
3151
3152 // Special lambda forwarding when there are inalloca parameters.
3153 if (hasInAllocaArg(MD)) {
3154 const CGFunctionInfo *ImplFnInfo = nullptr;
3155 llvm::Function *ImplFn = nullptr;
3156 EmitLambdaInAllocaImplFn(CallOp, ImplFnInfo: &ImplFnInfo, ImplFn: &ImplFn);
3157
3158 EmitForwardingCallToLambda(callOperator: CallOp, callArgs&: CallArgs, calleeFnInfo: ImplFnInfo, calleePtr: ImplFn);
3159 return;
3160 }
3161
3162 EmitForwardingCallToLambda(callOperator: CallOp, callArgs&: CallArgs);
3163}
3164
3165void CodeGenFunction::EmitLambdaInAllocaCallOpBody(const CXXMethodDecl *MD) {
3166 if (MD->isVariadic()) {
3167 // FIXME: Making this work correctly is nasty because it requires either
3168 // cloning the body of the call operator or making the call operator
3169 // forward.
3170 CGM.ErrorUnsupported(D: MD, Type: "lambda conversion to variadic function");
3171 return;
3172 }
3173
3174 // Forward %this argument.
3175 CallArgList CallArgs;
3176 CanQualType LambdaType = getContext().getCanonicalTagType(TD: MD->getParent());
3177 CanQualType ThisType = getContext().getPointerType(T: LambdaType);
3178 llvm::Value *ThisArg = CurFn->getArg(i: 0);
3179 CallArgs.add(rvalue: RValue::get(V: ThisArg), type: ThisType);
3180
3181 EmitLambdaDelegatingInvokeBody(MD, CallArgs);
3182}
3183
3184void CodeGenFunction::EmitLambdaInAllocaImplFn(
3185 const CXXMethodDecl *CallOp, const CGFunctionInfo **ImplFnInfo,
3186 llvm::Function **ImplFn) {
3187 const CGFunctionInfo &FnInfo =
3188 CGM.getTypes().arrangeCXXMethodDeclaration(MD: CallOp);
3189 llvm::Function *CallOpFn =
3190 cast<llvm::Function>(Val: CGM.GetAddrOfFunction(GD: GlobalDecl(CallOp)));
3191
3192 // Emit function containing the original call op body. __invoke will delegate
3193 // to this function.
3194 SmallVector<CanQualType, 4> ArgTypes;
3195 for (auto I = FnInfo.arg_begin(); I != FnInfo.arg_end(); ++I)
3196 ArgTypes.push_back(Elt: I->type);
3197 *ImplFnInfo = &CGM.getTypes().arrangeLLVMFunctionInfo(
3198 returnType: FnInfo.getReturnType(), opts: FnInfoOpts::IsDelegateCall, argTypes: ArgTypes,
3199 info: FnInfo.getExtInfo(), paramInfos: {}, args: FnInfo.getRequiredArgs(), ABIInfoFD: CallOp);
3200
3201 // Create mangled name as if this was a method named __impl. If for some
3202 // reason the name doesn't look as expected then just tack __impl to the
3203 // front.
3204 // TODO: Use the name mangler to produce the right name instead of using
3205 // string replacement.
3206 StringRef CallOpName = CallOpFn->getName();
3207 std::string ImplName;
3208 if (size_t Pos = CallOpName.find_first_of(Chars: "<lambda"))
3209 ImplName = ("?__impl@" + CallOpName.drop_front(N: Pos)).str();
3210 else
3211 ImplName = ("__impl" + CallOpName).str();
3212
3213 llvm::Function *Fn = CallOpFn->getParent()->getFunction(Name: ImplName);
3214 if (!Fn) {
3215 Fn = llvm::Function::Create(Ty: CGM.getTypes().GetFunctionType(Info: **ImplFnInfo),
3216 Linkage: llvm::GlobalValue::InternalLinkage, N: ImplName,
3217 M&: CGM.getModule());
3218 CGM.SetInternalFunctionAttributes(GD: CallOp, F: Fn, FI: **ImplFnInfo);
3219
3220 const GlobalDecl &GD = GlobalDecl(CallOp);
3221 const auto *D = cast<FunctionDecl>(Val: GD.getDecl());
3222 CodeGenFunction(CGM).GenerateCode(GD, Fn, FnInfo: **ImplFnInfo);
3223 CGM.SetLLVMFunctionAttributesForDefinition(D, F: Fn);
3224 }
3225 *ImplFn = Fn;
3226}
3227