110b7fc1fe158e4234ef5315e44d8005648dee23
[oota-llvm.git] / lib / CodeGen / RegAllocFast.cpp
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 #define DEBUG_TYPE "regalloc"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/IndexedMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 using namespace llvm;
37
38 STATISTIC(NumStores, "Number of stores added");
39 STATISTIC(NumLoads , "Number of loads added");
40
41 static RegisterRegAlloc
42   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
43
44 namespace {
45   class RAFast : public MachineFunctionPass {
46   public:
47     static char ID;
48     RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
49   private:
50     const TargetMachine *TM;
51     MachineFunction *MF;
52     MachineRegisterInfo *MRI;
53     const TargetRegisterInfo *TRI;
54     const TargetInstrInfo *TII;
55
56     // StackSlotForVirtReg - Maps virtual regs to the frame index where these
57     // values are spilled.
58     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
59
60     // Everything we know about a live virtual register.
61     struct LiveReg {
62       MachineInstr *LastUse;    // Last instr to use reg.
63       unsigned PhysReg;         // Currently held here.
64       unsigned short LastOpNum; // OpNum on LastUse.
65       bool Dirty;               // Register needs spill.
66
67       LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
68                               Dirty(false) {
69         assert(p && "Don't create LiveRegs without a PhysReg");
70       }
71     };
72
73     typedef DenseMap<unsigned, LiveReg> LiveRegMap;
74
75     // LiveVirtRegs - This map contains entries for each virtual register
76     // that is currently available in a physical register.
77     LiveRegMap LiveVirtRegs;
78
79     // RegState - Track the state of a physical register.
80     enum RegState {
81       // A disabled register is not available for allocation, but an alias may
82       // be in use. A register can only be moved out of the disabled state if
83       // all aliases are disabled.
84       regDisabled,
85
86       // A free register is not currently in use and can be allocated
87       // immediately without checking aliases.
88       regFree,
89
90       // A reserved register has been assigned expolicitly (e.g., setting up a
91       // call parameter), and it remains reserved until it is used.
92       regReserved
93
94       // A register state may also be a virtual register number, indication that
95       // the physical register is currently allocated to a virtual register. In
96       // that case, LiveVirtRegs contains the inverse mapping.
97     };
98
99     // PhysRegState - One of the RegState enums, or a virtreg.
100     std::vector<unsigned> PhysRegState;
101
102     // UsedInInstr - BitVector of physregs that are used in the current
103     // instruction, and so cannot be allocated.
104     BitVector UsedInInstr;
105
106     // ReservedRegs - vector of reserved physical registers.
107     BitVector ReservedRegs;
108
109   public:
110     virtual const char *getPassName() const {
111       return "Fast Register Allocator";
112     }
113
114     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115       AU.setPreservesCFG();
116       AU.addRequiredID(PHIEliminationID);
117       AU.addRequiredID(TwoAddressInstructionPassID);
118       MachineFunctionPass::getAnalysisUsage(AU);
119     }
120
121   private:
122     bool runOnMachineFunction(MachineFunction &Fn);
123     void AllocateBasicBlock(MachineBasicBlock &MBB);
124     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
125     void addKillFlag(LiveRegMap::iterator i);
126     void killVirtReg(LiveRegMap::iterator i);
127     void killVirtReg(unsigned VirtReg);
128     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
129                       unsigned VirtReg, bool isKill);
130     void killPhysReg(unsigned PhysReg);
131     void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
132                       unsigned PhysReg, bool isKill);
133     LiveRegMap::iterator assignVirtToPhysReg(unsigned VirtReg,
134                                              unsigned PhysReg);
135     LiveRegMap::iterator allocVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
136                                       unsigned VirtReg, unsigned Hint);
137     unsigned defineVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
138                            unsigned OpNum, unsigned VirtReg, unsigned Hint);
139     unsigned reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
140                            unsigned OpNum, unsigned VirtReg, unsigned Hint);
141     void reservePhysReg(MachineBasicBlock &MBB, MachineInstr *MI,
142                         unsigned PhysReg);
143     void spillAll(MachineBasicBlock &MBB, MachineInstr *MI);
144     void setPhysReg(MachineOperand &MO, unsigned PhysReg);
145   };
146   char RAFast::ID = 0;
147 }
148
149 /// getStackSpaceFor - This allocates space for the specified virtual register
150 /// to be held on the stack.
151 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
152   // Find the location Reg would belong...
153   int SS = StackSlotForVirtReg[VirtReg];
154   if (SS != -1)
155     return SS;          // Already has space allocated?
156
157   // Allocate a new stack object for this spill location...
158   int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
159                                                             RC->getAlignment());
160
161   // Assign the slot.
162   StackSlotForVirtReg[VirtReg] = FrameIdx;
163   return FrameIdx;
164 }
165
166 /// addKillFlag - Set kill flags on last use of a virtual register.
167 void RAFast::addKillFlag(LiveRegMap::iterator lri) {
168   assert(lri != LiveVirtRegs.end() && "Killing unmapped virtual register");
169   const LiveReg &LR = lri->second;
170   if (LR.LastUse) {
171     MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
172     if (MO.isDef())
173       MO.setIsDead();
174     else if (!LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum))
175       MO.setIsKill();
176     DEBUG(dbgs() << "  %reg" << lri->first << " killed: " << *LR.LastUse);
177   }
178 }
179
180 /// killVirtReg - Mark virtreg as no longer available.
181 void RAFast::killVirtReg(LiveRegMap::iterator lri) {
182   addKillFlag(lri);
183   const LiveReg &LR = lri->second;
184   assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
185   PhysRegState[LR.PhysReg] = regFree;
186   LiveVirtRegs.erase(lri);
187 }
188
189 /// killVirtReg - Mark virtreg as no longer available.
190 void RAFast::killVirtReg(unsigned VirtReg) {
191   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
192          "killVirtReg needs a virtual register");
193   DEBUG(dbgs() << "  Killing %reg" << VirtReg << "\n");
194   LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
195   if (lri != LiveVirtRegs.end())
196     killVirtReg(lri);
197 }
198
199 /// spillVirtReg - This method spills the value specified by VirtReg into the
200 /// corresponding stack slot if needed. If isKill is set, the register is also
201 /// killed.
202 void RAFast::spillVirtReg(MachineBasicBlock &MBB,
203                           MachineBasicBlock::iterator MI,
204                           unsigned VirtReg, bool isKill) {
205   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
206          "Spilling a physical register is illegal!");
207   LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
208   assert(lri != LiveVirtRegs.end() && "Spilling unmapped virtual register");
209   LiveReg &LR = lri->second;
210   assert(PhysRegState[LR.PhysReg] == VirtReg && "Broken RegState mapping");
211
212   // If this physreg is used by the instruction, we want to kill it on the
213   // instruction, not on the spill.
214   bool spillKill = isKill && LR.LastUse != MI;
215
216   if (LR.Dirty) {
217     LR.Dirty = false;
218     DEBUG(dbgs() << "  Spilling register " << TRI->getName(LR.PhysReg)
219       << " containing %reg" << VirtReg);
220     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
221     int FrameIndex = getStackSpaceFor(VirtReg, RC);
222     DEBUG(dbgs() << " to stack slot #" << FrameIndex << "\n");
223     TII->storeRegToStackSlot(MBB, MI, LR.PhysReg, spillKill,
224                              FrameIndex, RC, TRI);
225     ++NumStores;   // Update statistics
226
227     if (spillKill)
228       LR.LastUse = 0; // Don't kill register again
229     else if (!isKill) {
230       MachineInstr *Spill = llvm::prior(MI);
231       LR.LastUse = Spill;
232       LR.LastOpNum = Spill->findRegisterUseOperandIdx(LR.PhysReg);
233     }
234   }
235
236   if (isKill)
237     killVirtReg(lri);
238 }
239
240 /// spillAll - Spill all dirty virtregs without killing them.
241 void RAFast::spillAll(MachineBasicBlock &MBB, MachineInstr *MI) {
242   SmallVector<unsigned, 16> Dirty;
243   for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
244        e = LiveVirtRegs.end(); i != e; ++i)
245     if (i->second.Dirty)
246       Dirty.push_back(i->first);
247   for (unsigned i = 0, e = Dirty.size(); i != e; ++i)
248     spillVirtReg(MBB, MI, Dirty[i], false);
249 }
250
251 /// killPhysReg - Kill any virtual register aliased by PhysReg.
252 void RAFast::killPhysReg(unsigned PhysReg) {
253   // Fast path for the normal case.
254   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
255   case regDisabled:
256     break;
257   case regFree:
258     return;
259   case regReserved:
260     PhysRegState[PhysReg] = regFree;
261     return;
262   default:
263     killVirtReg(VirtReg);
264     return;
265   }
266
267   // This is a disabled register, we have to check aliases.
268   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
269        unsigned Alias = *AS; ++AS) {
270     switch (unsigned VirtReg = PhysRegState[Alias]) {
271     case regDisabled:
272     case regFree:
273       break;
274     case regReserved:
275       PhysRegState[Alias] = regFree;
276       break;
277     default:
278       killVirtReg(VirtReg);
279       break;
280     }
281   }
282 }
283
284 /// spillPhysReg - Spill any dirty virtual registers that aliases PhysReg. If
285 /// isKill is set, they are also killed.
286 void RAFast::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *MI,
287                            unsigned PhysReg, bool isKill) {
288   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
289   case regDisabled:
290     break;
291   case regFree:
292     return;
293   case regReserved:
294     if (isKill)
295       PhysRegState[PhysReg] = regFree;
296     return;
297   default:
298     spillVirtReg(MBB, MI, VirtReg, isKill);
299     return;
300   }
301
302   // This is a disabled register, we have to check aliases.
303   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
304        unsigned Alias = *AS; ++AS) {
305     switch (unsigned VirtReg = PhysRegState[Alias]) {
306     case regDisabled:
307     case regFree:
308       break;
309     case regReserved:
310       if (isKill)
311         PhysRegState[Alias] = regFree;
312       break;
313     default:
314       spillVirtReg(MBB, MI, VirtReg, isKill);
315       break;
316     }
317   }
318 }
319
320 /// assignVirtToPhysReg - This method updates local state so that we know
321 /// that PhysReg is the proper container for VirtReg now.  The physical
322 /// register must not be used for anything else when this is called.
323 ///
324 RAFast::LiveRegMap::iterator
325 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
326   DEBUG(dbgs() << "  Assigning %reg" << VirtReg << " to "
327                << TRI->getName(PhysReg) << "\n");
328   PhysRegState[PhysReg] = VirtReg;
329   return LiveVirtRegs.insert(std::make_pair(VirtReg, PhysReg)).first;
330 }
331
332 /// allocVirtReg - Allocate a physical register for VirtReg.
333 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineBasicBlock &MBB,
334                                                   MachineInstr *MI,
335                                                   unsigned VirtReg,
336                                                   unsigned Hint) {
337   const unsigned spillCost = 100;
338   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
339          "Can only allocate virtual registers");
340
341   const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
342   TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
343   TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
344
345   // Ignore invalid hints.
346   if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
347                !RC->contains(Hint) || UsedInInstr.test(Hint)))
348     Hint = 0;
349
350   // If there is no hint, peek at the first use of this register.
351   if (!Hint && !MRI->use_nodbg_empty(VirtReg)) {
352     MachineInstr &MI = *MRI->use_nodbg_begin(VirtReg);
353     unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
354     // Copy to physreg -> use physreg as hint.
355     if (TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
356         SrcReg == VirtReg && TargetRegisterInfo::isPhysicalRegister(DstReg) &&
357         RC->contains(DstReg) && !UsedInInstr.test(DstReg)) {
358       Hint = DstReg;
359       DEBUG(dbgs() << "  %reg" << VirtReg << " gets hint from " << MI);
360     }
361   }
362
363   // Take hint when possible.
364   if (Hint) {
365     assert(RC->contains(Hint) && !UsedInInstr.test(Hint) &&
366            "Invalid hint should have been cleared");
367     switch(PhysRegState[Hint]) {
368     case regDisabled:
369     case regReserved:
370       break;
371     default:
372       DEBUG(dbgs() << "  %reg" << VirtReg << " really wants "
373                    << TRI->getName(Hint) << "\n");
374       spillVirtReg(MBB, MI, PhysRegState[Hint], true);
375       // Fall through.
376     case regFree:
377       return assignVirtToPhysReg(VirtReg, Hint);
378     }
379   }
380
381   // First try to find a completely free register.
382   unsigned BestCost = 0, BestReg = 0;
383   bool hasDisabled = false;
384   for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
385     unsigned PhysReg = *I;
386     switch(PhysRegState[PhysReg]) {
387     case regDisabled:
388       hasDisabled = true;
389     case regReserved:
390       continue;
391     case regFree:
392       if (!UsedInInstr.test(PhysReg))
393         return assignVirtToPhysReg(VirtReg, PhysReg);
394       continue;
395     default:
396       // Grab the first spillable register we meet.
397       if (!BestReg && !UsedInInstr.test(PhysReg))
398         BestReg = PhysReg, BestCost = spillCost;
399       continue;
400     }
401   }
402
403   DEBUG(dbgs() << "  Allocating %reg" << VirtReg << " from " << RC->getName()
404                << " candidate=" << TRI->getName(BestReg) << "\n");
405
406   // Try to extend the working set for RC if there were any disabled registers.
407   if (hasDisabled && (!BestReg || BestCost >= spillCost)) {
408     for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
409       unsigned PhysReg = *I;
410       if (PhysRegState[PhysReg] != regDisabled || UsedInInstr.test(PhysReg))
411         continue;
412
413       // Calculate the cost of bringing PhysReg into the working set.
414       unsigned Cost=0;
415       bool Impossible = false;
416       for (const unsigned *AS = TRI->getAliasSet(PhysReg);
417       unsigned Alias = *AS; ++AS) {
418         if (UsedInInstr.test(Alias)) {
419           Impossible = true;
420           break;
421         }
422         switch (PhysRegState[Alias]) {
423         case regDisabled:
424           break;
425         case regReserved:
426           Impossible = true;
427           break;
428         case regFree:
429           Cost++;
430           break;
431         default:
432           Cost += spillCost;
433           break;
434         }
435       }
436       if (Impossible) continue;
437       DEBUG(dbgs() << "  - candidate " << TRI->getName(PhysReg)
438         << " cost=" << Cost << "\n");
439       if (!BestReg || Cost < BestCost) {
440         BestReg = PhysReg;
441         BestCost = Cost;
442         if (Cost < spillCost) break;
443       }
444     }
445   }
446
447   if (BestReg) {
448     // BestCost is 0 when all aliases are already disabled.
449     if (BestCost) {
450       if (PhysRegState[BestReg] != regDisabled)
451         spillVirtReg(MBB, MI, PhysRegState[BestReg], true);
452       else {
453         // Make sure all aliases are disabled.
454         for (const unsigned *AS = TRI->getAliasSet(BestReg);
455              unsigned Alias = *AS; ++AS) {
456           switch (PhysRegState[Alias]) {
457           case regDisabled:
458             continue;
459           case regFree:
460             PhysRegState[Alias] = regDisabled;
461             break;
462           default:
463             spillVirtReg(MBB, MI, PhysRegState[Alias], true);
464             PhysRegState[Alias] = regDisabled;
465             break;
466           }
467         }
468       }
469     }
470     return assignVirtToPhysReg(VirtReg, BestReg);
471   }
472
473   // Nothing we can do.
474   std::string msg;
475   raw_string_ostream Msg(msg);
476   Msg << "Ran out of registers during register allocation!";
477   if (MI->isInlineAsm()) {
478     Msg << "\nPlease check your inline asm statement for "
479         << "invalid constraints:\n";
480     MI->print(Msg, TM);
481   }
482   report_fatal_error(Msg.str());
483   return LiveVirtRegs.end();
484 }
485
486 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
487 unsigned RAFast::defineVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
488                               unsigned OpNum, unsigned VirtReg, unsigned Hint) {
489   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
490          "Not a virtual register");
491   LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
492   if (lri == LiveVirtRegs.end())
493     lri = allocVirtReg(MBB, MI, VirtReg, Hint);
494   else
495     addKillFlag(lri); // Kill before redefine.
496   LiveReg &LR = lri->second;
497   LR.LastUse = MI;
498   LR.LastOpNum = OpNum;
499   LR.Dirty = true;
500   UsedInInstr.set(LR.PhysReg);
501   return LR.PhysReg;
502 }
503
504 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
505 unsigned RAFast::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
506                               unsigned OpNum, unsigned VirtReg, unsigned Hint) {
507   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
508          "Not a virtual register");
509   LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
510   if (lri == LiveVirtRegs.end()) {
511     lri = allocVirtReg(MBB, MI, VirtReg, Hint);
512     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
513     int FrameIndex = getStackSpaceFor(VirtReg, RC);
514     DEBUG(dbgs() << "  Reloading %reg" << VirtReg << " into "
515                  << TRI->getName(lri->second.PhysReg) << "\n");
516     TII->loadRegFromStackSlot(MBB, MI, lri->second.PhysReg, FrameIndex, RC,
517                               TRI);
518     ++NumLoads;
519   }
520   LiveReg &LR = lri->second;
521   LR.LastUse = MI;
522   LR.LastOpNum = OpNum;
523   UsedInInstr.set(LR.PhysReg);
524   return LR.PhysReg;
525 }
526
527 /// reservePhysReg - Mark PhysReg as reserved. This is very similar to
528 /// defineVirtReg except the physreg is reserved instead of allocated.
529 void RAFast::reservePhysReg(MachineBasicBlock &MBB, MachineInstr *MI,
530                             unsigned PhysReg) {
531   UsedInInstr.set(PhysReg);
532   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
533   case regDisabled:
534     break;
535   case regFree:
536     PhysRegState[PhysReg] = regReserved;
537     return;
538   case regReserved:
539     return;
540   default:
541     spillVirtReg(MBB, MI, VirtReg, true);
542     PhysRegState[PhysReg] = regReserved;
543     return;
544   }
545
546   // This is a disabled register, disable all aliases.
547   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
548        unsigned Alias = *AS; ++AS) {
549     UsedInInstr.set(Alias);
550     switch (unsigned VirtReg = PhysRegState[Alias]) {
551     case regDisabled:
552     case regFree:
553       break;
554     case regReserved:
555       // is a super register already reserved?
556       if (TRI->isSuperRegister(PhysReg, Alias))
557         return;
558       break;
559     default:
560       spillVirtReg(MBB, MI, VirtReg, true);
561       break;
562     }
563     PhysRegState[Alias] = regDisabled;
564   }
565   PhysRegState[PhysReg] = regReserved;
566 }
567
568 // setPhysReg - Change MO the refer the PhysReg, considering subregs.
569 void RAFast::setPhysReg(MachineOperand &MO, unsigned PhysReg) {
570   if (unsigned Idx = MO.getSubReg()) {
571     MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, Idx) : 0);
572     MO.setSubReg(0);
573   } else
574     MO.setReg(PhysReg);
575 }
576
577 void RAFast::AllocateBasicBlock(MachineBasicBlock &MBB) {
578   DEBUG(dbgs() << "\nBB#" << MBB.getNumber() << ", "<< MBB.getName() << "\n");
579
580   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
581   assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
582
583   MachineBasicBlock::iterator MII = MBB.begin();
584
585   // Add live-in registers as live.
586   for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
587          E = MBB.livein_end(); I != E; ++I)
588     reservePhysReg(MBB, MII, *I);
589
590   SmallVector<unsigned, 8> VirtKills, PhysKills, PhysDefs;
591
592   // Otherwise, sequentially allocate each instruction in the MBB.
593   while (MII != MBB.end()) {
594     MachineInstr *MI = MII++;
595     const TargetInstrDesc &TID = MI->getDesc();
596     DEBUG({
597         dbgs() << "\nStarting RegAlloc of: " << *MI << "Working set:";
598         for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
599           if (PhysRegState[Reg] == regDisabled) continue;
600           dbgs() << " " << TRI->getName(Reg);
601           switch(PhysRegState[Reg]) {
602           case regFree:
603             break;
604           case regReserved:
605             dbgs() << "(resv)";
606             break;
607           default:
608             dbgs() << "=%reg" << PhysRegState[Reg];
609             if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
610               dbgs() << "*";
611             assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
612                    "Bad inverse map");
613             break;
614           }
615         }
616         dbgs() << '\n';
617         // Check that LiveVirtRegs is the inverse.
618         for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
619              e = LiveVirtRegs.end(); i != e; ++i) {
620            assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
621                   "Bad map key");
622            assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
623                   "Bad map value");
624            assert(PhysRegState[i->second.PhysReg] == i->first &&
625                   "Bad inverse map");
626         }
627       });
628
629     // Debug values are not allowed to change codegen in any way.
630     if (MI->isDebugValue()) {
631       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
632         MachineOperand &MO = MI->getOperand(i);
633         if (!MO.isReg()) continue;
634         unsigned Reg = MO.getReg();
635         if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
636         LiveRegMap::iterator lri = LiveVirtRegs.find(Reg);
637         if (lri != LiveVirtRegs.end())
638           setPhysReg(MO, lri->second.PhysReg);
639         else
640           MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
641       }
642       // Next instruction.
643       continue;
644     }
645
646     // If this is a copy, we may be able to coalesce.
647     unsigned CopySrc, CopyDst, CopySrcSub, CopyDstSub;
648     if (!TII->isMoveInstr(*MI, CopySrc, CopyDst, CopySrcSub, CopyDstSub))
649       CopySrc = CopyDst = 0;
650
651     // Track registers used by instruction.
652     UsedInInstr.reset();
653     PhysDefs.clear();
654
655     // First scan.
656     // Mark physreg uses and early clobbers as used.
657     // Collect PhysKills.
658     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
659       MachineOperand &MO = MI->getOperand(i);
660       if (!MO.isReg()) continue;
661
662       // FIXME: For now, don't trust kill flags
663       if (MO.isUse()) MO.setIsKill(false);
664
665       unsigned Reg = MO.getReg();
666       if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg) ||
667           ReservedRegs.test(Reg)) continue;
668       if (MO.isUse()) {
669 #ifndef NDEBUG
670         // We are using a physreg directly. It had better not be clobbered by a
671         // virtreg.
672         assert(PhysRegState[Reg] <= regReserved && "Using clobbered physreg");
673         if (PhysRegState[Reg] == regDisabled)
674           for (const unsigned *AS = TRI->getAliasSet(Reg);
675                unsigned Alias = *AS; ++AS)
676             assert(PhysRegState[Alias] <= regReserved &&
677                    "Physreg alias was clobbered");
678 #endif
679         PhysKills.push_back(Reg); // Any clean physreg use is a kill.
680         UsedInInstr.set(Reg);
681       } else if (MO.isEarlyClobber()) {
682         spillPhysReg(MBB, MI, Reg, true);
683         UsedInInstr.set(Reg);
684         PhysDefs.push_back(Reg);
685       }
686     }
687
688     // Second scan.
689     // Allocate virtreg uses and early clobbers.
690     // Collect VirtKills
691     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
692       MachineOperand &MO = MI->getOperand(i);
693       if (!MO.isReg()) continue;
694       unsigned Reg = MO.getReg();
695       if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
696       if (MO.isUse()) {
697         unsigned PhysReg = reloadVirtReg(MBB, MI, i, Reg, CopyDst);
698         if (CopySrc == Reg)
699           CopySrc = PhysReg;
700         setPhysReg(MO, PhysReg);
701         if (MO.isKill())
702           VirtKills.push_back(Reg);
703       } else if (MO.isEarlyClobber()) {
704         unsigned PhysReg = defineVirtReg(MBB, MI, i, Reg, 0);
705         setPhysReg(MO, PhysReg);
706         PhysDefs.push_back(PhysReg);
707       }
708     }
709
710     // Process virtreg kills
711     for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
712       killVirtReg(VirtKills[i]);
713     VirtKills.clear();
714
715     // Process physreg kills
716     for (unsigned i = 0, e = PhysKills.size(); i != e; ++i)
717       killPhysReg(PhysKills[i]);
718     PhysKills.clear();
719
720     MRI->addPhysRegsUsed(UsedInInstr);
721
722     // Track registers defined by instruction - early clobbers at this point.
723     UsedInInstr.reset();
724     for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
725       unsigned PhysReg = PhysDefs[i];
726       UsedInInstr.set(PhysReg);
727       for (const unsigned *AS = TRI->getAliasSet(PhysReg);
728             unsigned Alias = *AS; ++AS)
729         UsedInInstr.set(Alias);
730     }
731
732     // Third scan.
733     // Allocate defs and collect dead defs.
734     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
735       MachineOperand &MO = MI->getOperand(i);
736       if (!MO.isReg() || !MO.isDef() || !MO.getReg()) continue;
737       unsigned Reg = MO.getReg();
738
739       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
740         if (ReservedRegs.test(Reg)) continue;
741         if (MO.isImplicit())
742           spillPhysReg(MBB, MI, Reg, true);
743         else
744           reservePhysReg(MBB, MI, Reg);
745         if (MO.isDead())
746           PhysKills.push_back(Reg);
747         continue;
748       }
749       if (MO.isDead())
750         VirtKills.push_back(Reg);
751       unsigned PhysReg = defineVirtReg(MBB, MI, i, Reg, CopySrc);
752       if (CopyDst == Reg)
753         CopyDst = PhysReg;
754       setPhysReg(MO, PhysReg);
755     }
756
757     // Spill all dirty virtregs before a call, in case of an exception.
758     if (TID.isCall()) {
759       DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
760       spillAll(MBB, MI);
761     }
762
763     // Process virtreg deads.
764     for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
765       killVirtReg(VirtKills[i]);
766     VirtKills.clear();
767
768     // Process physreg deads.
769     for (unsigned i = 0, e = PhysKills.size(); i != e; ++i)
770       killPhysReg(PhysKills[i]);
771     PhysKills.clear();
772
773     MRI->addPhysRegsUsed(UsedInInstr);
774   }
775
776   // Spill all physical registers holding virtual registers now.
777   DEBUG(dbgs() << "Killing live registers at end of block.\n");
778   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
779   while (!LiveVirtRegs.empty())
780     spillVirtReg(MBB, MI, LiveVirtRegs.begin()->first, true);
781
782   DEBUG(MBB.dump());
783 }
784
785 /// runOnMachineFunction - Register allocate the whole function
786 ///
787 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
788   DEBUG(dbgs() << "Machine Function\n");
789   DEBUG(Fn.dump());
790   MF = &Fn;
791   MRI = &MF->getRegInfo();
792   TM = &Fn.getTarget();
793   TRI = TM->getRegisterInfo();
794   TII = TM->getInstrInfo();
795
796   UsedInInstr.resize(TRI->getNumRegs());
797   ReservedRegs = TRI->getReservedRegs(*MF);
798
799   // initialize the virtual->physical register map to have a 'null'
800   // mapping for all virtual registers
801   unsigned LastVirtReg = MRI->getLastVirtReg();
802   StackSlotForVirtReg.grow(LastVirtReg);
803
804   // Loop over all of the basic blocks, eliminating virtual register references
805   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
806        MBB != MBBe; ++MBB)
807     AllocateBasicBlock(*MBB);
808
809   // Make sure the set of used physregs is closed under subreg operations.
810   MRI->closePhysRegsUsed(*TRI);
811
812   StackSlotForVirtReg.clear();
813   return true;
814 }
815
816 FunctionPass *llvm::createFastRegisterAllocator() {
817   return new RAFast();
818 }