Skip to content

Commit

Permalink
[MS] Apply adjustments after storing 'this'
Browse files Browse the repository at this point in the history
Summary:
The MS ABI convention is that the 'this' pointer on entry is the address
of the vfptr that was used to make the virtual method call. In other
words, the pointer on entry always points to the base subobject that
introduced the virtual method. Consider this hierarchy:

  struct A { virtual void f() = 0; };
  struct B { virtual void g() = 0; };
  struct C : A, B {
    void f() override;
    void g() override;
  };

On entry to C::g, [ER]CX will contain the address of C's B subobject,
and C::g will have to subtract sizeof(A) to recover a pointer to C.

Before this change, we applied this adjustment in the prologue and
stored the new value into the "this" local variable alloca used for
debug info. However, MSVC does not do this, presumably because it is
often profitable to fold the adjustment into later field accesses. This
creates a problem, because the debugger expects the variable to be
unadjusted. Unfortunately, CodeView doesn't have anything like DWARF
expressions for computing variables that aren't in the program anymore,
so we have to declare 'this' to be the unadjusted value if we want the
debugger to see the right value.

This has the side benefit that, in optimized builds, the 'this' pointer
will usually be available on function entry because it doesn't require
any adjustment.

Reviewers: hans

Subscribers: aprantl, cfe-commits

Differential Revision: https://reviews.llvm.org/D40109

llvm-svn: 318440
  • Loading branch information
rnk committed Nov 16, 2017
1 parent 547fa15 commit 06239e4
Show file tree
Hide file tree
Showing 9 changed files with 116 additions and 114 deletions.
11 changes: 7 additions & 4 deletions clang/lib/CodeGen/CGCXXABI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,15 @@ void CGCXXABI::buildThisParam(CodeGenFunction &CGF, FunctionArgList &params) {
}
}

void CGCXXABI::EmitThisParam(CodeGenFunction &CGF) {
llvm::Value *CGCXXABI::loadIncomingCXXThis(CodeGenFunction &CGF) {
return CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)),
"this");
}

void CGCXXABI::setCXXABIThisValue(CodeGenFunction &CGF, llvm::Value *ThisPtr) {
/// Initialize the 'this' slot.
assert(getThisDecl(CGF) && "no 'this' variable for function");
CGF.CXXABIThisValue
= CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)),
"this");
CGF.CXXABIThisValue = ThisPtr;
}

void CGCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
Expand Down
14 changes: 4 additions & 10 deletions clang/lib/CodeGen/CGCXXABI.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,10 @@ class CGCXXABI {
return CGF.CXXStructorImplicitParamValue;
}

/// Perform prolog initialization of the parameter variable suitable
/// for 'this' emitted by buildThisParam.
void EmitThisParam(CodeGenFunction &CGF);
/// Loads the incoming C++ this pointer as it was passed by the caller.
llvm::Value *loadIncomingCXXThis(CodeGenFunction &CGF);

void setCXXABIThisValue(CodeGenFunction &CGF, llvm::Value *ThisPtr);

ASTContext &getContext() const { return CGM.getContext(); }

Expand Down Expand Up @@ -358,13 +359,6 @@ class CGCXXABI {
return CharUnits::Zero();
}

/// Perform ABI-specific "this" parameter adjustment in a virtual function
/// prologue.
virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
return This;
}

/// Emit the ABI-specific prolog for the function.
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;

Expand Down
18 changes: 0 additions & 18 deletions clang/lib/CodeGen/CGDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1796,24 +1796,6 @@ void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
return;
}

// Apply any prologue 'this' adjustments required by the ABI. Be careful to
// handle the case where 'this' is passed indirectly as part of an inalloca
// struct.
if (const CXXMethodDecl *MD =
dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
if (MD->isVirtual() && IPD == CXXABIThisDecl) {
llvm::Value *This = Arg.isIndirect()
? Builder.CreateLoad(Arg.getIndirectAddress())
: Arg.getDirectValue();
This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
*this, CurGD, This);
if (Arg.isIndirect())
Builder.CreateStore(This, Arg.getIndirectAddress());
else
Arg = ParamValue::forDirect(This);
}
}
}

Address DeclPtr = Address::invalid();
Expand Down
5 changes: 3 additions & 2 deletions clang/lib/CodeGen/ItaniumCXXABI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1443,8 +1443,9 @@ void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
return;

/// Initialize the 'this' slot.
EmitThisParam(CGF);
/// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
/// adjustments are required, becuase they are all handled by thunks.
setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));

