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