c1dacb6cb89c0299fc2b75a28c106b2ac4a79bd0
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This register allocator allocates registers to a basic block at a time,
11 // attempting to keep values in registers and reusing registers as appropriate.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/IndexedMap.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include <algorithm>
34 #include <map>
35 using namespace llvm;
36
37 STATISTIC(NumStores, "Number of stores added");
38 STATISTIC(NumLoads , "Number of loads added");
39
40 static RegisterRegAlloc
41   localRegAlloc("local", "  local register allocator",
42                 createLocalRegisterAllocator);
43
44 namespace {
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 TargetRegisterInfo *TRI;
53     const TargetInstrInfo *TII;
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     // Virt2LastUseMap - This maps each virtual register to its last use
89     // (MachineInstr*, operand index pair).
90     IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
91     Virt2LastUseMap;
92
93     std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
94       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
95       return Virt2LastUseMap[Reg];
96     }
97
98     // VirtRegModified - This bitset contains information about which virtual
99     // registers need to be spilled back to memory when their registers are
100     // scavenged.  If a virtual register has simply been rematerialized, there
101     // is no reason to spill it to memory when we need the register back.
102     //
103     BitVector VirtRegModified;
104     
105     // UsedInMultipleBlocks - Tracks whether a particular register is used in
106     // more than one block.
107     BitVector UsedInMultipleBlocks;
108
109     void markVirtRegModified(unsigned Reg, bool Val = true) {
110       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
111       Reg -= TargetRegisterInfo::FirstVirtualRegister;
112       if (Val)
113         VirtRegModified.set(Reg);
114       else
115         VirtRegModified.reset(Reg);
116     }
117
118     bool isVirtRegModified(unsigned Reg) const {
119       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
120       assert(Reg - TargetRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
121              && "Illegal virtual register!");
122       return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
123     }
124
125     void AddToPhysRegsUseOrder(unsigned Reg) {
126       std::vector<unsigned>::iterator It =
127         std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
128       if (It != PhysRegsUseOrder.end())
129         PhysRegsUseOrder.erase(It);
130       PhysRegsUseOrder.push_back(Reg);
131     }
132
133     void MarkPhysRegRecentlyUsed(unsigned Reg) {
134       if (PhysRegsUseOrder.empty() ||
135           PhysRegsUseOrder.back() == Reg) return;  // Already most recently used
136
137       for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
138         if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
139           unsigned RegMatch = PhysRegsUseOrder[i-1];       // remove from middle
140           PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
141           // Add it to the end of the list
142           PhysRegsUseOrder.push_back(RegMatch);
143           if (RegMatch == Reg)
144             return;    // Found an exact match, exit early
145         }
146     }
147
148   public:
149     virtual const char *getPassName() const {
150       return "Local Register Allocator";
151     }
152
153     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154       AU.addRequiredID(PHIEliminationID);
155       AU.addRequiredID(TwoAddressInstructionPassID);
156       MachineFunctionPass::getAnalysisUsage(AU);
157     }
158
159   private:
160     /// runOnMachineFunction - Register allocate the whole function
161     bool runOnMachineFunction(MachineFunction &Fn);
162
163     /// AllocateBasicBlock - Register allocate the specified basic block.
164     void AllocateBasicBlock(MachineBasicBlock &MBB);
165
166
167     /// areRegsEqual - This method returns true if the specified registers are
168     /// related to each other.  To do this, it checks to see if they are equal
169     /// or if the first register is in the alias set of the second register.
170     ///
171     bool areRegsEqual(unsigned R1, unsigned R2) const {
172       if (R1 == R2) return true;
173       for (const unsigned *AliasSet = TRI->getAliasSet(R2);
174            *AliasSet; ++AliasSet) {
175         if (*AliasSet == R1) return true;
176       }
177       return false;
178     }
179
180     /// getStackSpaceFor - This returns the frame index of the specified virtual
181     /// register on the stack, allocating space if necessary.
182     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
183
184     /// removePhysReg - This method marks the specified physical register as no
185     /// longer being in use.
186     ///
187     void removePhysReg(unsigned PhysReg);
188
189     /// spillVirtReg - This method spills the value specified by PhysReg into
190     /// the virtual register slot specified by VirtReg.  It then updates the RA
191     /// data structures to indicate the fact that PhysReg is now available.
192     ///
193     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
194                       unsigned VirtReg, unsigned PhysReg);
195
196     /// spillPhysReg - This method spills the specified physical register into
197     /// the virtual register slot associated with it.  If OnlyVirtRegs is set to
198     /// true, then the request is ignored if the physical register does not
199     /// contain a virtual register.
200     ///
201     void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
202                       unsigned PhysReg, bool OnlyVirtRegs = false);
203
204     /// assignVirtToPhysReg - This method updates local state so that we know
205     /// that PhysReg is the proper container for VirtReg now.  The physical
206     /// register must not be used for anything else when this is called.
207     ///
208     void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
209
210     /// isPhysRegAvailable - Return true if the specified physical register is
211     /// free and available for use.  This also includes checking to see if
212     /// aliased registers are all free...
213     ///
214     bool isPhysRegAvailable(unsigned PhysReg) const;
215
216     /// getFreeReg - Look to see if there is a free register available in the
217     /// specified register class.  If not, return 0.
218     ///
219     unsigned getFreeReg(const TargetRegisterClass *RC);
220
221     /// getReg - Find a physical register to hold the specified virtual
222     /// register.  If all compatible physical registers are used, this method
223     /// spills the last used virtual register to the stack, and uses that
224     /// register.
225     ///
226     unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
227                     unsigned VirtReg);
228
229     /// reloadVirtReg - This method transforms the specified specified virtual
230     /// register use to refer to a physical register.  This method may do this
231     /// in one of several ways: if the register is available in a physical
232     /// register already, it uses that physical register.  If the value is not
233     /// in a physical register, and if there are physical registers available,
234     /// it loads it into a register.  If register pressure is high, and it is
235     /// possible, it tries to fold the load of the virtual register into the
236     /// instruction itself.  It avoids doing this if register pressure is low to
237     /// improve the chance that subsequent instructions can use the reloaded
238     /// value.  This method returns the modified instruction.
239     ///
240     MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
241                                 unsigned OpNum);
242
243     /// ComputeLocalLiveness - Computes liveness of registers within a basic
244     /// block, setting the killed/dead flags as appropriate.
245     void ComputeLocalLiveness(MachineBasicBlock& MBB);
246
247     void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
248                        unsigned PhysReg);
249   };
250   char RALocal::ID = 0;
251 }
252
253 /// getStackSpaceFor - This allocates space for the specified virtual register
254 /// to be held on the stack.
255 int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
256   // Find the location Reg would belong...
257   std::map<unsigned, int>::iterator I = StackSlotForVirtReg.find(VirtReg);
258
259   if (I != StackSlotForVirtReg.end())
260     return I->second;          // Already has space allocated?
261
262   // Allocate a new stack object for this spill location...
263   int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
264                                                        RC->getAlignment());
265
266   // Assign the slot...
267   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
268   return FrameIdx;
269 }
270
271
272 /// removePhysReg - This method marks the specified physical register as no
273 /// longer being in use.
274 ///
275 void RALocal::removePhysReg(unsigned PhysReg) {
276   PhysRegsUsed[PhysReg] = -1;      // PhyReg no longer used
277
278   std::vector<unsigned>::iterator It =
279     std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
280   if (It != PhysRegsUseOrder.end())
281     PhysRegsUseOrder.erase(It);
282 }
283
284
285 /// spillVirtReg - This method spills the value specified by PhysReg into the
286 /// virtual register slot specified by VirtReg.  It then updates the RA data
287 /// structures to indicate the fact that PhysReg is now available.
288 ///
289 void RALocal::spillVirtReg(MachineBasicBlock &MBB,
290                            MachineBasicBlock::iterator I,
291                            unsigned VirtReg, unsigned PhysReg) {
292   assert(VirtReg && "Spilling a physical register is illegal!"
293          " Must not have appropriate kill for the register or use exists beyond"
294          " the intended one.");
295   DOUT << "  Spilling register " << TRI->getName(PhysReg)
296        << " containing %reg" << VirtReg;
297   
298   if (!isVirtRegModified(VirtReg)) {
299     DOUT << " which has not been modified, so no store necessary!";
300     std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
301     if (LastUse.first)
302       LastUse.first->getOperand(LastUse.second).setIsKill();
303   } else {
304     // Otherwise, there is a virtual register corresponding to this physical
305     // register.  We only need to spill it into its stack slot if it has been
306     // modified.
307     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
308     int FrameIndex = getStackSpaceFor(VirtReg, RC);
309     DOUT << " to stack slot #" << FrameIndex;
310     // If the instruction reads the register that's spilled, (e.g. this can
311     // happen if it is a move to a physical register), then the spill
312     // instruction is not a kill.
313     bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
314     TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC);
315     ++NumStores;   // Update statistics
316   }
317
318   getVirt2PhysRegMapSlot(VirtReg) = 0;   // VirtReg no longer available
319
320   DOUT << "\n";
321   removePhysReg(PhysReg);
322 }
323
324
325 /// spillPhysReg - This method spills the specified physical register into the
326 /// virtual register slot associated with it.  If OnlyVirtRegs is set to true,
327 /// then the request is ignored if the physical register does not contain a
328 /// virtual register.
329 ///
330 void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
331                            unsigned PhysReg, bool OnlyVirtRegs) {
332   if (PhysRegsUsed[PhysReg] != -1) {            // Only spill it if it's used!
333     assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
334     if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
335       spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
336   } else {
337     // If the selected register aliases any other registers, we must make
338     // sure that one of the aliases isn't alive.
339     for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
340          *AliasSet; ++AliasSet)
341       if (PhysRegsUsed[*AliasSet] != -1 &&     // Spill aliased register.
342           PhysRegsUsed[*AliasSet] != -2)       // If allocatable.
343           if (PhysRegsUsed[*AliasSet])
344             spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
345   }
346 }
347
348
349 /// assignVirtToPhysReg - This method updates local state so that we know
350 /// that PhysReg is the proper container for VirtReg now.  The physical
351 /// register must not be used for anything else when this is called.
352 ///
353 void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
354   assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
355   // Update information to note the fact that this register was just used, and
356   // it holds VirtReg.
357   PhysRegsUsed[PhysReg] = VirtReg;
358   getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
359   AddToPhysRegsUseOrder(PhysReg);   // New use of PhysReg
360 }
361
362
363 /// isPhysRegAvailable - Return true if the specified physical register is free
364 /// and available for use.  This also includes checking to see if aliased
365 /// registers are all free...
366 ///
367 bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
368   if (PhysRegsUsed[PhysReg] != -1) return false;
369
370   // If the selected register aliases any other allocated registers, it is
371   // not free!
372   for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
373        *AliasSet; ++AliasSet)
374     if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
375       return false;                    // Can't use this reg then.
376   return true;
377 }
378
379
380 /// getFreeReg - Look to see if there is a free register available in the
381 /// specified register class.  If not, return 0.
382 ///
383 unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
384   // Get iterators defining the range of registers that are valid to allocate in
385   // this class, which also specifies the preferred allocation order.
386   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
387   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
388
389   for (; RI != RE; ++RI)
390     if (isPhysRegAvailable(*RI)) {       // Is reg unused?
391       assert(*RI != 0 && "Cannot use register!");
392       return *RI; // Found an unused register!
393     }
394   return 0;
395 }
396
397
398 /// getReg - Find a physical register to hold the specified virtual
399 /// register.  If all compatible physical registers are used, this method spills
400 /// the last used virtual register to the stack, and uses that register.
401 ///
402 unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
403                          unsigned VirtReg) {
404   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
405
406   // First check to see if we have a free register of the requested type...
407   unsigned PhysReg = getFreeReg(RC);
408
409   // If we didn't find an unused register, scavenge one now!
410   if (PhysReg == 0) {
411     assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
412
413     // Loop over all of the preallocated registers from the least recently used
414     // to the most recently used.  When we find one that is capable of holding
415     // our register, use it.
416     for (unsigned i = 0; PhysReg == 0; ++i) {
417       assert(i != PhysRegsUseOrder.size() &&
418              "Couldn't find a register of the appropriate class!");
419
420       unsigned R = PhysRegsUseOrder[i];
421
422       // We can only use this register if it holds a virtual register (ie, it
423       // can be spilled).  Do not use it if it is an explicitly allocated
424       // physical register!
425       assert(PhysRegsUsed[R] != -1 &&
426              "PhysReg in PhysRegsUseOrder, but is not allocated?");
427       if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
428         // If the current register is compatible, use it.
429         if (RC->contains(R)) {
430           PhysReg = R;
431           break;
432         } else {
433           // If one of the registers aliased to the current register is
434           // compatible, use it.
435           for (const unsigned *AliasIt = TRI->getAliasSet(R);
436                *AliasIt; ++AliasIt) {
437             if (RC->contains(*AliasIt) &&
438                 // If this is pinned down for some reason, don't use it.  For
439                 // example, if CL is pinned, and we run across CH, don't use
440                 // CH as justification for using scavenging ECX (which will
441                 // fail).
442                 PhysRegsUsed[*AliasIt] != 0 &&
443                 
444                 // Make sure the register is allocatable.  Don't allocate SIL on
445                 // x86-32.
446                 PhysRegsUsed[*AliasIt] != -2) {
447               PhysReg = *AliasIt;    // Take an aliased register
448               break;
449             }
450           }
451         }
452       }
453     }
454
455     assert(PhysReg && "Physical register not assigned!?!?");
456
457     // At this point PhysRegsUseOrder[i] is the least recently used register of
458     // compatible register class.  Spill it to memory and reap its remains.
459     spillPhysReg(MBB, I, PhysReg);
460   }
461
462   // Now that we know which register we need to assign this to, do it now!
463   assignVirtToPhysReg(VirtReg, PhysReg);
464   return PhysReg;
465 }
466
467
468 /// reloadVirtReg - This method transforms the specified specified virtual
469 /// register use to refer to a physical register.  This method may do this in
470 /// one of several ways: if the register is available in a physical register
471 /// already, it uses that physical register.  If the value is not in a physical
472 /// register, and if there are physical registers available, it loads it into a
473 /// register.  If register pressure is high, and it is possible, it tries to
474 /// fold the load of the virtual register into the instruction itself.  It
475 /// avoids doing this if register pressure is low to improve the chance that
476 /// subsequent instructions can use the reloaded value.  This method returns the
477 /// modified instruction.
478 ///
479 MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
480                                      unsigned OpNum) {
481   unsigned VirtReg = MI->getOperand(OpNum).getReg();
482
483   // If the virtual register is already available, just update the instruction
484   // and return.
485   if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
486     MarkPhysRegRecentlyUsed(PR);       // Already have this value available!
487     MI->getOperand(OpNum).setReg(PR);  // Assign the input register
488     getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
489     return MI;
490   }
491
492   // Otherwise, we need to fold it into the current instruction, or reload it.
493   // If we have registers available to hold the value, use them.
494   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
495   unsigned PhysReg = getFreeReg(RC);
496   int FrameIndex = getStackSpaceFor(VirtReg, RC);
497
498   if (PhysReg) {   // Register is available, allocate it!
499     assignVirtToPhysReg(VirtReg, PhysReg);
500   } else {         // No registers available.
501     // Force some poor hapless value out of the register file to
502     // make room for the new register, and reload it.
503     PhysReg = getReg(MBB, MI, VirtReg);
504   }
505
506   markVirtRegModified(VirtReg, false);   // Note that this reg was just reloaded
507
508   DOUT << "  Reloading %reg" << VirtReg << " into "
509        << TRI->getName(PhysReg) << "\n";
510
511   // Add move instruction(s)
512   TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
513   ++NumLoads;    // Update statistics
514
515   MF->getRegInfo().setPhysRegUsed(PhysReg);
516   MI->getOperand(OpNum).setReg(PhysReg);  // Assign the input register
517   getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
518   return MI;
519 }
520
521 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
522 /// read/mod/write register, i.e. update partial register.
523 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
524   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
525     MachineOperand& MO = MI->getOperand(i);
526     if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
527         MO.isDef() && !MO.isDead())
528       return true;
529   }
530   return false;
531 }
532
533 /// isReadModWriteImplicitDef - True if this is an implicit def for a
534 /// read/mod/write register, i.e. update partial register.
535 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
536   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
537     MachineOperand& MO = MI->getOperand(i);
538     if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
539         !MO.isDef() && MO.isKill())
540       return true;
541   }
542   return false;
543 }
544
545 // precedes - Helper function to determine with MachineInstr A
546 // precedes MachineInstr B within the same MBB.
547 static bool precedes(MachineBasicBlock::iterator A,
548                      MachineBasicBlock::iterator B) {
549   if (A == B)
550     return false;
551   
552   MachineBasicBlock::iterator I = A->getParent()->begin();
553   while (I != A->getParent()->end()) {
554     if (I == A)
555       return true;
556     else if (I == B)
557       return false;
558     
559     ++I;
560   }
561   
562   return false;
563 }
564
565 namespace llvm {
566   template<> struct DenseMapInfo<uint32_t> {
567     static inline uint32_t getEmptyKey() { return ~0; }
568     static inline uint32_t getTombstoneKey() { return ~0 - 1; }
569     static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
570     static bool isPod() { return true; }
571     static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
572       return LHS == RHS;
573     }
574   };
575 }
576
577 /// ComputeLocalLiveness - Computes liveness of registers within a basic
578 /// block, setting the killed/dead flags as appropriate.
579 void RALocal::ComputeLocalLiveness(MachineBasicBlock& MBB) {
580   MachineRegisterInfo& MRI = MBB.getParent()->getRegInfo();
581   // Keep track of the most recently seen previous use or def of each reg, 
582   // so that we can update them with dead/kill markers.
583   DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
584   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
585        I != E; ++I) {
586     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
587       MachineOperand& MO = I->getOperand(i);
588       // Uses don't trigger any flags, but we need to save
589       // them for later.  Also, we have to process these
590       // _before_ processing the defs, since an instr
591       // uses regs before it defs them.
592       if (MO.isReg() && MO.getReg() && MO.isUse())
593         LastUseDef[MO.getReg()] = std::make_pair(I, i);
594     }
595     
596     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
597       MachineOperand& MO = I->getOperand(i);
598       // Defs others than 2-addr redefs _do_ trigger flag changes:
599       //   - A def followed by a def is dead
600       //   - A use followed by a def is a kill
601       if (MO.isReg() && MO.getReg() && MO.isDef()) {
602         DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
603           last = LastUseDef.find(MO.getReg());
604         if (last != LastUseDef.end()) {
605           // Check if this is a two address instruction.  If so, then
606           // the def does not kill the use.
607           if (last->second.first == I) {
608             bool isTwoAddr = false;
609             for (unsigned j = i+1, je = I->getDesc().getNumOperands();
610                 j < je; ++j) {
611               const MachineOperand &MO2 = I->getOperand(j);
612               if (MO2.isRegister() && MO2.isUse() &&
613                   MO2.getReg() == MO.getReg() &&
614                   I->getDesc().getOperandConstraint(j, TOI::TIED_TO) == (int)i)
615                 isTwoAddr = true;
616             }
617
618             if (isTwoAddr) continue;
619           }
620           
621           MachineOperand& lastUD =
622                       last->second.first->getOperand(last->second.second);
623           if (lastUD.isDef())
624             lastUD.setIsDead(true);
625           else if (lastUD.isUse())
626             lastUD.setIsKill(true);
627         }
628         
629         LastUseDef[MO.getReg()] = std::make_pair(I, i);
630       }
631     }
632   }
633   
634   // Live-out (of the function) registers contain return values of the function,
635   // so we need to make sure they are alive at return time.
636   if (!MBB.empty() && MBB.back().getDesc().isReturn()) {
637     MachineInstr* Ret = &MBB.back();
638     for (MachineRegisterInfo::liveout_iterator
639          I = MF->getRegInfo().liveout_begin(),
640          E = MF->getRegInfo().liveout_end(); I != E; ++I)
641       if (!Ret->readsRegister(*I)) {
642         Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
643         LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
644       }
645   }
646   
647   // Finally, loop over the final use/def of each reg 
648   // in the block and determine if it is dead.
649   for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
650        I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
651     MachineInstr* MI = I->second.first;
652     unsigned idx = I->second.second;
653     MachineOperand& MO = MI->getOperand(idx);
654     
655     bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
656     
657     // A crude approximation of "live-out" calculation
658     bool usedOutsideBlock = isPhysReg ? false :   
659           UsedInMultipleBlocks.test(MO.getReg() -  
660                                     TargetRegisterInfo::FirstVirtualRegister);
661     if (!isPhysReg && !usedOutsideBlock)
662       for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
663            UE = MRI.reg_end(); UI != UE; ++UI)
664         // Two cases:
665         // - used in another block
666         // - used in the same block before it is defined (loop)
667         if (UI->getParent() != &MBB ||
668             (MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI))) {
669           UsedInMultipleBlocks.set(MO.getReg() - 
670                                    TargetRegisterInfo::FirstVirtualRegister);
671           usedOutsideBlock = true;
672           break;
673         }
674     
675     // Physical registers and those that are not live-out of the block
676     // are killed/dead at their last use/def within this block.
677     if (isPhysReg || !usedOutsideBlock) {
678       if (MO.isUse())
679         MO.setIsKill(true);
680       else if (MI->getOperand(idx).isDef())
681         MO.setIsDead(true);
682     }
683   }
684 }
685
686 void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
687   // loop over each instruction
688   MachineBasicBlock::iterator MII = MBB.begin();
689   
690   DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
691         if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
692
693   // If this is the first basic block in the machine function, add live-in
694   // registers as active.
695   if (&MBB == &*MF->begin() || MBB.isLandingPad()) {
696     for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
697          E = MBB.livein_end(); I != E; ++I) {
698       unsigned Reg = *I;
699       MF->getRegInfo().setPhysRegUsed(Reg);
700       PhysRegsUsed[Reg] = 0;            // It is free and reserved now
701       AddToPhysRegsUseOrder(Reg); 
702       for (const unsigned *AliasSet = TRI->getSubRegisters(Reg);
703            *AliasSet; ++AliasSet) {
704         if (PhysRegsUsed[*AliasSet] != -2) {
705           AddToPhysRegsUseOrder(*AliasSet); 
706           PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
707           MF->getRegInfo().setPhysRegUsed(*AliasSet);
708         }
709       }
710     }    
711   }
712   
713   ComputeLocalLiveness(MBB);
714   
715   // Otherwise, sequentially allocate each instruction in the MBB.
716   while (MII != MBB.end()) {
717     MachineInstr *MI = MII++;
718     const TargetInstrDesc &TID = MI->getDesc();
719     DEBUG(DOUT << "\nStarting RegAlloc of: " << *MI;
720           DOUT << "  Regs have values: ";
721           for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
722             if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
723                DOUT << "[" << TRI->getName(i)
724                     << ",%reg" << PhysRegsUsed[i] << "] ";
725           DOUT << "\n");
726
727     // Loop over the implicit uses, making sure that they are at the head of the
728     // use order list, so they don't get reallocated.
729     if (TID.ImplicitUses) {
730       for (const unsigned *ImplicitUses = TID.ImplicitUses;
731            *ImplicitUses; ++ImplicitUses)
732         MarkPhysRegRecentlyUsed(*ImplicitUses);
733     }
734
735     SmallVector<unsigned, 8> Kills;
736     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
737       MachineOperand& MO = MI->getOperand(i);
738       if (MO.isRegister() && MO.isKill()) {
739         if (!MO.isImplicit())
740           Kills.push_back(MO.getReg());
741         else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
742           // These are extra physical register kills when a sub-register
743           // is defined (def of a sub-register is a read/mod/write of the
744           // larger registers). Ignore.
745           Kills.push_back(MO.getReg());
746       }
747     }
748
749     // Get the used operands into registers.  This has the potential to spill
750     // incoming values if we are out of registers.  Note that we completely
751     // ignore physical register uses here.  We assume that if an explicit
752     // physical register is referenced by the instruction, that it is guaranteed
753     // to be live-in, or the input is badly hosed.
754     //
755     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
756       MachineOperand& MO = MI->getOperand(i);
757       // here we are looking for only used operands (never def&use)
758       if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
759           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
760         MI = reloadVirtReg(MBB, MI, i);
761     }
762
763     // If this instruction is the last user of this register, kill the
764     // value, freeing the register being used, so it doesn't need to be
765     // spilled to memory.
766     //
767     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
768       unsigned VirtReg = Kills[i];
769       unsigned PhysReg = VirtReg;
770       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
771         // If the virtual register was never materialized into a register, it
772         // might not be in the map, but it won't hurt to zero it out anyway.
773         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
774         PhysReg = PhysRegSlot;
775         PhysRegSlot = 0;
776       } else if (PhysRegsUsed[PhysReg] == -2) {
777         // Unallocatable register dead, ignore.
778         continue;
779       } else {
780         assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
781                "Silently clearing a virtual register?");
782       }
783
784       if (PhysReg) {
785         DOUT << "  Last use of " << TRI->getName(PhysReg)
786              << "[%reg" << VirtReg <<"], removing it from live set\n";
787         removePhysReg(PhysReg);
788         for (const unsigned *AliasSet = TRI->getSubRegisters(PhysReg);
789              *AliasSet; ++AliasSet) {
790           if (PhysRegsUsed[*AliasSet] != -2) {
791             DOUT  << "  Last use of "
792                   << TRI->getName(*AliasSet)
793                   << "[%reg" << VirtReg <<"], removing it from live set\n";
794             removePhysReg(*AliasSet);
795           }
796         }
797       }
798     }
799
800     // Loop over all of the operands of the instruction, spilling registers that
801     // are defined, and marking explicit destinations in the PhysRegsUsed map.
802     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
803       MachineOperand& MO = MI->getOperand(i);
804       if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
805           TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
806         unsigned Reg = MO.getReg();
807         if (PhysRegsUsed[Reg] == -2) continue;  // Something like ESP.
808         // These are extra physical register defs when a sub-register
809         // is defined (def of a sub-register is a read/mod/write of the
810         // larger registers). Ignore.
811         if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
812
813         MF->getRegInfo().setPhysRegUsed(Reg);
814         spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
815         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
816         AddToPhysRegsUseOrder(Reg); 
817
818         for (const unsigned *AliasSet = TRI->getSubRegisters(Reg);
819              *AliasSet; ++AliasSet) {
820           if (PhysRegsUsed[*AliasSet] != -2) {
821             MF->getRegInfo().setPhysRegUsed(*AliasSet);
822             PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
823             AddToPhysRegsUseOrder(*AliasSet); 
824           }
825         }
826       }
827     }
828
829     // Loop over the implicit defs, spilling them as well.
830     if (TID.ImplicitDefs) {
831       for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
832            *ImplicitDefs; ++ImplicitDefs) {
833         unsigned Reg = *ImplicitDefs;
834         if (PhysRegsUsed[Reg] != -2) {
835           spillPhysReg(MBB, MI, Reg, true);
836           AddToPhysRegsUseOrder(Reg); 
837           PhysRegsUsed[Reg] = 0;            // It is free and reserved now
838         }
839         MF->getRegInfo().setPhysRegUsed(Reg);
840         for (const unsigned *AliasSet = TRI->getSubRegisters(Reg);
841              *AliasSet; ++AliasSet) {
842           if (PhysRegsUsed[*AliasSet] != -2) {
843             AddToPhysRegsUseOrder(*AliasSet); 
844             PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
845             MF->getRegInfo().setPhysRegUsed(*AliasSet);
846           }
847         }
848       }
849     }
850
851     SmallVector<unsigned, 8> DeadDefs;
852     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
853       MachineOperand& MO = MI->getOperand(i);
854       if (MO.isRegister() && MO.isDead())
855         DeadDefs.push_back(MO.getReg());
856     }
857
858     // Okay, we have allocated all of the source operands and spilled any values
859     // that would be destroyed by defs of this instruction.  Loop over the
860     // explicit defs and assign them to a register, spilling incoming values if
861     // we need to scavenge a register.
862     //
863     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
864       MachineOperand& MO = MI->getOperand(i);
865       if (MO.isRegister() && MO.isDef() && MO.getReg() &&
866           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
867         unsigned DestVirtReg = MO.getReg();
868         unsigned DestPhysReg;
869
870         // If DestVirtReg already has a value, use it.
871         if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
872           DestPhysReg = getReg(MBB, MI, DestVirtReg);
873         MF->getRegInfo().setPhysRegUsed(DestPhysReg);
874         markVirtRegModified(DestVirtReg);
875         getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
876         DOUT << "  Assigning " << TRI->getName(DestPhysReg)
877              << " to %reg" << DestVirtReg << "\n";
878         MO.setReg(DestPhysReg);  // Assign the output register
879       }
880     }
881
882     // If this instruction defines any registers that are immediately dead,
883     // kill them now.
884     //
885     for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
886       unsigned VirtReg = DeadDefs[i];
887       unsigned PhysReg = VirtReg;
888       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
889         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
890         PhysReg = PhysRegSlot;
891         assert(PhysReg != 0);
892         PhysRegSlot = 0;
893       } else if (PhysRegsUsed[PhysReg] == -2) {
894         // Unallocatable register dead, ignore.
895         continue;
896       }
897
898       if (PhysReg) {
899         DOUT  << "  Register " << TRI->getName(PhysReg)
900               << " [%reg" << VirtReg
901               << "] is never used, removing it frame live list\n";
902         removePhysReg(PhysReg);
903         for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
904              *AliasSet; ++AliasSet) {
905           if (PhysRegsUsed[*AliasSet] != -2) {
906             DOUT  << "  Register " << TRI->getName(*AliasSet)
907                   << " [%reg" << *AliasSet
908                   << "] is never used, removing it frame live list\n";
909             removePhysReg(*AliasSet);
910           }
911         }
912       }
913     }
914     
915     // Finally, if this is a noop copy instruction, zap it.
916     unsigned SrcReg, DstReg;
917     if (TII->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg)
918       MBB.erase(MI);
919   }
920
921   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
922
923   // Spill all physical registers holding virtual registers now.
924   for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
925     if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
926       if (unsigned VirtReg = PhysRegsUsed[i])
927         spillVirtReg(MBB, MI, VirtReg, i);
928       else
929         removePhysReg(i);
930     }
931
932 #if 0
933   // This checking code is very expensive.
934   bool AllOk = true;
935   for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
936            e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
937     if (unsigned PR = Virt2PhysRegMap[i]) {
938       cerr << "Register still mapped: " << i << " -> " << PR << "\n";
939       AllOk = false;
940     }
941   assert(AllOk && "Virtual registers still in phys regs?");
942 #endif
943
944   // Clear any physical register which appear live at the end of the basic
945   // block, but which do not hold any virtual registers.  e.g., the stack
946   // pointer.
947   PhysRegsUseOrder.clear();
948 }
949
950 /// runOnMachineFunction - Register allocate the whole function
951 ///
952 bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
953   DOUT << "Machine Function " << "\n";
954   MF = &Fn;
955   TM = &Fn.getTarget();
956   TRI = TM->getRegisterInfo();
957   TII = TM->getInstrInfo();
958
959   PhysRegsUsed.assign(TRI->getNumRegs(), -1);
960   
961   // At various places we want to efficiently check to see whether a register
962   // is allocatable.  To handle this, we mark all unallocatable registers as
963   // being pinned down, permanently.
964   {
965     BitVector Allocable = TRI->getAllocatableSet(Fn);
966     for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
967       if (!Allocable[i])
968         PhysRegsUsed[i] = -2;  // Mark the reg unallocable.
969   }
970
971   // initialize the virtual->physical register map to have a 'null'
972   // mapping for all virtual registers
973   unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
974   Virt2PhysRegMap.grow(LastVirtReg);
975   Virt2LastUseMap.grow(LastVirtReg);
976   VirtRegModified.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
977   UsedInMultipleBlocks.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
978  
979   // Loop over all of the basic blocks, eliminating virtual register references
980   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
981        MBB != MBBe; ++MBB)
982     AllocateBasicBlock(*MBB);
983
984   StackSlotForVirtReg.clear();
985   PhysRegsUsed.clear();
986   VirtRegModified.clear();
987   UsedInMultipleBlocks.clear();
988   Virt2PhysRegMap.clear();
989   Virt2LastUseMap.clear();
990   return true;
991 }
992
993 FunctionPass *llvm::createLocalRegisterAllocator() {
994   return new RALocal();
995 }