/// Initialize the 'vtt' slot if needed.
if (getStructorImplicitParamDecl(CGF)) {
Expand Down
75 changes: 38 additions & 37 deletions clang/lib/CodeGen/MicrosoftCXXABI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -244,9 +244,6 @@ class MicrosoftCXXABI : public CGCXXABI {
void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
FunctionArgList &Params) override;

llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;

void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;

AddedStructorArgs
Expand Down Expand Up @@ -1433,50 +1430,54 @@ void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
}
}

llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
// In this ABI, every virtual function takes a pointer to one of the
// subobjects that first defines it as the 'this' parameter, rather than a
// pointer to the final overrider subobject. Thus, we need to adjust it back
// to the final overrider subobject before use.
// See comments in the MicrosoftVFTableContext implementation for the details.
CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
if (Adjustment.isZero())
return This;

unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
*thisTy = This->getType();

This = CGF.Builder.CreateBitCast(This, charPtrTy);
assert(Adjustment.isPositive());
This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
-Adjustment.getQuantity());
return CGF.Builder.CreateBitCast(This, thisTy);
}

void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
// Naked functions have no prolog.
if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
return;

EmitThisParam(CGF);
// Overridden virtual methods of non-primary bases need to adjust the incoming
// 'this' pointer in the prologue. In this hierarchy, C::b will subtract
// sizeof(void*) to adjust from B* to C*:
// struct A { virtual void a(); };
// struct B { virtual void b(); };
// struct C : A, B { virtual void b(); };
//
// Leave the value stored in the 'this' alloca unadjusted, so that the
// debugger sees the unadjusted value. Microsoft debuggers require this, and
// will apply the ThisAdjustment in the method type information.
// FIXME: Do something better for DWARF debuggers, which won't expect this,
// without making our codegen depend on debug info settings.
llvm::Value *This = loadIncomingCXXThis(CGF);
const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
if (!Adjustment.isZero()) {
unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
*thisTy = This->getType();
This = CGF.Builder.CreateBitCast(This, charPtrTy);
assert(Adjustment.isPositive());
This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
-Adjustment.getQuantity());
This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
}
}
setCXXABIThisValue(CGF, This);

/// If this is a function that the ABI specifies returns 'this', initialize
/// the return slot to 'this' at the start of the function.
///
/// Unlike the setting of return types, this is done within the ABI
/// implementation instead of by clients of CGCXXABI because:
/// 1) getThisValue is currently protected
/// 2) in theory, an ABI could implement 'this' returns some other way;
/// HasThisReturn only specifies a contract, not the implementation
// If this is a function that the ABI specifies returns 'this', initialize
// the return slot to 'this' at the start of the function.
//
// Unlike the setting of return types, this is done within the ABI
// implementation instead of by clients of CGCXXABI because:
// 1) getThisValue is currently protected
// 2) in theory, an ABI could implement 'this' returns some other way;
// HasThisReturn only specifies a contract, not the implementation
if (HasThisReturn(CGF.CurGD))
CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
else if (hasMostDerivedReturn(CGF.CurGD))
CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
CGF.ReturnValue);

const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
assert(getStructorImplicitParamDecl(CGF) &&
"no implicit parameter for a constructor with virtual bases?");
Expand Down Expand Up @@ -1961,7 +1962,7 @@ llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
// Start defining the function.
CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
FunctionArgs, MD->getLocation(), SourceLocation());
EmitThisParam(CGF);
setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));

// Load the vfptr and then callee from the vftable. The callee should have
// adjusted 'this' so that the vfptr is at offset zero.
Expand Down Expand Up @@ -3900,7 +3901,7 @@ MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
FunctionArgs, CD->getLocation(), SourceLocation());
// Create a scope with an artificial location for the body of this function.
auto AL = ApplyDebugLocation::CreateArtificial(CGF);
EmitThisParam(CGF);
setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
llvm::Value *This = getThisValue(CGF);

