Skip to content

[DirectX] Add GlobalDCE pass after finalize linkage pass in DirectX backend #151071

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions llvm/include/llvm/InitializePasses.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ LLVM_ABI void initializeGCEmptyBasicBlocksPass(PassRegistry &);
LLVM_ABI void initializeGCMachineCodeAnalysisPass(PassRegistry &);
LLVM_ABI void initializeGCModuleInfoPass(PassRegistry &);
LLVM_ABI void initializeGVNLegacyPassPass(PassRegistry &);
LLVM_ABI void initializeGlobalDCELegacyPassPass(PassRegistry &);
LLVM_ABI void initializeGlobalMergeFuncPassWrapperPass(PassRegistry &);
LLVM_ABI void initializeGlobalMergePass(PassRegistry &);
LLVM_ABI void initializeGlobalsAAWrapperPassPass(PassRegistry &);
Expand Down
2 changes: 2 additions & 0 deletions llvm/include/llvm/LinkAllPasses.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
#include "llvm/Support/Valgrind.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/GlobalDCE.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/ObjCARC.h"
#include "llvm/Transforms/Scalar.h"
Expand Down Expand Up @@ -83,6 +84,7 @@ struct ForcePassLinking {
(void)llvm::createDomOnlyViewerWrapperPassPass();
(void)llvm::createDomViewerWrapperPassPass();
(void)llvm::createAlwaysInlinerLegacyPass();
(void)llvm::createGlobalDCEPass();
(void)llvm::createGlobalMergeFuncPass();
(void)llvm::createGlobalsAAWrapperPass();
(void)llvm::createInstSimplifyLegacyPass();
Expand Down
2 changes: 2 additions & 0 deletions llvm/include/llvm/Transforms/IPO/GlobalDCE.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class GlobalVariable;
class Metadata;
class Module;
class Value;
class ModulePass;

/// Pass to remove unused function declarations.
class GlobalDCEPass : public PassInfoMixin<GlobalDCEPass> {
Expand Down Expand Up @@ -80,6 +81,7 @@ class GlobalDCEPass : public PassInfoMixin<GlobalDCEPass> {
void ComputeDependencies(Value *V, SmallPtrSetImpl<GlobalValue *> &U);
};

ModulePass *createGlobalDCEPass();
}

#endif // LLVM_TRANSFORMS_IPO_GLOBALDCE_H
1 change: 1 addition & 0 deletions llvm/lib/Target/DirectX/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ add_llvm_target(DirectXCodeGen
DirectXInfo
DirectXPointerTypeAnalysis
FrontendHLSL
IPO
MC
ScalarOpts
SelectionDAG
Expand Down
8 changes: 4 additions & 4 deletions llvm/lib/Target/DirectX/DXILFinalizeLinkage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ using namespace llvm;
static bool finalizeLinkage(Module &M) {
bool MadeChange = false;

// Convert private global variables to internal linkage.
for (GlobalVariable &GV : M.globals()) {
if (GV.hasPrivateLinkage()) {
// Convert private globals and external globals with no usage to internal
// linkage.
for (GlobalVariable &GV : M.globals())
if (GV.hasPrivateLinkage() || (GV.hasExternalLinkage() && GV.use_empty())) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For anyone else looking this is the crux of the change right here. GlobalDCE is conservative so it won't remove globals marked external. This is because Linker would handle these globals and usually something like the internalizer pass would run and do a similar conversion to what we are doing here.

In HLSL's case after finalize linkage we should be able to assume that it is safe to mark all external globals with no uses as internal. If we then run GlobalDCE after this these globals will get cleaned up.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're just concerned with deleting unused external variables... we could do that as part of DXILFinalizeLinkage instead of running GlobalDCE in the backend.

Are there other cases that GlobalDCE catches that we need to catch late?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Justin suggested we not do special casing of global_ctors and that GlobalDCE was a more complete solution. Hence why we closed the previous attempt at fixing this issue.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to special case global constructors for library shaders. That's not optional.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we use GlobalDCE we don't need to special case, things just work by converting to internal.

GV.setLinkage(GlobalValue::InternalLinkage);
MadeChange = true;
}
}

SmallVector<Function *> Funcs;

Expand Down
1 change: 1 addition & 0 deletions llvm/lib/Target/DirectX/DirectXPassRegistry.def
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ MODULE_ANALYSIS("dxil-root-signature-analysis", dxil::RootSignatureAnalysis())
#define MODULE_PASS(NAME, CREATE_PASS)
#endif
MODULE_PASS("dxil-cbuffer-access", DXILCBufferAccess())
MODULE_PASS("dxil-finalize-linkage", DXILFinalizeLinkage())
MODULE_PASS("dxil-data-scalarization", DXILDataScalarization())
MODULE_PASS("dxil-flatten-arrays", DXILFlattenArrays())
MODULE_PASS("dxil-intrinsic-expansion", DXILIntrinsicExpansion())
Expand Down
4 changes: 4 additions & 0 deletions llvm/lib/Target/DirectX/DirectXTargetMachine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include "DirectXTargetMachine.h"
#include "DXILCBufferAccess.h"
#include "DXILDataScalarization.h"
#include "DXILFinalizeLinkage.h"
#include "DXILFlattenArrays.h"
#include "DXILForwardHandleAccesses.h"
#include "DXILIntrinsicExpansion.h"
Expand Down Expand Up @@ -45,6 +46,7 @@
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Transforms/IPO/GlobalDCE.h"
#include "llvm/Transforms/Scalar/Scalarizer.h"
#include <optional>

Expand All @@ -62,6 +64,7 @@ extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeDirectXTarget() {
initializeEmbedDXILPassPass(*PR);
initializeWriteDXILPassPass(*PR);
initializeDXContainerGlobalsPass(*PR);
initializeGlobalDCELegacyPassPass(*PR);
initializeDXILOpLoweringLegacyPass(*PR);
initializeDXILResourceAccessLegacyPass(*PR);
initializeDXILResourceImplicitBindingLegacyPass(*PR);
Expand Down Expand Up @@ -103,6 +106,7 @@ class DirectXPassConfig : public TargetPassConfig {
FunctionPass *createTargetRegisterAllocator(bool) override { return nullptr; }
void addCodeGenPrepare() override {
addPass(createDXILFinalizeLinkageLegacyPass());
addPass(createGlobalDCEPass());
addPass(createDXILResourceAccessLegacyPass());
addPass(createDXILIntrinsicExpansionLegacyPass());
addPass(createDXILCBufferAccessLegacyPass());
Expand Down
32 changes: 32 additions & 0 deletions llvm/lib/Transforms/IPO/GlobalDCE.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/CtorUtils.h"
Expand All @@ -30,6 +32,36 @@ using namespace llvm;

#define DEBUG_TYPE "globaldce"

namespace {
class GlobalDCELegacyPass : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
GlobalDCELegacyPass() : ModulePass(ID) {
initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override {
if (skipModule(M))
return false;
// Note: GlobalDCEPass does not use MAM. That
// means we can get away with init and pass
// as arg.
ModuleAnalysisManager MAM;
auto PA = Impl.run(M, MAM);
return !PA.areAllPreserved();
}

private:
GlobalDCEPass Impl;
};
} // namespace

char GlobalDCELegacyPass::ID = 0;
INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", "Dead Global Elimination",
false, false)

// Public interface to the GlobalDCEPass.
ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCELegacyPass(); }

static cl::opt<bool>
ClEnableVFE("enable-vfe", cl::Hidden, cl::init(true),
cl::desc("Enable virtual function elimination"));
Expand Down
22 changes: 20 additions & 2 deletions llvm/test/CodeGen/DirectX/finalize_linkage.ll
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
; RUN: opt -S -dxil-finalize-linkage -mtriple=dxil-unknown-shadermodel6.5-compute %s | FileCheck %s
; RUN: opt -S -passes='dxil-finalize-linkage,globaldce' -mtriple=dxil-unknown-shadermodel6.5-compute %s | FileCheck %s
; RUN: llc %s --filetype=asm -o - | FileCheck %s --check-prefixes=CHECK-LLC

target triple = "dxilv1.5-pc-shadermodel6.5-compute"

; DXILFinalizeLinkage changes linkage of all functions that are hidden to
; internal, and converts private global variables to internal linkage.
; internal, converts private global variables to internal linkage, and removes
; unused global variables.

; CHECK-NOT: @aTile
@aTile = hidden addrspace(3) global [4 x [1 x i32]] zeroinitializer, align 4

; CHECK-NOT: @bTile
@bTile = hidden addrspace(3) global [1 x <1 x i32>] zeroinitializer, align 4

; CHECK: @switch.table = internal unnamed_addr constant [4 x i32]
@switch.table = private unnamed_addr constant [4 x i32] [i32 1, i32 257, i32 65793, i32 16843009], align 4
Expand All @@ -27,6 +34,17 @@ target triple = "dxilv1.5-pc-shadermodel6.5-compute"
; CHECK: @hidden_var = hidden global i32
@hidden_var = hidden global i32 1, align 4

define void @anchor_function() #0 {
entry:
%0 = load i32, ptr @switch.table, align 4
%1 = load [3 x float], ptr @private_array, align 4
%2 = load i32, ptr @private_var, align 4
%3 = load i32, ptr @internal_var, align 4
%4 = load i32, ptr @external_var, align 4
%5 = load i32, ptr @hidden_var, align 4
ret void
}

; CHECK-NOT: define internal void @"?f1@@YAXXZ"()
define void @"?f1@@YAXXZ"() #0 {
entry:
Expand Down
1 change: 1 addition & 0 deletions llvm/test/CodeGen/DirectX/llc-pipeline.ll
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

; CHECK-NEXT: ModulePass Manager
; CHECK-NEXT: DXIL Finalize Linkage
; CHECK-NEXT: Dead Global Elimination
; CHECK-NEXT: FunctionPass Manager
; CHECK-NEXT: DXIL Resource Access
; CHECK-NEXT: DXIL Intrinsic Expansion
Expand Down
2 changes: 1 addition & 1 deletion llvm/test/CodeGen/DirectX/scalar-data.ll
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
; RUN: llc %s -mtriple=dxil-pc-shadermodel6.3-library --filetype=asm -o - | FileCheck %s
; RUN: opt -S -passes='dxil-data-scalarization,dxil-flatten-arrays' -mtriple=dxil-unknown-shadermodel6.5-compute %s | FileCheck %s

; Make sure we don't touch arrays without vectors and that can recurse and flatten multiple-dimension arrays of vectors

Expand Down
1 change: 1 addition & 0 deletions llvm/test/tools/dxil-dis/opaque-value_as_metadata.ll
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ target triple = "dxil-unknown-shadermodel6.7-library"
@CBV = external constant %"$Globals"

define void @main() #0 {
%1 = load float, ptr @CBV, align 4
ret void
}

Expand Down