1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This contains code dealing with C++ code generation of classes
11 //===----------------------------------------------------------------------===//
15 #include "CGDebugInfo.h"
16 #include "CGRecordLayout.h"
17 #include "CodeGenFunction.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Basic/CodeGenOptions.h"
27 #include "clang/Basic/TargetBuiltins.h"
28 #include "clang/CodeGen/CGFunctionInfo.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/Transforms/Utils/SanitizerStats.h"
34 using namespace clang
;
35 using namespace CodeGen
;
37 /// Return the best known alignment for an unknown pointer to a
39 CharUnits
CodeGenModule::getClassPointerAlignment(const CXXRecordDecl
*RD
) {
40 if (!RD
->hasDefinition())
41 return CharUnits::One(); // Hopefully won't be used anywhere.
43 auto &layout
= getContext().getASTRecordLayout(RD
);
45 // If the class is final, then we know that the pointer points to an
46 // object of that type and can use the full alignment.
47 if (RD
->isEffectivelyFinal())
48 return layout
.getAlignment();
50 // Otherwise, we have to assume it could be a subclass.
51 return layout
.getNonVirtualAlignment();
54 /// Return the smallest possible amount of storage that might be allocated
55 /// starting from the beginning of an object of a particular class.
57 /// This may be smaller than sizeof(RD) if RD has virtual base classes.
58 CharUnits
CodeGenModule::getMinimumClassObjectSize(const CXXRecordDecl
*RD
) {
59 if (!RD
->hasDefinition())
60 return CharUnits::One();
62 auto &layout
= getContext().getASTRecordLayout(RD
);
64 // If the class is final, then we know that the pointer points to an
65 // object of that type and can use the full alignment.
66 if (RD
->isEffectivelyFinal())
67 return layout
.getSize();
69 // Otherwise, we have to assume it could be a subclass.
70 return std::max(layout
.getNonVirtualSize(), CharUnits::One());
73 /// Return the best known alignment for a pointer to a virtual base,
74 /// given the alignment of a pointer to the derived class.
75 CharUnits
CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign
,
76 const CXXRecordDecl
*derivedClass
,
77 const CXXRecordDecl
*vbaseClass
) {
78 // The basic idea here is that an underaligned derived pointer might
79 // indicate an underaligned base pointer.
81 assert(vbaseClass
->isCompleteDefinition());
82 auto &baseLayout
= getContext().getASTRecordLayout(vbaseClass
);
83 CharUnits expectedVBaseAlign
= baseLayout
.getNonVirtualAlignment();
85 return getDynamicOffsetAlignment(actualDerivedAlign
, derivedClass
,
90 CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign
,
91 const CXXRecordDecl
*baseDecl
,
92 CharUnits expectedTargetAlign
) {
93 // If the base is an incomplete type (which is, alas, possible with
94 // member pointers), be pessimistic.
95 if (!baseDecl
->isCompleteDefinition())
96 return std::min(actualBaseAlign
, expectedTargetAlign
);
98 auto &baseLayout
= getContext().getASTRecordLayout(baseDecl
);
99 CharUnits expectedBaseAlign
= baseLayout
.getNonVirtualAlignment();
101 // If the class is properly aligned, assume the target offset is, too.
103 // This actually isn't necessarily the right thing to do --- if the
104 // class is a complete object, but it's only properly aligned for a
105 // base subobject, then the alignments of things relative to it are
106 // probably off as well. (Note that this requires the alignment of
107 // the target to be greater than the NV alignment of the derived
110 // However, our approach to this kind of under-alignment can only
111 // ever be best effort; after all, we're never going to propagate
112 // alignments through variables or parameters. Note, in particular,
113 // that constructing a polymorphic type in an address that's less
114 // than pointer-aligned will generally trap in the constructor,
115 // unless we someday add some sort of attribute to change the
116 // assumed alignment of 'this'. So our goal here is pretty much
117 // just to allow the user to explicitly say that a pointer is
118 // under-aligned and then safely access its fields and vtables.
119 if (actualBaseAlign
>= expectedBaseAlign
) {
120 return expectedTargetAlign
;
123 // Otherwise, we might be offset by an arbitrary multiple of the
124 // actual alignment. The correct adjustment is to take the min of
125 // the two alignments.
126 return std::min(actualBaseAlign
, expectedTargetAlign
);
129 Address
CodeGenFunction::LoadCXXThisAddress() {
130 assert(CurFuncDecl
&& "loading 'this' without a func declaration?");
131 auto *MD
= cast
<CXXMethodDecl
>(CurFuncDecl
);
133 // Lazily compute CXXThisAlignment.
134 if (CXXThisAlignment
.isZero()) {
135 // Just use the best known alignment for the parent.
136 // TODO: if we're currently emitting a complete-object ctor/dtor,
137 // we can always use the complete-object alignment.
138 CXXThisAlignment
= CGM
.getClassPointerAlignment(MD
->getParent());
141 llvm::Type
*Ty
= ConvertType(MD
->getThisType()->getPointeeType());
142 return Address(LoadCXXThis(), Ty
, CXXThisAlignment
, KnownNonNull
);
145 /// Emit the address of a field using a member data pointer.
147 /// \param E Only used for emergency diagnostics
149 CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr
*E
, Address base
,
150 llvm::Value
*memberPtr
,
151 const MemberPointerType
*memberPtrType
,
152 LValueBaseInfo
*BaseInfo
,
153 TBAAAccessInfo
*TBAAInfo
) {
154 // Ask the ABI to compute the actual address.
156 CGM
.getCXXABI().EmitMemberDataPointerAddress(*this, E
, base
,
157 memberPtr
, memberPtrType
);
159 QualType memberType
= memberPtrType
->getPointeeType();
160 CharUnits memberAlign
=
161 CGM
.getNaturalTypeAlignment(memberType
, BaseInfo
, TBAAInfo
);
163 CGM
.getDynamicOffsetAlignment(base
.getAlignment(),
164 memberPtrType
->getClass()->getAsCXXRecordDecl(),
166 return Address(ptr
, ConvertTypeForMem(memberPtrType
->getPointeeType()),
170 CharUnits
CodeGenModule::computeNonVirtualBaseClassOffset(
171 const CXXRecordDecl
*DerivedClass
, CastExpr::path_const_iterator Start
,
172 CastExpr::path_const_iterator End
) {
173 CharUnits Offset
= CharUnits::Zero();
175 const ASTContext
&Context
= getContext();
176 const CXXRecordDecl
*RD
= DerivedClass
;
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!");
183 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
185 const auto *BaseDecl
=
186 cast
<CXXRecordDecl
>(Base
->getType()->castAs
<RecordType
>()->getDecl());
189 Offset
+= Layout
.getBaseClassOffset(BaseDecl
);
198 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl
*ClassDecl
,
199 CastExpr::path_const_iterator PathBegin
,
200 CastExpr::path_const_iterator PathEnd
) {
201 assert(PathBegin
!= PathEnd
&& "Base path should not be empty!");
204 computeNonVirtualBaseClassOffset(ClassDecl
, PathBegin
, PathEnd
);
208 llvm::Type
*PtrDiffTy
=
209 Types
.ConvertType(getContext().getPointerDiffType());
211 return llvm::ConstantInt::get(PtrDiffTy
, Offset
.getQuantity());
214 /// Gets the address of a direct base class within a complete object.
215 /// This should only be used for (1) non-virtual bases or (2) virtual bases
216 /// when the type is known to be complete (e.g. in complete destructors).
218 /// The object pointed to by 'This' is assumed to be non-null.
220 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This
,
221 const CXXRecordDecl
*Derived
,
222 const CXXRecordDecl
*Base
,
223 bool BaseIsVirtual
) {
224 // 'this' must be a pointer (in some address space) to Derived.
225 assert(This
.getElementType() == ConvertType(Derived
));
227 // Compute the offset of the virtual base.
229 const ASTRecordLayout
&Layout
= getContext().getASTRecordLayout(Derived
);
231 Offset
= Layout
.getVBaseClassOffset(Base
);
233 Offset
= Layout
.getBaseClassOffset(Base
);
235 // Shift and cast down to the base type.
236 // TODO: for complete types, this should be possible with a GEP.
238 if (!Offset
.isZero()) {
239 V
= V
.withElementType(Int8Ty
);
240 V
= Builder
.CreateConstInBoundsByteGEP(V
, Offset
);
242 return V
.withElementType(ConvertType(Base
));
246 ApplyNonVirtualAndVirtualOffset(CodeGenFunction
&CGF
, Address addr
,
247 CharUnits nonVirtualOffset
,
248 llvm::Value
*virtualOffset
,
249 const CXXRecordDecl
*derivedClass
,
250 const CXXRecordDecl
*nearestVBase
) {
251 // Assert that we have something to do.
252 assert(!nonVirtualOffset
.isZero() || virtualOffset
!= nullptr);
254 // Compute the offset from the static and dynamic components.
255 llvm::Value
*baseOffset
;
256 if (!nonVirtualOffset
.isZero()) {
257 llvm::Type
*OffsetType
=
258 (CGF
.CGM
.getTarget().getCXXABI().isItaniumFamily() &&
259 CGF
.CGM
.getItaniumVTableContext().isRelativeLayout())
263 llvm::ConstantInt::get(OffsetType
, nonVirtualOffset
.getQuantity());
265 baseOffset
= CGF
.Builder
.CreateAdd(virtualOffset
, baseOffset
);
268 baseOffset
= virtualOffset
;
271 // Apply the base offset.
272 llvm::Value
*ptr
= addr
.getPointer();
273 ptr
= CGF
.Builder
.CreateInBoundsGEP(CGF
.Int8Ty
, ptr
, baseOffset
, "add.ptr");
275 // If we have a virtual component, the alignment of the result will
276 // be relative only to the known alignment of that vbase.
279 assert(nearestVBase
&& "virtual offset without vbase?");
280 alignment
= CGF
.CGM
.getVBaseAlignment(addr
.getAlignment(),
281 derivedClass
, nearestVBase
);
283 alignment
= addr
.getAlignment();
285 alignment
= alignment
.alignmentAtOffset(nonVirtualOffset
);
287 return Address(ptr
, CGF
.Int8Ty
, alignment
);
290 Address
CodeGenFunction::GetAddressOfBaseClass(
291 Address Value
, const CXXRecordDecl
*Derived
,
292 CastExpr::path_const_iterator PathBegin
,
293 CastExpr::path_const_iterator PathEnd
, bool NullCheckValue
,
294 SourceLocation Loc
) {
295 assert(PathBegin
!= PathEnd
&& "Base path should not be empty!");
297 CastExpr::path_const_iterator Start
= PathBegin
;
298 const CXXRecordDecl
*VBase
= nullptr;
300 // Sema has done some convenient canonicalization here: if the
301 // access path involved any virtual steps, the conversion path will
302 // *start* with a step down to the correct virtual base subobject,
303 // and hence will not require any further steps.
304 if ((*Start
)->isVirtual()) {
305 VBase
= cast
<CXXRecordDecl
>(
306 (*Start
)->getType()->castAs
<RecordType
>()->getDecl());
310 // Compute the static offset of the ultimate destination within its
311 // allocating subobject (the virtual base, if there is one, or else
312 // the "complete" object that we see).
313 CharUnits NonVirtualOffset
= CGM
.computeNonVirtualBaseClassOffset(
314 VBase
? VBase
: Derived
, Start
, PathEnd
);
316 // If there's a virtual step, we can sometimes "devirtualize" it.
317 // For now, that's limited to when the derived type is final.
318 // TODO: "devirtualize" this for accesses to known-complete objects.
319 if (VBase
&& Derived
->hasAttr
<FinalAttr
>()) {
320 const ASTRecordLayout
&layout
= getContext().getASTRecordLayout(Derived
);
321 CharUnits vBaseOffset
= layout
.getVBaseClassOffset(VBase
);
322 NonVirtualOffset
+= vBaseOffset
;
323 VBase
= nullptr; // we no longer have a virtual step
326 // Get the base pointer type.
327 llvm::Type
*BaseValueTy
= ConvertType((PathEnd
[-1])->getType());
328 llvm::Type
*PtrTy
= llvm::PointerType::get(
329 CGM
.getLLVMContext(), Value
.getType()->getPointerAddressSpace());
331 QualType DerivedTy
= getContext().getRecordType(Derived
);
332 CharUnits DerivedAlign
= CGM
.getClassPointerAlignment(Derived
);
334 // If the static offset is zero and we don't have a virtual step,
335 // just do a bitcast; null checks are unnecessary.
336 if (NonVirtualOffset
.isZero() && !VBase
) {
337 if (sanitizePerformTypeCheck()) {
338 SanitizerSet SkippedChecks
;
339 SkippedChecks
.set(SanitizerKind::Null
, !NullCheckValue
);
340 EmitTypeCheck(TCK_Upcast
, Loc
, Value
.getPointer(),
341 DerivedTy
, DerivedAlign
, SkippedChecks
);
343 return Value
.withElementType(BaseValueTy
);
346 llvm::BasicBlock
*origBB
= nullptr;
347 llvm::BasicBlock
*endBB
= nullptr;
349 // Skip over the offset (and the vtable load) if we're supposed to
350 // null-check the pointer.
351 if (NullCheckValue
) {
352 origBB
= Builder
.GetInsertBlock();
353 llvm::BasicBlock
*notNullBB
= createBasicBlock("cast.notnull");
354 endBB
= createBasicBlock("cast.end");
356 llvm::Value
*isNull
= Builder
.CreateIsNull(Value
.getPointer());
357 Builder
.CreateCondBr(isNull
, endBB
, notNullBB
);
358 EmitBlock(notNullBB
);
361 if (sanitizePerformTypeCheck()) {
362 SanitizerSet SkippedChecks
;
363 SkippedChecks
.set(SanitizerKind::Null
, true);
364 EmitTypeCheck(VBase
? TCK_UpcastToVirtualBase
: TCK_Upcast
, Loc
,
365 Value
.getPointer(), DerivedTy
, DerivedAlign
, SkippedChecks
);
368 // Compute the virtual offset.
369 llvm::Value
*VirtualOffset
= nullptr;
372 CGM
.getCXXABI().GetVirtualBaseClassOffset(*this, Value
, Derived
, VBase
);
375 // Apply both offsets.
376 Value
= ApplyNonVirtualAndVirtualOffset(*this, Value
, NonVirtualOffset
,
377 VirtualOffset
, Derived
, VBase
);
379 // Cast to the destination type.
380 Value
= Value
.withElementType(BaseValueTy
);
382 // Build a phi if we needed a null check.
383 if (NullCheckValue
) {
384 llvm::BasicBlock
*notNullBB
= Builder
.GetInsertBlock();
385 Builder
.CreateBr(endBB
);
388 llvm::PHINode
*PHI
= Builder
.CreatePHI(PtrTy
, 2, "cast.result");
389 PHI
->addIncoming(Value
.getPointer(), notNullBB
);
390 PHI
->addIncoming(llvm::Constant::getNullValue(PtrTy
), origBB
);
391 Value
= Value
.withPointer(PHI
, NotKnownNonNull
);
398 CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr
,
399 const CXXRecordDecl
*Derived
,
400 CastExpr::path_const_iterator PathBegin
,
401 CastExpr::path_const_iterator PathEnd
,
402 bool NullCheckValue
) {
403 assert(PathBegin
!= PathEnd
&& "Base path should not be empty!");
406 getContext().getCanonicalType(getContext().getTagDeclType(Derived
));
407 llvm::Type
*DerivedValueTy
= ConvertType(DerivedTy
);
409 llvm::Value
*NonVirtualOffset
=
410 CGM
.GetNonVirtualBaseClassOffset(Derived
, PathBegin
, PathEnd
);
412 if (!NonVirtualOffset
) {
413 // No offset, we can just cast back.
414 return BaseAddr
.withElementType(DerivedValueTy
);
417 llvm::BasicBlock
*CastNull
= nullptr;
418 llvm::BasicBlock
*CastNotNull
= nullptr;
419 llvm::BasicBlock
*CastEnd
= nullptr;
421 if (NullCheckValue
) {
422 CastNull
= createBasicBlock("cast.null");
423 CastNotNull
= createBasicBlock("cast.notnull");
424 CastEnd
= createBasicBlock("cast.end");
426 llvm::Value
*IsNull
= Builder
.CreateIsNull(BaseAddr
.getPointer());
427 Builder
.CreateCondBr(IsNull
, CastNull
, CastNotNull
);
428 EmitBlock(CastNotNull
);
432 llvm::Value
*Value
= BaseAddr
.getPointer();
433 Value
= Builder
.CreateInBoundsGEP(
434 Int8Ty
, Value
, Builder
.CreateNeg(NonVirtualOffset
), "sub.ptr");
436 // Produce a PHI if we had a null-check.
437 if (NullCheckValue
) {
438 Builder
.CreateBr(CastEnd
);
440 Builder
.CreateBr(CastEnd
);
443 llvm::PHINode
*PHI
= Builder
.CreatePHI(Value
->getType(), 2);
444 PHI
->addIncoming(Value
, CastNotNull
);
445 PHI
->addIncoming(llvm::Constant::getNullValue(Value
->getType()), CastNull
);
449 return Address(Value
, DerivedValueTy
, CGM
.getClassPointerAlignment(Derived
));
452 llvm::Value
*CodeGenFunction::GetVTTParameter(GlobalDecl GD
,
455 if (!CGM
.getCXXABI().NeedsVTTParameter(GD
)) {
456 // This constructor/destructor does not need a VTT parameter.
460 const CXXRecordDecl
*RD
= cast
<CXXMethodDecl
>(CurCodeDecl
)->getParent();
461 const CXXRecordDecl
*Base
= cast
<CXXMethodDecl
>(GD
.getDecl())->getParent();
463 uint64_t SubVTTIndex
;
466 // If this is a delegating constructor call, just load the VTT.
468 } else if (RD
== Base
) {
469 // If the record matches the base, this is the complete ctor/dtor
470 // variant calling the base variant in a class with virtual bases.
471 assert(!CGM
.getCXXABI().NeedsVTTParameter(CurGD
) &&
472 "doing no-op VTT offset in base dtor/ctor?");
473 assert(!ForVirtualBase
&& "Can't have same class as virtual base!");
476 const ASTRecordLayout
&Layout
= getContext().getASTRecordLayout(RD
);
477 CharUnits BaseOffset
= ForVirtualBase
?
478 Layout
.getVBaseClassOffset(Base
) :
479 Layout
.getBaseClassOffset(Base
);
482 CGM
.getVTables().getSubVTTIndex(RD
, BaseSubobject(Base
, BaseOffset
));
483 assert(SubVTTIndex
!= 0 && "Sub-VTT index must be greater than zero!");
486 if (CGM
.getCXXABI().NeedsVTTParameter(CurGD
)) {
487 // A VTT parameter was passed to the constructor, use it.
488 llvm::Value
*VTT
= LoadCXXVTT();
489 return Builder
.CreateConstInBoundsGEP1_64(VoidPtrTy
, VTT
, SubVTTIndex
);
491 // We're the complete constructor, so get the VTT by name.
492 llvm::GlobalValue
*VTT
= CGM
.getVTables().GetAddrOfVTT(RD
);
493 return Builder
.CreateConstInBoundsGEP2_64(
494 VTT
->getValueType(), VTT
, 0, SubVTTIndex
);
499 /// Call the destructor for a direct base class.
500 struct CallBaseDtor final
: EHScopeStack::Cleanup
{
501 const CXXRecordDecl
*BaseClass
;
503 CallBaseDtor(const CXXRecordDecl
*Base
, bool BaseIsVirtual
)
504 : BaseClass(Base
), BaseIsVirtual(BaseIsVirtual
) {}
506 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
507 const CXXRecordDecl
*DerivedClass
=
508 cast
<CXXMethodDecl
>(CGF
.CurCodeDecl
)->getParent();
510 const CXXDestructorDecl
*D
= BaseClass
->getDestructor();
511 // We are already inside a destructor, so presumably the object being
512 // destroyed should have the expected type.
513 QualType ThisTy
= D
->getThisObjectType();
515 CGF
.GetAddressOfDirectBaseInCompleteClass(CGF
.LoadCXXThisAddress(),
516 DerivedClass
, BaseClass
,
518 CGF
.EmitCXXDestructorCall(D
, Dtor_Base
, BaseIsVirtual
,
519 /*Delegating=*/false, Addr
, ThisTy
);
523 /// A visitor which checks whether an initializer uses 'this' in a
524 /// way which requires the vtable to be properly set.
525 struct DynamicThisUseChecker
: ConstEvaluatedExprVisitor
<DynamicThisUseChecker
> {
526 typedef ConstEvaluatedExprVisitor
<DynamicThisUseChecker
> super
;
530 DynamicThisUseChecker(const ASTContext
&C
) : super(C
), UsesThis(false) {}
532 // Black-list all explicit and implicit references to 'this'.
534 // Do we need to worry about external references to 'this' derived
535 // from arbitrary code? If so, then anything which runs arbitrary
536 // external code might potentially access the vtable.
537 void VisitCXXThisExpr(const CXXThisExpr
*E
) { UsesThis
= true; }
539 } // end anonymous namespace
541 static bool BaseInitializerUsesThis(ASTContext
&C
, const Expr
*Init
) {
542 DynamicThisUseChecker
Checker(C
);
544 return Checker
.UsesThis
;
547 static void EmitBaseInitializer(CodeGenFunction
&CGF
,
548 const CXXRecordDecl
*ClassDecl
,
549 CXXCtorInitializer
*BaseInit
) {
550 assert(BaseInit
->isBaseInitializer() &&
551 "Must have base initializer!");
553 Address ThisPtr
= CGF
.LoadCXXThisAddress();
555 const Type
*BaseType
= BaseInit
->getBaseClass();
556 const auto *BaseClassDecl
=
557 cast
<CXXRecordDecl
>(BaseType
->castAs
<RecordType
>()->getDecl());
559 bool isBaseVirtual
= BaseInit
->isBaseVirtual();
561 // If the initializer for the base (other than the constructor
562 // itself) accesses 'this' in any way, we need to initialize the
564 if (BaseInitializerUsesThis(CGF
.getContext(), BaseInit
->getInit()))
565 CGF
.InitializeVTablePointers(ClassDecl
);
567 // We can pretend to be a complete class because it only matters for
568 // virtual bases, and we only do virtual bases for complete ctors.
570 CGF
.GetAddressOfDirectBaseInCompleteClass(ThisPtr
, ClassDecl
,
573 AggValueSlot AggSlot
=
574 AggValueSlot::forAddr(
576 AggValueSlot::IsDestructed
,
577 AggValueSlot::DoesNotNeedGCBarriers
,
578 AggValueSlot::IsNotAliased
,
579 CGF
.getOverlapForBaseInit(ClassDecl
, BaseClassDecl
, isBaseVirtual
));
581 CGF
.EmitAggExpr(BaseInit
->getInit(), AggSlot
);
583 if (CGF
.CGM
.getLangOpts().Exceptions
&&
584 !BaseClassDecl
->hasTrivialDestructor())
585 CGF
.EHStack
.pushCleanup
<CallBaseDtor
>(EHCleanup
, BaseClassDecl
,
589 static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl
*D
) {
590 auto *CD
= dyn_cast
<CXXConstructorDecl
>(D
);
591 if (!(CD
&& CD
->isCopyOrMoveConstructor()) &&
592 !D
->isCopyAssignmentOperator() && !D
->isMoveAssignmentOperator())
595 // We can emit a memcpy for a trivial copy or move constructor/assignment.
596 if (D
->isTrivial() && !D
->getParent()->mayInsertExtraPadding())
599 // We *must* emit a memcpy for a defaulted union copy or move op.
600 if (D
->getParent()->isUnion() && D
->isDefaulted())
606 static void EmitLValueForAnyFieldInitialization(CodeGenFunction
&CGF
,
607 CXXCtorInitializer
*MemberInit
,
609 FieldDecl
*Field
= MemberInit
->getAnyMember();
610 if (MemberInit
->isIndirectMemberInitializer()) {
611 // If we are initializing an anonymous union field, drill down to the field.
612 IndirectFieldDecl
*IndirectField
= MemberInit
->getIndirectMember();
613 for (const auto *I
: IndirectField
->chain())
614 LHS
= CGF
.EmitLValueForFieldInitialization(LHS
, cast
<FieldDecl
>(I
));
616 LHS
= CGF
.EmitLValueForFieldInitialization(LHS
, Field
);
620 static void EmitMemberInitializer(CodeGenFunction
&CGF
,
621 const CXXRecordDecl
*ClassDecl
,
622 CXXCtorInitializer
*MemberInit
,
623 const CXXConstructorDecl
*Constructor
,
624 FunctionArgList
&Args
) {
625 ApplyDebugLocation
Loc(CGF
, MemberInit
->getSourceLocation());
626 assert(MemberInit
->isAnyMemberInitializer() &&
627 "Must have member initializer!");
628 assert(MemberInit
->getInit() && "Must have initializer!");
630 // non-static data member initializers.
631 FieldDecl
*Field
= MemberInit
->getAnyMember();
632 QualType FieldType
= Field
->getType();
634 llvm::Value
*ThisPtr
= CGF
.LoadCXXThis();
635 QualType RecordTy
= CGF
.getContext().getTypeDeclType(ClassDecl
);
638 // If a base constructor is being emitted, create an LValue that has the
639 // non-virtual alignment.
640 if (CGF
.CurGD
.getCtorType() == Ctor_Base
)
641 LHS
= CGF
.MakeNaturalAlignPointeeAddrLValue(ThisPtr
, RecordTy
);
643 LHS
= CGF
.MakeNaturalAlignAddrLValue(ThisPtr
, RecordTy
);
645 EmitLValueForAnyFieldInitialization(CGF
, MemberInit
, LHS
);
647 // Special case: if we are in a copy or move constructor, and we are copying
648 // an array of PODs or classes with trivial copy constructors, ignore the
649 // AST and perform the copy we know is equivalent.
650 // FIXME: This is hacky at best... if we had a bit more explicit information
651 // in the AST, we could generalize it more easily.
652 const ConstantArrayType
*Array
653 = CGF
.getContext().getAsConstantArrayType(FieldType
);
654 if (Array
&& Constructor
->isDefaulted() &&
655 Constructor
->isCopyOrMoveConstructor()) {
656 QualType BaseElementTy
= CGF
.getContext().getBaseElementType(Array
);
657 CXXConstructExpr
*CE
= dyn_cast
<CXXConstructExpr
>(MemberInit
->getInit());
658 if (BaseElementTy
.isPODType(CGF
.getContext()) ||
659 (CE
&& isMemcpyEquivalentSpecialMember(CE
->getConstructor()))) {
660 unsigned SrcArgIndex
=
661 CGF
.CGM
.getCXXABI().getSrcArgforCopyCtor(Constructor
, Args
);
663 = CGF
.Builder
.CreateLoad(CGF
.GetAddrOfLocalVar(Args
[SrcArgIndex
]));
664 LValue ThisRHSLV
= CGF
.MakeNaturalAlignAddrLValue(SrcPtr
, RecordTy
);
665 LValue Src
= CGF
.EmitLValueForFieldInitialization(ThisRHSLV
, Field
);
667 // Copy the aggregate.
668 CGF
.EmitAggregateCopy(LHS
, Src
, FieldType
, CGF
.getOverlapForFieldInit(Field
),
669 LHS
.isVolatileQualified());
670 // Ensure that we destroy the objects if an exception is thrown later in
672 QualType::DestructionKind dtorKind
= FieldType
.isDestructedType();
673 if (CGF
.needsEHCleanup(dtorKind
))
674 CGF
.pushEHDestroy(dtorKind
, LHS
.getAddress(CGF
), FieldType
);
679 CGF
.EmitInitializerForField(Field
, LHS
, MemberInit
->getInit());
682 void CodeGenFunction::EmitInitializerForField(FieldDecl
*Field
, LValue LHS
,
684 QualType FieldType
= Field
->getType();
685 switch (getEvaluationKind(FieldType
)) {
687 if (LHS
.isSimple()) {
688 EmitExprAsInit(Init
, Field
, LHS
, false);
690 RValue RHS
= RValue::get(EmitScalarExpr(Init
));
691 EmitStoreThroughLValue(RHS
, LHS
);
695 EmitComplexExprIntoLValue(Init
, LHS
, /*isInit*/ true);
697 case TEK_Aggregate
: {
698 AggValueSlot Slot
= AggValueSlot::forLValue(
699 LHS
, *this, AggValueSlot::IsDestructed
,
700 AggValueSlot::DoesNotNeedGCBarriers
, AggValueSlot::IsNotAliased
,
701 getOverlapForFieldInit(Field
), AggValueSlot::IsNotZeroed
,
702 // Checks are made by the code that calls constructor.
703 AggValueSlot::IsSanitizerChecked
);
704 EmitAggExpr(Init
, Slot
);
709 // Ensure that we destroy this object if an exception is thrown
710 // later in the constructor.
711 QualType::DestructionKind dtorKind
= FieldType
.isDestructedType();
712 if (needsEHCleanup(dtorKind
))
713 pushEHDestroy(dtorKind
, LHS
.getAddress(*this), FieldType
);
716 /// Checks whether the given constructor is a valid subject for the
717 /// complete-to-base constructor delegation optimization, i.e.
718 /// emitting the complete constructor as a simple call to the base
720 bool CodeGenFunction::IsConstructorDelegationValid(
721 const CXXConstructorDecl
*Ctor
) {
723 // Currently we disable the optimization for classes with virtual
724 // bases because (1) the addresses of parameter variables need to be
725 // consistent across all initializers but (2) the delegate function
726 // call necessarily creates a second copy of the parameter variable.
728 // The limiting example (purely theoretical AFAIK):
729 // struct A { A(int &c) { c++; } };
730 // struct B : virtual A {
731 // B(int count) : A(count) { printf("%d\n", count); }
733 // ...although even this example could in principle be emitted as a
734 // delegation since the address of the parameter doesn't escape.
735 if (Ctor
->getParent()->getNumVBases()) {
736 // TODO: white-list trivial vbase initializers. This case wouldn't
737 // be subject to the restrictions below.
739 // TODO: white-list cases where:
740 // - there are no non-reference parameters to the constructor
741 // - the initializers don't access any non-reference parameters
742 // - the initializers don't take the address of non-reference
745 // If we ever add any of the above cases, remember that:
746 // - function-try-blocks will always exclude this optimization
747 // - we need to perform the constructor prologue and cleanup in
748 // EmitConstructorBody.
753 // We also disable the optimization for variadic functions because
754 // it's impossible to "re-pass" varargs.
755 if (Ctor
->getType()->castAs
<FunctionProtoType
>()->isVariadic())
758 // FIXME: Decide if we can do a delegation of a delegating constructor.
759 if (Ctor
->isDelegatingConstructor())
765 // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
766 // to poison the extra field paddings inserted under
767 // -fsanitize-address-field-padding=1|2.
768 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue
) {
769 ASTContext
&Context
= getContext();
770 const CXXRecordDecl
*ClassDecl
=
771 Prologue
? cast
<CXXConstructorDecl
>(CurGD
.getDecl())->getParent()
772 : cast
<CXXDestructorDecl
>(CurGD
.getDecl())->getParent();
773 if (!ClassDecl
->mayInsertExtraPadding()) return;
775 struct SizeAndOffset
{
780 unsigned PtrSize
= CGM
.getDataLayout().getPointerSizeInBits();
781 const ASTRecordLayout
&Info
= Context
.getASTRecordLayout(ClassDecl
);
783 // Populate sizes and offsets of fields.
784 SmallVector
<SizeAndOffset
, 16> SSV(Info
.getFieldCount());
785 for (unsigned i
= 0, e
= Info
.getFieldCount(); i
!= e
; ++i
)
787 Context
.toCharUnitsFromBits(Info
.getFieldOffset(i
)).getQuantity();
789 size_t NumFields
= 0;
790 for (const auto *Field
: ClassDecl
->fields()) {
791 const FieldDecl
*D
= Field
;
792 auto FieldInfo
= Context
.getTypeInfoInChars(D
->getType());
793 CharUnits FieldSize
= FieldInfo
.Width
;
794 assert(NumFields
< SSV
.size());
795 SSV
[NumFields
].Size
= D
->isBitField() ? 0 : FieldSize
.getQuantity();
798 assert(NumFields
== SSV
.size());
799 if (SSV
.size() <= 1) return;
801 // We will insert calls to __asan_* run-time functions.
802 // LLVM AddressSanitizer pass may decide to inline them later.
803 llvm::Type
*Args
[2] = {IntPtrTy
, IntPtrTy
};
804 llvm::FunctionType
*FTy
=
805 llvm::FunctionType::get(CGM
.VoidTy
, Args
, false);
806 llvm::FunctionCallee F
= CGM
.CreateRuntimeFunction(
807 FTy
, Prologue
? "__asan_poison_intra_object_redzone"
808 : "__asan_unpoison_intra_object_redzone");
810 llvm::Value
*ThisPtr
= LoadCXXThis();
811 ThisPtr
= Builder
.CreatePtrToInt(ThisPtr
, IntPtrTy
);
812 uint64_t TypeSize
= Info
.getNonVirtualSize().getQuantity();
813 // For each field check if it has sufficient padding,
814 // if so (un)poison it with a call.
815 for (size_t i
= 0; i
< SSV
.size(); i
++) {
816 uint64_t AsanAlignment
= 8;
817 uint64_t NextField
= i
== SSV
.size() - 1 ? TypeSize
: SSV
[i
+ 1].Offset
;
818 uint64_t PoisonSize
= NextField
- SSV
[i
].Offset
- SSV
[i
].Size
;
819 uint64_t EndOffset
= SSV
[i
].Offset
+ SSV
[i
].Size
;
820 if (PoisonSize
< AsanAlignment
|| !SSV
[i
].Size
||
821 (NextField
% AsanAlignment
) != 0)
824 F
, {Builder
.CreateAdd(ThisPtr
, Builder
.getIntN(PtrSize
, EndOffset
)),
825 Builder
.getIntN(PtrSize
, PoisonSize
)});
829 /// EmitConstructorBody - Emits the body of the current constructor.
830 void CodeGenFunction::EmitConstructorBody(FunctionArgList
&Args
) {
831 EmitAsanPrologueOrEpilogue(true);
832 const CXXConstructorDecl
*Ctor
= cast
<CXXConstructorDecl
>(CurGD
.getDecl());
833 CXXCtorType CtorType
= CurGD
.getCtorType();
835 assert((CGM
.getTarget().getCXXABI().hasConstructorVariants() ||
836 CtorType
== Ctor_Complete
) &&
837 "can only generate complete ctor for this ABI");
839 // Before we go any further, try the complete->base constructor
840 // delegation optimization.
841 if (CtorType
== Ctor_Complete
&& IsConstructorDelegationValid(Ctor
) &&
842 CGM
.getTarget().getCXXABI().hasConstructorVariants()) {
843 EmitDelegateCXXConstructorCall(Ctor
, Ctor_Base
, Args
, Ctor
->getEndLoc());
847 const FunctionDecl
*Definition
= nullptr;
848 Stmt
*Body
= Ctor
->getBody(Definition
);
849 assert(Definition
== Ctor
&& "emitting wrong constructor body");
851 // Enter the function-try-block before the constructor prologue if
853 bool IsTryBody
= (Body
&& isa
<CXXTryStmt
>(Body
));
855 EnterCXXTryStmt(*cast
<CXXTryStmt
>(Body
), true);
857 incrementProfileCounter(Body
);
859 RunCleanupsScope
RunCleanups(*this);
861 // TODO: in restricted cases, we can emit the vbase initializers of
862 // a complete ctor and then delegate to the base ctor.
864 // Emit the constructor prologue, i.e. the base and member
866 EmitCtorPrologue(Ctor
, CtorType
, Args
);
868 // Emit the body of the statement.
870 EmitStmt(cast
<CXXTryStmt
>(Body
)->getTryBlock());
874 // Emit any cleanup blocks associated with the member or base
875 // initializers, which includes (along the exceptional path) the
876 // destructors for those members and bases that were fully
878 RunCleanups
.ForceCleanup();
881 ExitCXXTryStmt(*cast
<CXXTryStmt
>(Body
), true);
885 /// RAII object to indicate that codegen is copying the value representation
886 /// instead of the object representation. Useful when copying a struct or
887 /// class which has uninitialized members and we're only performing
888 /// lvalue-to-rvalue conversion on the object but not its members.
889 class CopyingValueRepresentation
{
891 explicit CopyingValueRepresentation(CodeGenFunction
&CGF
)
892 : CGF(CGF
), OldSanOpts(CGF
.SanOpts
) {
893 CGF
.SanOpts
.set(SanitizerKind::Bool
, false);
894 CGF
.SanOpts
.set(SanitizerKind::Enum
, false);
896 ~CopyingValueRepresentation() {
897 CGF
.SanOpts
= OldSanOpts
;
900 CodeGenFunction
&CGF
;
901 SanitizerSet OldSanOpts
;
903 } // end anonymous namespace
906 class FieldMemcpyizer
{
908 FieldMemcpyizer(CodeGenFunction
&CGF
, const CXXRecordDecl
*ClassDecl
,
909 const VarDecl
*SrcRec
)
910 : CGF(CGF
), ClassDecl(ClassDecl
), SrcRec(SrcRec
),
911 RecLayout(CGF
.getContext().getASTRecordLayout(ClassDecl
)),
912 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
913 LastFieldOffset(0), LastAddedFieldIndex(0) {}
915 bool isMemcpyableField(FieldDecl
*F
) const {
916 // Never memcpy fields when we are adding poisoned paddings.
917 if (CGF
.getContext().getLangOpts().SanitizeAddressFieldPadding
)
919 Qualifiers Qual
= F
->getType().getQualifiers();
920 if (Qual
.hasVolatile() || Qual
.hasObjCLifetime())
925 void addMemcpyableField(FieldDecl
*F
) {
926 if (F
->isZeroSize(CGF
.getContext()))
934 CharUnits
getMemcpySize(uint64_t FirstByteOffset
) const {
935 ASTContext
&Ctx
= CGF
.getContext();
936 unsigned LastFieldSize
=
937 LastField
->isBitField()
938 ? LastField
->getBitWidthValue(Ctx
)
940 Ctx
.getTypeInfoDataSizeInChars(LastField
->getType()).Width
);
941 uint64_t MemcpySizeBits
= LastFieldOffset
+ LastFieldSize
-
942 FirstByteOffset
+ Ctx
.getCharWidth() - 1;
943 CharUnits MemcpySize
= Ctx
.toCharUnitsFromBits(MemcpySizeBits
);
948 // Give the subclass a chance to bail out if it feels the memcpy isn't
949 // worth it (e.g. Hasn't aggregated enough data).
954 uint64_t FirstByteOffset
;
955 if (FirstField
->isBitField()) {
956 const CGRecordLayout
&RL
=
957 CGF
.getTypes().getCGRecordLayout(FirstField
->getParent());
958 const CGBitFieldInfo
&BFInfo
= RL
.getBitFieldInfo(FirstField
);
959 // FirstFieldOffset is not appropriate for bitfields,
960 // we need to use the storage offset instead.
961 FirstByteOffset
= CGF
.getContext().toBits(BFInfo
.StorageOffset
);
963 FirstByteOffset
= FirstFieldOffset
;
966 CharUnits MemcpySize
= getMemcpySize(FirstByteOffset
);
967 QualType RecordTy
= CGF
.getContext().getTypeDeclType(ClassDecl
);
968 Address ThisPtr
= CGF
.LoadCXXThisAddress();
969 LValue DestLV
= CGF
.MakeAddrLValue(ThisPtr
, RecordTy
);
970 LValue Dest
= CGF
.EmitLValueForFieldInitialization(DestLV
, FirstField
);
971 llvm::Value
*SrcPtr
= CGF
.Builder
.CreateLoad(CGF
.GetAddrOfLocalVar(SrcRec
));
972 LValue SrcLV
= CGF
.MakeNaturalAlignAddrLValue(SrcPtr
, RecordTy
);
973 LValue Src
= CGF
.EmitLValueForFieldInitialization(SrcLV
, FirstField
);
976 Dest
.isBitField() ? Dest
.getBitFieldAddress() : Dest
.getAddress(CGF
),
977 Src
.isBitField() ? Src
.getBitFieldAddress() : Src
.getAddress(CGF
),
983 FirstField
= nullptr;
987 CodeGenFunction
&CGF
;
988 const CXXRecordDecl
*ClassDecl
;
991 void emitMemcpyIR(Address DestPtr
, Address SrcPtr
, CharUnits Size
) {
992 DestPtr
= DestPtr
.withElementType(CGF
.Int8Ty
);
993 SrcPtr
= SrcPtr
.withElementType(CGF
.Int8Ty
);
994 CGF
.Builder
.CreateMemCpy(DestPtr
, SrcPtr
, Size
.getQuantity());
997 void addInitialField(FieldDecl
*F
) {
1000 FirstFieldOffset
= RecLayout
.getFieldOffset(F
->getFieldIndex());
1001 LastFieldOffset
= FirstFieldOffset
;
1002 LastAddedFieldIndex
= F
->getFieldIndex();
1005 void addNextField(FieldDecl
*F
) {
1006 // For the most part, the following invariant will hold:
1007 // F->getFieldIndex() == LastAddedFieldIndex + 1
1008 // The one exception is that Sema won't add a copy-initializer for an
1009 // unnamed bitfield, which will show up here as a gap in the sequence.
1010 assert(F
->getFieldIndex() >= LastAddedFieldIndex
+ 1 &&
1011 "Cannot aggregate fields out of order.");
1012 LastAddedFieldIndex
= F
->getFieldIndex();
1014 // The 'first' and 'last' fields are chosen by offset, rather than field
1015 // index. This allows the code to support bitfields, as well as regular
1017 uint64_t FOffset
= RecLayout
.getFieldOffset(F
->getFieldIndex());
1018 if (FOffset
< FirstFieldOffset
) {
1020 FirstFieldOffset
= FOffset
;
1021 } else if (FOffset
>= LastFieldOffset
) {
1023 LastFieldOffset
= FOffset
;
1027 const VarDecl
*SrcRec
;
1028 const ASTRecordLayout
&RecLayout
;
1029 FieldDecl
*FirstField
;
1030 FieldDecl
*LastField
;
1031 uint64_t FirstFieldOffset
, LastFieldOffset
;
1032 unsigned LastAddedFieldIndex
;
1035 class ConstructorMemcpyizer
: public FieldMemcpyizer
{
1037 /// Get source argument for copy constructor. Returns null if not a copy
1039 static const VarDecl
*getTrivialCopySource(CodeGenFunction
&CGF
,
1040 const CXXConstructorDecl
*CD
,
1041 FunctionArgList
&Args
) {
1042 if (CD
->isCopyOrMoveConstructor() && CD
->isDefaulted())
1043 return Args
[CGF
.CGM
.getCXXABI().getSrcArgforCopyCtor(CD
, Args
)];
1047 // Returns true if a CXXCtorInitializer represents a member initialization
1048 // that can be rolled into a memcpy.
1049 bool isMemberInitMemcpyable(CXXCtorInitializer
*MemberInit
) const {
1050 if (!MemcpyableCtor
)
1052 FieldDecl
*Field
= MemberInit
->getMember();
1053 assert(Field
&& "No field for member init.");
1054 QualType FieldType
= Field
->getType();
1055 CXXConstructExpr
*CE
= dyn_cast
<CXXConstructExpr
>(MemberInit
->getInit());
1057 // Bail out on non-memcpyable, not-trivially-copyable members.
1058 if (!(CE
&& isMemcpyEquivalentSpecialMember(CE
->getConstructor())) &&
1059 !(FieldType
.isTriviallyCopyableType(CGF
.getContext()) ||
1060 FieldType
->isReferenceType()))
1063 // Bail out on volatile fields.
1064 if (!isMemcpyableField(Field
))
1067 // Otherwise we're good.
1072 ConstructorMemcpyizer(CodeGenFunction
&CGF
, const CXXConstructorDecl
*CD
,
1073 FunctionArgList
&Args
)
1074 : FieldMemcpyizer(CGF
, CD
->getParent(), getTrivialCopySource(CGF
, CD
, Args
)),
1075 ConstructorDecl(CD
),
1076 MemcpyableCtor(CD
->isDefaulted() &&
1077 CD
->isCopyOrMoveConstructor() &&
1078 CGF
.getLangOpts().getGC() == LangOptions::NonGC
),
1081 void addMemberInitializer(CXXCtorInitializer
*MemberInit
) {
1082 if (isMemberInitMemcpyable(MemberInit
)) {
1083 AggregatedInits
.push_back(MemberInit
);
1084 addMemcpyableField(MemberInit
->getMember());
1086 emitAggregatedInits();
1087 EmitMemberInitializer(CGF
, ConstructorDecl
->getParent(), MemberInit
,
1088 ConstructorDecl
, Args
);
1092 void emitAggregatedInits() {
1093 if (AggregatedInits
.size() <= 1) {
1094 // This memcpy is too small to be worthwhile. Fall back on default
1096 if (!AggregatedInits
.empty()) {
1097 CopyingValueRepresentation
CVR(CGF
);
1098 EmitMemberInitializer(CGF
, ConstructorDecl
->getParent(),
1099 AggregatedInits
[0], ConstructorDecl
, Args
);
1100 AggregatedInits
.clear();
1106 pushEHDestructors();
1108 AggregatedInits
.clear();
1111 void pushEHDestructors() {
1112 Address ThisPtr
= CGF
.LoadCXXThisAddress();
1113 QualType RecordTy
= CGF
.getContext().getTypeDeclType(ClassDecl
);
1114 LValue LHS
= CGF
.MakeAddrLValue(ThisPtr
, RecordTy
);
1116 for (unsigned i
= 0; i
< AggregatedInits
.size(); ++i
) {
1117 CXXCtorInitializer
*MemberInit
= AggregatedInits
[i
];
1118 QualType FieldType
= MemberInit
->getAnyMember()->getType();
1119 QualType::DestructionKind dtorKind
= FieldType
.isDestructedType();
1120 if (!CGF
.needsEHCleanup(dtorKind
))
1122 LValue FieldLHS
= LHS
;
1123 EmitLValueForAnyFieldInitialization(CGF
, MemberInit
, FieldLHS
);
1124 CGF
.pushEHDestroy(dtorKind
, FieldLHS
.getAddress(CGF
), FieldType
);
1129 emitAggregatedInits();
1133 const CXXConstructorDecl
*ConstructorDecl
;
1134 bool MemcpyableCtor
;
1135 FunctionArgList
&Args
;
1136 SmallVector
<CXXCtorInitializer
*, 16> AggregatedInits
;
1139 class AssignmentMemcpyizer
: public FieldMemcpyizer
{
1141 // Returns the memcpyable field copied by the given statement, if one
1142 // exists. Otherwise returns null.
1143 FieldDecl
*getMemcpyableField(Stmt
*S
) {
1144 if (!AssignmentsMemcpyable
)
1146 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(S
)) {
1147 // Recognise trivial assignments.
1148 if (BO
->getOpcode() != BO_Assign
)
1150 MemberExpr
*ME
= dyn_cast
<MemberExpr
>(BO
->getLHS());
1153 FieldDecl
*Field
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl());
1154 if (!Field
|| !isMemcpyableField(Field
))
1156 Stmt
*RHS
= BO
->getRHS();
1157 if (ImplicitCastExpr
*EC
= dyn_cast
<ImplicitCastExpr
>(RHS
))
1158 RHS
= EC
->getSubExpr();
1161 if (MemberExpr
*ME2
= dyn_cast
<MemberExpr
>(RHS
)) {
1162 if (ME2
->getMemberDecl() == Field
)
1166 } else if (CXXMemberCallExpr
*MCE
= dyn_cast
<CXXMemberCallExpr
>(S
)) {
1167 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(MCE
->getCalleeDecl());
1168 if (!(MD
&& isMemcpyEquivalentSpecialMember(MD
)))
1170 MemberExpr
*IOA
= dyn_cast
<MemberExpr
>(MCE
->getImplicitObjectArgument());
1173 FieldDecl
*Field
= dyn_cast
<FieldDecl
>(IOA
->getMemberDecl());
1174 if (!Field
|| !isMemcpyableField(Field
))
1176 MemberExpr
*Arg0
= dyn_cast
<MemberExpr
>(MCE
->getArg(0));
1177 if (!Arg0
|| Field
!= dyn_cast
<FieldDecl
>(Arg0
->getMemberDecl()))
1180 } else if (CallExpr
*CE
= dyn_cast
<CallExpr
>(S
)) {
1181 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(CE
->getCalleeDecl());
1182 if (!FD
|| FD
->getBuiltinID() != Builtin::BI__builtin_memcpy
)
1184 Expr
*DstPtr
= CE
->getArg(0);
1185 if (ImplicitCastExpr
*DC
= dyn_cast
<ImplicitCastExpr
>(DstPtr
))
1186 DstPtr
= DC
->getSubExpr();
1187 UnaryOperator
*DUO
= dyn_cast
<UnaryOperator
>(DstPtr
);
1188 if (!DUO
|| DUO
->getOpcode() != UO_AddrOf
)
1190 MemberExpr
*ME
= dyn_cast
<MemberExpr
>(DUO
->getSubExpr());
1193 FieldDecl
*Field
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl());
1194 if (!Field
|| !isMemcpyableField(Field
))
1196 Expr
*SrcPtr
= CE
->getArg(1);
1197 if (ImplicitCastExpr
*SC
= dyn_cast
<ImplicitCastExpr
>(SrcPtr
))
1198 SrcPtr
= SC
->getSubExpr();
1199 UnaryOperator
*SUO
= dyn_cast
<UnaryOperator
>(SrcPtr
);
1200 if (!SUO
|| SUO
->getOpcode() != UO_AddrOf
)
1202 MemberExpr
*ME2
= dyn_cast
<MemberExpr
>(SUO
->getSubExpr());
1203 if (!ME2
|| Field
!= dyn_cast
<FieldDecl
>(ME2
->getMemberDecl()))
1211 bool AssignmentsMemcpyable
;
1212 SmallVector
<Stmt
*, 16> AggregatedStmts
;
1215 AssignmentMemcpyizer(CodeGenFunction
&CGF
, const CXXMethodDecl
*AD
,
1216 FunctionArgList
&Args
)
1217 : FieldMemcpyizer(CGF
, AD
->getParent(), Args
[Args
.size() - 1]),
1218 AssignmentsMemcpyable(CGF
.getLangOpts().getGC() == LangOptions::NonGC
) {
1219 assert(Args
.size() == 2);
1222 void emitAssignment(Stmt
*S
) {
1223 FieldDecl
*F
= getMemcpyableField(S
);
1225 addMemcpyableField(F
);
1226 AggregatedStmts
.push_back(S
);
1228 emitAggregatedStmts();
1233 void emitAggregatedStmts() {
1234 if (AggregatedStmts
.size() <= 1) {
1235 if (!AggregatedStmts
.empty()) {
1236 CopyingValueRepresentation
CVR(CGF
);
1237 CGF
.EmitStmt(AggregatedStmts
[0]);
1243 AggregatedStmts
.clear();
1247 emitAggregatedStmts();
1250 } // end anonymous namespace
1252 static bool isInitializerOfDynamicClass(const CXXCtorInitializer
*BaseInit
) {
1253 const Type
*BaseType
= BaseInit
->getBaseClass();
1254 const auto *BaseClassDecl
=
1255 cast
<CXXRecordDecl
>(BaseType
->castAs
<RecordType
>()->getDecl());
1256 return BaseClassDecl
->isDynamicClass();
1259 /// EmitCtorPrologue - This routine generates necessary code to initialize
1260 /// base classes and non-static data members belonging to this constructor.
1261 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl
*CD
,
1262 CXXCtorType CtorType
,
1263 FunctionArgList
&Args
) {
1264 if (CD
->isDelegatingConstructor())
1265 return EmitDelegatingCXXConstructorCall(CD
, Args
);
1267 const CXXRecordDecl
*ClassDecl
= CD
->getParent();
1269 CXXConstructorDecl::init_const_iterator B
= CD
->init_begin(),
1272 // Virtual base initializers first, if any. They aren't needed if:
1273 // - This is a base ctor variant
1274 // - There are no vbases
1275 // - The class is abstract, so a complete object of it cannot be constructed
1277 // The check for an abstract class is necessary because sema may not have
1278 // marked virtual base destructors referenced.
1279 bool ConstructVBases
= CtorType
!= Ctor_Base
&&
1280 ClassDecl
->getNumVBases() != 0 &&
1281 !ClassDecl
->isAbstract();
1283 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1284 // constructor of a class with virtual bases takes an additional parameter to
1285 // conditionally construct the virtual bases. Emit that check here.
1286 llvm::BasicBlock
*BaseCtorContinueBB
= nullptr;
1287 if (ConstructVBases
&&
1288 !CGM
.getTarget().getCXXABI().hasConstructorVariants()) {
1289 BaseCtorContinueBB
=
1290 CGM
.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl
);
1291 assert(BaseCtorContinueBB
);
1294 llvm::Value
*const OldThis
= CXXThisValue
;
1295 for (; B
!= E
&& (*B
)->isBaseInitializer() && (*B
)->isBaseVirtual(); B
++) {
1296 if (!ConstructVBases
)
1298 if (CGM
.getCodeGenOpts().StrictVTablePointers
&&
1299 CGM
.getCodeGenOpts().OptimizationLevel
> 0 &&
1300 isInitializerOfDynamicClass(*B
))
1301 CXXThisValue
= Builder
.CreateLaunderInvariantGroup(LoadCXXThis());
1302 EmitBaseInitializer(*this, ClassDecl
, *B
);
1305 if (BaseCtorContinueBB
) {
1306 // Complete object handler should continue to the remaining initializers.
1307 Builder
.CreateBr(BaseCtorContinueBB
);
1308 EmitBlock(BaseCtorContinueBB
);
1311 // Then, non-virtual base initializers.
1312 for (; B
!= E
&& (*B
)->isBaseInitializer(); B
++) {
1313 assert(!(*B
)->isBaseVirtual());
1315 if (CGM
.getCodeGenOpts().StrictVTablePointers
&&
1316 CGM
.getCodeGenOpts().OptimizationLevel
> 0 &&
1317 isInitializerOfDynamicClass(*B
))
1318 CXXThisValue
= Builder
.CreateLaunderInvariantGroup(LoadCXXThis());
1319 EmitBaseInitializer(*this, ClassDecl
, *B
);
1322 CXXThisValue
= OldThis
;
1324 InitializeVTablePointers(ClassDecl
);
1326 // And finally, initialize class members.
1327 FieldConstructionScope
FCS(*this, LoadCXXThisAddress());
1328 ConstructorMemcpyizer
CM(*this, CD
, Args
);
1329 for (; B
!= E
; B
++) {
1330 CXXCtorInitializer
*Member
= (*B
);
1331 assert(!Member
->isBaseInitializer());
1332 assert(Member
->isAnyMemberInitializer() &&
1333 "Delegating initializer on non-delegating constructor");
1334 CM
.addMemberInitializer(Member
);
1340 FieldHasTrivialDestructorBody(ASTContext
&Context
, const FieldDecl
*Field
);
1343 HasTrivialDestructorBody(ASTContext
&Context
,
1344 const CXXRecordDecl
*BaseClassDecl
,
1345 const CXXRecordDecl
*MostDerivedClassDecl
)
1347 // If the destructor is trivial we don't have to check anything else.
1348 if (BaseClassDecl
->hasTrivialDestructor())
1351 if (!BaseClassDecl
->getDestructor()->hasTrivialBody())
1355 for (const auto *Field
: BaseClassDecl
->fields())
1356 if (!FieldHasTrivialDestructorBody(Context
, Field
))
1359 // Check non-virtual bases.
1360 for (const auto &I
: BaseClassDecl
->bases()) {
1364 const CXXRecordDecl
*NonVirtualBase
=
1365 cast
<CXXRecordDecl
>(I
.getType()->castAs
<RecordType
>()->getDecl());
1366 if (!HasTrivialDestructorBody(Context
, NonVirtualBase
,
1367 MostDerivedClassDecl
))
1371 if (BaseClassDecl
== MostDerivedClassDecl
) {
1372 // Check virtual bases.
1373 for (const auto &I
: BaseClassDecl
->vbases()) {
1374 const CXXRecordDecl
*VirtualBase
=
1375 cast
<CXXRecordDecl
>(I
.getType()->castAs
<RecordType
>()->getDecl());
1376 if (!HasTrivialDestructorBody(Context
, VirtualBase
,
1377 MostDerivedClassDecl
))
1386 FieldHasTrivialDestructorBody(ASTContext
&Context
,
1387 const FieldDecl
*Field
)
1389 QualType FieldBaseElementType
= Context
.getBaseElementType(Field
->getType());
1391 const RecordType
*RT
= FieldBaseElementType
->getAs
<RecordType
>();
1395 CXXRecordDecl
*FieldClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
1397 // The destructor for an implicit anonymous union member is never invoked.
1398 if (FieldClassDecl
->isUnion() && FieldClassDecl
->isAnonymousStructOrUnion())
1401 return HasTrivialDestructorBody(Context
, FieldClassDecl
, FieldClassDecl
);
1404 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1405 /// any vtable pointers before calling this destructor.
1406 static bool CanSkipVTablePointerInitialization(CodeGenFunction
&CGF
,
1407 const CXXDestructorDecl
*Dtor
) {
1408 const CXXRecordDecl
*ClassDecl
= Dtor
->getParent();
1409 if (!ClassDecl
->isDynamicClass())
1412 // For a final class, the vtable pointer is known to already point to the
1414 if (ClassDecl
->isEffectivelyFinal())
1417 if (!Dtor
->hasTrivialBody())
1420 // Check the fields.
1421 for (const auto *Field
: ClassDecl
->fields())
1422 if (!FieldHasTrivialDestructorBody(CGF
.getContext(), Field
))
1428 /// EmitDestructorBody - Emits the body of the current destructor.
1429 void CodeGenFunction::EmitDestructorBody(FunctionArgList
&Args
) {
1430 const CXXDestructorDecl
*Dtor
= cast
<CXXDestructorDecl
>(CurGD
.getDecl());
1431 CXXDtorType DtorType
= CurGD
.getDtorType();
1433 // For an abstract class, non-base destructors are never used (and can't
1434 // be emitted in general, because vbase dtors may not have been validated
1435 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1436 // in fact emit references to them from other compilations, so emit them
1437 // as functions containing a trap instruction.
1438 if (DtorType
!= Dtor_Base
&& Dtor
->getParent()->isAbstract()) {
1439 llvm::CallInst
*TrapCall
= EmitTrapCall(llvm::Intrinsic::trap
);
1440 TrapCall
->setDoesNotReturn();
1441 TrapCall
->setDoesNotThrow();
1442 Builder
.CreateUnreachable();
1443 Builder
.ClearInsertionPoint();
1447 Stmt
*Body
= Dtor
->getBody();
1449 incrementProfileCounter(Body
);
1451 // The call to operator delete in a deleting destructor happens
1452 // outside of the function-try-block, which means it's always
1453 // possible to delegate the destructor body to the complete
1454 // destructor. Do so.
1455 if (DtorType
== Dtor_Deleting
) {
1456 RunCleanupsScope
DtorEpilogue(*this);
1457 EnterDtorCleanups(Dtor
, Dtor_Deleting
);
1458 if (HaveInsertPoint()) {
1459 QualType ThisTy
= Dtor
->getThisObjectType();
1460 EmitCXXDestructorCall(Dtor
, Dtor_Complete
, /*ForVirtualBase=*/false,
1461 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy
);
1466 // If the body is a function-try-block, enter the try before
1468 bool isTryBody
= (Body
&& isa
<CXXTryStmt
>(Body
));
1470 EnterCXXTryStmt(*cast
<CXXTryStmt
>(Body
), true);
1471 EmitAsanPrologueOrEpilogue(false);
1473 // Enter the epilogue cleanups.
1474 RunCleanupsScope
DtorEpilogue(*this);
1476 // If this is the complete variant, just invoke the base variant;
1477 // the epilogue will destruct the virtual bases. But we can't do
1478 // this optimization if the body is a function-try-block, because
1479 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1480 // always delegate because we might not have a definition in this TU.
1482 case Dtor_Comdat
: llvm_unreachable("not expecting a COMDAT");
1483 case Dtor_Deleting
: llvm_unreachable("already handled deleting case");
1486 assert((Body
|| getTarget().getCXXABI().isMicrosoft()) &&
1487 "can't emit a dtor without a body for non-Microsoft ABIs");
1489 // Enter the cleanup scopes for virtual bases.
1490 EnterDtorCleanups(Dtor
, Dtor_Complete
);
1493 QualType ThisTy
= Dtor
->getThisObjectType();
1494 EmitCXXDestructorCall(Dtor
, Dtor_Base
, /*ForVirtualBase=*/false,
1495 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy
);
1499 // Fallthrough: act like we're in the base variant.
1505 // Enter the cleanup scopes for fields and non-virtual bases.
1506 EnterDtorCleanups(Dtor
, Dtor_Base
);
1508 // Initialize the vtable pointers before entering the body.
1509 if (!CanSkipVTablePointerInitialization(*this, Dtor
)) {
1510 // Insert the llvm.launder.invariant.group intrinsic before initializing
1511 // the vptrs to cancel any previous assumptions we might have made.
1512 if (CGM
.getCodeGenOpts().StrictVTablePointers
&&
1513 CGM
.getCodeGenOpts().OptimizationLevel
> 0)
1514 CXXThisValue
= Builder
.CreateLaunderInvariantGroup(LoadCXXThis());
1515 InitializeVTablePointers(Dtor
->getParent());
1519 EmitStmt(cast
<CXXTryStmt
>(Body
)->getTryBlock());
1523 assert(Dtor
->isImplicit() && "bodyless dtor not implicit");
1524 // nothing to do besides what's in the epilogue
1526 // -fapple-kext must inline any call to this dtor into
1527 // the caller's body.
1528 if (getLangOpts().AppleKext
)
1529 CurFn
->addFnAttr(llvm::Attribute::AlwaysInline
);
1534 // Jump out through the epilogue cleanups.
1535 DtorEpilogue
.ForceCleanup();
1537 // Exit the try if applicable.
1539 ExitCXXTryStmt(*cast
<CXXTryStmt
>(Body
), true);
1542 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList
&Args
) {
1543 const CXXMethodDecl
*AssignOp
= cast
<CXXMethodDecl
>(CurGD
.getDecl());
1544 const Stmt
*RootS
= AssignOp
->getBody();
1545 assert(isa
<CompoundStmt
>(RootS
) &&
1546 "Body of an implicit assignment operator should be compound stmt.");
1547 const CompoundStmt
*RootCS
= cast
<CompoundStmt
>(RootS
);
1549 LexicalScope
Scope(*this, RootCS
->getSourceRange());
1551 incrementProfileCounter(RootCS
);
1552 AssignmentMemcpyizer
AM(*this, AssignOp
, Args
);
1553 for (auto *I
: RootCS
->body())
1554 AM
.emitAssignment(I
);
1559 llvm::Value
*LoadThisForDtorDelete(CodeGenFunction
&CGF
,
1560 const CXXDestructorDecl
*DD
) {
1561 if (Expr
*ThisArg
= DD
->getOperatorDeleteThisArg())
1562 return CGF
.EmitScalarExpr(ThisArg
);
1563 return CGF
.LoadCXXThis();
1566 /// Call the operator delete associated with the current destructor.
1567 struct CallDtorDelete final
: EHScopeStack::Cleanup
{
1570 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1571 const CXXDestructorDecl
*Dtor
= cast
<CXXDestructorDecl
>(CGF
.CurCodeDecl
);
1572 const CXXRecordDecl
*ClassDecl
= Dtor
->getParent();
1573 CGF
.EmitDeleteCall(Dtor
->getOperatorDelete(),
1574 LoadThisForDtorDelete(CGF
, Dtor
),
1575 CGF
.getContext().getTagDeclType(ClassDecl
));
1579 void EmitConditionalDtorDeleteCall(CodeGenFunction
&CGF
,
1580 llvm::Value
*ShouldDeleteCondition
,
1581 bool ReturnAfterDelete
) {
1582 llvm::BasicBlock
*callDeleteBB
= CGF
.createBasicBlock("dtor.call_delete");
1583 llvm::BasicBlock
*continueBB
= CGF
.createBasicBlock("dtor.continue");
1584 llvm::Value
*ShouldCallDelete
1585 = CGF
.Builder
.CreateIsNull(ShouldDeleteCondition
);
1586 CGF
.Builder
.CreateCondBr(ShouldCallDelete
, continueBB
, callDeleteBB
);
1588 CGF
.EmitBlock(callDeleteBB
);
1589 const CXXDestructorDecl
*Dtor
= cast
<CXXDestructorDecl
>(CGF
.CurCodeDecl
);
1590 const CXXRecordDecl
*ClassDecl
= Dtor
->getParent();
1591 CGF
.EmitDeleteCall(Dtor
->getOperatorDelete(),
1592 LoadThisForDtorDelete(CGF
, Dtor
),
1593 CGF
.getContext().getTagDeclType(ClassDecl
));
1594 assert(Dtor
->getOperatorDelete()->isDestroyingOperatorDelete() ==
1595 ReturnAfterDelete
&&
1596 "unexpected value for ReturnAfterDelete");
1597 if (ReturnAfterDelete
)
1598 CGF
.EmitBranchThroughCleanup(CGF
.ReturnBlock
);
1600 CGF
.Builder
.CreateBr(continueBB
);
1602 CGF
.EmitBlock(continueBB
);
1605 struct CallDtorDeleteConditional final
: EHScopeStack::Cleanup
{
1606 llvm::Value
*ShouldDeleteCondition
;
1609 CallDtorDeleteConditional(llvm::Value
*ShouldDeleteCondition
)
1610 : ShouldDeleteCondition(ShouldDeleteCondition
) {
1611 assert(ShouldDeleteCondition
!= nullptr);
1614 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1615 EmitConditionalDtorDeleteCall(CGF
, ShouldDeleteCondition
,
1616 /*ReturnAfterDelete*/false);
1620 class DestroyField final
: public EHScopeStack::Cleanup
{
1621 const FieldDecl
*field
;
1622 CodeGenFunction::Destroyer
*destroyer
;
1623 bool useEHCleanupForArray
;
1626 DestroyField(const FieldDecl
*field
, CodeGenFunction::Destroyer
*destroyer
,
1627 bool useEHCleanupForArray
)
1628 : field(field
), destroyer(destroyer
),
1629 useEHCleanupForArray(useEHCleanupForArray
) {}
1631 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1632 // Find the address of the field.
1633 Address thisValue
= CGF
.LoadCXXThisAddress();
1634 QualType RecordTy
= CGF
.getContext().getTagDeclType(field
->getParent());
1635 LValue ThisLV
= CGF
.MakeAddrLValue(thisValue
, RecordTy
);
1636 LValue LV
= CGF
.EmitLValueForField(ThisLV
, field
);
1637 assert(LV
.isSimple());
1639 CGF
.emitDestroy(LV
.getAddress(CGF
), field
->getType(), destroyer
,
1640 flags
.isForNormalCleanup() && useEHCleanupForArray
);
1644 class DeclAsInlineDebugLocation
{
1646 llvm::MDNode
*InlinedAt
;
1647 std::optional
<ApplyDebugLocation
> Location
;
1650 DeclAsInlineDebugLocation(CodeGenFunction
&CGF
, const NamedDecl
&Decl
)
1651 : DI(CGF
.getDebugInfo()) {
1654 InlinedAt
= DI
->getInlinedAt();
1655 DI
->setInlinedAt(CGF
.Builder
.getCurrentDebugLocation());
1656 Location
.emplace(CGF
, Decl
.getLocation());
1659 ~DeclAsInlineDebugLocation() {
1663 DI
->setInlinedAt(InlinedAt
);
1667 static void EmitSanitizerDtorCallback(
1668 CodeGenFunction
&CGF
, StringRef Name
, llvm::Value
*Ptr
,
1669 std::optional
<CharUnits::QuantityType
> PoisonSize
= {}) {
1670 CodeGenFunction::SanitizerScope
SanScope(&CGF
);
1671 // Pass in void pointer and size of region as arguments to runtime
1673 SmallVector
<llvm::Value
*, 2> Args
= {Ptr
};
1674 SmallVector
<llvm::Type
*, 2> ArgTypes
= {CGF
.VoidPtrTy
};
1676 if (PoisonSize
.has_value()) {
1677 Args
.emplace_back(llvm::ConstantInt::get(CGF
.SizeTy
, *PoisonSize
));
1678 ArgTypes
.emplace_back(CGF
.SizeTy
);
1681 llvm::FunctionType
*FnType
=
1682 llvm::FunctionType::get(CGF
.VoidTy
, ArgTypes
, false);
1683 llvm::FunctionCallee Fn
= CGF
.CGM
.CreateRuntimeFunction(FnType
, Name
);
1685 CGF
.EmitNounwindRuntimeCall(Fn
, Args
);
1689 EmitSanitizerDtorFieldsCallback(CodeGenFunction
&CGF
, llvm::Value
*Ptr
,
1690 CharUnits::QuantityType PoisonSize
) {
1691 EmitSanitizerDtorCallback(CGF
, "__sanitizer_dtor_callback_fields", Ptr
,
1695 /// Poison base class with a trivial destructor.
1696 struct SanitizeDtorTrivialBase final
: EHScopeStack::Cleanup
{
1697 const CXXRecordDecl
*BaseClass
;
1699 SanitizeDtorTrivialBase(const CXXRecordDecl
*Base
, bool BaseIsVirtual
)
1700 : BaseClass(Base
), BaseIsVirtual(BaseIsVirtual
) {}
1702 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1703 const CXXRecordDecl
*DerivedClass
=
1704 cast
<CXXMethodDecl
>(CGF
.CurCodeDecl
)->getParent();
1706 Address Addr
= CGF
.GetAddressOfDirectBaseInCompleteClass(
1707 CGF
.LoadCXXThisAddress(), DerivedClass
, BaseClass
, BaseIsVirtual
);
1709 const ASTRecordLayout
&BaseLayout
=
1710 CGF
.getContext().getASTRecordLayout(BaseClass
);
1711 CharUnits BaseSize
= BaseLayout
.getSize();
1713 if (!BaseSize
.isPositive())
1716 // Use the base class declaration location as inline DebugLocation. All
1717 // fields of the class are destroyed.
1718 DeclAsInlineDebugLocation
InlineHere(CGF
, *BaseClass
);
1719 EmitSanitizerDtorFieldsCallback(CGF
, Addr
.getPointer(),
1720 BaseSize
.getQuantity());
1722 // Prevent the current stack frame from disappearing from the stack trace.
1723 CGF
.CurFn
->addFnAttr("disable-tail-calls", "true");
1727 class SanitizeDtorFieldRange final
: public EHScopeStack::Cleanup
{
1728 const CXXDestructorDecl
*Dtor
;
1729 unsigned StartIndex
;
1733 SanitizeDtorFieldRange(const CXXDestructorDecl
*Dtor
, unsigned StartIndex
,
1735 : Dtor(Dtor
), StartIndex(StartIndex
), EndIndex(EndIndex
) {}
1737 // Generate function call for handling object poisoning.
1738 // Disables tail call elimination, to prevent the current stack frame
1739 // from disappearing from the stack trace.
1740 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1741 const ASTContext
&Context
= CGF
.getContext();
1742 const ASTRecordLayout
&Layout
=
1743 Context
.getASTRecordLayout(Dtor
->getParent());
1745 // It's a first trivial field so it should be at the begining of a char,
1746 // still round up start offset just in case.
1747 CharUnits PoisonStart
= Context
.toCharUnitsFromBits(
1748 Layout
.getFieldOffset(StartIndex
) + Context
.getCharWidth() - 1);
1749 llvm::ConstantInt
*OffsetSizePtr
=
1750 llvm::ConstantInt::get(CGF
.SizeTy
, PoisonStart
.getQuantity());
1752 llvm::Value
*OffsetPtr
=
1753 CGF
.Builder
.CreateGEP(CGF
.Int8Ty
, CGF
.LoadCXXThis(), OffsetSizePtr
);
1755 CharUnits PoisonEnd
;
1756 if (EndIndex
>= Layout
.getFieldCount()) {
1757 PoisonEnd
= Layout
.getNonVirtualSize();
1760 Context
.toCharUnitsFromBits(Layout
.getFieldOffset(EndIndex
));
1762 CharUnits PoisonSize
= PoisonEnd
- PoisonStart
;
1763 if (!PoisonSize
.isPositive())
1766 // Use the top field declaration location as inline DebugLocation.
1767 DeclAsInlineDebugLocation
InlineHere(
1768 CGF
, **std::next(Dtor
->getParent()->field_begin(), StartIndex
));
1769 EmitSanitizerDtorFieldsCallback(CGF
, OffsetPtr
, PoisonSize
.getQuantity());
1771 // Prevent the current stack frame from disappearing from the stack trace.
1772 CGF
.CurFn
->addFnAttr("disable-tail-calls", "true");
1776 class SanitizeDtorVTable final
: public EHScopeStack::Cleanup
{
1777 const CXXDestructorDecl
*Dtor
;
1780 SanitizeDtorVTable(const CXXDestructorDecl
*Dtor
) : Dtor(Dtor
) {}
1782 // Generate function call for handling vtable pointer poisoning.
1783 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1784 assert(Dtor
->getParent()->isDynamicClass());
1786 // Poison vtable and vtable ptr if they exist for this class.
1787 llvm::Value
*VTablePtr
= CGF
.LoadCXXThis();
1789 // Pass in void pointer and size of region as arguments to runtime
1791 EmitSanitizerDtorCallback(CGF
, "__sanitizer_dtor_callback_vptr",
1796 class SanitizeDtorCleanupBuilder
{
1797 ASTContext
&Context
;
1798 EHScopeStack
&EHStack
;
1799 const CXXDestructorDecl
*DD
;
1800 std::optional
<unsigned> StartIndex
;
1803 SanitizeDtorCleanupBuilder(ASTContext
&Context
, EHScopeStack
&EHStack
,
1804 const CXXDestructorDecl
*DD
)
1805 : Context(Context
), EHStack(EHStack
), DD(DD
), StartIndex(std::nullopt
) {}
1806 void PushCleanupForField(const FieldDecl
*Field
) {
1807 if (Field
->isZeroSize(Context
))
1809 unsigned FieldIndex
= Field
->getFieldIndex();
1810 if (FieldHasTrivialDestructorBody(Context
, Field
)) {
1812 StartIndex
= FieldIndex
;
1813 } else if (StartIndex
) {
1814 EHStack
.pushCleanup
<SanitizeDtorFieldRange
>(NormalAndEHCleanup
, DD
,
1815 *StartIndex
, FieldIndex
);
1816 StartIndex
= std::nullopt
;
1821 EHStack
.pushCleanup
<SanitizeDtorFieldRange
>(NormalAndEHCleanup
, DD
,
1825 } // end anonymous namespace
1827 /// Emit all code that comes at the end of class's
1828 /// destructor. This is to call destructors on members and base classes
1829 /// in reverse order of their construction.
1831 /// For a deleting destructor, this also handles the case where a destroying
1832 /// operator delete completely overrides the definition.
1833 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl
*DD
,
1834 CXXDtorType DtorType
) {
1835 assert((!DD
->isTrivial() || DD
->hasAttr
<DLLExportAttr
>()) &&
1836 "Should not emit dtor epilogue for non-exported trivial dtor!");
1838 // The deleting-destructor phase just needs to call the appropriate
1839 // operator delete that Sema picked up.
1840 if (DtorType
== Dtor_Deleting
) {
1841 assert(DD
->getOperatorDelete() &&
1842 "operator delete missing - EnterDtorCleanups");
1843 if (CXXStructorImplicitParamValue
) {
1844 // If there is an implicit param to the deleting dtor, it's a boolean
1845 // telling whether this is a deleting destructor.
1846 if (DD
->getOperatorDelete()->isDestroyingOperatorDelete())
1847 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue
,
1848 /*ReturnAfterDelete*/true);
1850 EHStack
.pushCleanup
<CallDtorDeleteConditional
>(
1851 NormalAndEHCleanup
, CXXStructorImplicitParamValue
);
1853 if (DD
->getOperatorDelete()->isDestroyingOperatorDelete()) {
1854 const CXXRecordDecl
*ClassDecl
= DD
->getParent();
1855 EmitDeleteCall(DD
->getOperatorDelete(),
1856 LoadThisForDtorDelete(*this, DD
),
1857 getContext().getTagDeclType(ClassDecl
));
1858 EmitBranchThroughCleanup(ReturnBlock
);
1860 EHStack
.pushCleanup
<CallDtorDelete
>(NormalAndEHCleanup
);
1866 const CXXRecordDecl
*ClassDecl
= DD
->getParent();
1868 // Unions have no bases and do not call field destructors.
1869 if (ClassDecl
->isUnion())
1872 // The complete-destructor phase just destructs all the virtual bases.
1873 if (DtorType
== Dtor_Complete
) {
1874 // Poison the vtable pointer such that access after the base
1875 // and member destructors are invoked is invalid.
1876 if (CGM
.getCodeGenOpts().SanitizeMemoryUseAfterDtor
&&
1877 SanOpts
.has(SanitizerKind::Memory
) && ClassDecl
->getNumVBases() &&
1878 ClassDecl
->isPolymorphic())
1879 EHStack
.pushCleanup
<SanitizeDtorVTable
>(NormalAndEHCleanup
, DD
);
1881 // We push them in the forward order so that they'll be popped in
1882 // the reverse order.
1883 for (const auto &Base
: ClassDecl
->vbases()) {
1884 auto *BaseClassDecl
=
1885 cast
<CXXRecordDecl
>(Base
.getType()->castAs
<RecordType
>()->getDecl());
1887 if (BaseClassDecl
->hasTrivialDestructor()) {
1888 // Under SanitizeMemoryUseAfterDtor, poison the trivial base class
1889 // memory. For non-trival base classes the same is done in the class
1891 if (CGM
.getCodeGenOpts().SanitizeMemoryUseAfterDtor
&&
1892 SanOpts
.has(SanitizerKind::Memory
) && !BaseClassDecl
->isEmpty())
1893 EHStack
.pushCleanup
<SanitizeDtorTrivialBase
>(NormalAndEHCleanup
,
1895 /*BaseIsVirtual*/ true);
1897 EHStack
.pushCleanup
<CallBaseDtor
>(NormalAndEHCleanup
, BaseClassDecl
,
1898 /*BaseIsVirtual*/ true);
1905 assert(DtorType
== Dtor_Base
);
1906 // Poison the vtable pointer if it has no virtual bases, but inherits
1907 // virtual functions.
1908 if (CGM
.getCodeGenOpts().SanitizeMemoryUseAfterDtor
&&
1909 SanOpts
.has(SanitizerKind::Memory
) && !ClassDecl
->getNumVBases() &&
1910 ClassDecl
->isPolymorphic())
1911 EHStack
.pushCleanup
<SanitizeDtorVTable
>(NormalAndEHCleanup
, DD
);
1913 // Destroy non-virtual bases.
1914 for (const auto &Base
: ClassDecl
->bases()) {
1915 // Ignore virtual bases.
1916 if (Base
.isVirtual())
1919 CXXRecordDecl
*BaseClassDecl
= Base
.getType()->getAsCXXRecordDecl();
1921 if (BaseClassDecl
->hasTrivialDestructor()) {
1922 if (CGM
.getCodeGenOpts().SanitizeMemoryUseAfterDtor
&&
1923 SanOpts
.has(SanitizerKind::Memory
) && !BaseClassDecl
->isEmpty())
1924 EHStack
.pushCleanup
<SanitizeDtorTrivialBase
>(NormalAndEHCleanup
,
1926 /*BaseIsVirtual*/ false);
1928 EHStack
.pushCleanup
<CallBaseDtor
>(NormalAndEHCleanup
, BaseClassDecl
,
1929 /*BaseIsVirtual*/ false);
1933 // Poison fields such that access after their destructors are
1934 // invoked, and before the base class destructor runs, is invalid.
1935 bool SanitizeFields
= CGM
.getCodeGenOpts().SanitizeMemoryUseAfterDtor
&&
1936 SanOpts
.has(SanitizerKind::Memory
);
1937 SanitizeDtorCleanupBuilder
SanitizeBuilder(getContext(), EHStack
, DD
);
1939 // Destroy direct fields.
1940 for (const auto *Field
: ClassDecl
->fields()) {
1942 SanitizeBuilder
.PushCleanupForField(Field
);
1944 QualType type
= Field
->getType();
1945 QualType::DestructionKind dtorKind
= type
.isDestructedType();
1949 // Anonymous union members do not have their destructors called.
1950 const RecordType
*RT
= type
->getAsUnionType();
1951 if (RT
&& RT
->getDecl()->isAnonymousStructOrUnion())
1954 CleanupKind cleanupKind
= getCleanupKind(dtorKind
);
1955 EHStack
.pushCleanup
<DestroyField
>(
1956 cleanupKind
, Field
, getDestroyer(dtorKind
), cleanupKind
& EHCleanup
);
1960 SanitizeBuilder
.End();
1963 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1964 /// constructor for each of several members of an array.
1966 /// \param ctor the constructor to call for each element
1967 /// \param arrayType the type of the array to initialize
1968 /// \param arrayBegin an arrayType*
1969 /// \param zeroInitialize true if each element should be
1970 /// zero-initialized before it is constructed
1971 void CodeGenFunction::EmitCXXAggrConstructorCall(
1972 const CXXConstructorDecl
*ctor
, const ArrayType
*arrayType
,
1973 Address arrayBegin
, const CXXConstructExpr
*E
, bool NewPointerIsChecked
,
1974 bool zeroInitialize
) {
1975 QualType elementType
;
1976 llvm::Value
*numElements
=
1977 emitArrayLength(arrayType
, elementType
, arrayBegin
);
1979 EmitCXXAggrConstructorCall(ctor
, numElements
, arrayBegin
, E
,
1980 NewPointerIsChecked
, zeroInitialize
);
1983 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1984 /// constructor for each of several members of an array.
1986 /// \param ctor the constructor to call for each element
1987 /// \param numElements the number of elements in the array;
1989 /// \param arrayBase a T*, where T is the type constructed by ctor
1990 /// \param zeroInitialize true if each element should be
1991 /// zero-initialized before it is constructed
1992 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl
*ctor
,
1993 llvm::Value
*numElements
,
1995 const CXXConstructExpr
*E
,
1996 bool NewPointerIsChecked
,
1997 bool zeroInitialize
) {
1998 // It's legal for numElements to be zero. This can happen both
1999 // dynamically, because x can be zero in 'new A[x]', and statically,
2000 // because of GCC extensions that permit zero-length arrays. There
2001 // are probably legitimate places where we could assume that this
2002 // doesn't happen, but it's not clear that it's worth it.
2003 llvm::BranchInst
*zeroCheckBranch
= nullptr;
2005 // Optimize for a constant count.
2006 llvm::ConstantInt
*constantCount
2007 = dyn_cast
<llvm::ConstantInt
>(numElements
);
2008 if (constantCount
) {
2009 // Just skip out if the constant count is zero.
2010 if (constantCount
->isZero()) return;
2012 // Otherwise, emit the check.
2014 llvm::BasicBlock
*loopBB
= createBasicBlock("new.ctorloop");
2015 llvm::Value
*iszero
= Builder
.CreateIsNull(numElements
, "isempty");
2016 zeroCheckBranch
= Builder
.CreateCondBr(iszero
, loopBB
, loopBB
);
2020 // Find the end of the array.
2021 llvm::Type
*elementType
= arrayBase
.getElementType();
2022 llvm::Value
*arrayBegin
= arrayBase
.getPointer();
2023 llvm::Value
*arrayEnd
= Builder
.CreateInBoundsGEP(
2024 elementType
, arrayBegin
, numElements
, "arrayctor.end");
2026 // Enter the loop, setting up a phi for the current location to initialize.
2027 llvm::BasicBlock
*entryBB
= Builder
.GetInsertBlock();
2028 llvm::BasicBlock
*loopBB
= createBasicBlock("arrayctor.loop");
2030 llvm::PHINode
*cur
= Builder
.CreatePHI(arrayBegin
->getType(), 2,
2032 cur
->addIncoming(arrayBegin
, entryBB
);
2034 // Inside the loop body, emit the constructor call on the array element.
2036 // The alignment of the base, adjusted by the size of a single element,
2037 // provides a conservative estimate of the alignment of every element.
2038 // (This assumes we never start tracking offsetted alignments.)
2040 // Note that these are complete objects and so we don't need to
2041 // use the non-virtual size or alignment.
2042 QualType type
= getContext().getTypeDeclType(ctor
->getParent());
2043 CharUnits eltAlignment
=
2044 arrayBase
.getAlignment()
2045 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type
));
2046 Address curAddr
= Address(cur
, elementType
, eltAlignment
);
2048 // Zero initialize the storage, if requested.
2050 EmitNullInitialization(curAddr
, type
);
2052 // C++ [class.temporary]p4:
2053 // There are two contexts in which temporaries are destroyed at a different
2054 // point than the end of the full-expression. The first context is when a
2055 // default constructor is called to initialize an element of an array.
2056 // If the constructor has one or more default arguments, the destruction of
2057 // every temporary created in a default argument expression is sequenced
2058 // before the construction of the next array element, if any.
2061 RunCleanupsScope
Scope(*this);
2063 // Evaluate the constructor and its arguments in a regular
2064 // partial-destroy cleanup.
2065 if (getLangOpts().Exceptions
&&
2066 !ctor
->getParent()->hasTrivialDestructor()) {
2067 Destroyer
*destroyer
= destroyCXXObject
;
2068 pushRegularPartialArrayCleanup(arrayBegin
, cur
, type
, eltAlignment
,
2071 auto currAVS
= AggValueSlot::forAddr(
2072 curAddr
, type
.getQualifiers(), AggValueSlot::IsDestructed
,
2073 AggValueSlot::DoesNotNeedGCBarriers
, AggValueSlot::IsNotAliased
,
2074 AggValueSlot::DoesNotOverlap
, AggValueSlot::IsNotZeroed
,
2075 NewPointerIsChecked
? AggValueSlot::IsSanitizerChecked
2076 : AggValueSlot::IsNotSanitizerChecked
);
2077 EmitCXXConstructorCall(ctor
, Ctor_Complete
, /*ForVirtualBase=*/false,
2078 /*Delegating=*/false, currAVS
, E
);
2081 // Go to the next element.
2082 llvm::Value
*next
= Builder
.CreateInBoundsGEP(
2083 elementType
, cur
, llvm::ConstantInt::get(SizeTy
, 1), "arrayctor.next");
2084 cur
->addIncoming(next
, Builder
.GetInsertBlock());
2086 // Check whether that's the end of the loop.
2087 llvm::Value
*done
= Builder
.CreateICmpEQ(next
, arrayEnd
, "arrayctor.done");
2088 llvm::BasicBlock
*contBB
= createBasicBlock("arrayctor.cont");
2089 Builder
.CreateCondBr(done
, contBB
, loopBB
);
2091 // Patch the earlier check to skip over the loop.
2092 if (zeroCheckBranch
) zeroCheckBranch
->setSuccessor(0, contBB
);
2097 void CodeGenFunction::destroyCXXObject(CodeGenFunction
&CGF
,
2100 const RecordType
*rtype
= type
->castAs
<RecordType
>();
2101 const CXXRecordDecl
*record
= cast
<CXXRecordDecl
>(rtype
->getDecl());
2102 const CXXDestructorDecl
*dtor
= record
->getDestructor();
2103 assert(!dtor
->isTrivial());
2104 CGF
.EmitCXXDestructorCall(dtor
, Dtor_Complete
, /*for vbase*/ false,
2105 /*Delegating=*/false, addr
, type
);
2108 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl
*D
,
2110 bool ForVirtualBase
,
2112 AggValueSlot ThisAVS
,
2113 const CXXConstructExpr
*E
) {
2115 Address This
= ThisAVS
.getAddress();
2116 LangAS SlotAS
= ThisAVS
.getQualifiers().getAddressSpace();
2117 QualType ThisType
= D
->getThisType();
2118 LangAS ThisAS
= ThisType
.getTypePtr()->getPointeeType().getAddressSpace();
2119 llvm::Value
*ThisPtr
= This
.getPointer();
2121 if (SlotAS
!= ThisAS
) {
2122 unsigned TargetThisAS
= getContext().getTargetAddressSpace(ThisAS
);
2123 llvm::Type
*NewType
=
2124 llvm::PointerType::get(getLLVMContext(), TargetThisAS
);
2125 ThisPtr
= getTargetHooks().performAddrSpaceCast(*this, This
.getPointer(),
2126 ThisAS
, SlotAS
, NewType
);
2129 // Push the this ptr.
2130 Args
.add(RValue::get(ThisPtr
), D
->getThisType());
2132 // If this is a trivial constructor, emit a memcpy now before we lose
2133 // the alignment information on the argument.
2134 // FIXME: It would be better to preserve alignment information into CallArg.
2135 if (isMemcpyEquivalentSpecialMember(D
)) {
2136 assert(E
->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2138 const Expr
*Arg
= E
->getArg(0);
2139 LValue Src
= EmitLValue(Arg
);
2140 QualType DestTy
= getContext().getTypeDeclType(D
->getParent());
2141 LValue Dest
= MakeAddrLValue(This
, DestTy
);
2142 EmitAggregateCopyCtor(Dest
, Src
, ThisAVS
.mayOverlap());
2146 // Add the rest of the user-supplied arguments.
2147 const FunctionProtoType
*FPT
= D
->getType()->castAs
<FunctionProtoType
>();
2148 EvaluationOrder Order
= E
->isListInitialization()
2149 ? EvaluationOrder::ForceLeftToRight
2150 : EvaluationOrder::Default
;
2151 EmitCallArgs(Args
, FPT
, E
->arguments(), E
->getConstructor(),
2152 /*ParamsToSkip*/ 0, Order
);
2154 EmitCXXConstructorCall(D
, Type
, ForVirtualBase
, Delegating
, This
, Args
,
2155 ThisAVS
.mayOverlap(), E
->getExprLoc(),
2156 ThisAVS
.isSanitizerChecked());
2159 static bool canEmitDelegateCallArgs(CodeGenFunction
&CGF
,
2160 const CXXConstructorDecl
*Ctor
,
2161 CXXCtorType Type
, CallArgList
&Args
) {
2162 // We can't forward a variadic call.
2163 if (Ctor
->isVariadic())
2166 if (CGF
.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2167 // If the parameters are callee-cleanup, it's not safe to forward.
2168 for (auto *P
: Ctor
->parameters())
2169 if (P
->needsDestruction(CGF
.getContext()))
2172 // Likewise if they're inalloca.
2173 const CGFunctionInfo
&Info
=
2174 CGF
.CGM
.getTypes().arrangeCXXConstructorCall(Args
, Ctor
, Type
, 0, 0);
2175 if (Info
.usesInAlloca())
2179 // Anything else should be OK.
2183 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl
*D
,
2185 bool ForVirtualBase
,
2189 AggValueSlot::Overlap_t Overlap
,
2191 bool NewPointerIsChecked
) {
2192 const CXXRecordDecl
*ClassDecl
= D
->getParent();
2194 if (!NewPointerIsChecked
)
2195 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall
, Loc
, This
.getPointer(),
2196 getContext().getRecordType(ClassDecl
), CharUnits::Zero());
2198 if (D
->isTrivial() && D
->isDefaultConstructor()) {
2199 assert(Args
.size() == 1 && "trivial default ctor with args");
2203 // If this is a trivial constructor, just emit what's needed. If this is a
2204 // union copy constructor, we must emit a memcpy, because the AST does not
2206 if (isMemcpyEquivalentSpecialMember(D
)) {
2207 assert(Args
.size() == 2 && "unexpected argcount for trivial ctor");
2209 QualType SrcTy
= D
->getParamDecl(0)->getType().getNonReferenceType();
2210 Address Src
= Address(Args
[1].getRValue(*this).getScalarVal(), ConvertTypeForMem(SrcTy
),
2211 CGM
.getNaturalTypeAlignment(SrcTy
));
2212 LValue SrcLVal
= MakeAddrLValue(Src
, SrcTy
);
2213 QualType DestTy
= getContext().getTypeDeclType(ClassDecl
);
2214 LValue DestLVal
= MakeAddrLValue(This
, DestTy
);
2215 EmitAggregateCopyCtor(DestLVal
, SrcLVal
, Overlap
);
2219 bool PassPrototypeArgs
= true;
2220 // Check whether we can actually emit the constructor before trying to do so.
2221 if (auto Inherited
= D
->getInheritedConstructor()) {
2222 PassPrototypeArgs
= getTypes().inheritingCtorHasParams(Inherited
, Type
);
2223 if (PassPrototypeArgs
&& !canEmitDelegateCallArgs(*this, D
, Type
, Args
)) {
2224 EmitInlinedInheritingCXXConstructorCall(D
, Type
, ForVirtualBase
,
2230 // Insert any ABI-specific implicit constructor arguments.
2231 CGCXXABI::AddedStructorArgCounts ExtraArgs
=
2232 CGM
.getCXXABI().addImplicitConstructorArgs(*this, D
, Type
, ForVirtualBase
,
2236 llvm::Constant
*CalleePtr
= CGM
.getAddrOfCXXStructor(GlobalDecl(D
, Type
));
2237 const CGFunctionInfo
&Info
= CGM
.getTypes().arrangeCXXConstructorCall(
2238 Args
, D
, Type
, ExtraArgs
.Prefix
, ExtraArgs
.Suffix
, PassPrototypeArgs
);
2239 CGCallee Callee
= CGCallee::forDirect(CalleePtr
, GlobalDecl(D
, Type
));
2240 EmitCall(Info
, Callee
, ReturnValueSlot(), Args
, nullptr, false, Loc
);
2242 // Generate vtable assumptions if we're constructing a complete object
2243 // with a vtable. We don't do this for base subobjects for two reasons:
2244 // first, it's incorrect for classes with virtual bases, and second, we're
2245 // about to overwrite the vptrs anyway.
2246 // We also have to make sure if we can refer to vtable:
2247 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2248 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2249 // sure that definition of vtable is not hidden,
2250 // then we are always safe to refer to it.
2251 // FIXME: It looks like InstCombine is very inefficient on dealing with
2252 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
2253 if (CGM
.getCodeGenOpts().OptimizationLevel
> 0 &&
2254 ClassDecl
->isDynamicClass() && Type
!= Ctor_Base
&&
2255 CGM
.getCXXABI().canSpeculativelyEmitVTable(ClassDecl
) &&
2256 CGM
.getCodeGenOpts().StrictVTablePointers
)
2257 EmitVTableAssumptionLoads(ClassDecl
, This
);
2260 void CodeGenFunction::EmitInheritedCXXConstructorCall(
2261 const CXXConstructorDecl
*D
, bool ForVirtualBase
, Address This
,
2262 bool InheritedFromVBase
, const CXXInheritedCtorInitExpr
*E
) {
2264 CallArg
ThisArg(RValue::get(This
.getPointer()), D
->getThisType());
2266 // Forward the parameters.
2267 if (InheritedFromVBase
&&
2268 CGM
.getTarget().getCXXABI().hasConstructorVariants()) {
2269 // Nothing to do; this construction is not responsible for constructing
2270 // the base class containing the inherited constructor.
2271 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2272 // have constructor variants?
2273 Args
.push_back(ThisArg
);
2274 } else if (!CXXInheritedCtorInitExprArgs
.empty()) {
2275 // The inheriting constructor was inlined; just inject its arguments.
2276 assert(CXXInheritedCtorInitExprArgs
.size() >= D
->getNumParams() &&
2277 "wrong number of parameters for inherited constructor call");
2278 Args
= CXXInheritedCtorInitExprArgs
;
2281 // The inheriting constructor was not inlined. Emit delegating arguments.
2282 Args
.push_back(ThisArg
);
2283 const auto *OuterCtor
= cast
<CXXConstructorDecl
>(CurCodeDecl
);
2284 assert(OuterCtor
->getNumParams() == D
->getNumParams());
2285 assert(!OuterCtor
->isVariadic() && "should have been inlined");
2287 for (const auto *Param
: OuterCtor
->parameters()) {
2288 assert(getContext().hasSameUnqualifiedType(
2289 OuterCtor
->getParamDecl(Param
->getFunctionScopeIndex())->getType(),
2291 EmitDelegateCallArg(Args
, Param
, E
->getLocation());
2293 // Forward __attribute__(pass_object_size).
2294 if (Param
->hasAttr
<PassObjectSizeAttr
>()) {
2295 auto *POSParam
= SizeArguments
[Param
];
2296 assert(POSParam
&& "missing pass_object_size value for forwarding");
2297 EmitDelegateCallArg(Args
, POSParam
, E
->getLocation());
2302 EmitCXXConstructorCall(D
, Ctor_Base
, ForVirtualBase
, /*Delegating*/false,
2303 This
, Args
, AggValueSlot::MayOverlap
,
2304 E
->getLocation(), /*NewPointerIsChecked*/true);
2307 void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2308 const CXXConstructorDecl
*Ctor
, CXXCtorType CtorType
, bool ForVirtualBase
,
2309 bool Delegating
, CallArgList
&Args
) {
2310 GlobalDecl
GD(Ctor
, CtorType
);
2311 InlinedInheritingConstructorScope
Scope(*this, GD
);
2312 ApplyInlineDebugLocation
DebugScope(*this, GD
);
2313 RunCleanupsScope
RunCleanups(*this);
2315 // Save the arguments to be passed to the inherited constructor.
2316 CXXInheritedCtorInitExprArgs
= Args
;
2318 FunctionArgList Params
;
2319 QualType RetType
= BuildFunctionArgList(CurGD
, Params
);
2322 // Insert any ABI-specific implicit constructor arguments.
2323 CGM
.getCXXABI().addImplicitConstructorArgs(*this, Ctor
, CtorType
,
2324 ForVirtualBase
, Delegating
, Args
);
2326 // Emit a simplified prolog. We only need to emit the implicit params.
2327 assert(Args
.size() >= Params
.size() && "too few arguments for call");
2328 for (unsigned I
= 0, N
= Args
.size(); I
!= N
; ++I
) {
2329 if (I
< Params
.size() && isa
<ImplicitParamDecl
>(Params
[I
])) {
2330 const RValue
&RV
= Args
[I
].getRValue(*this);
2331 assert(!RV
.isComplex() && "complex indirect params not supported");
2332 ParamValue Val
= RV
.isScalar()
2333 ? ParamValue::forDirect(RV
.getScalarVal())
2334 : ParamValue::forIndirect(RV
.getAggregateAddress());
2335 EmitParmDecl(*Params
[I
], Val
, I
+ 1);
2339 // Create a return value slot if the ABI implementation wants one.
2340 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2342 if (!RetType
->isVoidType())
2343 ReturnValue
= CreateIRTemp(RetType
, "retval.inhctor");
2345 CGM
.getCXXABI().EmitInstanceFunctionProlog(*this);
2346 CXXThisValue
= CXXABIThisValue
;
2348 // Directly emit the constructor initializers.
2349 EmitCtorPrologue(Ctor
, CtorType
, Params
);
2352 void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr
&Vptr
, Address This
) {
2353 llvm::Value
*VTableGlobal
=
2354 CGM
.getCXXABI().getVTableAddressPoint(Vptr
.Base
, Vptr
.VTableClass
);
2358 // We can just use the base offset in the complete class.
2359 CharUnits NonVirtualOffset
= Vptr
.Base
.getBaseOffset();
2361 if (!NonVirtualOffset
.isZero())
2363 ApplyNonVirtualAndVirtualOffset(*this, This
, NonVirtualOffset
, nullptr,
2364 Vptr
.VTableClass
, Vptr
.NearestVBase
);
2366 llvm::Value
*VPtrValue
=
2367 GetVTablePtr(This
, VTableGlobal
->getType(), Vptr
.VTableClass
);
2369 Builder
.CreateICmpEQ(VPtrValue
, VTableGlobal
, "cmp.vtables");
2370 Builder
.CreateAssumption(Cmp
);
2373 void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl
*ClassDecl
,
2375 if (CGM
.getCXXABI().doStructorsInitializeVPtrs(ClassDecl
))
2376 for (const VPtr
&Vptr
: getVTablePointers(ClassDecl
))
2377 EmitVTableAssumptionLoad(Vptr
, This
);
2381 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl
*D
,
2382 Address This
, Address Src
,
2383 const CXXConstructExpr
*E
) {
2384 const FunctionProtoType
*FPT
= D
->getType()->castAs
<FunctionProtoType
>();
2388 // Push the this ptr.
2389 Args
.add(RValue::get(This
.getPointer()), D
->getThisType());
2391 // Push the src ptr.
2392 QualType QT
= *(FPT
->param_type_begin());
2393 llvm::Type
*t
= CGM
.getTypes().ConvertType(QT
);
2394 llvm::Value
*SrcVal
= Builder
.CreateBitCast(Src
.getPointer(), t
);
2395 Args
.add(RValue::get(SrcVal
), QT
);
2397 // Skip over first argument (Src).
2398 EmitCallArgs(Args
, FPT
, drop_begin(E
->arguments(), 1), E
->getConstructor(),
2399 /*ParamsToSkip*/ 1);
2401 EmitCXXConstructorCall(D
, Ctor_Complete
, /*ForVirtualBase*/false,
2402 /*Delegating*/false, This
, Args
,
2403 AggValueSlot::MayOverlap
, E
->getExprLoc(),
2404 /*NewPointerIsChecked*/false);
2408 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl
*Ctor
,
2409 CXXCtorType CtorType
,
2410 const FunctionArgList
&Args
,
2411 SourceLocation Loc
) {
2412 CallArgList DelegateArgs
;
2414 FunctionArgList::const_iterator I
= Args
.begin(), E
= Args
.end();
2415 assert(I
!= E
&& "no parameters to constructor");
2418 Address This
= LoadCXXThisAddress();
2419 DelegateArgs
.add(RValue::get(This
.getPointer()), (*I
)->getType());
2422 // FIXME: The location of the VTT parameter in the parameter list is
2423 // specific to the Itanium ABI and shouldn't be hardcoded here.
2424 if (CGM
.getCXXABI().NeedsVTTParameter(CurGD
)) {
2425 assert(I
!= E
&& "cannot skip vtt parameter, already done with args");
2426 assert((*I
)->getType()->isPointerType() &&
2427 "skipping parameter not of vtt type");
2431 // Explicit arguments.
2432 for (; I
!= E
; ++I
) {
2433 const VarDecl
*param
= *I
;
2434 // FIXME: per-argument source location
2435 EmitDelegateCallArg(DelegateArgs
, param
, Loc
);
2438 EmitCXXConstructorCall(Ctor
, CtorType
, /*ForVirtualBase=*/false,
2439 /*Delegating=*/true, This
, DelegateArgs
,
2440 AggValueSlot::MayOverlap
, Loc
,
2441 /*NewPointerIsChecked=*/true);
2445 struct CallDelegatingCtorDtor final
: EHScopeStack::Cleanup
{
2446 const CXXDestructorDecl
*Dtor
;
2450 CallDelegatingCtorDtor(const CXXDestructorDecl
*D
, Address Addr
,
2452 : Dtor(D
), Addr(Addr
), Type(Type
) {}
2454 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
2455 // We are calling the destructor from within the constructor.
2456 // Therefore, "this" should have the expected type.
2457 QualType ThisTy
= Dtor
->getThisObjectType();
2458 CGF
.EmitCXXDestructorCall(Dtor
, Type
, /*ForVirtualBase=*/false,
2459 /*Delegating=*/true, Addr
, ThisTy
);
2462 } // end anonymous namespace
2465 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl
*Ctor
,
2466 const FunctionArgList
&Args
) {
2467 assert(Ctor
->isDelegatingConstructor());
2469 Address ThisPtr
= LoadCXXThisAddress();
2471 AggValueSlot AggSlot
=
2472 AggValueSlot::forAddr(ThisPtr
, Qualifiers(),
2473 AggValueSlot::IsDestructed
,
2474 AggValueSlot::DoesNotNeedGCBarriers
,
2475 AggValueSlot::IsNotAliased
,
2476 AggValueSlot::MayOverlap
,
2477 AggValueSlot::IsNotZeroed
,
2478 // Checks are made by the code that calls constructor.
2479 AggValueSlot::IsSanitizerChecked
);
2481 EmitAggExpr(Ctor
->init_begin()[0]->getInit(), AggSlot
);
2483 const CXXRecordDecl
*ClassDecl
= Ctor
->getParent();
2484 if (CGM
.getLangOpts().Exceptions
&& !ClassDecl
->hasTrivialDestructor()) {
2486 CurGD
.getCtorType() == Ctor_Complete
? Dtor_Complete
: Dtor_Base
;
2488 EHStack
.pushCleanup
<CallDelegatingCtorDtor
>(EHCleanup
,
2489 ClassDecl
->getDestructor(),
2494 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl
*DD
,
2496 bool ForVirtualBase
,
2497 bool Delegating
, Address This
,
2499 CGM
.getCXXABI().EmitDestructorCall(*this, DD
, Type
, ForVirtualBase
,
2500 Delegating
, This
, ThisTy
);
2504 struct CallLocalDtor final
: EHScopeStack::Cleanup
{
2505 const CXXDestructorDecl
*Dtor
;
2509 CallLocalDtor(const CXXDestructorDecl
*D
, Address Addr
, QualType Ty
)
2510 : Dtor(D
), Addr(Addr
), Ty(Ty
) {}
2512 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
2513 CGF
.EmitCXXDestructorCall(Dtor
, Dtor_Complete
,
2514 /*ForVirtualBase=*/false,
2515 /*Delegating=*/false, Addr
, Ty
);
2518 } // end anonymous namespace
2520 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl
*D
,
2521 QualType T
, Address Addr
) {
2522 EHStack
.pushCleanup
<CallLocalDtor
>(NormalAndEHCleanup
, D
, Addr
, T
);
2525 void CodeGenFunction::PushDestructorCleanup(QualType T
, Address Addr
) {
2526 CXXRecordDecl
*ClassDecl
= T
->getAsCXXRecordDecl();
2527 if (!ClassDecl
) return;
2528 if (ClassDecl
->hasTrivialDestructor()) return;
2530 const CXXDestructorDecl
*D
= ClassDecl
->getDestructor();
2531 assert(D
&& D
->isUsed() && "destructor not marked as used!");
2532 PushDestructorCleanup(D
, T
, Addr
);
2535 void CodeGenFunction::InitializeVTablePointer(const VPtr
&Vptr
) {
2536 // Compute the address point.
2537 llvm::Value
*VTableAddressPoint
=
2538 CGM
.getCXXABI().getVTableAddressPointInStructor(
2539 *this, Vptr
.VTableClass
, Vptr
.Base
, Vptr
.NearestVBase
);
2541 if (!VTableAddressPoint
)
2544 // Compute where to store the address point.
2545 llvm::Value
*VirtualOffset
= nullptr;
2546 CharUnits NonVirtualOffset
= CharUnits::Zero();
2548 if (CGM
.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr
)) {
2549 // We need to use the virtual base offset offset because the virtual base
2550 // might have a different offset in the most derived class.
2552 VirtualOffset
= CGM
.getCXXABI().GetVirtualBaseClassOffset(
2553 *this, LoadCXXThisAddress(), Vptr
.VTableClass
, Vptr
.NearestVBase
);
2554 NonVirtualOffset
= Vptr
.OffsetFromNearestVBase
;
2556 // We can just use the base offset in the complete class.
2557 NonVirtualOffset
= Vptr
.Base
.getBaseOffset();
2560 // Apply the offsets.
2561 Address VTableField
= LoadCXXThisAddress();
2562 if (!NonVirtualOffset
.isZero() || VirtualOffset
)
2563 VTableField
= ApplyNonVirtualAndVirtualOffset(
2564 *this, VTableField
, NonVirtualOffset
, VirtualOffset
, Vptr
.VTableClass
,
2567 // Finally, store the address point. Use the same LLVM types as the field to
2568 // support optimization.
2569 unsigned GlobalsAS
= CGM
.getDataLayout().getDefaultGlobalsAddressSpace();
2570 llvm::Type
*PtrTy
= llvm::PointerType::get(CGM
.getLLVMContext(), GlobalsAS
);
2571 // vtable field is derived from `this` pointer, therefore they should be in
2572 // the same addr space. Note that this might not be LLVM address space 0.
2573 VTableField
= VTableField
.withElementType(PtrTy
);
2575 llvm::StoreInst
*Store
= Builder
.CreateStore(VTableAddressPoint
, VTableField
);
2576 TBAAAccessInfo TBAAInfo
= CGM
.getTBAAVTablePtrAccessInfo(PtrTy
);
2577 CGM
.DecorateInstructionWithTBAA(Store
, TBAAInfo
);
2578 if (CGM
.getCodeGenOpts().OptimizationLevel
> 0 &&
2579 CGM
.getCodeGenOpts().StrictVTablePointers
)
2580 CGM
.DecorateInstructionWithInvariantGroup(Store
, Vptr
.VTableClass
);
2583 CodeGenFunction::VPtrsVector
2584 CodeGenFunction::getVTablePointers(const CXXRecordDecl
*VTableClass
) {
2585 CodeGenFunction::VPtrsVector VPtrsResult
;
2586 VisitedVirtualBasesSetTy VBases
;
2587 getVTablePointers(BaseSubobject(VTableClass
, CharUnits::Zero()),
2588 /*NearestVBase=*/nullptr,
2589 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2590 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass
, VBases
,
2595 void CodeGenFunction::getVTablePointers(BaseSubobject Base
,
2596 const CXXRecordDecl
*NearestVBase
,
2597 CharUnits OffsetFromNearestVBase
,
2598 bool BaseIsNonVirtualPrimaryBase
,
2599 const CXXRecordDecl
*VTableClass
,
2600 VisitedVirtualBasesSetTy
&VBases
,
2601 VPtrsVector
&Vptrs
) {
2602 // If this base is a non-virtual primary base the address point has already
2604 if (!BaseIsNonVirtualPrimaryBase
) {
2605 // Initialize the vtable pointer for this base.
2606 VPtr Vptr
= {Base
, NearestVBase
, OffsetFromNearestVBase
, VTableClass
};
2607 Vptrs
.push_back(Vptr
);
2610 const CXXRecordDecl
*RD
= Base
.getBase();
2613 for (const auto &I
: RD
->bases()) {
2615 cast
<CXXRecordDecl
>(I
.getType()->castAs
<RecordType
>()->getDecl());
2617 // Ignore classes without a vtable.
2618 if (!BaseDecl
->isDynamicClass())
2621 CharUnits BaseOffset
;
2622 CharUnits BaseOffsetFromNearestVBase
;
2623 bool BaseDeclIsNonVirtualPrimaryBase
;
2625 if (I
.isVirtual()) {
2626 // Check if we've visited this virtual base before.
2627 if (!VBases
.insert(BaseDecl
).second
)
2630 const ASTRecordLayout
&Layout
=
2631 getContext().getASTRecordLayout(VTableClass
);
2633 BaseOffset
= Layout
.getVBaseClassOffset(BaseDecl
);
2634 BaseOffsetFromNearestVBase
= CharUnits::Zero();
2635 BaseDeclIsNonVirtualPrimaryBase
= false;
2637 const ASTRecordLayout
&Layout
= getContext().getASTRecordLayout(RD
);
2639 BaseOffset
= Base
.getBaseOffset() + Layout
.getBaseClassOffset(BaseDecl
);
2640 BaseOffsetFromNearestVBase
=
2641 OffsetFromNearestVBase
+ Layout
.getBaseClassOffset(BaseDecl
);
2642 BaseDeclIsNonVirtualPrimaryBase
= Layout
.getPrimaryBase() == BaseDecl
;
2646 BaseSubobject(BaseDecl
, BaseOffset
),
2647 I
.isVirtual() ? BaseDecl
: NearestVBase
, BaseOffsetFromNearestVBase
,
2648 BaseDeclIsNonVirtualPrimaryBase
, VTableClass
, VBases
, Vptrs
);
2652 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl
*RD
) {
2653 // Ignore classes without a vtable.
2654 if (!RD
->isDynamicClass())
2657 // Initialize the vtable pointers for this class and all of its bases.
2658 if (CGM
.getCXXABI().doStructorsInitializeVPtrs(RD
))
2659 for (const VPtr
&Vptr
: getVTablePointers(RD
))
2660 InitializeVTablePointer(Vptr
);
2662 if (RD
->getNumVBases())
2663 CGM
.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD
);
2666 llvm::Value
*CodeGenFunction::GetVTablePtr(Address This
,
2667 llvm::Type
*VTableTy
,
2668 const CXXRecordDecl
*RD
) {
2669 Address VTablePtrSrc
= This
.withElementType(VTableTy
);
2670 llvm::Instruction
*VTable
= Builder
.CreateLoad(VTablePtrSrc
, "vtable");
2671 TBAAAccessInfo TBAAInfo
= CGM
.getTBAAVTablePtrAccessInfo(VTableTy
);
2672 CGM
.DecorateInstructionWithTBAA(VTable
, TBAAInfo
);
2674 if (CGM
.getCodeGenOpts().OptimizationLevel
> 0 &&
2675 CGM
.getCodeGenOpts().StrictVTablePointers
)
2676 CGM
.DecorateInstructionWithInvariantGroup(VTable
, RD
);
2681 // If a class has a single non-virtual base and does not introduce or override
2682 // virtual member functions or fields, it will have the same layout as its base.
2683 // This function returns the least derived such class.
2685 // Casting an instance of a base class to such a derived class is technically
2686 // undefined behavior, but it is a relatively common hack for introducing member
2687 // functions on class instances with specific properties (e.g. llvm::Operator)
2688 // that works under most compilers and should not have security implications, so
2689 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2690 static const CXXRecordDecl
*
2691 LeastDerivedClassWithSameLayout(const CXXRecordDecl
*RD
) {
2692 if (!RD
->field_empty())
2695 if (RD
->getNumVBases() != 0)
2698 if (RD
->getNumBases() != 1)
2701 for (const CXXMethodDecl
*MD
: RD
->methods()) {
2702 if (MD
->isVirtual()) {
2703 // Virtual member functions are only ok if they are implicit destructors
2704 // because the implicit destructor will have the same semantics as the
2705 // base class's destructor if no fields are added.
2706 if (isa
<CXXDestructorDecl
>(MD
) && MD
->isImplicit())
2712 return LeastDerivedClassWithSameLayout(
2713 RD
->bases_begin()->getType()->getAsCXXRecordDecl());
2716 void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl
*RD
,
2717 llvm::Value
*VTable
,
2718 SourceLocation Loc
) {
2719 if (SanOpts
.has(SanitizerKind::CFIVCall
))
2720 EmitVTablePtrCheckForCall(RD
, VTable
, CodeGenFunction::CFITCK_VCall
, Loc
);
2721 else if (CGM
.getCodeGenOpts().WholeProgramVTables
&&
2722 // Don't insert type test assumes if we are forcing public
2724 !CGM
.AlwaysHasLTOVisibilityPublic(RD
)) {
2725 QualType Ty
= QualType(RD
->getTypeForDecl(), 0);
2726 llvm::Metadata
*MD
= CGM
.CreateMetadataIdentifierForType(Ty
);
2727 llvm::Value
*TypeId
=
2728 llvm::MetadataAsValue::get(CGM
.getLLVMContext(), MD
);
2730 // If we already know that the call has hidden LTO visibility, emit
2731 // @llvm.type.test(). Otherwise emit @llvm.public.type.test(), which WPD
2732 // will convert to @llvm.type.test() if we assert at link time that we have
2733 // whole program visibility.
2734 llvm::Intrinsic::ID IID
= CGM
.HasHiddenLTOVisibility(RD
)
2735 ? llvm::Intrinsic::type_test
2736 : llvm::Intrinsic::public_type_test
;
2737 llvm::Value
*TypeTest
=
2738 Builder
.CreateCall(CGM
.getIntrinsic(IID
), {VTable
, TypeId
});
2739 Builder
.CreateCall(CGM
.getIntrinsic(llvm::Intrinsic::assume
), TypeTest
);
2743 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl
*RD
,
2744 llvm::Value
*VTable
,
2745 CFITypeCheckKind TCK
,
2746 SourceLocation Loc
) {
2747 if (!SanOpts
.has(SanitizerKind::CFICastStrict
))
2748 RD
= LeastDerivedClassWithSameLayout(RD
);
2750 EmitVTablePtrCheck(RD
, VTable
, TCK
, Loc
);
2753 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T
, Address Derived
,
2755 CFITypeCheckKind TCK
,
2756 SourceLocation Loc
) {
2757 if (!getLangOpts().CPlusPlus
)
2760 auto *ClassTy
= T
->getAs
<RecordType
>();
2764 const CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(ClassTy
->getDecl());
2766 if (!ClassDecl
->isCompleteDefinition() || !ClassDecl
->isDynamicClass())
2769 if (!SanOpts
.has(SanitizerKind::CFICastStrict
))
2770 ClassDecl
= LeastDerivedClassWithSameLayout(ClassDecl
);
2772 llvm::BasicBlock
*ContBlock
= nullptr;
2775 llvm::Value
*DerivedNotNull
=
2776 Builder
.CreateIsNotNull(Derived
.getPointer(), "cast.nonnull");
2778 llvm::BasicBlock
*CheckBlock
= createBasicBlock("cast.check");
2779 ContBlock
= createBasicBlock("cast.cont");
2781 Builder
.CreateCondBr(DerivedNotNull
, CheckBlock
, ContBlock
);
2783 EmitBlock(CheckBlock
);
2786 llvm::Value
*VTable
;
2787 std::tie(VTable
, ClassDecl
) =
2788 CGM
.getCXXABI().LoadVTablePtr(*this, Derived
, ClassDecl
);
2790 EmitVTablePtrCheck(ClassDecl
, VTable
, TCK
, Loc
);
2793 Builder
.CreateBr(ContBlock
);
2794 EmitBlock(ContBlock
);
2798 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl
*RD
,
2799 llvm::Value
*VTable
,
2800 CFITypeCheckKind TCK
,
2801 SourceLocation Loc
) {
2802 if (!CGM
.getCodeGenOpts().SanitizeCfiCrossDso
&&
2803 !CGM
.HasHiddenLTOVisibility(RD
))
2807 llvm::SanitizerStatKind SSK
;
2810 M
= SanitizerKind::CFIVCall
;
2811 SSK
= llvm::SanStat_CFI_VCall
;
2814 M
= SanitizerKind::CFINVCall
;
2815 SSK
= llvm::SanStat_CFI_NVCall
;
2817 case CFITCK_DerivedCast
:
2818 M
= SanitizerKind::CFIDerivedCast
;
2819 SSK
= llvm::SanStat_CFI_DerivedCast
;
2821 case CFITCK_UnrelatedCast
:
2822 M
= SanitizerKind::CFIUnrelatedCast
;
2823 SSK
= llvm::SanStat_CFI_UnrelatedCast
;
2826 case CFITCK_NVMFCall
:
2827 case CFITCK_VMFCall
:
2828 llvm_unreachable("unexpected sanitizer kind");
2831 std::string TypeName
= RD
->getQualifiedNameAsString();
2832 if (getContext().getNoSanitizeList().containsType(M
, TypeName
))
2835 SanitizerScope
SanScope(this);
2836 EmitSanitizerStatReport(SSK
);
2838 llvm::Metadata
*MD
=
2839 CGM
.CreateMetadataIdentifierForType(QualType(RD
->getTypeForDecl(), 0));
2840 llvm::Value
*TypeId
= llvm::MetadataAsValue::get(getLLVMContext(), MD
);
2842 llvm::Value
*TypeTest
= Builder
.CreateCall(
2843 CGM
.getIntrinsic(llvm::Intrinsic::type_test
), {VTable
, TypeId
});
2845 llvm::Constant
*StaticData
[] = {
2846 llvm::ConstantInt::get(Int8Ty
, TCK
),
2847 EmitCheckSourceLocation(Loc
),
2848 EmitCheckTypeDescriptor(QualType(RD
->getTypeForDecl(), 0)),
2851 auto CrossDsoTypeId
= CGM
.CreateCrossDsoCfiTypeId(MD
);
2852 if (CGM
.getCodeGenOpts().SanitizeCfiCrossDso
&& CrossDsoTypeId
) {
2853 EmitCfiSlowPathCheck(M
, TypeTest
, CrossDsoTypeId
, VTable
, StaticData
);
2857 if (CGM
.getCodeGenOpts().SanitizeTrap
.has(M
)) {
2858 EmitTrapCheck(TypeTest
, SanitizerHandler::CFICheckFail
);
2862 llvm::Value
*AllVtables
= llvm::MetadataAsValue::get(
2863 CGM
.getLLVMContext(),
2864 llvm::MDString::get(CGM
.getLLVMContext(), "all-vtables"));
2865 llvm::Value
*ValidVtable
= Builder
.CreateCall(
2866 CGM
.getIntrinsic(llvm::Intrinsic::type_test
), {VTable
, AllVtables
});
2867 EmitCheck(std::make_pair(TypeTest
, M
), SanitizerHandler::CFICheckFail
,
2868 StaticData
, {VTable
, ValidVtable
});
2871 bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl
*RD
) {
2872 if (!CGM
.getCodeGenOpts().WholeProgramVTables
||
2873 !CGM
.HasHiddenLTOVisibility(RD
))
2876 if (CGM
.getCodeGenOpts().VirtualFunctionElimination
)
2879 if (!SanOpts
.has(SanitizerKind::CFIVCall
) ||
2880 !CGM
.getCodeGenOpts().SanitizeTrap
.has(SanitizerKind::CFIVCall
))
2883 std::string TypeName
= RD
->getQualifiedNameAsString();
2884 return !getContext().getNoSanitizeList().containsType(SanitizerKind::CFIVCall
,
2888 llvm::Value
*CodeGenFunction::EmitVTableTypeCheckedLoad(
2889 const CXXRecordDecl
*RD
, llvm::Value
*VTable
, llvm::Type
*VTableTy
,
2890 uint64_t VTableByteOffset
) {
2891 SanitizerScope
SanScope(this);
2893 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall
);
2895 llvm::Metadata
*MD
=
2896 CGM
.CreateMetadataIdentifierForType(QualType(RD
->getTypeForDecl(), 0));
2897 llvm::Value
*TypeId
= llvm::MetadataAsValue::get(CGM
.getLLVMContext(), MD
);
2899 llvm::Value
*CheckedLoad
= Builder
.CreateCall(
2900 CGM
.getIntrinsic(llvm::Intrinsic::type_checked_load
),
2901 {VTable
, llvm::ConstantInt::get(Int32Ty
, VTableByteOffset
), TypeId
});
2902 llvm::Value
*CheckResult
= Builder
.CreateExtractValue(CheckedLoad
, 1);
2904 std::string TypeName
= RD
->getQualifiedNameAsString();
2905 if (SanOpts
.has(SanitizerKind::CFIVCall
) &&
2906 !getContext().getNoSanitizeList().containsType(SanitizerKind::CFIVCall
,
2908 EmitCheck(std::make_pair(CheckResult
, SanitizerKind::CFIVCall
),
2909 SanitizerHandler::CFICheckFail
, {}, {});
2912 return Builder
.CreateBitCast(Builder
.CreateExtractValue(CheckedLoad
, 0),
2916 void CodeGenFunction::EmitForwardingCallToLambda(
2917 const CXXMethodDecl
*callOperator
, CallArgList
&callArgs
,
2918 const CGFunctionInfo
*calleeFnInfo
, llvm::Constant
*calleePtr
) {
2919 // Get the address of the call operator.
2921 calleeFnInfo
= &CGM
.getTypes().arrangeCXXMethodDeclaration(callOperator
);
2925 CGM
.GetAddrOfFunction(GlobalDecl(callOperator
),
2926 CGM
.getTypes().GetFunctionType(*calleeFnInfo
));
2928 // Prepare the return slot.
2929 const FunctionProtoType
*FPT
=
2930 callOperator
->getType()->castAs
<FunctionProtoType
>();
2931 QualType resultType
= FPT
->getReturnType();
2932 ReturnValueSlot returnSlot
;
2933 if (!resultType
->isVoidType() &&
2934 calleeFnInfo
->getReturnInfo().getKind() == ABIArgInfo::Indirect
&&
2935 !hasScalarEvaluationKind(calleeFnInfo
->getReturnType()))
2937 ReturnValueSlot(ReturnValue
, resultType
.isVolatileQualified(),
2938 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
2940 // We don't need to separately arrange the call arguments because
2941 // the call can't be variadic anyway --- it's impossible to forward
2942 // variadic arguments.
2944 // Now emit our call.
2945 auto callee
= CGCallee::forDirect(calleePtr
, GlobalDecl(callOperator
));
2946 RValue RV
= EmitCall(*calleeFnInfo
, callee
, returnSlot
, callArgs
);
2948 // If necessary, copy the returned value into the slot.
2949 if (!resultType
->isVoidType() && returnSlot
.isNull()) {
2950 if (getLangOpts().ObjCAutoRefCount
&& resultType
->isObjCRetainableType()) {
2951 RV
= RValue::get(EmitARCRetainAutoreleasedReturnValue(RV
.getScalarVal()));
2953 EmitReturnOfRValue(RV
, resultType
);
2955 EmitBranchThroughCleanup(ReturnBlock
);
2958 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2959 const BlockDecl
*BD
= BlockInfo
->getBlockDecl();
2960 const VarDecl
*variable
= BD
->capture_begin()->getVariable();
2961 const CXXRecordDecl
*Lambda
= variable
->getType()->getAsCXXRecordDecl();
2962 const CXXMethodDecl
*CallOp
= Lambda
->getLambdaCallOperator();
2964 if (CallOp
->isVariadic()) {
2965 // FIXME: Making this work correctly is nasty because it requires either
2966 // cloning the body of the call operator or making the call operator
2968 CGM
.ErrorUnsupported(CurCodeDecl
, "lambda conversion to variadic function");
2972 // Start building arguments for forwarding call
2973 CallArgList CallArgs
;
2975 QualType ThisType
= getContext().getPointerType(getContext().getRecordType(Lambda
));
2976 Address ThisPtr
= GetAddrOfBlockDecl(variable
);
2977 CallArgs
.add(RValue::get(ThisPtr
.getPointer()), ThisType
);
2979 // Add the rest of the parameters.
2980 for (auto *param
: BD
->parameters())
2981 EmitDelegateCallArg(CallArgs
, param
, param
->getBeginLoc());
2983 assert(!Lambda
->isGenericLambda() &&
2984 "generic lambda interconversion to block not implemented");
2985 EmitForwardingCallToLambda(CallOp
, CallArgs
);
2988 void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl
*MD
) {
2989 if (MD
->isVariadic()) {
2990 // FIXME: Making this work correctly is nasty because it requires either
2991 // cloning the body of the call operator or making the call operator
2993 CGM
.ErrorUnsupported(MD
, "lambda conversion to variadic function");
2997 const CXXRecordDecl
*Lambda
= MD
->getParent();
2999 // Start building arguments for forwarding call
3000 CallArgList CallArgs
;
3002 QualType LambdaType
= getContext().getRecordType(Lambda
);
3003 QualType ThisType
= getContext().getPointerType(LambdaType
);
3004 Address ThisPtr
= CreateMemTemp(LambdaType
, "unused.capture");
3005 CallArgs
.add(RValue::get(ThisPtr
.getPointer()), ThisType
);
3007 EmitLambdaDelegatingInvokeBody(MD
, CallArgs
);
3010 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl
*MD
,
3011 CallArgList
&CallArgs
) {
3012 // Add the rest of the forwarded parameters.
3013 for (auto *Param
: MD
->parameters())
3014 EmitDelegateCallArg(CallArgs
, Param
, Param
->getBeginLoc());
3016 const CXXRecordDecl
*Lambda
= MD
->getParent();
3017 const CXXMethodDecl
*CallOp
= Lambda
->getLambdaCallOperator();
3018 // For a generic lambda, find the corresponding call operator specialization
3019 // to which the call to the static-invoker shall be forwarded.
3020 if (Lambda
->isGenericLambda()) {
3021 assert(MD
->isFunctionTemplateSpecialization());
3022 const TemplateArgumentList
*TAL
= MD
->getTemplateSpecializationArgs();
3023 FunctionTemplateDecl
*CallOpTemplate
= CallOp
->getDescribedFunctionTemplate();
3024 void *InsertPos
= nullptr;
3025 FunctionDecl
*CorrespondingCallOpSpecialization
=
3026 CallOpTemplate
->findSpecialization(TAL
->asArray(), InsertPos
);
3027 assert(CorrespondingCallOpSpecialization
);
3028 CallOp
= cast
<CXXMethodDecl
>(CorrespondingCallOpSpecialization
);
3031 // Special lambda forwarding when there are inalloca parameters.
3032 if (hasInAllocaArg(MD
)) {
3033 const CGFunctionInfo
*ImplFnInfo
= nullptr;
3034 llvm::Function
*ImplFn
= nullptr;
3035 EmitLambdaInAllocaImplFn(CallOp
, &ImplFnInfo
, &ImplFn
);
3037 EmitForwardingCallToLambda(CallOp
, CallArgs
, ImplFnInfo
, ImplFn
);
3041 EmitForwardingCallToLambda(CallOp
, CallArgs
);
3044 void CodeGenFunction::EmitLambdaInAllocaCallOpBody(const CXXMethodDecl
*MD
) {
3045 if (MD
->isVariadic()) {
3046 // FIXME: Making this work correctly is nasty because it requires either
3047 // cloning the body of the call operator or making the call operator forward.
3048 CGM
.ErrorUnsupported(MD
, "lambda conversion to variadic function");
3052 // Forward %this argument.
3053 CallArgList CallArgs
;
3054 QualType LambdaType
= getContext().getRecordType(MD
->getParent());
3055 QualType ThisType
= getContext().getPointerType(LambdaType
);
3056 llvm::Value
*ThisArg
= CurFn
->getArg(0);
3057 CallArgs
.add(RValue::get(ThisArg
), ThisType
);
3059 EmitLambdaDelegatingInvokeBody(MD
, CallArgs
);
3062 void CodeGenFunction::EmitLambdaInAllocaImplFn(
3063 const CXXMethodDecl
*CallOp
, const CGFunctionInfo
**ImplFnInfo
,
3064 llvm::Function
**ImplFn
) {
3065 const CGFunctionInfo
&FnInfo
=
3066 CGM
.getTypes().arrangeCXXMethodDeclaration(CallOp
);
3067 llvm::Function
*CallOpFn
=
3068 cast
<llvm::Function
>(CGM
.GetAddrOfFunction(GlobalDecl(CallOp
)));
3070 // Emit function containing the original call op body. __invoke will delegate
3071 // to this function.
3072 SmallVector
<CanQualType
, 4> ArgTypes
;
3073 for (auto I
= FnInfo
.arg_begin(); I
!= FnInfo
.arg_end(); ++I
)
3074 ArgTypes
.push_back(I
->type
);
3075 *ImplFnInfo
= &CGM
.getTypes().arrangeLLVMFunctionInfo(
3076 FnInfo
.getReturnType(), FnInfoOpts::IsDelegateCall
, ArgTypes
,
3077 FnInfo
.getExtInfo(), {}, FnInfo
.getRequiredArgs());
3079 // Create mangled name as if this was a method named __impl. If for some
3080 // reason the name doesn't look as expected then just tack __impl to the
3082 // TODO: Use the name mangler to produce the right name instead of using
3083 // string replacement.
3084 StringRef CallOpName
= CallOpFn
->getName();
3085 std::string ImplName
;
3086 if (size_t Pos
= CallOpName
.find_first_of("<lambda"))
3087 ImplName
= ("?__impl@" + CallOpName
.drop_front(Pos
)).str();
3089 ImplName
= ("__impl" + CallOpName
).str();
3091 llvm::Function
*Fn
= CallOpFn
->getParent()->getFunction(ImplName
);
3093 Fn
= llvm::Function::Create(CGM
.getTypes().GetFunctionType(**ImplFnInfo
),
3094 llvm::GlobalValue::InternalLinkage
, ImplName
,
3096 CGM
.SetInternalFunctionAttributes(CallOp
, Fn
, **ImplFnInfo
);
3098 const GlobalDecl
&GD
= GlobalDecl(CallOp
);
3099 const auto *D
= cast
<FunctionDecl
>(GD
.getDecl());
3100 CodeGenFunction(CGM
).GenerateCode(GD
, Fn
, **ImplFnInfo
);
3101 CGM
.SetLLVMFunctionAttributesForDefinition(D
, Fn
);