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