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