llvm::Value *SrcVal =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ struct ChildOverride : Left, Right {
extern "C" void foo(void *);

void call_left_no_override(ChildNoOverride *child) {
// CHECK: define void @"\01?call_left_no_override
// CHECK-LABEL: define void @"\01?call_left_no_override
// CHECK: %[[CHILD:.*]] = load %struct.ChildNoOverride

child->left();
Expand All @@ -34,7 +34,8 @@ void call_left_no_override(ChildNoOverride *child) {
}

void ChildOverride::left() {
// CHECK: define x86_thiscallcc void @"\01?left@ChildOverride@@UAEXXZ"(%struct.ChildOverride* %[[THIS:.*]])
// CHECK-LABEL: define x86_thiscallcc void @"\01?left@ChildOverride@@UAEXXZ"
// CHECK-SAME: (%struct.ChildOverride* %[[THIS:.*]])
//
// No need to adjust 'this' as the ChildOverride's layout begins with Left.
// CHECK: %[[THIS_ADDR:.*]] = alloca %struct.ChildOverride*, align 4
Expand All @@ -48,7 +49,7 @@ void ChildOverride::left() {
}

void call_left_override(ChildOverride *child) {
// CHECK: define void @"\01?call_left_override
// CHECK-LABEL: define void @"\01?call_left_override
// CHECK: %[[CHILD:.*]] = load %struct.ChildOverride

child->left();
Expand All @@ -62,7 +63,7 @@ void call_left_override(ChildOverride *child) {
}

void call_right_no_override(ChildNoOverride *child) {
// CHECK: define void @"\01?call_right_no_override
// CHECK-LABEL: define void @"\01?call_right_no_override
// CHECK: %[[CHILD:.*]] = load %struct.ChildNoOverride

child->right();
Expand All @@ -82,25 +83,27 @@ void call_right_no_override(ChildNoOverride *child) {
}

void ChildOverride::right() {
// CHECK: define x86_thiscallcc void @"\01?right@ChildOverride@@UAEXXZ"(i8*
// CHECK-LABEL: define x86_thiscallcc void @"\01?right@ChildOverride@@UAEXXZ"(i8*
//
// ChildOverride::right gets 'this' cast to Right* in ECX (i.e. this+4) so we
// need to adjust 'this' before use.
//
// CHECK: %[[THIS_ADDR:.*]] = alloca %struct.ChildOverride*, align 4
// CHECK: %[[THIS_i8:.*]] = getelementptr inbounds i8, i8* %[[ECX:.*]], i32 -4
// CHECK: %[[THIS:.*]] = bitcast i8* %[[THIS_i8]] to %struct.ChildOverride*
// CHECK: store %struct.ChildOverride* %[[THIS]], %struct.ChildOverride** %[[THIS_ADDR]], align 4
// CHECK: %[[THIS_INIT:.*]] = bitcast i8* %[[ECX:.*]] to %struct.ChildOverride*
// CHECK: store %struct.ChildOverride* %[[THIS_INIT]], %struct.ChildOverride** %[[THIS_ADDR]], align 4
// CHECK: %[[THIS_RELOAD:.*]] = load %struct.ChildOverride*, %struct.ChildOverride** %[[THIS_ADDR]]
// CHECK: %[[THIS_i8:.*]] = bitcast %struct.ChildOverride* %[[THIS_RELOAD]] to i8*
// CHECK: %[[THIS_ADJUSTED:.*]] = getelementptr inbounds i8, i8* %[[THIS_i8]], i32 -4
// CHECK: %[[THIS:.*]] = bitcast i8* %[[THIS_ADJUSTED]] to %struct.ChildOverride*

foo(this);
// CHECK: %[[THIS:.*]] = load %struct.ChildOverride*, %struct.ChildOverride** %[[THIS_ADDR]]
// CHECK: %[[THIS_PARAM:.*]] = bitcast %struct.ChildOverride* %[[THIS]] to i8*
// CHECK: call void @foo(i8* %[[THIS_PARAM]])
// CHECK: ret
}

void call_right_override(ChildOverride *child) {
// CHECK: define void @"\01?call_right_override
// CHECK-LABEL: define void @"\01?call_right_override
// CHECK: %[[CHILD:.*]] = load %struct.ChildOverride

child->right();
Expand All @@ -127,15 +130,17 @@ struct GrandchildOverride : ChildOverride {
};

void GrandchildOverride::right() {
// CHECK: define x86_thiscallcc void @"\01?right@GrandchildOverride@@UAEXXZ"(i8*
// CHECK-LABEL: define x86_thiscallcc void @"\01?right@GrandchildOverride@@UAEXXZ"(i8*
//
// CHECK: %[[THIS_ADDR:.*]] = alloca %struct.GrandchildOverride*, align 4
// CHECK: %[[THIS_i8:.*]] = getelementptr inbounds i8, i8* %[[ECX:.*]], i32 -4
// CHECK: %[[THIS:.*]] = bitcast i8* %[[THIS_i8]] to %struct.GrandchildOverride*
// CHECK: store %struct.GrandchildOverride* %[[THIS]], %struct.GrandchildOverride** %[[THIS_ADDR]], align 4
// CHECK: %[[THIS_INIT:.*]] = bitcast i8* %[[ECX:.*]] to %struct.GrandchildOverride*
// CHECK: store %struct.GrandchildOverride* %[[THIS_INIT]], %struct.GrandchildOverride** %[[THIS_ADDR]], align 4
// CHECK: %[[THIS_RELOAD:.*]] = load %struct.GrandchildOverride*, %struct.GrandchildOverride** %[[THIS_ADDR]]
// CHECK: %[[THIS_i8:.*]] = bitcast %struct.GrandchildOverride* %[[THIS_RELOAD]] to i8*
// CHECK: %[[THIS_ADJUSTED:.*]] = getelementptr inbounds i8, i8* %[[THIS_i8]], i32 -4
// CHECK: %[[THIS:.*]] = bitcast i8* %[[THIS_ADJUSTED]] to %struct.GrandchildOverride*

foo(this);
// CHECK: %[[THIS:.*]] = load %struct.GrandchildOverride*, %struct.GrandchildOverride** %[[THIS_ADDR]]
// CHECK: %[[THIS_PARAM:.*]] = bitcast %struct.GrandchildOverride* %[[THIS]] to i8*
// CHECK: call void @foo(i8* %[[THIS_PARAM]])
// CHECK: ret
Expand All @@ -148,19 +153,19 @@ void call_grandchild_right(GrandchildOverride *obj) {

void emit_ctors() {
Left l;
// CHECK: define {{.*}} @"\01??0Left@@QAE@XZ"
// CHECK-LABEL: define {{.*}} @"\01??0Left@@QAE@XZ"
// CHECK-NOT: getelementptr
// CHECK: store i32 (...)** bitcast ({ [1 x i8*] }* @"\01??_7Left@@6B@" to i32 (...)**)
// CHECK: ret

Right r;
// CHECK: define {{.*}} @"\01??0Right@@QAE@XZ"
// CHECK-LABEL: define {{.*}} @"\01??0Right@@QAE@XZ"
// CHECK-NOT: getelementptr
// CHECK: store i32 (...)** bitcast ({ [1 x i8*] }* @"\01??_7Right@@6B@" to i32 (...)**)
// CHECK: ret

ChildOverride co;
// CHECK: define {{.*}} @"\01??0ChildOverride@@QAE@XZ"
// CHECK-LABEL: define {{.*}} @"\01??0ChildOverride@@QAE@XZ"
// CHECK: %[[THIS:.*]] = load %struct.ChildOverride*, %struct.ChildOverride**
// CHECK: %[[VFPTR:.*]] = bitcast %struct.ChildOverride* %[[THIS]] to i32 (...)***
// CHECK: store i32 (...)** bitcast ({ [1 x i8*] }* @"\01??_7ChildOverride@@6BLeft@@@" to i32 (...)**), i32 (...)*** %[[VFPTR]]
Expand All @@ -171,7 +176,7 @@ void emit_ctors() {
// CHECK: ret

GrandchildOverride gc;
// CHECK: define {{.*}} @"\01??0GrandchildOverride@@QAE@XZ"
// CHECK-LABEL: define {{.*}} @"\01??0GrandchildOverride@@QAE@XZ"
// CHECK: %[[THIS:.*]] = load %struct.GrandchildOverride*, %struct.GrandchildOverride**
// CHECK: %[[VFPTR:.*]] = bitcast %struct.GrandchildOverride* %[[THIS]] to i32 (...)***
// CHECK: store i32 (...)** bitcast ({ [1 x i8*] }* @"\01??_7GrandchildOverride@@6BLeft@@@" to i32 (...)**), i32 (...)*** %[[VFPTR]]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ struct D : virtual C {
D::D() {} // Forces vftable emission.

// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01?f@D@@$4PPPPPPPM@A@AEXXZ"
// Note that the vtordisp is applied before really adjusting to D*.
// CHECK: %[[ECX:.*]] = load %struct.D*, %struct.D** %{{.*}}
// CHECK: %[[ECX_i8:.*]] = bitcast %struct.D* %[[ECX]] to i8*
// CHECK: %[[VTORDISP_PTR_i8:.*]] = getelementptr inbounds i8, i8* %[[ECX_i8]], i32 -4
Expand Down

0 comments on commit 06239e4

Please sign in to comment.