[llvm] [SPIRV] Emit intrinsics for globals only in function that references them (PR #178143)
Juan Manuel Martinez CaamaƱo via llvm-commits
llvm-commits at lists.llvm.org
Wed Jan 28 06:55:44 PST 2026
================
@@ -62,6 +62,83 @@ namespace llvm::SPIRV {
} // namespace llvm::SPIRV
namespace {
+// This class keeps track of which functions reference which global variables.
+class GlobalVariableReferences {
+ template <typename T1, typename T2>
+ using OneToManyMapTy = DenseMap<T1, SmallPtrSet<T2, 4>>;
+
+ OneToManyMapTy<GlobalVariable *, Function *> GlobalIsReferencedByFun;
+
+ void collectGlobalReferences(
+ GlobalVariable *GV,
+ OneToManyMapTy<GlobalVariable *, GlobalVariable *> &Global2Global,
+ OneToManyMapTy<GlobalVariable *, Function *> &Global2Function) {
+ SmallVector<Value *> Stack = {GV->user_begin(), GV->user_end()};
+ while (!Stack.empty()) {
+ Value *V = Stack.pop_back_val();
+
+ if (Instruction *I = dyn_cast<Instruction>(V)) {
+ Global2Function[GV].insert(I->getFunction());
+ continue;
+ }
+
+ if (GlobalVariable *UserGV = dyn_cast<GlobalVariable>(V)) {
+ Global2Global[GV].insert(UserGV);
+ continue;
+ }
+
+ if (Constant *C = dyn_cast<Constant>(V))
+ Stack.append(C->user_begin(), C->user_end());
+ }
+ }
+
+public:
+ void init(Module &M) {
+ // Collect which global variables are referenced by which global variables
+ // and which functions reference each global variables.
+ OneToManyMapTy<GlobalVariable *, GlobalVariable *>
+ GlobalIsReferencedByGlobal;
+ GlobalIsReferencedByFun.clear();
+ for (GlobalVariable &GV : M.globals())
+ collectGlobalReferences(&GV, GlobalIsReferencedByGlobal,
+ GlobalIsReferencedByFun);
+
+ // Compute indirect references by iterating until a fixed point is found.
+ bool Changed;
+ do {
+ Changed = false;
+ for (auto &[GV, ReferencedBy] : GlobalIsReferencedByGlobal) {
+ SmallVector<GlobalVariable *> OldReferencedBy(ReferencedBy.begin(),
----------------
jmmartinez wrote:
I declared `OldReferencedBy` outside of the loop and used `OldReferencedBy.assign(B,E)` in the loop.
https://github.com/llvm/llvm-project/pull/178143
More information about the llvm-commits
mailing list