1 //===-- WebAssemblyRegColoring.cpp - Register coloring --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements a virtual register coloring pass.
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.
16 /// This code is modeled after lib/CodeGen/StackSlotColoring.cpp.
18 //===----------------------------------------------------------------------===//
20 #include "WebAssembly.h"
21 #include "WebAssemblyMachineFunctionInfo.h"
22 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
31 #define DEBUG_TYPE "wasm-reg-coloring"
34 class WebAssemblyRegColoring final : public MachineFunctionPass {
36 static char ID; // Pass identification, replacement for typeid
37 WebAssemblyRegColoring() : MachineFunctionPass(ID) {}
39 const char *getPassName() const override {
40 return "WebAssembly Register Coloring";
43 void getAnalysisUsage(AnalysisUsage &AU) const override {
45 AU.addRequired<LiveIntervals>();
46 AU.addRequired<MachineBlockFrequencyInfo>();
47 AU.addPreserved<MachineBlockFrequencyInfo>();
48 AU.addPreservedID(MachineDominatorsID);
49 AU.addRequired<SlotIndexes>(); // for ARGUMENT fixups
50 MachineFunctionPass::getAnalysisUsage(AU);
53 bool runOnMachineFunction(MachineFunction &MF) override;
57 } // end anonymous namespace
59 char WebAssemblyRegColoring::ID = 0;
60 FunctionPass *llvm::createWebAssemblyRegColoring() {
61 return new WebAssemblyRegColoring();
64 // Compute the total spill weight for VReg.
65 static float computeWeight(const MachineRegisterInfo *MRI,
66 const MachineBlockFrequencyInfo *MBFI,
69 for (MachineOperand &MO : MRI->reg_nodbg_operands(VReg))
70 weight += LiveIntervals::getSpillWeight(MO.isDef(), MO.isUse(), MBFI,
75 bool WebAssemblyRegColoring::runOnMachineFunction(MachineFunction &MF) {
77 dbgs() << "********** Register Coloring **********\n"
78 << "********** Function: " << MF.getName() << '\n';
81 // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual
82 // registers could be modified before the longjmp is executed, resulting in
83 // the wrong value being used afterwards. (See <rdar://problem/8007500>.)
84 // TODO: Does WebAssembly need to care about setjmp for register coloring?
85 if (MF.exposesReturnsTwice())
88 MachineRegisterInfo *MRI = &MF.getRegInfo();
89 LiveIntervals *Liveness = &getAnalysis<LiveIntervals>();
90 const MachineBlockFrequencyInfo *MBFI =
91 &getAnalysis<MachineBlockFrequencyInfo>();
92 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
94 // Gather all register intervals into a list and sort them.
95 unsigned NumVRegs = MRI->getNumVirtRegs();
96 SmallVector<LiveInterval *, 0> SortedIntervals;
97 SortedIntervals.reserve(NumVRegs);
99 // FIXME: If scheduling has moved an ARGUMENT virtual register, move it back,
100 // and recompute liveness. This is a temporary hack.
101 bool SawNonArg = false;
102 bool MovedArg = false;
103 MachineBasicBlock &EntryMBB = MF.front();
104 for (auto MII = EntryMBB.begin(); MII != EntryMBB.end(); ) {
105 MachineInstr *MI = &*MII++;
106 if (MI->getOpcode() == WebAssembly::ARGUMENT_I32 ||
107 MI->getOpcode() == WebAssembly::ARGUMENT_I64 ||
108 MI->getOpcode() == WebAssembly::ARGUMENT_F32 ||
109 MI->getOpcode() == WebAssembly::ARGUMENT_F64) {
110 EntryMBB.insert(EntryMBB.begin(), MI->removeFromParent());
118 SlotIndexes &Slots = getAnalysis<SlotIndexes>();
119 Liveness->releaseMemory();
120 Slots.releaseMemory();
121 Slots.runOnMachineFunction(MF);
122 Liveness->runOnMachineFunction(MF);
125 DEBUG(dbgs() << "Interesting register intervals:\n");
126 for (unsigned i = 0; i < NumVRegs; ++i) {
127 unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
128 if (MFI.isVRegStackified(VReg))
131 LiveInterval *LI = &Liveness->getInterval(VReg);
132 assert(LI->weight == 0.0f);
133 LI->weight = computeWeight(MRI, MBFI, VReg);
135 SortedIntervals.push_back(LI);
137 DEBUG(dbgs() << '\n');
139 // Sort them to put arguments first (since we don't want to rename live-in
140 // registers), by weight next, and then by position.
141 // TODO: Investigate more intelligent sorting heuristics. For starters, we
142 // should try to coalesce adjacent live intervals before non-adjacent ones.
143 std::sort(SortedIntervals.begin(), SortedIntervals.end(),
144 [MRI](LiveInterval *LHS, LiveInterval *RHS) {
145 if (MRI->isLiveIn(LHS->reg) != MRI->isLiveIn(RHS->reg))
146 return MRI->isLiveIn(LHS->reg);
147 if (LHS->weight != RHS->weight)
148 return LHS->weight > RHS->weight;
149 if (LHS->empty() || RHS->empty())
150 return !LHS->empty() && RHS->empty();
154 DEBUG(dbgs() << "Coloring register intervals:\n");
155 SmallVector<unsigned, 16> SlotMapping(SortedIntervals.size(), -1u);
156 SmallVector<SmallVector<LiveInterval *, 4>, 16> Assignments(
157 SortedIntervals.size());
158 BitVector UsedColors(SortedIntervals.size());
159 bool Changed = false;
160 for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) {
161 LiveInterval *LI = SortedIntervals[i];
162 unsigned Old = LI->reg;
164 const TargetRegisterClass *RC = MRI->getRegClass(Old);
166 // Check if it's possible to reuse any of the used colors.
167 if (!MRI->isLiveIn(Old))
168 for (int C(UsedColors.find_first()); C != -1;
169 C = UsedColors.find_next(C)) {
170 if (MRI->getRegClass(SortedIntervals[C]->reg) != RC)
172 for (LiveInterval *OtherLI : Assignments[C])
173 if (!OtherLI->empty() && OtherLI->overlaps(*LI))
180 unsigned New = SortedIntervals[Color]->reg;
181 SlotMapping[i] = New;
182 Changed |= Old != New;
183 UsedColors.set(Color);
184 Assignments[Color].push_back(LI);
185 DEBUG(dbgs() << "Assigning vreg"
186 << TargetRegisterInfo::virtReg2Index(LI->reg) << " to vreg"
187 << TargetRegisterInfo::virtReg2Index(New) << "\n");
192 // Rewrite register operands.
193 for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) {
194 unsigned Old = SortedIntervals[i]->reg;
195 unsigned New = SlotMapping[i];
197 MRI->replaceRegWith(Old, New);