[llvm] [SPIRV] Emit intrinsics for globals only in function that references them (PR #178143)
Manuel Carrasco via llvm-commits
llvm-commits at lists.llvm.org
Tue Jan 27 08:57:36 PST 2026
Juan Manuel Martinez =?utf-8?q?Caamaño?=,
Juan Manuel Martinez =?utf-8?q?Caamaño?Message-ID:
In-Reply-To: <llvm.org/llvm/llvm-project/pull/178143 at github.com>
================
@@ -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(),
+ ReferencedBy.end());
+ for (GlobalVariable *ReferencedGV : OldReferencedBy) {
+ auto It = GlobalIsReferencedByGlobal.find(ReferencedGV);
+ if (It == GlobalIsReferencedByGlobal.end())
+ continue;
+ Changed |= set_union(ReferencedBy, It->second);
+ }
+ }
+ } while (Changed);
+
+ for (auto &[GV, ReferencedBy] : GlobalIsReferencedByGlobal) {
----------------
mgcarrasco wrote:
Just to understand better, why no fixed point in this case?
https://github.com/llvm/llvm-project/pull/178143
More information about the llvm-commits
mailing list