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