LLVM 24.0.0git
WebAssemblyRegColoring.cpp
Go to the documentation of this file.
1//===-- WebAssemblyRegColoring.cpp - Register coloring --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a virtual register coloring pass.
11///
12/// WebAssembly doesn't have a fixed number of registers, but it is still
13/// desirable to minimize the total number of registers used in each function.
14///
15/// This code is modeled after lib/CodeGen/StackSlotColoring.cpp.
16///
17//===----------------------------------------------------------------------===//
18
19#include "WebAssembly.h"
26#include "llvm/CodeGen/Passes.h"
28#include "llvm/IR/Analysis.h"
29#include "llvm/Support/Debug.h"
31using namespace llvm;
32
33#define DEBUG_TYPE "wasm-reg-coloring"
34
35namespace {
36class WebAssemblyRegColoringLegacy final : public MachineFunctionPass {
37public:
38 static char ID; // Pass identification, replacement for typeid
39 WebAssemblyRegColoringLegacy() : MachineFunctionPass(ID) {}
40
41 StringRef getPassName() const override {
42 return "WebAssembly Register Coloring";
43 }
44
45 void getAnalysisUsage(AnalysisUsage &AU) const override {
46 AU.setPreservesCFG();
52 }
53
54 bool runOnMachineFunction(MachineFunction &MF) override;
55};
56} // end anonymous namespace
57
58char WebAssemblyRegColoringLegacy::ID = 0;
59INITIALIZE_PASS(WebAssemblyRegColoringLegacy, DEBUG_TYPE,
60 "Minimize number of registers used", false, false)
61
63 return new WebAssemblyRegColoringLegacy();
64}
65
66// Compute the total spill weight for VReg.
67static float computeWeight(const MachineRegisterInfo *MRI,
68 const MachineBlockFrequencyInfo *MBFI,
69 unsigned VReg) {
70 float Weight = 0.0f;
71 for (MachineOperand &MO : MRI->reg_nodbg_operands(VReg))
72 Weight += LiveIntervals::getSpillWeight(MO.isDef(), MO.isUse(), MBFI,
73 *MO.getParent());
74 return Weight;
75}
76
77// Create a map of "Register -> vector of <SlotIndex, DBG_VALUE>".
78// The SlotIndex is the slot index of the next non-debug instruction or the end
79// of a BB, because DBG_VALUE's don't have slot index themselves.
80// Adapted from RegisterCoalescer::buildVRegToDbgValueMap.
84 DbgVRegToValues;
85 const SlotIndexes *Slots = Liveness->getSlotIndexes();
87
88 // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
89 // map.
90 auto CloseNewDVRange = [&DbgVRegToValues, &ToInsert](SlotIndex Slot) {
91 for (auto *X : ToInsert) {
92 for (const auto &Op : X->debug_operands()) {
93 if (Op.isReg() && Op.getReg().isVirtual())
94 DbgVRegToValues[Op.getReg()].push_back({Slot, X});
95 }
96 }
97
98 ToInsert.clear();
99 };
100
101 // Iterate over all instructions, collecting them into the ToInsert vector.
102 // Once a non-debug instruction is found, record the slot index of the
103 // collected DBG_VALUEs.
104 for (auto &MBB : MF) {
105 SlotIndex CurrentSlot = Slots->getMBBStartIdx(&MBB);
106
107 for (auto &MI : MBB) {
108 if (MI.isDebugValue()) {
109 if (any_of(MI.debug_operands(), [](const MachineOperand &MO) {
110 return MO.isReg() && MO.getReg().isVirtual();
111 }))
112 ToInsert.push_back(&MI);
113 } else if (!MI.isDebugOrPseudoInstr()) {
114 CurrentSlot = Slots->getInstructionIndex(MI);
115 CloseNewDVRange(CurrentSlot);
116 }
117 }
118
119 // Close range of DBG_VALUEs at the end of blocks.
120 CloseNewDVRange(Slots->getMBBEndIdx(&MBB));
121 }
122
123 // Sort all DBG_VALUEs we've seen by slot number.
124 for (auto &Pair : DbgVRegToValues)
125 llvm::sort(Pair.second);
126 return DbgVRegToValues;
127}
128
129// After register coalescing, some DBG_VALUEs will be invalid. Set them undef.
130// This function has to run before the actual coalescing, i.e., the register
131// changes.
133 const LiveIntervals *Liveness,
135 DenseMap<Register, std::vector<std::pair<SlotIndex, MachineInstr *>>>
136 &DbgVRegToValues) {
137#ifndef NDEBUG
138 DenseSet<Register> SeenRegs;
139#endif
140 for (const auto &CoalescedIntervals : Assignments) {
141 if (CoalescedIntervals.empty())
142 continue;
143 for (LiveInterval *LI : CoalescedIntervals) {
144 Register Reg = LI->reg();
145#ifndef NDEBUG
146 // Ensure we don't process the same register twice
147 assert(SeenRegs.insert(Reg).second);
148#endif
149 auto RegMapIt = DbgVRegToValues.find(Reg);
150 if (RegMapIt == DbgVRegToValues.end())
151 continue;
152 SlotIndex LastSlot;
153 bool LastUndefResult = false;
154 for (auto [Slot, DbgValue] : RegMapIt->second) {
155 // All consecutive DBG_VALUEs have the same slot because the slot
156 // indices they have is the one for the first non-debug instruction
157 // after it, because DBG_VALUEs don't have slot index themselves. Before
158 // doing live range queries, quickly check if the current DBG_VALUE has
159 // the same slot index as the previous one, in which case we should do
160 // the same. Note that RegMapIt->second, the vector of {SlotIndex,
161 // DBG_VALUE}, is sorted by SlotIndex, which is necessary for this
162 // check.
163 if (Slot == LastSlot) {
164 if (LastUndefResult) {
165 LLVM_DEBUG(dbgs() << "Undefed: " << *DbgValue << "\n");
166 DbgValue->setDebugValueUndef();
167 }
168 continue;
169 }
170 LastSlot = Slot;
171 LastUndefResult = false;
172 for (LiveInterval *OtherLI : CoalescedIntervals) {
173 if (LI == OtherLI)
174 continue;
175
176 // This DBG_VALUE has 'Reg' (the current LiveInterval's register) as
177 // its operand. If this DBG_VALUE's slot index is within other
178 // registers' live ranges, this DBG_VALUE should be undefed. For
179 // example, suppose %0 and %1 are to be coalesced into %0.
180 // ; %0's live range starts
181 // %0 = value_0
182 // DBG_VALUE %0, !"a", ... (a)
183 // DBG_VALUE %1, !"b", ... (b)
184 // use %0
185 // ; %0's live range ends
186 // ...
187 // ; %1's live range starts
188 // %1 = value_1
189 // DBG_VALUE %0, !"c", ... (c)
190 // DBG_VALUE %1, !"d", ... (d)
191 // use %1
192 // ; %1's live range ends
193 //
194 // In this code, (b) and (c) should be set to undef. After the two
195 // registers are coalesced, (b) will incorrectly say the variable
196 // "b"'s value is 'value_0', and (c) will also incorrectly say the
197 // variable "c"'s value is value_1. Note it doesn't actually matter
198 // which register they are coalesced into (%0 or %1); (b) and (c)
199 // should be set to undef as well if they are coalesced into %1.
200 //
201 // This happens DBG_VALUEs are not included when computing live
202 // ranges.
203 //
204 // Note that it is not possible for this DBG_VALUE to be
205 // simultaneously within 'Reg''s live range and one of other coalesced
206 // registers' live ranges because if their live ranges overlapped they
207 // would have not been selected as a coalescing candidate in the first
208 // place.
209 auto *SegmentIt = OtherLI->find(Slot);
210 if (SegmentIt != OtherLI->end() && SegmentIt->contains(Slot)) {
211 LLVM_DEBUG(dbgs() << "Undefed: " << *DbgValue << "\n");
212 DbgValue->setDebugValueUndef();
213 LastUndefResult = true;
214 break;
215 }
216 }
217 }
218 }
219 }
220}
221
222static bool regColoring(MachineFunction &MF, LiveIntervals *Liveness,
223 const MachineBlockFrequencyInfo *MBFI) {
224 LLVM_DEBUG({
225 dbgs() << "********** Register Coloring **********\n"
226 << "********** Function: " << MF.getName() << '\n';
227 });
228
229 MachineRegisterInfo *MRI = &MF.getRegInfo();
231
232 // We don't preserve SSA form.
233 MRI->leaveSSA();
234
235 // Gather all register intervals into a list and sort them.
236 unsigned NumVRegs = MRI->getNumVirtRegs();
237 SmallVector<LiveInterval *, 0> SortedIntervals;
238 SortedIntervals.reserve(NumVRegs);
239
240 // Record DBG_VALUEs and their SlotIndexes.
241 auto DbgVRegToValues = buildVRegToDbgValueMap(MF, Liveness);
242
243 LLVM_DEBUG(dbgs() << "Interesting register intervals:\n");
244 for (unsigned I = 0; I < NumVRegs; ++I) {
246 if (MFI.isVRegStackified(VReg))
247 continue;
248 // Skip unused registers, which can use $drop.
249 if (MRI->use_empty(VReg))
250 continue;
251
252 LiveInterval *LI = &Liveness->getInterval(VReg);
253 assert(LI->weight() == 0.0f);
254 LI->setWeight(computeWeight(MRI, MBFI, VReg));
255 LLVM_DEBUG(LI->dump());
256 SortedIntervals.push_back(LI);
257 }
258 LLVM_DEBUG(dbgs() << '\n');
259
260 // Sort them to put arguments first (since we don't want to rename live-in
261 // registers), by weight next, and then by position.
262 // TODO: Investigate more intelligent sorting heuristics. For starters, we
263 // should try to coalesce adjacent live intervals before non-adjacent ones.
264 llvm::sort(SortedIntervals, [MRI](LiveInterval *LHS, LiveInterval *RHS) {
265 if (MRI->isLiveIn(LHS->reg()) != MRI->isLiveIn(RHS->reg()))
266 return MRI->isLiveIn(LHS->reg());
267 if (LHS->weight() != RHS->weight())
268 return LHS->weight() > RHS->weight();
269 if (LHS->empty() || RHS->empty())
270 return !LHS->empty() && RHS->empty();
271 return *LHS < *RHS;
272 });
273
274 LLVM_DEBUG(dbgs() << "Coloring register intervals:\n");
275 SmallVector<unsigned, 16> SlotMapping(SortedIntervals.size(), -1u);
277 SortedIntervals.size());
278 BitVector UsedColors(SortedIntervals.size());
279 bool Changed = false;
280 for (size_t I = 0, E = SortedIntervals.size(); I < E; ++I) {
281 LiveInterval *LI = SortedIntervals[I];
282 Register Old = LI->reg();
283 size_t Color = I;
284 const TargetRegisterClass *RC = MRI->getRegClass(Old);
285
286 // Check if it's possible to reuse any of the used colors.
287 if (!MRI->isLiveIn(Old))
288 for (unsigned C : UsedColors.set_bits()) {
289 if (MRI->getRegClass(SortedIntervals[C]->reg()) != RC)
290 continue;
291 for (LiveInterval *OtherLI : Assignments[C])
292 if (!OtherLI->empty() && OtherLI->overlaps(*LI))
293 goto continue_outer;
294 Color = C;
295 break;
296 continue_outer:;
297 }
298
299 Register New = SortedIntervals[Color]->reg();
300 SlotMapping[I] = New;
301 Changed |= Old != New;
302 UsedColors.set(Color);
303 Assignments[Color].push_back(LI);
304 // If we reassigned the stack pointer, update the debug frame base info.
305 if (Old != New && MFI.isFrameBaseVirtual() && MFI.getFrameBaseVreg() == Old)
306 MFI.setFrameBaseVreg(New);
307 LLVM_DEBUG(dbgs() << "Assigning vreg " << printReg(LI->reg()) << " to vreg "
308 << printReg(New) << "\n");
309 }
310 if (!Changed)
311 return false;
312
313 // Set DBG_VALUEs that will be invalid after coalescing to undef.
314 undefInvalidDbgValues(Liveness, Assignments, DbgVRegToValues);
315
316 // Rewrite register operands.
317 for (size_t I = 0, E = SortedIntervals.size(); I < E; ++I) {
318 Register Old = SortedIntervals[I]->reg();
319 unsigned New = SlotMapping[I];
320 if (Old != New)
321 MRI->replaceRegWith(Old, New);
322 }
323 return true;
324}
325
326bool WebAssemblyRegColoringLegacy::runOnMachineFunction(MachineFunction &MF) {
327 // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual
328 // registers could be modified before the longjmp is executed, resulting in
329 // the wrong value being used afterwards.
330 // TODO: Does WebAssembly need to care about setjmp for register coloring?
331 if (MF.exposesReturnsTwice())
332 return false;
333
334 LiveIntervals *Liveness = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
335 const MachineBlockFrequencyInfo *MBFI =
336 &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
337 return regColoring(MF, Liveness, MBFI);
338}
339
340PreservedAnalyses
343 // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual
344 // registers could be modified before the longjmp is executed, resulting in
345 // the wrong value being used afterwards.
346 // TODO: Does WebAssembly need to care about setjmp for register coloring?
347 if (MF.exposesReturnsTwice())
348 return PreservedAnalyses::all();
349
350 LiveIntervals *Liveness = &MFAM.getResult<LiveIntervalsAnalysis>(MF);
351 const MachineBlockFrequencyInfo *MBFI =
353 return regColoring(MF, Liveness, MBFI)
357}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file declares WebAssembly-specific per-machine-function information.
static bool regColoring(MachineFunction &MF, LiveIntervals *Liveness, const MachineBlockFrequencyInfo *MBFI)
static void undefInvalidDbgValues(const LiveIntervals *Liveness, ArrayRef< SmallVector< LiveInterval *, 4 > > Assignments, DenseMap< Register, std::vector< std::pair< SlotIndex, MachineInstr * > > > &DbgVRegToValues)
static DenseMap< Register, std::vector< std::pair< SlotIndex, MachineInstr * > > > buildVRegToDbgValueMap(MachineFunction &MF, const LiveIntervals *Liveness)
static float computeWeight(const MachineRegisterInfo *MRI, const MachineBlockFrequencyInfo *MBFI, unsigned VReg)
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
Value * RHS
Value * LHS
Class recording the (high level) value of a variable.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LiveInterval - This class represents the liveness of a register, or stack slot.
float weight() const
Register reg() const
LLVM_ABI void dump() const
void setWeight(float Value)
SlotIndexes * getSlotIndexes() const
static LLVM_ABI float getSpillWeight(bool isDef, bool isUse, const MachineBlockFrequencyInfo *MBFI, const MachineInstr &MI, ProfileSummaryInfo *PSI=nullptr)
Calculate the spill weight to assign to a single instruction.
LiveInterval & getInterval(Register Reg)
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(Register Reg) const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndexes pass.
SlotIndex getMBBEndIdx(unsigned Num) const
Returns the index past the last valid index in the given basic block.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
Changed
Pass manager infrastructure for declaring and invalidating analyses.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionPass * createWebAssemblyRegColoringLegacyPass()
DWARFExpression::Operation Op
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32