1cf9956a3e9134159fb8e8c2676917f3df76e778
[oota-llvm.git] / lib / Target / WebAssembly / WebAssemblyRegColoring.cpp
1 //===-- WebAssemblyRegColoring.cpp - Register coloring --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements a virtual register coloring pass.
12 ///
13 /// WebAssembly doesn't have a fixed number of registers, but it is still
14 /// desirable to minimize the total number of registers used in each function.
15 ///
16 /// This code is modeled after lib/CodeGen/StackSlotColoring.cpp.
17 ///
18 //===----------------------------------------------------------------------===//
19
20 #include "WebAssembly.h"
21 #include "WebAssemblyMachineFunctionInfo.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
30 #define DEBUG_TYPE "wasm-reg-coloring"
31
32 namespace {
33 class WebAssemblyRegColoring final : public MachineFunctionPass {
34 public:
35   static char ID; // Pass identification, replacement for typeid
36   WebAssemblyRegColoring() : MachineFunctionPass(ID) {}
37
38   const char *getPassName() const override {
39     return "WebAssembly Register Coloring";
40   }
41
42   void getAnalysisUsage(AnalysisUsage &AU) const override {
43     AU.setPreservesCFG();
44     AU.addRequired<LiveIntervals>();
45     AU.addRequired<MachineBlockFrequencyInfo>();
46     AU.addPreserved<MachineBlockFrequencyInfo>();
47     AU.addPreservedID(MachineDominatorsID);
48     MachineFunctionPass::getAnalysisUsage(AU);
49   }
50
51   bool runOnMachineFunction(MachineFunction &MF) override;
52
53 private:
54 };
55 } // end anonymous namespace
56
57 char WebAssemblyRegColoring::ID = 0;
58 FunctionPass *llvm::createWebAssemblyRegColoring() {
59   return new WebAssemblyRegColoring();
60 }
61
62 // Compute the total spill weight for VReg.
63 static float computeWeight(const MachineRegisterInfo *MRI,
64                            const MachineBlockFrequencyInfo *MBFI,
65                            unsigned VReg) {
66   float weight = 0.0f;
67   for (MachineOperand &MO : MRI->reg_nodbg_operands(VReg))
68     weight += LiveIntervals::getSpillWeight(MO.isDef(), MO.isUse(), MBFI,
69                                             MO.getParent());
70   return weight;
71 }
72
73 bool WebAssemblyRegColoring::runOnMachineFunction(MachineFunction &MF) {
74   DEBUG({
75     dbgs() << "********** Register Coloring **********\n"
76            << "********** Function: " << MF.getName() << '\n';
77   });
78
79   // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual
80   // registers could be modified before the longjmp is executed, resulting in
81   // the wrong value being used afterwards. (See <rdar://problem/8007500>.)
82   // TODO: Does WebAssembly need to care about setjmp for register coloring?
83   if (MF.exposesReturnsTwice())
84     return false;
85
86   MachineRegisterInfo *MRI = &MF.getRegInfo();
87   LiveIntervals *Liveness = &getAnalysis<LiveIntervals>();
88   const MachineBlockFrequencyInfo *MBFI =
89       &getAnalysis<MachineBlockFrequencyInfo>();
90   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
91
92   // Gather all register intervals into a list and sort them.
93   unsigned NumVRegs = MRI->getNumVirtRegs();
94   SmallVector<LiveInterval *, 0> SortedIntervals;
95   SortedIntervals.reserve(NumVRegs);
96
97   DEBUG(dbgs() << "Interesting register intervals:\n");
98   for (unsigned i = 0; i < NumVRegs; ++i) {
99     unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
100     if (MFI.isVRegStackified(VReg))
101       continue;
102
103     LiveInterval *LI = &Liveness->getInterval(VReg);
104     assert(LI->weight == 0.0f);
105     LI->weight = computeWeight(MRI, MBFI, VReg);
106     DEBUG(LI->dump());
107     SortedIntervals.push_back(LI);
108   }
109   DEBUG(dbgs() << '\n');
110
111   // Sort them to put arguments first (since we don't want to rename live-in
112   // registers), by weight next, and then by position.
113   // TODO: Investigate more intelligent sorting heuristics. For starters, we
114   // should try to coalesce adjacent live intervals before non-adjacent ones.
115   std::sort(SortedIntervals.begin(), SortedIntervals.end(),
116             [MRI](LiveInterval *LHS, LiveInterval *RHS) {
117               if (MRI->isLiveIn(LHS->reg) != MRI->isLiveIn(RHS->reg))
118                 return MRI->isLiveIn(LHS->reg);
119               if (LHS->weight != RHS->weight)
120                 return LHS->weight > RHS->weight;
121               if (LHS->empty() || RHS->empty())
122                 return !LHS->empty() && RHS->empty();
123               return *LHS < *RHS;
124             });
125
126   DEBUG(dbgs() << "Coloring register intervals:\n");
127   SmallVector<unsigned, 16> SlotMapping(SortedIntervals.size(), -1u);
128   SmallVector<SmallVector<LiveInterval *, 4>, 16> Assignments(
129       SortedIntervals.size());
130   BitVector UsedColors(SortedIntervals.size());
131   bool Changed = false;
132   for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) {
133     LiveInterval *LI = SortedIntervals[i];
134     unsigned Old = LI->reg;
135     size_t Color = i;
136     const TargetRegisterClass *RC = MRI->getRegClass(Old);
137
138     // Check if it's possible to reuse any of the used colors.
139     if (!MRI->isLiveIn(Old))
140       for (int C(UsedColors.find_first()); C != -1;
141            C = UsedColors.find_next(C)) {
142         if (MRI->getRegClass(SortedIntervals[C]->reg) != RC)
143           continue;
144         for (LiveInterval *OtherLI : Assignments[C])
145           if (!OtherLI->empty() && OtherLI->overlaps(*LI))
146             goto continue_outer;
147         Color = C;
148         break;
149       continue_outer:;
150       }
151
152     unsigned New = SortedIntervals[Color]->reg;
153     SlotMapping[i] = New;
154     Changed |= Old != New;
155     UsedColors.set(Color);
156     Assignments[Color].push_back(LI);
157     DEBUG(dbgs() << "Assigning vreg"
158                  << TargetRegisterInfo::virtReg2Index(LI->reg) << " to vreg"
159                  << TargetRegisterInfo::virtReg2Index(New) << "\n");
160   }
161   if (!Changed)
162     return false;
163
164   // Rewrite register operands.
165   for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) {
166     unsigned Old = SortedIntervals[i]->reg;
167     unsigned New = SlotMapping[i];
168     if (Old != New)
169       MRI->replaceRegWith(Old, New);
170   }
171   return true;
172 }