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