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();
50 }
51
52 bool runOnMachineFunction(MachineFunction &MF) override;
53};
54} // end anonymous namespace
55
56char WebAssemblyRegColoringLegacy::ID = 0;
57INITIALIZE_PASS(WebAssemblyRegColoringLegacy, DEBUG_TYPE,
58 "Minimize number of registers used", false, false)
59
61 return new WebAssemblyRegColoringLegacy();
62}
63
64// Compute the total spill weight for VReg.
65static float computeWeight(const MachineRegisterInfo *MRI,
66 const MachineBlockFrequencyInfo *MBFI,
67 unsigned VReg) {
68 float Weight = 0.0f;
69 for (MachineOperand &MO : MRI->reg_nodbg_operands(VReg))
70 Weight += LiveIntervals::getSpillWeight(MO.isDef(), MO.isUse(), MBFI,
71 *MO.getParent());
72 return Weight;
73}
74
75// Create a map of "Register -> vector of <SlotIndex, DBG_VALUE>".
76// The SlotIndex is the slot index of the next non-debug instruction or the end
77// of a BB, because DBG_VALUE's don't have slot index themselves.
78// Adapted from RegisterCoalescer::buildVRegToDbgValueMap.
82 DbgVRegToValues;
83 const SlotIndexes *Slots = Liveness->getSlotIndexes();
85
86 // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
87 // map.
88 auto CloseNewDVRange = [&DbgVRegToValues, &ToInsert](SlotIndex Slot) {
89 for (auto *X : ToInsert) {
90 for (const auto &Op : X->debug_operands()) {
91 if (Op.isReg() && Op.getReg().isVirtual())
92 DbgVRegToValues[Op.getReg()].push_back({Slot, X});
93 }
94 }
95
96 ToInsert.clear();
97 };
98
99 // Iterate over all instructions, collecting them into the ToInsert vector.
100 // Once a non-debug instruction is found, record the slot index of the
101 // collected DBG_VALUEs.
102 for (auto &MBB : MF) {
103 SlotIndex CurrentSlot = Slots->getMBBStartIdx(&MBB);
104
105 for (auto &MI : MBB) {
106 if (MI.isDebugValue()) {
107 if (any_of(MI.debug_operands(), [](const MachineOperand &MO) {
108 return MO.isReg() && MO.getReg().isVirtual();
109 }))
110 ToInsert.push_back(&MI);
111 } else if (!MI.isDebugOrPseudoInstr()) {
112 CurrentSlot = Slots->getInstructionIndex(MI);
113 CloseNewDVRange(CurrentSlot);
114 }
115 }
116
117 // Close range of DBG_VALUEs at the end of blocks.
118 CloseNewDVRange(Slots->getMBBEndIdx(&MBB));
119 }
120
121 // Sort all DBG_VALUEs we've seen by slot number.
122 for (auto &Pair : DbgVRegToValues)
123 llvm::sort(Pair.second);
124 return DbgVRegToValues;
125}
126
127// After register coalescing, some DBG_VALUEs will be invalid. Set them undef.
128// This function has to run before the actual coalescing, i.e., the register
129// changes.
131 const LiveIntervals *Liveness,
133 DenseMap<Register, std::vector<std::pair<SlotIndex, MachineInstr *>>>
134 &DbgVRegToValues) {
135#ifndef NDEBUG
136 DenseSet<Register> SeenRegs;
137#endif
138 for (const auto &CoalescedIntervals : Assignments) {
139 if (CoalescedIntervals.empty())
140 continue;
141 for (LiveInterval *LI : CoalescedIntervals) {
142 Register Reg = LI->reg();
143#ifndef NDEBUG
144 // Ensure we don't process the same register twice
145 assert(SeenRegs.insert(Reg).second);
146#endif
147 auto RegMapIt = DbgVRegToValues.find(Reg);
148 if (RegMapIt == DbgVRegToValues.end())
149 continue;
150 SlotIndex LastSlot;
151 bool LastUndefResult = false;
152 for (auto [Slot, DbgValue] : RegMapIt->second) {
153 // All consecutive DBG_VALUEs have the same slot because the slot
154 // indices they have is the one for the first non-debug instruction
155 // after it, because DBG_VALUEs don't have slot index themselves. Before
156 // doing live range queries, quickly check if the current DBG_VALUE has
157 // the same slot index as the previous one, in which case we should do
158 // the same. Note that RegMapIt->second, the vector of {SlotIndex,
159 // DBG_VALUE}, is sorted by SlotIndex, which is necessary for this
160 // check.
161 if (Slot == LastSlot) {
162 if (LastUndefResult) {
163 LLVM_DEBUG(dbgs() << "Undefed: " << *DbgValue << "\n");
164 DbgValue->setDebugValueUndef();
165 }
166 continue;
167 }
168 LastSlot = Slot;
169 LastUndefResult = false;
170 for (LiveInterval *OtherLI : CoalescedIntervals) {
171 if (LI == OtherLI)
172 continue;
173
174 // This DBG_VALUE has 'Reg' (the current LiveInterval's register) as
175 // its operand. If this DBG_VALUE's slot index is within other
176 // registers' live ranges, this DBG_VALUE should be undefed. For
177 // example, suppose %0 and %1 are to be coalesced into %0.
178 // ; %0's live range starts
179 // %0 = value_0
180 // DBG_VALUE %0, !"a", ... (a)
181 // DBG_VALUE %1, !"b", ... (b)
182 // use %0
183 // ; %0's live range ends
184 // ...
185 // ; %1's live range starts
186 // %1 = value_1
187 // DBG_VALUE %0, !"c", ... (c)
188 // DBG_VALUE %1, !"d", ... (d)
189 // use %1
190 // ; %1's live range ends
191 //
192 // In this code, (b) and (c) should be set to undef. After the two
193 // registers are coalesced, (b) will incorrectly say the variable
194 // "b"'s value is 'value_0', and (c) will also incorrectly say the
195 // variable "c"'s value is value_1. Note it doesn't actually matter
196 // which register they are coalesced into (%0 or %1); (b) and (c)
197 // should be set to undef as well if they are coalesced into %1.
198 //
199 // This happens DBG_VALUEs are not included when computing live
200 // ranges.
201 //
202 // Note that it is not possible for this DBG_VALUE to be
203 // simultaneously within 'Reg''s live range and one of other coalesced
204 // registers' live ranges because if their live ranges overlapped they
205 // would have not been selected as a coalescing candidate in the first
206 // place.
207 auto *SegmentIt = OtherLI->find(Slot);
208 if (SegmentIt != OtherLI->end() && SegmentIt->contains(Slot)) {
209 LLVM_DEBUG(dbgs() << "Undefed: " << *DbgValue << "\n");
210 DbgValue->setDebugValueUndef();
211 LastUndefResult = true;
212 break;
213 }
214 }
215 }
216 }
217 }
218}
219
220static bool regColoring(MachineFunction &MF, LiveIntervals *Liveness,
221 const MachineBlockFrequencyInfo *MBFI) {
222 LLVM_DEBUG({
223 dbgs() << "********** Register Coloring **********\n"
224 << "********** Function: " << MF.getName() << '\n';
225 });
226
227 MachineRegisterInfo *MRI = &MF.getRegInfo();
229
230 // We don't preserve SSA form.
231 MRI->leaveSSA();
232
233 // Gather all register intervals into a list and sort them.
234 unsigned NumVRegs = MRI->getNumVirtRegs();
235 SmallVector<LiveInterval *, 0> SortedIntervals;
236 SortedIntervals.reserve(NumVRegs);
237
238 // Record DBG_VALUEs and their SlotIndexes.
239 auto DbgVRegToValues = buildVRegToDbgValueMap(MF, Liveness);
240
241 LLVM_DEBUG(dbgs() << "Interesting register intervals:\n");
242 for (unsigned I = 0; I < NumVRegs; ++I) {
244 if (MFI.isVRegStackified(VReg))
245 continue;
246 // Skip unused registers, which can use $drop.
247 if (MRI->use_empty(VReg))
248 continue;
249
250 LiveInterval *LI = &Liveness->getInterval(VReg);
251 assert(LI->weight() == 0.0f);
252 LI->setWeight(computeWeight(MRI, MBFI, VReg));
253 LLVM_DEBUG(LI->dump());
254 SortedIntervals.push_back(LI);
255 }
256 LLVM_DEBUG(dbgs() << '\n');
257
258 // Sort them to put arguments first (since we don't want to rename live-in
259 // registers), by weight next, and then by position.
260 // TODO: Investigate more intelligent sorting heuristics. For starters, we
261 // should try to coalesce adjacent live intervals before non-adjacent ones.
262 llvm::sort(SortedIntervals, [MRI](LiveInterval *LHS, LiveInterval *RHS) {
263 if (MRI->isLiveIn(LHS->reg()) != MRI->isLiveIn(RHS->reg()))
264 return MRI->isLiveIn(LHS->reg());
265 if (LHS->weight() != RHS->weight())
266 return LHS->weight() > RHS->weight();
267 if (LHS->empty() || RHS->empty())
268 return !LHS->empty() && RHS->empty();
269 return *LHS < *RHS;
270 });
271
272 LLVM_DEBUG(dbgs() << "Coloring register intervals:\n");
273 SmallVector<unsigned, 16> SlotMapping(SortedIntervals.size(), -1u);
275 SortedIntervals.size());
276 BitVector UsedColors(SortedIntervals.size());
277 bool Changed = false;
278 for (size_t I = 0, E = SortedIntervals.size(); I < E; ++I) {
279 LiveInterval *LI = SortedIntervals[I];
280 Register Old = LI->reg();
281 size_t Color = I;
282 const TargetRegisterClass *RC = MRI->getRegClass(Old);
283
284 // Check if it's possible to reuse any of the used colors.
285 if (!MRI->isLiveIn(Old))
286 for (unsigned C : UsedColors.set_bits()) {
287 if (MRI->getRegClass(SortedIntervals[C]->reg()) != RC)
288 continue;
289 for (LiveInterval *OtherLI : Assignments[C])
290 if (!OtherLI->empty() && OtherLI->overlaps(*LI))
291 goto continue_outer;
292 Color = C;
293 break;
294 continue_outer:;
295 }
296
297 Register New = SortedIntervals[Color]->reg();
298 SlotMapping[I] = New;
299 Changed |= Old != New;
300 UsedColors.set(Color);
301 Assignments[Color].push_back(LI);
302 // If we reassigned the stack pointer, update the debug frame base info.
303 if (Old != New && MFI.isFrameBaseVirtual() && MFI.getFrameBaseVreg() == Old)
304 MFI.setFrameBaseVreg(New);
305 LLVM_DEBUG(dbgs() << "Assigning vreg " << printReg(LI->reg()) << " to vreg "
306 << printReg(New) << "\n");
307 }
308 if (!Changed)
309 return false;
310
311 // Set DBG_VALUEs that will be invalid after coalescing to undef.
312 undefInvalidDbgValues(Liveness, Assignments, DbgVRegToValues);
313
314 // Rewrite register operands.
315 for (size_t I = 0, E = SortedIntervals.size(); I < E; ++I) {
316 Register Old = SortedIntervals[I]->reg();
317 unsigned New = SlotMapping[I];
318 if (Old != New)
319 MRI->replaceRegWith(Old, New);
320 }
321 return true;
322}
323
324bool WebAssemblyRegColoringLegacy::runOnMachineFunction(MachineFunction &MF) {
325 // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual
326 // registers could be modified before the longjmp is executed, resulting in
327 // the wrong value being used afterwards.
328 // TODO: Does WebAssembly need to care about setjmp for register coloring?
329 if (MF.exposesReturnsTwice())
330 return false;
331
332 LiveIntervals *Liveness = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
333 const MachineBlockFrequencyInfo *MBFI =
334 &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
335 return regColoring(MF, Liveness, MBFI);
336}
337
338PreservedAnalyses
341 // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual
342 // registers could be modified before the longjmp is executed, resulting in
343 // the wrong value being used afterwards.
344 // TODO: Does WebAssembly need to care about setjmp for register coloring?
345 if (MF.exposesReturnsTwice())
346 return PreservedAnalyses::all();
347
348 LiveIntervals *Liveness = &MFAM.getResult<LiveIntervalsAnalysis>(MF);
349 const MachineBlockFrequencyInfo *MBFI =
351 return regColoring(MF, Liveness, MBFI)
355}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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 & addRequired()
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.
This is an optimization pass for GlobalISel generic memory operations.
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