Joos1W Compiler Framework
All Classes Functions Typedefs Pages
GlobalDCE.cc
1 #include "../IRContextPass.h"
2 #include "tir/Constant.h"
3 #include "utils/PassManager.h"
4 
5 using std::string_view;
6 using utils::Pass;
7 using utils::PassManager;
8 
9 class GlobalDCE final : public Pass {
10 public:
11  GlobalDCE(PassManager& PM) noexcept : Pass(PM) {}
12  void Run() override {
13  tir::CompilationUnit& CU = GetPass<IRContextPass>().CU();
14  bool changed;
15  do {
16  changed = removeAllGlobals(CU);
17  } while(changed);
18  }
19  string_view Name() const override { return "globaldce"; }
20  string_view Desc() const override { return "Global Dead Code Elimination"; }
21 
22 private:
23  bool removeAllGlobals(tir::CompilationUnit& CU) {
24  std::vector<std::string> toRemove;
25  for(auto p : CU.global_objects_kv()) {
26  auto [name, go] = p;
27  if(go->isExternalLinkage()) continue;
28  if(!go->users().empty()) continue;
29  // Destroy the global object
30  if(auto fn = dyn_cast<tir::Function>(go)) {
31  for(auto bb : fn->body()) {
32  auto* inst = *bb->begin();
33  while(inst) {
34  auto next = inst->next();
35  inst->eraseFromParent();
36  inst = next;
37  }
38  }
39  }
40  toRemove.push_back(std::string{name});
41  }
42  for(auto name : toRemove) {
43  CU.removeGlobalObject(name);
44  }
45  return toRemove.size() > 0;
46  }
47 
48 private:
49  void computeDependencies() override {
50  ComputeDependency(GetPass<IRContextPass>());
51  }
52 };
53 
54 REGISTER_PASS(GlobalDCE);