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