Move some methods out of MachineInstr into MachineOperand
[oota-llvm.git] / lib / CodeGen / RegAllocLocal.cpp
1 //===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/Statistic.h"
28 #include <algorithm>
29 #include <iostream>
30 using namespace llvm;
31
32 namespace {
33   Statistic<> NumStores("ra-local", "Number of stores added");
34   Statistic<> NumLoads ("ra-local", "Number of loads added");
35   Statistic<> NumFolded("ra-local", "Number of loads/stores folded into "
36                         "instructions");
37   class RA : public MachineFunctionPass {
38     const TargetMachine *TM;
39     MachineFunction *MF;
40     const MRegisterInfo *RegInfo;
41     LiveVariables *LV;
42     bool *PhysRegsEverUsed;
43
44     // StackSlotForVirtReg - Maps virtual regs to the frame index where these
45     // values are spilled.
46     std::map<unsigned, int> StackSlotForVirtReg;
47
48     // Virt2PhysRegMap - This map contains entries for each virtual register
49     // that is currently available in a physical register.
50     DenseMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
51
52     unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
53       return Virt2PhysRegMap[VirtReg];
54     }
55
56     // PhysRegsUsed - This array is effectively a map, containing entries for
57     // each physical register that currently has a value (ie, it is in
58     // Virt2PhysRegMap).  The value mapped to is the virtual register
59     // corresponding to the physical register (the inverse of the
60     // Virt2PhysRegMap), or 0.  The value is set to 0 if this register is pinned
61     // because it is used by a future instruction.  If the entry for a physical
62     // register is -1, then the physical register is "not in the map".
63     //
64     std::vector<int> PhysRegsUsed;
65
66     // PhysRegsUseOrder - This contains a list of the physical registers that
67     // currently have a virtual register value in them.  This list provides an
68     // ordering of registers, imposing a reallocation order.  This list is only
69     // used if all registers are allocated and we have to spill one, in which
70     // case we spill the least recently used register.  Entries at the front of
71     // the list are the least recently used registers, entries at the back are
72     // the most recently used.
73     //
74     std::vector<unsigned> PhysRegsUseOrder;
75
76     // VirtRegModified - This bitset contains information about which virtual
77     // registers need to be spilled back to memory when their registers are
78     // scavenged.  If a virtual register has simply been rematerialized, there
79     // is no reason to spill it to memory when we need the register back.
80     //
81     std::vector<bool> VirtRegModified;
82
83     void markVirtRegModified(unsigned Reg, bool Val = true) {
84       assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
85       Reg -= MRegisterInfo::FirstVirtualRegister;
86       if (VirtRegModified.size() <= Reg) VirtRegModified.resize(Reg+1);
87       VirtRegModified[Reg] = Val;
88     }
89
90     bool isVirtRegModified(unsigned Reg) const {
91       assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
92       assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
93              && "Illegal virtual register!");
94       return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
95     }
96
97     void MarkPhysRegRecentlyUsed(unsigned Reg) {
98       if(PhysRegsUseOrder.empty() ||
99          PhysRegsUseOrder.back() == Reg) return;  // Already most recently used
100
101       for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
102         if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
103           unsigned RegMatch = PhysRegsUseOrder[i-1];       // remove from middle
104           PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
105           // Add it to the end of the list
106           PhysRegsUseOrder.push_back(RegMatch);
107           if (RegMatch == Reg)
108             return;    // Found an exact match, exit early
109         }
110     }
111
112   public:
113     virtual const char *getPassName() const {
114       return "Local Register Allocator";
115     }
116
117     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
118       AU.addRequired<LiveVariables>();
119       AU.addRequiredID(PHIEliminationID);
120       AU.addRequiredID(TwoAddressInstructionPassID);
121       MachineFunctionPass::getAnalysisUsage(AU);
122     }
123
124   private:
125     /// runOnMachineFunction - Register allocate the whole function
126     bool runOnMachineFunction(MachineFunction &Fn);
127
128     /// AllocateBasicBlock - Register allocate the specified basic block.
129     void AllocateBasicBlock(MachineBasicBlock &MBB);
130
131
132     /// areRegsEqual - This method returns true if the specified registers are
133     /// related to each other.  To do this, it checks to see if they are equal
134     /// or if the first register is in the alias set of the second register.
135     ///
136     bool areRegsEqual(unsigned R1, unsigned R2) const {
137       if (R1 == R2) return true;
138       for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
139            *AliasSet; ++AliasSet) {
140         if (*AliasSet == R1) return true;
141       }
142       return false;
143     }
144
145     /// getStackSpaceFor - This returns the frame index of the specified virtual
146     /// register on the stack, allocating space if necessary.
147     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
148
149     /// removePhysReg - This method marks the specified physical register as no
150     /// longer being in use.
151     ///
152     void removePhysReg(unsigned PhysReg);
153
154     /// spillVirtReg - This method spills the value specified by PhysReg into
155     /// the virtual register slot specified by VirtReg.  It then updates the RA
156     /// data structures to indicate the fact that PhysReg is now available.
157     ///
158     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
159                       unsigned VirtReg, unsigned PhysReg);
160
161     /// spillPhysReg - This method spills the specified physical register into
162     /// the virtual register slot associated with it.  If OnlyVirtRegs is set to
163     /// true, then the request is ignored if the physical register does not
164     /// contain a virtual register.
165     ///
166     void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
167                       unsigned PhysReg, bool OnlyVirtRegs = false);
168
169     /// assignVirtToPhysReg - This method updates local state so that we know
170     /// that PhysReg is the proper container for VirtReg now.  The physical
171     /// register must not be used for anything else when this is called.
172     ///
173     void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
174
175     /// liberatePhysReg - Make sure the specified physical register is available
176     /// for use.  If there is currently a value in it, it is either moved out of
177     /// the way or spilled to memory.
178     ///
179     void liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
180                          unsigned PhysReg);
181
182     /// isPhysRegAvailable - Return true if the specified physical register is
183     /// free and available for use.  This also includes checking to see if
184     /// aliased registers are all free...
185     ///
186     bool isPhysRegAvailable(unsigned PhysReg) const;
187
188     /// getFreeReg - Look to see if there is a free register available in the
189     /// specified register class.  If not, return 0.
190     ///
191     unsigned getFreeReg(const TargetRegisterClass *RC);
192
193     /// getReg - Find a physical register to hold the specified virtual
194     /// register.  If all compatible physical registers are used, this method
195     /// spills the last used virtual register to the stack, and uses that
196     /// register.
197     ///
198     unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
199                     unsigned VirtReg);
200
201     /// reloadVirtReg - This method transforms the specified specified virtual
202     /// register use to refer to a physical register.  This method may do this
203     /// in one of several ways: if the register is available in a physical
204     /// register already, it uses that physical register.  If the value is not
205     /// in a physical register, and if there are physical registers available,
206     /// it loads it into a register.  If register pressure is high, and it is
207     /// possible, it tries to fold the load of the virtual register into the
208     /// instruction itself.  It avoids doing this if register pressure is low to
209     /// improve the chance that subsequent instructions can use the reloaded
210     /// value.  This method returns the modified instruction.
211     ///
212     MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
213                                 unsigned OpNum);
214
215
216     void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
217                        unsigned PhysReg);
218   };
219 }
220
221 /// getStackSpaceFor - This allocates space for the specified virtual register
222 /// to be held on the stack.
223 int RA::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
224   // Find the location Reg would belong...
225   std::map<unsigned, int>::iterator I =StackSlotForVirtReg.lower_bound(VirtReg);
226
227   if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
228     return I->second;          // Already has space allocated?
229
230   // Allocate a new stack object for this spill location...
231   int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
232                                                        RC->getAlignment());
233
234   // Assign the slot...
235   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
236   return FrameIdx;
237 }
238
239
240 /// removePhysReg - This method marks the specified physical register as no
241 /// longer being in use.
242 ///
243 void RA::removePhysReg(unsigned PhysReg) {
244   PhysRegsUsed[PhysReg] = -1;      // PhyReg no longer used
245
246   std::vector<unsigned>::iterator It =
247     std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
248   if (It != PhysRegsUseOrder.end())
249     PhysRegsUseOrder.erase(It);
250 }
251
252
253 /// spillVirtReg - This method spills the value specified by PhysReg into the
254 /// virtual register slot specified by VirtReg.  It then updates the RA data
255 /// structures to indicate the fact that PhysReg is now available.
256 ///
257 void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
258                       unsigned VirtReg, unsigned PhysReg) {
259   assert(VirtReg && "Spilling a physical register is illegal!"
260          " Must not have appropriate kill for the register or use exists beyond"
261          " the intended one.");
262   DEBUG(std::cerr << "  Spilling register " << RegInfo->getName(PhysReg);
263         std::cerr << " containing %reg" << VirtReg;
264         if (!isVirtRegModified(VirtReg))
265         std::cerr << " which has not been modified, so no store necessary!");
266
267   // Otherwise, there is a virtual register corresponding to this physical
268   // register.  We only need to spill it into its stack slot if it has been
269   // modified.
270   if (isVirtRegModified(VirtReg)) {
271     const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
272     int FrameIndex = getStackSpaceFor(VirtReg, RC);
273     DEBUG(std::cerr << " to stack slot #" << FrameIndex);
274     RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
275     ++NumStores;   // Update statistics
276   }
277
278   getVirt2PhysRegMapSlot(VirtReg) = 0;   // VirtReg no longer available
279
280   DEBUG(std::cerr << "\n");
281   removePhysReg(PhysReg);
282 }
283
284
285 /// spillPhysReg - This method spills the specified physical register into the
286 /// virtual register slot associated with it.  If OnlyVirtRegs is set to true,
287 /// then the request is ignored if the physical register does not contain a
288 /// virtual register.
289 ///
290 void RA::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
291                       unsigned PhysReg, bool OnlyVirtRegs) {
292   if (PhysRegsUsed[PhysReg] != -1) {            // Only spill it if it's used!
293     if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
294       spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
295   } else {
296     // If the selected register aliases any other registers, we must make
297     // sure that one of the aliases isn't alive...
298     for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
299          *AliasSet; ++AliasSet)
300       if (PhysRegsUsed[*AliasSet] != -1)     // Spill aliased register...
301         if (PhysRegsUsed[*AliasSet] || !OnlyVirtRegs)
302           spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
303   }
304 }
305
306
307 /// assignVirtToPhysReg - This method updates local state so that we know
308 /// that PhysReg is the proper container for VirtReg now.  The physical
309 /// register must not be used for anything else when this is called.
310 ///
311 void RA::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
312   assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
313   // Update information to note the fact that this register was just used, and
314   // it holds VirtReg.
315   PhysRegsUsed[PhysReg] = VirtReg;
316   getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
317   PhysRegsUseOrder.push_back(PhysReg);   // New use of PhysReg
318 }
319
320
321 /// isPhysRegAvailable - Return true if the specified physical register is free
322 /// and available for use.  This also includes checking to see if aliased
323 /// registers are all free...
324 ///
325 bool RA::isPhysRegAvailable(unsigned PhysReg) const {
326   if (PhysRegsUsed[PhysReg] != -1) return false;
327
328   // If the selected register aliases any other allocated registers, it is
329   // not free!
330   for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
331        *AliasSet; ++AliasSet)
332     if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
333       return false;                    // Can't use this reg then.
334   return true;
335 }
336
337
338 /// getFreeReg - Look to see if there is a free register available in the
339 /// specified register class.  If not, return 0.
340 ///
341 unsigned RA::getFreeReg(const TargetRegisterClass *RC) {
342   // Get iterators defining the range of registers that are valid to allocate in
343   // this class, which also specifies the preferred allocation order.
344   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
345   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
346
347   for (; RI != RE; ++RI)
348     if (isPhysRegAvailable(*RI)) {       // Is reg unused?
349       assert(*RI != 0 && "Cannot use register!");
350       return *RI; // Found an unused register!
351     }
352   return 0;
353 }
354
355
356 /// liberatePhysReg - Make sure the specified physical register is available for
357 /// use.  If there is currently a value in it, it is either moved out of the way
358 /// or spilled to memory.
359 ///
360 void RA::liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
361                          unsigned PhysReg) {
362   spillPhysReg(MBB, I, PhysReg);
363 }
364
365
366 /// getReg - Find a physical register to hold the specified virtual
367 /// register.  If all compatible physical registers are used, this method spills
368 /// the last used virtual register to the stack, and uses that register.
369 ///
370 unsigned RA::getReg(MachineBasicBlock &MBB, MachineInstr *I,
371                     unsigned VirtReg) {
372   const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
373
374   // First check to see if we have a free register of the requested type...
375   unsigned PhysReg = getFreeReg(RC);
376
377   // If we didn't find an unused register, scavenge one now!
378   if (PhysReg == 0) {
379     assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
380
381     // Loop over all of the preallocated registers from the least recently used
382     // to the most recently used.  When we find one that is capable of holding
383     // our register, use it.
384     for (unsigned i = 0; PhysReg == 0; ++i) {
385       assert(i != PhysRegsUseOrder.size() &&
386              "Couldn't find a register of the appropriate class!");
387
388       unsigned R = PhysRegsUseOrder[i];
389
390       // We can only use this register if it holds a virtual register (ie, it
391       // can be spilled).  Do not use it if it is an explicitly allocated
392       // physical register!
393       assert(PhysRegsUsed[R] != -1 &&
394              "PhysReg in PhysRegsUseOrder, but is not allocated?");
395       if (PhysRegsUsed[R]) {
396         // If the current register is compatible, use it.
397         if (RC->contains(R)) {
398           PhysReg = R;
399           break;
400         } else {
401           // If one of the registers aliased to the current register is
402           // compatible, use it.
403           for (const unsigned *AliasSet = RegInfo->getAliasSet(R);
404                *AliasSet; ++AliasSet) {
405             if (RC->contains(*AliasSet)) {
406               PhysReg = *AliasSet;    // Take an aliased register
407               break;
408             }
409           }
410         }
411       }
412     }
413
414     assert(PhysReg && "Physical register not assigned!?!?");
415
416     // At this point PhysRegsUseOrder[i] is the least recently used register of
417     // compatible register class.  Spill it to memory and reap its remains.
418     spillPhysReg(MBB, I, PhysReg);
419   }
420
421   // Now that we know which register we need to assign this to, do it now!
422   assignVirtToPhysReg(VirtReg, PhysReg);
423   return PhysReg;
424 }
425
426
427 /// reloadVirtReg - This method transforms the specified specified virtual
428 /// register use to refer to a physical register.  This method may do this in
429 /// one of several ways: if the register is available in a physical register
430 /// already, it uses that physical register.  If the value is not in a physical
431 /// register, and if there are physical registers available, it loads it into a
432 /// register.  If register pressure is high, and it is possible, it tries to
433 /// fold the load of the virtual register into the instruction itself.  It
434 /// avoids doing this if register pressure is low to improve the chance that
435 /// subsequent instructions can use the reloaded value.  This method returns the
436 /// modified instruction.
437 ///
438 MachineInstr *RA::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
439                                 unsigned OpNum) {
440   unsigned VirtReg = MI->getOperand(OpNum).getReg();
441
442   // If the virtual register is already available, just update the instruction
443   // and return.
444   if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
445     MarkPhysRegRecentlyUsed(PR);          // Already have this value available!
446     MI->getOperand(OpNum).setReg(PR);  // Assign the input register
447     return MI;
448   }
449
450   // Otherwise, we need to fold it into the current instruction, or reload it.
451   // If we have registers available to hold the value, use them.
452   const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
453   unsigned PhysReg = getFreeReg(RC);
454   int FrameIndex = getStackSpaceFor(VirtReg, RC);
455
456   if (PhysReg) {   // Register is available, allocate it!
457     assignVirtToPhysReg(VirtReg, PhysReg);
458   } else {         // No registers available.
459     // If we can fold this spill into this instruction, do so now.
460     if (MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)){
461       ++NumFolded;
462       // Since we changed the address of MI, make sure to update live variables
463       // to know that the new instruction has the properties of the old one.
464       LV->instructionChanged(MI, FMI);
465       return MBB.insert(MBB.erase(MI), FMI);
466     }
467
468     // It looks like we can't fold this virtual register load into this
469     // instruction.  Force some poor hapless value out of the register file to
470     // make room for the new register, and reload it.
471     PhysReg = getReg(MBB, MI, VirtReg);
472   }
473
474   markVirtRegModified(VirtReg, false);   // Note that this reg was just reloaded
475
476   DEBUG(std::cerr << "  Reloading %reg" << VirtReg << " into "
477                   << RegInfo->getName(PhysReg) << "\n");
478
479   // Add move instruction(s)
480   RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
481   ++NumLoads;    // Update statistics
482
483   PhysRegsEverUsed[PhysReg] = true;
484   MI->getOperand(OpNum).setReg(PhysReg);  // Assign the input register
485   return MI;
486 }
487
488
489
490 void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
491   // loop over each instruction
492   MachineBasicBlock::iterator MII = MBB.begin();
493   const TargetInstrInfo &TII = *TM->getInstrInfo();
494   while (MII != MBB.end()) {
495     MachineInstr *MI = MII++;
496     const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
497     DEBUG(std::cerr << "\nStarting RegAlloc of: " << *MI;
498           std::cerr << "  Regs have values: ";
499           for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
500             if (PhysRegsUsed[i] != -1)
501                std::cerr << "[" << RegInfo->getName(i)
502                          << ",%reg" << PhysRegsUsed[i] << "] ";
503           std::cerr << "\n");
504
505     // Loop over the implicit uses, making sure that they are at the head of the
506     // use order list, so they don't get reallocated.
507     for (const unsigned *ImplicitUses = TID.ImplicitUses;
508          *ImplicitUses; ++ImplicitUses)
509       MarkPhysRegRecentlyUsed(*ImplicitUses);
510
511     // Get the used operands into registers.  This has the potential to spill
512     // incoming values if we are out of registers.  Note that we completely
513     // ignore physical register uses here.  We assume that if an explicit
514     // physical register is referenced by the instruction, that it is guaranteed
515     // to be live-in, or the input is badly hosed.
516     //
517     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
518       MachineOperand& MO = MI->getOperand(i);
519       // here we are looking for only used operands (never def&use)
520       if (!MO.isDef() && MO.isRegister() && MO.getReg() &&
521           MRegisterInfo::isVirtualRegister(MO.getReg()))
522         MI = reloadVirtReg(MBB, MI, i);
523     }
524
525     // If this instruction is the last user of anything in registers, kill the
526     // value, freeing the register being used, so it doesn't need to be
527     // spilled to memory.
528     //
529     for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
530            KE = LV->killed_end(MI); KI != KE; ++KI) {
531       unsigned VirtReg = *KI;
532       unsigned PhysReg = VirtReg;
533       if (MRegisterInfo::isVirtualRegister(VirtReg)) {
534         // If the virtual register was never materialized into a register, it
535         // might not be in the map, but it won't hurt to zero it out anyway.
536         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
537         PhysReg = PhysRegSlot;
538         PhysRegSlot = 0;
539       }
540
541       if (PhysReg) {
542         DEBUG(std::cerr << "  Last use of " << RegInfo->getName(PhysReg)
543               << "[%reg" << VirtReg <<"], removing it from live set\n");
544         removePhysReg(PhysReg);
545       }
546     }
547
548     // Loop over all of the operands of the instruction, spilling registers that
549     // are defined, and marking explicit destinations in the PhysRegsUsed map.
550     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
551       MachineOperand& MO = MI->getOperand(i);
552       if (MO.isDef() && MO.isRegister() && MO.getReg() &&
553           MRegisterInfo::isPhysicalRegister(MO.getReg())) {
554         unsigned Reg = MO.getReg();
555         PhysRegsEverUsed[Reg] = true;
556         spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in the reg
557         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
558         PhysRegsUseOrder.push_back(Reg);
559         for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
560              *AliasSet; ++AliasSet) {
561           PhysRegsUseOrder.push_back(*AliasSet);
562           PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
563           PhysRegsEverUsed[*AliasSet] = true;
564         }
565       }
566     }
567
568     // Loop over the implicit defs, spilling them as well.
569     for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
570          *ImplicitDefs; ++ImplicitDefs) {
571       unsigned Reg = *ImplicitDefs;
572       spillPhysReg(MBB, MI, Reg, true);
573       PhysRegsUseOrder.push_back(Reg);
574       PhysRegsUsed[Reg] = 0;            // It is free and reserved now
575       PhysRegsEverUsed[Reg] = true;
576
577       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
578            *AliasSet; ++AliasSet) {
579         PhysRegsUseOrder.push_back(*AliasSet);
580         PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
581         PhysRegsEverUsed[*AliasSet] = true;
582       }
583     }
584
585     // Okay, we have allocated all of the source operands and spilled any values
586     // that would be destroyed by defs of this instruction.  Loop over the
587     // explicit defs and assign them to a register, spilling incoming values if
588     // we need to scavenge a register.
589     //
590     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
591       MachineOperand& MO = MI->getOperand(i);
592       if (MO.isDef() && MO.isRegister() && MO.getReg() &&
593           MRegisterInfo::isVirtualRegister(MO.getReg())) {
594         unsigned DestVirtReg = MO.getReg();
595         unsigned DestPhysReg;
596
597         // If DestVirtReg already has a value, use it.
598         if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
599           DestPhysReg = getReg(MBB, MI, DestVirtReg);
600         PhysRegsEverUsed[DestPhysReg] = true;
601         markVirtRegModified(DestVirtReg);
602         MI->getOperand(i).setReg(DestPhysReg);  // Assign the output register
603       }
604     }
605
606     // If this instruction defines any registers that are immediately dead,
607     // kill them now.
608     //
609     for (LiveVariables::killed_iterator KI = LV->dead_begin(MI),
610            KE = LV->dead_end(MI); KI != KE; ++KI) {
611       unsigned VirtReg = *KI;
612       unsigned PhysReg = VirtReg;
613       if (MRegisterInfo::isVirtualRegister(VirtReg)) {
614         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
615         PhysReg = PhysRegSlot;
616         assert(PhysReg != 0);
617         PhysRegSlot = 0;
618       }
619
620       if (PhysReg) {
621         DEBUG(std::cerr << "  Register " << RegInfo->getName(PhysReg)
622               << " [%reg" << VirtReg
623               << "] is never used, removing it frame live list\n");
624         removePhysReg(PhysReg);
625       }
626     }
627     
628     // Finally, if this is a noop copy instruction, zap it.
629     unsigned SrcReg, DstReg;
630     if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg)
631       MBB.erase(MI);
632   }
633
634   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
635
636   // Spill all physical registers holding virtual registers now.
637   for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
638     if (PhysRegsUsed[i] != -1)
639       if (unsigned VirtReg = PhysRegsUsed[i])
640         spillVirtReg(MBB, MI, VirtReg, i);
641       else
642         removePhysReg(i);
643
644 #if 0
645   // This checking code is very expensive.
646   bool AllOk = true;
647   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
648            e = MF->getSSARegMap()->getLastVirtReg(); i <= e; ++i)
649     if (unsigned PR = Virt2PhysRegMap[i]) {
650       std::cerr << "Register still mapped: " << i << " -> " << PR << "\n";
651       AllOk = false;
652     }
653   assert(AllOk && "Virtual registers still in phys regs?");
654 #endif
655
656   // Clear any physical register which appear live at the end of the basic
657   // block, but which do not hold any virtual registers.  e.g., the stack
658   // pointer.
659   PhysRegsUseOrder.clear();
660 }
661
662
663 /// runOnMachineFunction - Register allocate the whole function
664 ///
665 bool RA::runOnMachineFunction(MachineFunction &Fn) {
666   DEBUG(std::cerr << "Machine Function " << "\n");
667   MF = &Fn;
668   TM = &Fn.getTarget();
669   RegInfo = TM->getRegisterInfo();
670   LV = &getAnalysis<LiveVariables>();
671
672   PhysRegsEverUsed = new bool[RegInfo->getNumRegs()];
673   std::fill(PhysRegsEverUsed, PhysRegsEverUsed+RegInfo->getNumRegs(), false);
674   Fn.setUsedPhysRegs(PhysRegsEverUsed);
675
676   PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
677
678   // initialize the virtual->physical register map to have a 'null'
679   // mapping for all virtual registers
680   Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
681
682   // Loop over all of the basic blocks, eliminating virtual register references
683   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
684        MBB != MBBe; ++MBB)
685     AllocateBasicBlock(*MBB);
686
687   StackSlotForVirtReg.clear();
688   PhysRegsUsed.clear();
689   VirtRegModified.clear();
690   Virt2PhysRegMap.clear();
691   return true;
692 }
693
694 FunctionPass *llvm::createLocalRegisterAllocator() {
695   return new RA();
696 }