1 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
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 This register allocator allocates registers to a basic block at a
11 /// time, attempting to keep values in registers and reusing registers as
12 /// appropriate.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/IndexedMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/SparseSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegAllocRegistry.h"
30 #include "llvm/CodeGen/RegisterClassInfo.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
36 #include <algorithm>
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "regalloc"
40 
41 STATISTIC(NumStores, "Number of stores added");
42 STATISTIC(NumLoads , "Number of loads added");
43 STATISTIC(NumCopies, "Number of copies coalesced");
44 
45 static RegisterRegAlloc
46   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
47 
48 namespace {
49   class RegAllocFast : public MachineFunctionPass {
50   public:
51     static char ID;
52     RegAllocFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1) {}
53 
54   private:
55     MachineFrameInfo *MFI;
56     MachineRegisterInfo *MRI;
57     const TargetRegisterInfo *TRI;
58     const TargetInstrInfo *TII;
59     RegisterClassInfo RegClassInfo;
60 
61     /// Basic block currently being allocated.
62     MachineBasicBlock *MBB;
63 
64     /// Maps virtual regs to the frame index where these values are spilled.
65     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
66 
67     /// Everything we know about a live virtual register.
68     struct LiveReg {
69       MachineInstr *LastUse;    ///< Last instr to use reg.
70       unsigned VirtReg;         ///< Virtual register number.
71       MCPhysReg PhysReg;        ///< Currently held here.
72       unsigned short LastOpNum; ///< OpNum on LastUse.
73       bool Dirty;               ///< Register needs spill.
74 
75       explicit LiveReg(unsigned v)
76         : LastUse(nullptr), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false){}
77 
78       unsigned getSparseSetIndex() const {
79         return TargetRegisterInfo::virtReg2Index(VirtReg);
80       }
81     };
82 
83     typedef SparseSet<LiveReg> LiveRegMap;
84 
85     /// This map contains entries for each virtual register that is currently
86     /// available in a physical register.
87     LiveRegMap LiveVirtRegs;
88 
89     DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
90 
91     /// Track the state of a physical register.
92     enum RegState {
93       /// A disabled register is not available for allocation, but an alias may
94       /// be in use. A register can only be moved out of the disabled state if
95       /// all aliases are disabled.
96       regDisabled,
97 
98       /// A free register is not currently in use and can be allocated
99       /// immediately without checking aliases.
100       regFree,
101 
102       /// A reserved register has been assigned explicitly (e.g., setting up a
103       /// call parameter), and it remains reserved until it is used.
104       regReserved
105 
106       /// A register state may also be a virtual register number, indication
107       /// that the physical register is currently allocated to a virtual
108       /// register. In that case, LiveVirtRegs contains the inverse mapping.
109     };
110 
111     /// One of the RegState enums, or a virtreg.
112     std::vector<unsigned> PhysRegState;
113 
114     SmallVector<unsigned, 16> VirtDead;
115     SmallVector<MachineInstr*, 32> Coalesced;
116 
117     /// Set of register units.
118     typedef SparseSet<unsigned> UsedInInstrSet;
119 
120     /// Set of register units that are used in the current instruction, and so
121     /// cannot be allocated.
122     UsedInInstrSet UsedInInstr;
123 
124     /// Mark a physreg as used in this instruction.
125     void markRegUsedInInstr(MCPhysReg PhysReg) {
126       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
127         UsedInInstr.insert(*Units);
128     }
129 
130     /// Check if a physreg or any of its aliases are used in this instruction.
131     bool isRegUsedInInstr(MCPhysReg PhysReg) const {
132       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
133         if (UsedInInstr.count(*Units))
134           return true;
135       return false;
136     }
137 
138     /// This flag is set when LiveRegMap will be cleared completely after
139     /// spilling all live registers. LiveRegMap entries should not be erased.
140     bool isBulkSpilling = false;
141 
142     enum : unsigned {
143       spillClean = 1,
144       spillDirty = 100,
145       spillImpossible = ~0u
146     };
147   public:
148     StringRef getPassName() const override { return "Fast Register Allocator"; }
149 
150     void getAnalysisUsage(AnalysisUsage &AU) const override {
151       AU.setPreservesCFG();
152       MachineFunctionPass::getAnalysisUsage(AU);
153     }
154 
155     MachineFunctionProperties getRequiredProperties() const override {
156       return MachineFunctionProperties().set(
157           MachineFunctionProperties::Property::NoPHIs);
158     }
159 
160     MachineFunctionProperties getSetProperties() const override {
161       return MachineFunctionProperties().set(
162           MachineFunctionProperties::Property::NoVRegs);
163     }
164 
165   private:
166     bool runOnMachineFunction(MachineFunction &Fn) override;
167     void allocateBasicBlock(MachineBasicBlock &MBB);
168     void handleThroughOperands(MachineInstr &MI,
169                                SmallVectorImpl<unsigned> &VirtDead);
170     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass &RC);
171     bool isLastUseOfLocalReg(const MachineOperand &MO) const;
172 
173     void addKillFlag(const LiveReg &LRI);
174     void killVirtReg(LiveRegMap::iterator LRI);
175     void killVirtReg(unsigned VirtReg);
176     void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
177     void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
178 
179     void usePhysReg(MachineOperand &MO);
180     void definePhysReg(MachineInstr &MI, MCPhysReg PhysReg, RegState NewState);
181     unsigned calcSpillCost(MCPhysReg PhysReg) const;
182     void assignVirtToPhysReg(LiveReg&, MCPhysReg PhysReg);
183     LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
184       return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
185     }
186     LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
187       return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
188     }
189     LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, MCPhysReg PhysReg);
190     LiveRegMap::iterator allocVirtReg(MachineInstr &MI, LiveRegMap::iterator,
191                                       unsigned Hint);
192     LiveRegMap::iterator defineVirtReg(MachineInstr &MI, unsigned OpNum,
193                                        unsigned VirtReg, unsigned Hint);
194     LiveRegMap::iterator reloadVirtReg(MachineInstr &MI, unsigned OpNum,
195                                        unsigned VirtReg, unsigned Hint);
196     void spillAll(MachineBasicBlock::iterator MI);
197     bool setPhysReg(MachineInstr &MI, unsigned OpNum, MCPhysReg PhysReg);
198 
199     void dumpState();
200   };
201   char RegAllocFast::ID = 0;
202 }
203 
204 INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
205                 false)
206 
207 /// This allocates space for the specified virtual register to be held on the
208 /// stack.
209 int RegAllocFast::getStackSpaceFor(unsigned VirtReg,
210                                    const TargetRegisterClass &RC) {
211   // Find the location Reg would belong...
212   int SS = StackSlotForVirtReg[VirtReg];
213   // Already has space allocated?
214   if (SS != -1)
215     return SS;
216 
217   // Allocate a new stack object for this spill location...
218   unsigned Size = TRI->getSpillSize(RC);
219   unsigned Align = TRI->getSpillAlignment(RC);
220   int FrameIdx = MFI->CreateSpillStackObject(Size, Align);
221 
222   // Assign the slot.
223   StackSlotForVirtReg[VirtReg] = FrameIdx;
224   return FrameIdx;
225 }
226 
227 /// Return true if MO is the only remaining reference to its virtual register,
228 /// and it is guaranteed to be a block-local register.
229 bool RegAllocFast::isLastUseOfLocalReg(const MachineOperand &MO) const {
230   // If the register has ever been spilled or reloaded, we conservatively assume
231   // it is a global register used in multiple blocks.
232   if (StackSlotForVirtReg[MO.getReg()] != -1)
233     return false;
234 
235   // Check that the use/def chain has exactly one operand - MO.
236   MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
237   if (&*I != &MO)
238     return false;
239   return ++I == MRI->reg_nodbg_end();
240 }
241 
242 /// Set kill flags on last use of a virtual register.
243 void RegAllocFast::addKillFlag(const LiveReg &LR) {
244   if (!LR.LastUse) return;
245   MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
246   if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
247     if (MO.getReg() == LR.PhysReg)
248       MO.setIsKill();
249     // else, don't do anything we are problably redefining a
250     // subreg of this register and given we don't track which
251     // lanes are actually dead, we cannot insert a kill flag here.
252     // Otherwise we may end up in a situation like this:
253     // ... = (MO) physreg:sub1, physreg <implicit-use, kill>
254     // ... <== Here we would allow later pass to reuse physreg:sub1
255     //         which is potentially wrong.
256     // LR:sub0 = ...
257     // ... = LR.sub1 <== This is going to use physreg:sub1
258   }
259 }
260 
261 /// Mark virtreg as no longer available.
262 void RegAllocFast::killVirtReg(LiveRegMap::iterator LRI) {
263   addKillFlag(*LRI);
264   assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
265          "Broken RegState mapping");
266   PhysRegState[LRI->PhysReg] = regFree;
267   // Erase from LiveVirtRegs unless we're spilling in bulk.
268   if (!isBulkSpilling)
269     LiveVirtRegs.erase(LRI);
270 }
271 
272 /// Mark virtreg as no longer available.
273 void RegAllocFast::killVirtReg(unsigned VirtReg) {
274   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
275          "killVirtReg needs a virtual register");
276   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
277   if (LRI != LiveVirtRegs.end())
278     killVirtReg(LRI);
279 }
280 
281 /// This method spills the value specified by VirtReg into the corresponding
282 /// stack slot if needed.
283 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI,
284                                 unsigned VirtReg) {
285   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
286          "Spilling a physical register is illegal!");
287   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
288   assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
289   spillVirtReg(MI, LRI);
290 }
291 
292 /// Do the actual work of spilling.
293 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI,
294                                 LiveRegMap::iterator LRI) {
295   LiveReg &LR = *LRI;
296   assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
297 
298   if (LR.Dirty) {
299     // If this physreg is used by the instruction, we want to kill it on the
300     // instruction, not on the spill.
301     bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI;
302     LR.Dirty = false;
303     DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
304                  << " in " << PrintReg(LR.PhysReg, TRI));
305     const TargetRegisterClass &RC = *MRI->getRegClass(LRI->VirtReg);
306     int FI = getStackSpaceFor(LRI->VirtReg, RC);
307     DEBUG(dbgs() << " to stack slot #" << FI << "\n");
308     TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, &RC, TRI);
309     ++NumStores;   // Update statistics
310 
311     // If this register is used by DBG_VALUE then insert new DBG_VALUE to
312     // identify spilled location as the place to find corresponding variable's
313     // value.
314     SmallVectorImpl<MachineInstr *> &LRIDbgValues =
315       LiveDbgValueMap[LRI->VirtReg];
316     for (MachineInstr *DBG : LRIDbgValues) {
317       MachineInstr *NewDV = buildDbgValueForSpill(*MBB, MI, *DBG, FI);
318       assert(NewDV->getParent() == MBB && "dangling parent pointer");
319       (void)NewDV;
320       DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
321     }
322     // Now this register is spilled there is should not be any DBG_VALUE
323     // pointing to this register because they are all pointing to spilled value
324     // now.
325     LRIDbgValues.clear();
326     if (SpillKill)
327       LR.LastUse = nullptr; // Don't kill register again
328   }
329   killVirtReg(LRI);
330 }
331 
332 /// Spill all dirty virtregs without killing them.
333 void RegAllocFast::spillAll(MachineBasicBlock::iterator MI) {
334   if (LiveVirtRegs.empty()) return;
335   isBulkSpilling = true;
336   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
337   // of spilling here is deterministic, if arbitrary.
338   for (LiveRegMap::iterator I = LiveVirtRegs.begin(), E = LiveVirtRegs.end();
339        I != E; ++I)
340     spillVirtReg(MI, I);
341   LiveVirtRegs.clear();
342   isBulkSpilling = false;
343 }
344 
345 /// Handle the direct use of a physical register.  Check that the register is
346 /// not used by a virtreg. Kill the physreg, marking it free. This may add
347 /// implicit kills to MO->getParent() and invalidate MO.
348 void RegAllocFast::usePhysReg(MachineOperand &MO) {
349   // Ignore undef uses.
350   if (MO.isUndef())
351     return;
352 
353   unsigned PhysReg = MO.getReg();
354   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
355          "Bad usePhysReg operand");
356 
357   markRegUsedInInstr(PhysReg);
358   switch (PhysRegState[PhysReg]) {
359   case regDisabled:
360     break;
361   case regReserved:
362     PhysRegState[PhysReg] = regFree;
363     LLVM_FALLTHROUGH;
364   case regFree:
365     MO.setIsKill();
366     return;
367   default:
368     // The physreg was allocated to a virtual register. That means the value we
369     // wanted has been clobbered.
370     llvm_unreachable("Instruction uses an allocated register");
371   }
372 
373   // Maybe a superregister is reserved?
374   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
375     MCPhysReg Alias = *AI;
376     switch (PhysRegState[Alias]) {
377     case regDisabled:
378       break;
379     case regReserved:
380       // Either PhysReg is a subregister of Alias and we mark the
381       // whole register as free, or PhysReg is the superregister of
382       // Alias and we mark all the aliases as disabled before freeing
383       // PhysReg.
384       // In the latter case, since PhysReg was disabled, this means that
385       // its value is defined only by physical sub-registers. This check
386       // is performed by the assert of the default case in this loop.
387       // Note: The value of the superregister may only be partial
388       // defined, that is why regDisabled is a valid state for aliases.
389       assert((TRI->isSuperRegister(PhysReg, Alias) ||
390               TRI->isSuperRegister(Alias, PhysReg)) &&
391              "Instruction is not using a subregister of a reserved register");
392       LLVM_FALLTHROUGH;
393     case regFree:
394       if (TRI->isSuperRegister(PhysReg, Alias)) {
395         // Leave the superregister in the working set.
396         PhysRegState[Alias] = regFree;
397         MO.getParent()->addRegisterKilled(Alias, TRI, true);
398         return;
399       }
400       // Some other alias was in the working set - clear it.
401       PhysRegState[Alias] = regDisabled;
402       break;
403     default:
404       llvm_unreachable("Instruction uses an alias of an allocated register");
405     }
406   }
407 
408   // All aliases are disabled, bring register into working set.
409   PhysRegState[PhysReg] = regFree;
410   MO.setIsKill();
411 }
412 
413 /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
414 /// similar to defineVirtReg except the physreg is reserved instead of
415 /// allocated.
416 void RegAllocFast::definePhysReg(MachineInstr &MI, MCPhysReg PhysReg,
417                                  RegState NewState) {
418   markRegUsedInInstr(PhysReg);
419   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
420   case regDisabled:
421     break;
422   default:
423     spillVirtReg(MI, VirtReg);
424     LLVM_FALLTHROUGH;
425   case regFree:
426   case regReserved:
427     PhysRegState[PhysReg] = NewState;
428     return;
429   }
430 
431   // This is a disabled register, disable all aliases.
432   PhysRegState[PhysReg] = NewState;
433   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
434     MCPhysReg Alias = *AI;
435     switch (unsigned VirtReg = PhysRegState[Alias]) {
436     case regDisabled:
437       break;
438     default:
439       spillVirtReg(MI, VirtReg);
440       LLVM_FALLTHROUGH;
441     case regFree:
442     case regReserved:
443       PhysRegState[Alias] = regDisabled;
444       if (TRI->isSuperRegister(PhysReg, Alias))
445         return;
446       break;
447     }
448   }
449 }
450 
451 
452 /// \brief Return the cost of spilling clearing out PhysReg and aliases so it is
453 /// free for allocation. Returns 0 when PhysReg is free or disabled with all
454 /// aliases disabled - it can be allocated directly.
455 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
456 unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
457   if (isRegUsedInInstr(PhysReg)) {
458     DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
459     return spillImpossible;
460   }
461   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
462   case regDisabled:
463     break;
464   case regFree:
465     return 0;
466   case regReserved:
467     DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
468                  << PrintReg(PhysReg, TRI) << " is reserved already.\n");
469     return spillImpossible;
470   default: {
471     LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
472     assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
473     return I->Dirty ? spillDirty : spillClean;
474   }
475   }
476 
477   // This is a disabled register, add up cost of aliases.
478   DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
479   unsigned Cost = 0;
480   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
481     MCPhysReg Alias = *AI;
482     switch (unsigned VirtReg = PhysRegState[Alias]) {
483     case regDisabled:
484       break;
485     case regFree:
486       ++Cost;
487       break;
488     case regReserved:
489       return spillImpossible;
490     default: {
491       LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
492       assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
493       Cost += I->Dirty ? spillDirty : spillClean;
494       break;
495     }
496     }
497   }
498   return Cost;
499 }
500 
501 
502 /// \brief This method updates local state so that we know that PhysReg is the
503 /// proper container for VirtReg now.  The physical register must not be used
504 /// for anything else when this is called.
505 void RegAllocFast::assignVirtToPhysReg(LiveReg &LR, MCPhysReg PhysReg) {
506   DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
507                << PrintReg(PhysReg, TRI) << "\n");
508   PhysRegState[PhysReg] = LR.VirtReg;
509   assert(!LR.PhysReg && "Already assigned a physreg");
510   LR.PhysReg = PhysReg;
511 }
512 
513 RegAllocFast::LiveRegMap::iterator
514 RegAllocFast::assignVirtToPhysReg(unsigned VirtReg, MCPhysReg PhysReg) {
515   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
516   assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
517   assignVirtToPhysReg(*LRI, PhysReg);
518   return LRI;
519 }
520 
521 /// Allocates a physical register for VirtReg.
522 RegAllocFast::LiveRegMap::iterator RegAllocFast::allocVirtReg(MachineInstr &MI,
523     LiveRegMap::iterator LRI, unsigned Hint) {
524   const unsigned VirtReg = LRI->VirtReg;
525 
526   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
527          "Can only allocate virtual registers");
528 
529   // Take hint when possible.
530   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
531   if (TargetRegisterInfo::isPhysicalRegister(Hint) &&
532       MRI->isAllocatable(Hint) && RC.contains(Hint)) {
533     // Ignore the hint if we would have to spill a dirty register.
534     unsigned Cost = calcSpillCost(Hint);
535     if (Cost < spillDirty) {
536       if (Cost)
537         definePhysReg(MI, Hint, regFree);
538       // definePhysReg may kill virtual registers and modify LiveVirtRegs.
539       // That invalidates LRI, so run a new lookup for VirtReg.
540       return assignVirtToPhysReg(VirtReg, Hint);
541     }
542   }
543 
544   // First try to find a completely free register.
545   ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(&RC);
546   for (MCPhysReg PhysReg : AO) {
547     if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
548       assignVirtToPhysReg(*LRI, PhysReg);
549       return LRI;
550     }
551   }
552 
553   DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
554                << TRI->getRegClassName(&RC) << "\n");
555 
556   unsigned BestReg = 0;
557   unsigned BestCost = spillImpossible;
558   for (MCPhysReg PhysReg : AO) {
559     unsigned Cost = calcSpillCost(PhysReg);
560     DEBUG(dbgs() << "\tRegister: " << PrintReg(PhysReg, TRI) << "\n");
561     DEBUG(dbgs() << "\tCost: " << Cost << "\n");
562     DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
563     // Cost is 0 when all aliases are already disabled.
564     if (Cost == 0) {
565       assignVirtToPhysReg(*LRI, PhysReg);
566       return LRI;
567     }
568     if (Cost < BestCost)
569       BestReg = PhysReg, BestCost = Cost;
570   }
571 
572   if (BestReg) {
573     definePhysReg(MI, BestReg, regFree);
574     // definePhysReg may kill virtual registers and modify LiveVirtRegs.
575     // That invalidates LRI, so run a new lookup for VirtReg.
576     return assignVirtToPhysReg(VirtReg, BestReg);
577   }
578 
579   // Nothing we can do. Report an error and keep going with a bad allocation.
580   if (MI.isInlineAsm())
581     MI.emitError("inline assembly requires more registers than available");
582   else
583     MI.emitError("ran out of registers during register allocation");
584   definePhysReg(MI, *AO.begin(), regFree);
585   return assignVirtToPhysReg(VirtReg, *AO.begin());
586 }
587 
588 /// Allocates a register for VirtReg and mark it as dirty.
589 RegAllocFast::LiveRegMap::iterator RegAllocFast::defineVirtReg(MachineInstr &MI,
590                                                                unsigned OpNum,
591                                                                unsigned VirtReg,
592                                                                unsigned Hint) {
593   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
594          "Not a virtual register");
595   LiveRegMap::iterator LRI;
596   bool New;
597   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
598   if (New) {
599     // If there is no hint, peek at the only use of this register.
600     if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
601         MRI->hasOneNonDBGUse(VirtReg)) {
602       const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
603       // It's a copy, use the destination register as a hint.
604       if (UseMI.isCopyLike())
605         Hint = UseMI.getOperand(0).getReg();
606     }
607     LRI = allocVirtReg(MI, LRI, Hint);
608   } else if (LRI->LastUse) {
609     // Redefining a live register - kill at the last use, unless it is this
610     // instruction defining VirtReg multiple times.
611     if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
612       addKillFlag(*LRI);
613   }
614   assert(LRI->PhysReg && "Register not assigned");
615   LRI->LastUse = &MI;
616   LRI->LastOpNum = OpNum;
617   LRI->Dirty = true;
618   markRegUsedInInstr(LRI->PhysReg);
619   return LRI;
620 }
621 
622 /// Make sure VirtReg is available in a physreg and return it.
623 RegAllocFast::LiveRegMap::iterator RegAllocFast::reloadVirtReg(MachineInstr &MI,
624                                                                unsigned OpNum,
625                                                                unsigned VirtReg,
626                                                                unsigned Hint) {
627   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
628          "Not a virtual register");
629   LiveRegMap::iterator LRI;
630   bool New;
631   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
632   MachineOperand &MO = MI.getOperand(OpNum);
633   if (New) {
634     LRI = allocVirtReg(MI, LRI, Hint);
635     const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
636     int FrameIndex = getStackSpaceFor(VirtReg, RC);
637     DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
638                  << PrintReg(LRI->PhysReg, TRI) << "\n");
639     TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, &RC, TRI);
640     ++NumLoads;
641   } else if (LRI->Dirty) {
642     if (isLastUseOfLocalReg(MO)) {
643       DEBUG(dbgs() << "Killing last use: " << MO << "\n");
644       if (MO.isUse())
645         MO.setIsKill();
646       else
647         MO.setIsDead();
648     } else if (MO.isKill()) {
649       DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
650       MO.setIsKill(false);
651     } else if (MO.isDead()) {
652       DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
653       MO.setIsDead(false);
654     }
655   } else if (MO.isKill()) {
656     // We must remove kill flags from uses of reloaded registers because the
657     // register would be killed immediately, and there might be a second use:
658     //   %foo = OR %x<kill>, %x
659     // This would cause a second reload of %x into a different register.
660     DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
661     MO.setIsKill(false);
662   } else if (MO.isDead()) {
663     DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
664     MO.setIsDead(false);
665   }
666   assert(LRI->PhysReg && "Register not assigned");
667   LRI->LastUse = &MI;
668   LRI->LastOpNum = OpNum;
669   markRegUsedInInstr(LRI->PhysReg);
670   return LRI;
671 }
672 
673 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
674 /// may invalidate any operand pointers.  Return true if the operand kills its
675 /// register.
676 bool RegAllocFast::setPhysReg(MachineInstr &MI, unsigned OpNum,
677                               MCPhysReg PhysReg) {
678   MachineOperand &MO = MI.getOperand(OpNum);
679   bool Dead = MO.isDead();
680   if (!MO.getSubReg()) {
681     MO.setReg(PhysReg);
682     return MO.isKill() || Dead;
683   }
684 
685   // Handle subregister index.
686   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
687   MO.setSubReg(0);
688 
689   // A kill flag implies killing the full register. Add corresponding super
690   // register kill.
691   if (MO.isKill()) {
692     MI.addRegisterKilled(PhysReg, TRI, true);
693     return true;
694   }
695 
696   // A <def,read-undef> of a sub-register requires an implicit def of the full
697   // register.
698   if (MO.isDef() && MO.isUndef())
699     MI.addRegisterDefined(PhysReg, TRI);
700 
701   return Dead;
702 }
703 
704 // Handles special instruction operand like early clobbers and tied ops when
705 // there are additional physreg defines.
706 void RegAllocFast::handleThroughOperands(MachineInstr &MI,
707                                          SmallVectorImpl<unsigned> &VirtDead) {
708   DEBUG(dbgs() << "Scanning for through registers:");
709   SmallSet<unsigned, 8> ThroughRegs;
710   for (const MachineOperand &MO : MI.operands()) {
711     if (!MO.isReg()) continue;
712     unsigned Reg = MO.getReg();
713     if (!TargetRegisterInfo::isVirtualRegister(Reg))
714       continue;
715     if (MO.isEarlyClobber() || (MO.isUse() && MO.isTied()) ||
716         (MO.getSubReg() && MI.readsVirtualRegister(Reg))) {
717       if (ThroughRegs.insert(Reg).second)
718         DEBUG(dbgs() << ' ' << PrintReg(Reg));
719     }
720   }
721 
722   // If any physreg defines collide with preallocated through registers,
723   // we must spill and reallocate.
724   DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
725   for (const MachineOperand &MO : MI.operands()) {
726     if (!MO.isReg() || !MO.isDef()) continue;
727     unsigned Reg = MO.getReg();
728     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
729     markRegUsedInInstr(Reg);
730     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
731       if (ThroughRegs.count(PhysRegState[*AI]))
732         definePhysReg(MI, *AI, regFree);
733     }
734   }
735 
736   SmallVector<unsigned, 8> PartialDefs;
737   DEBUG(dbgs() << "Allocating tied uses.\n");
738   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
739     const MachineOperand &MO = MI.getOperand(I);
740     if (!MO.isReg()) continue;
741     unsigned Reg = MO.getReg();
742     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
743     if (MO.isUse()) {
744       if (!MO.isTied()) continue;
745       DEBUG(dbgs() << "Operand " << I << "("<< MO << ") is tied to operand "
746         << MI.findTiedOperandIdx(I) << ".\n");
747       LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, 0);
748       MCPhysReg PhysReg = LRI->PhysReg;
749       setPhysReg(MI, I, PhysReg);
750       // Note: we don't update the def operand yet. That would cause the normal
751       // def-scan to attempt spilling.
752     } else if (MO.getSubReg() && MI.readsVirtualRegister(Reg)) {
753       DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
754       // Reload the register, but don't assign to the operand just yet.
755       // That would confuse the later phys-def processing pass.
756       LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, 0);
757       PartialDefs.push_back(LRI->PhysReg);
758     }
759   }
760 
761   DEBUG(dbgs() << "Allocating early clobbers.\n");
762   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
763     const MachineOperand &MO = MI.getOperand(I);
764     if (!MO.isReg()) continue;
765     unsigned Reg = MO.getReg();
766     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
767     if (!MO.isEarlyClobber())
768       continue;
769     // Note: defineVirtReg may invalidate MO.
770     LiveRegMap::iterator LRI = defineVirtReg(MI, I, Reg, 0);
771     MCPhysReg PhysReg = LRI->PhysReg;
772     if (setPhysReg(MI, I, PhysReg))
773       VirtDead.push_back(Reg);
774   }
775 
776   // Restore UsedInInstr to a state usable for allocating normal virtual uses.
777   UsedInInstr.clear();
778   for (const MachineOperand &MO : MI.operands()) {
779     if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
780     unsigned Reg = MO.getReg();
781     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
782     DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
783                  << " as used in instr\n");
784     markRegUsedInInstr(Reg);
785   }
786 
787   // Also mark PartialDefs as used to avoid reallocation.
788   for (unsigned PartialDef : PartialDefs)
789     markRegUsedInInstr(PartialDef);
790 }
791 
792 #ifndef NDEBUG
793 void RegAllocFast::dumpState() {
794   for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
795     if (PhysRegState[Reg] == regDisabled) continue;
796     dbgs() << " " << TRI->getName(Reg);
797     switch(PhysRegState[Reg]) {
798     case regFree:
799       break;
800     case regReserved:
801       dbgs() << "*";
802       break;
803     default: {
804       dbgs() << '=' << PrintReg(PhysRegState[Reg]);
805       LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
806       assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
807       if (I->Dirty)
808         dbgs() << "*";
809       assert(I->PhysReg == Reg && "Bad inverse map");
810       break;
811     }
812     }
813   }
814   dbgs() << '\n';
815   // Check that LiveVirtRegs is the inverse.
816   for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
817        e = LiveVirtRegs.end(); i != e; ++i) {
818     assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
819            "Bad map key");
820     assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
821            "Bad map value");
822     assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
823   }
824 }
825 #endif
826 
827 void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
828   this->MBB = &MBB;
829   DEBUG(dbgs() << "\nAllocating " << MBB);
830 
831   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
832   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
833 
834   MachineBasicBlock::iterator MII = MBB.begin();
835 
836   // Add live-in registers as live.
837   for (const MachineBasicBlock::RegisterMaskPair LI : MBB.liveins())
838     if (MRI->isAllocatable(LI.PhysReg))
839       definePhysReg(*MII, LI.PhysReg, regReserved);
840 
841   VirtDead.clear();
842   Coalesced.clear();
843 
844   // Otherwise, sequentially allocate each instruction in the MBB.
845   for (MachineInstr &MI : MBB) {
846     const MCInstrDesc &MCID = MI.getDesc();
847     DEBUG(
848       dbgs() << "\n>> " << MI << "Regs:";
849       dumpState()
850     );
851 
852     // Debug values are not allowed to change codegen in any way.
853     if (MI.isDebugValue()) {
854       bool ScanDbgValue = true;
855       MachineInstr *DebugMI = &MI;
856       while (ScanDbgValue) {
857         ScanDbgValue = false;
858         for (unsigned I = 0, E = DebugMI->getNumOperands(); I != E; ++I) {
859           MachineOperand &MO = DebugMI->getOperand(I);
860           if (!MO.isReg()) continue;
861           unsigned Reg = MO.getReg();
862           if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
863           LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
864           if (LRI != LiveVirtRegs.end())
865             setPhysReg(*DebugMI, I, LRI->PhysReg);
866           else {
867             int SS = StackSlotForVirtReg[Reg];
868             if (SS == -1) {
869               // We can't allocate a physreg for a DebugValue, sorry!
870               DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
871               MO.setReg(0);
872             }
873             else {
874               // Modify DBG_VALUE now that the value is in a spill slot.
875               bool IsIndirect = DebugMI->isIndirectDebugValue();
876               if (IsIndirect)
877                 assert(DebugMI->getOperand(1).getImm() == 0 &&
878                        "DBG_VALUE with nonzero offset");
879               const MDNode *Var = DebugMI->getDebugVariable();
880               const MDNode *Expr = DebugMI->getDebugExpression();
881               DebugLoc DL = DebugMI->getDebugLoc();
882               MachineBasicBlock *MBB = DebugMI->getParent();
883               assert(
884                   cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
885                   "Expected inlined-at fields to agree");
886               MachineInstr *NewDV = BuildMI(*MBB, MBB->erase(DebugMI), DL,
887                                             TII->get(TargetOpcode::DBG_VALUE))
888                                         .addFrameIndex(SS)
889                                         .addImm(0U)
890                                         .addMetadata(Var)
891                                         .addMetadata(Expr);
892               DEBUG(dbgs() << "Modifying debug info due to spill:"
893                            << "\t" << *NewDV);
894               // Scan NewDV operands from the beginning.
895               DebugMI = NewDV;
896               ScanDbgValue = true;
897               break;
898             }
899           }
900           LiveDbgValueMap[Reg].push_back(DebugMI);
901         }
902       }
903       // Next instruction.
904       continue;
905     }
906 
907     // If this is a copy, we may be able to coalesce.
908     unsigned CopySrcReg = 0;
909     unsigned CopyDstReg = 0;
910     unsigned CopySrcSub = 0;
911     unsigned CopyDstSub = 0;
912     if (MI.isCopy()) {
913       CopyDstReg = MI.getOperand(0).getReg();
914       CopySrcReg = MI.getOperand(1).getReg();
915       CopyDstSub = MI.getOperand(0).getSubReg();
916       CopySrcSub = MI.getOperand(1).getSubReg();
917     }
918 
919     // Track registers used by instruction.
920     UsedInInstr.clear();
921 
922     // First scan.
923     // Mark physreg uses and early clobbers as used.
924     // Find the end of the virtreg operands
925     unsigned VirtOpEnd = 0;
926     bool hasTiedOps = false;
927     bool hasEarlyClobbers = false;
928     bool hasPartialRedefs = false;
929     bool hasPhysDefs = false;
930     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
931       MachineOperand &MO = MI.getOperand(i);
932       // Make sure MRI knows about registers clobbered by regmasks.
933       if (MO.isRegMask()) {
934         MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
935         continue;
936       }
937       if (!MO.isReg()) continue;
938       unsigned Reg = MO.getReg();
939       if (!Reg) continue;
940       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
941         VirtOpEnd = i+1;
942         if (MO.isUse()) {
943           hasTiedOps = hasTiedOps ||
944                               MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
945         } else {
946           if (MO.isEarlyClobber())
947             hasEarlyClobbers = true;
948           if (MO.getSubReg() && MI.readsVirtualRegister(Reg))
949             hasPartialRedefs = true;
950         }
951         continue;
952       }
953       if (!MRI->isAllocatable(Reg)) continue;
954       if (MO.isUse()) {
955         usePhysReg(MO);
956       } else if (MO.isEarlyClobber()) {
957         definePhysReg(MI, Reg,
958                       (MO.isImplicit() || MO.isDead()) ? regFree : regReserved);
959         hasEarlyClobbers = true;
960       } else
961         hasPhysDefs = true;
962     }
963 
964     // The instruction may have virtual register operands that must be allocated
965     // the same register at use-time and def-time: early clobbers and tied
966     // operands. If there are also physical defs, these registers must avoid
967     // both physical defs and uses, making them more constrained than normal
968     // operands.
969     // Similarly, if there are multiple defs and tied operands, we must make
970     // sure the same register is allocated to uses and defs.
971     // We didn't detect inline asm tied operands above, so just make this extra
972     // pass for all inline asm.
973     if (MI.isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
974         (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
975       handleThroughOperands(MI, VirtDead);
976       // Don't attempt coalescing when we have funny stuff going on.
977       CopyDstReg = 0;
978       // Pretend we have early clobbers so the use operands get marked below.
979       // This is not necessary for the common case of a single tied use.
980       hasEarlyClobbers = true;
981     }
982 
983     // Second scan.
984     // Allocate virtreg uses.
985     for (unsigned I = 0; I != VirtOpEnd; ++I) {
986       const MachineOperand &MO = MI.getOperand(I);
987       if (!MO.isReg()) continue;
988       unsigned Reg = MO.getReg();
989       if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
990       if (MO.isUse()) {
991         LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, CopyDstReg);
992         MCPhysReg PhysReg = LRI->PhysReg;
993         CopySrcReg = (CopySrcReg == Reg || CopySrcReg == PhysReg) ? PhysReg : 0;
994         if (setPhysReg(MI, I, PhysReg))
995           killVirtReg(LRI);
996       }
997     }
998 
999     // Track registers defined by instruction - early clobbers and tied uses at
1000     // this point.
1001     UsedInInstr.clear();
1002     if (hasEarlyClobbers) {
1003       for (const MachineOperand &MO : MI.operands()) {
1004         if (!MO.isReg()) continue;
1005         unsigned Reg = MO.getReg();
1006         if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1007         // Look for physreg defs and tied uses.
1008         if (!MO.isDef() && !MO.isTied()) continue;
1009         markRegUsedInInstr(Reg);
1010       }
1011     }
1012 
1013     unsigned DefOpEnd = MI.getNumOperands();
1014     if (MI.isCall()) {
1015       // Spill all virtregs before a call. This serves one purpose: If an
1016       // exception is thrown, the landing pad is going to expect to find
1017       // registers in their spill slots.
1018       // Note: although this is appealing to just consider all definitions
1019       // as call-clobbered, this is not correct because some of those
1020       // definitions may be used later on and we do not want to reuse
1021       // those for virtual registers in between.
1022       DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
1023       spillAll(MI);
1024     }
1025 
1026     // Third scan.
1027     // Allocate defs and collect dead defs.
1028     for (unsigned I = 0; I != DefOpEnd; ++I) {
1029       const MachineOperand &MO = MI.getOperand(I);
1030       if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1031         continue;
1032       unsigned Reg = MO.getReg();
1033 
1034       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1035         if (!MRI->isAllocatable(Reg)) continue;
1036         definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
1037         continue;
1038       }
1039       LiveRegMap::iterator LRI = defineVirtReg(MI, I, Reg, CopySrcReg);
1040       MCPhysReg PhysReg = LRI->PhysReg;
1041       if (setPhysReg(MI, I, PhysReg)) {
1042         VirtDead.push_back(Reg);
1043         CopyDstReg = 0; // cancel coalescing;
1044       } else
1045         CopyDstReg = (CopyDstReg == Reg || CopyDstReg == PhysReg) ? PhysReg : 0;
1046     }
1047 
1048     // Kill dead defs after the scan to ensure that multiple defs of the same
1049     // register are allocated identically. We didn't need to do this for uses
1050     // because we are crerating our own kill flags, and they are always at the
1051     // last use.
1052     for (unsigned VirtReg : VirtDead)
1053       killVirtReg(VirtReg);
1054     VirtDead.clear();
1055 
1056     if (CopyDstReg && CopyDstReg == CopySrcReg && CopyDstSub == CopySrcSub) {
1057       DEBUG(dbgs() << "-- coalescing: " << MI);
1058       Coalesced.push_back(&MI);
1059     } else {
1060       DEBUG(dbgs() << "<< " << MI);
1061     }
1062   }
1063 
1064   // Spill all physical registers holding virtual registers now.
1065   DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1066   spillAll(MBB.getFirstTerminator());
1067 
1068   // Erase all the coalesced copies. We are delaying it until now because
1069   // LiveVirtRegs might refer to the instrs.
1070   for (MachineInstr *MI : Coalesced)
1071     MBB.erase(MI);
1072   NumCopies += Coalesced.size();
1073 
1074   DEBUG(MBB.dump());
1075 }
1076 
1077 /// Allocates registers for a function.
1078 bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
1079   DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1080                << "********** Function: " << MF.getName() << '\n');
1081   MRI = &MF.getRegInfo();
1082   const TargetSubtargetInfo &STI = MF.getSubtarget();
1083   TRI = STI.getRegisterInfo();
1084   TII = STI.getInstrInfo();
1085   MFI = &MF.getFrameInfo();
1086   MRI->freezeReservedRegs(MF);
1087   RegClassInfo.runOnMachineFunction(MF);
1088   UsedInInstr.clear();
1089   UsedInInstr.setUniverse(TRI->getNumRegUnits());
1090 
1091   // initialize the virtual->physical register map to have a 'null'
1092   // mapping for all virtual registers
1093   unsigned NumVirtRegs = MRI->getNumVirtRegs();
1094   StackSlotForVirtReg.resize(NumVirtRegs);
1095   LiveVirtRegs.setUniverse(NumVirtRegs);
1096 
1097   // Loop over all of the basic blocks, eliminating virtual register references
1098   for (MachineBasicBlock &MBB : MF)
1099     allocateBasicBlock(MBB);
1100 
1101   // All machine operands and other references to virtual registers have been
1102   // replaced. Remove the virtual registers.
1103   MRI->clearVirtRegs();
1104 
1105   StackSlotForVirtReg.clear();
1106   LiveDbgValueMap.clear();
1107   return true;
1108 }
1109 
1110 FunctionPass *llvm::createFastRegisterAllocator() {
1111   return new RegAllocFast();
1112 }
1113