9567308aa73d255329dfb64358966ffa039d3e10
[oota-llvm.git] / lib / CodeGen / RegAllocFast.cpp
1 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This register allocator allocates registers to a basic block at a time,
11 // attempting to keep values in registers and reusing registers as appropriate.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/Passes.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/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/IndexedMap.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 STATISTIC(NumStores, "Number of stores added");
40 STATISTIC(NumLoads , "Number of loads added");
41 STATISTIC(NumCopies, "Number of copies coalesced");
42
43 static RegisterRegAlloc
44   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
45
46 namespace {
47   class RAFast : public MachineFunctionPass {
48   public:
49     static char ID;
50     RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1),
51                isBulkSpilling(false) {}
52   private:
53     const TargetMachine *TM;
54     MachineFunction *MF;
55     MachineRegisterInfo *MRI;
56     const TargetRegisterInfo *TRI;
57     const TargetInstrInfo *TII;
58
59     // Basic block currently being allocated.
60     MachineBasicBlock *MBB;
61
62     // StackSlotForVirtReg - Maps virtual regs to the frame index where these
63     // values are spilled.
64     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
65
66     // Everything we know about a live virtual register.
67     struct LiveReg {
68       MachineInstr *LastUse;    // Last instr to use reg.
69       unsigned PhysReg;         // Currently held here.
70       unsigned short LastOpNum; // OpNum on LastUse.
71       bool Dirty;               // Register needs spill.
72
73       LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
74                               Dirty(false) {}
75     };
76
77     typedef DenseMap<unsigned, LiveReg> LiveRegMap;
78     typedef LiveRegMap::value_type LiveRegEntry;
79
80     // LiveVirtRegs - This map contains entries for each virtual register
81     // that is currently available in a physical register.
82     LiveRegMap LiveVirtRegs;
83
84     DenseMap<unsigned, MachineInstr *> LiveDbgValueMap;
85
86     // RegState - Track the state of a physical register.
87     enum RegState {
88       // A disabled register is not available for allocation, but an alias may
89       // be in use. A register can only be moved out of the disabled state if
90       // all aliases are disabled.
91       regDisabled,
92
93       // A free register is not currently in use and can be allocated
94       // immediately without checking aliases.
95       regFree,
96
97       // A reserved register has been assigned expolicitly (e.g., setting up a
98       // call parameter), and it remains reserved until it is used.
99       regReserved
100
101       // A register state may also be a virtual register number, indication that
102       // the physical register is currently allocated to a virtual register. In
103       // that case, LiveVirtRegs contains the inverse mapping.
104     };
105
106     // PhysRegState - One of the RegState enums, or a virtreg.
107     std::vector<unsigned> PhysRegState;
108
109     // UsedInInstr - BitVector of physregs that are used in the current
110     // instruction, and so cannot be allocated.
111     BitVector UsedInInstr;
112
113     // Allocatable - vector of allocatable physical registers.
114     BitVector Allocatable;
115
116     // SkippedInstrs - Descriptors of instructions whose clobber list was ignored
117     // because all registers were spilled. It is still necessary to mark all the
118     // clobbered registers as used by the function.
119     SmallPtrSet<const TargetInstrDesc*, 4> SkippedInstrs;
120
121     // isBulkSpilling - This flag is set when LiveRegMap will be cleared
122     // completely after spilling all live registers. LiveRegMap entries should
123     // not be erased.
124     bool isBulkSpilling;
125
126     enum {
127       spillClean = 1,
128       spillDirty = 100,
129       spillImpossible = ~0u
130     };
131   public:
132     virtual const char *getPassName() const {
133       return "Fast Register Allocator";
134     }
135
136     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
137       AU.setPreservesCFG();
138       AU.addRequiredID(PHIEliminationID);
139       AU.addRequiredID(TwoAddressInstructionPassID);
140       MachineFunctionPass::getAnalysisUsage(AU);
141     }
142
143   private:
144     bool runOnMachineFunction(MachineFunction &Fn);
145     void AllocateBasicBlock();
146     void handleThroughOperands(MachineInstr *MI,
147                                SmallVectorImpl<unsigned> &VirtDead);
148     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
149     bool isLastUseOfLocalReg(MachineOperand&);
150
151     void addKillFlag(const LiveReg&);
152     void killVirtReg(LiveRegMap::iterator);
153     void killVirtReg(unsigned VirtReg);
154     void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
155     void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
156
157     void usePhysReg(MachineOperand&);
158     void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
159     unsigned calcSpillCost(unsigned PhysReg) const;
160     void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
161     void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
162     LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
163                                        unsigned VirtReg, unsigned Hint);
164     LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
165                                        unsigned VirtReg, unsigned Hint);
166     void spillAll(MachineInstr *MI);
167     bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
168   };
169   char RAFast::ID = 0;
170 }
171
172 /// getStackSpaceFor - This allocates space for the specified virtual register
173 /// to be held on the stack.
174 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
175   // Find the location Reg would belong...
176   int SS = StackSlotForVirtReg[VirtReg];
177   if (SS != -1)
178     return SS;          // Already has space allocated?
179
180   // Allocate a new stack object for this spill location...
181   int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
182                                                             RC->getAlignment());
183
184   // Assign the slot.
185   StackSlotForVirtReg[VirtReg] = FrameIdx;
186   return FrameIdx;
187 }
188
189 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
190 /// its virtual register, and it is guaranteed to be a block-local register.
191 ///
192 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
193   // Check for non-debug uses or defs following MO.
194   // This is the most likely way to fail - fast path it.
195   MachineOperand *Next = &MO;
196   while ((Next = Next->getNextOperandForReg()))
197     if (!Next->isDebug())
198       return false;
199
200   // If the register has ever been spilled or reloaded, we conservatively assume
201   // it is a global register used in multiple blocks.
202   if (StackSlotForVirtReg[MO.getReg()] != -1)
203     return false;
204
205   // Check that the use/def chain has exactly one operand - MO.
206   return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
207 }
208
209 /// addKillFlag - Set kill flags on last use of a virtual register.
210 void RAFast::addKillFlag(const LiveReg &LR) {
211   if (!LR.LastUse) return;
212   MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
213   if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
214     if (MO.getReg() == LR.PhysReg)
215       MO.setIsKill();
216     else
217       LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
218   }
219 }
220
221 /// killVirtReg - Mark virtreg as no longer available.
222 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
223   addKillFlag(LRI->second);
224   const LiveReg &LR = LRI->second;
225   assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
226   PhysRegState[LR.PhysReg] = regFree;
227   // Erase from LiveVirtRegs unless we're spilling in bulk.
228   if (!isBulkSpilling)
229     LiveVirtRegs.erase(LRI);
230 }
231
232 /// killVirtReg - Mark virtreg as no longer available.
233 void RAFast::killVirtReg(unsigned VirtReg) {
234   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
235          "killVirtReg needs a virtual register");
236   LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
237   if (LRI != LiveVirtRegs.end())
238     killVirtReg(LRI);
239 }
240
241 /// spillVirtReg - This method spills the value specified by VirtReg into the
242 /// corresponding stack slot if needed. If isKill is set, the register is also
243 /// killed.
244 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
245   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
246          "Spilling a physical register is illegal!");
247   LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
248   assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
249   spillVirtReg(MI, LRI);
250 }
251
252 /// spillVirtReg - Do the actual work of spilling.
253 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
254                           LiveRegMap::iterator LRI) {
255   LiveReg &LR = LRI->second;
256   assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
257
258   if (LR.Dirty) {
259     // If this physreg is used by the instruction, we want to kill it on the
260     // instruction, not on the spill.
261     bool SpillKill = LR.LastUse != MI;
262     LR.Dirty = false;
263     DEBUG(dbgs() << "Spilling %reg" << LRI->first
264                  << " in " << TRI->getName(LR.PhysReg));
265     const TargetRegisterClass *RC = MRI->getRegClass(LRI->first);
266     int FI = getStackSpaceFor(LRI->first, RC);
267     DEBUG(dbgs() << " to stack slot #" << FI << "\n");
268     TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
269     ++NumStores;   // Update statistics
270
271     // If this register is used by DBG_VALUE then insert new DBG_VALUE to 
272     // identify spilled location as the place to find corresponding variable's
273     // value.
274     if (MachineInstr *DBG = LiveDbgValueMap.lookup(LRI->first)) {
275       const MDNode *MDPtr = 
276         DBG->getOperand(DBG->getNumOperands()-1).getMetadata();
277       int64_t Offset = 0;
278       if (DBG->getOperand(1).isImm())
279         Offset = DBG->getOperand(1).getImm();
280       DebugLoc DL = MI->getDebugLoc();
281       if (MachineInstr *NewDV = 
282           TII->emitFrameIndexDebugValue(*MF, FI, Offset, MDPtr, DL)) {
283         MachineBasicBlock *MBB = DBG->getParent();
284         MBB->insert(MI, NewDV);
285         DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
286         LiveDbgValueMap[LRI->first] = NewDV;
287       }
288     }
289     if (SpillKill)
290       LR.LastUse = 0; // Don't kill register again
291   }
292   killVirtReg(LRI);
293 }
294
295 /// spillAll - Spill all dirty virtregs without killing them.
296 void RAFast::spillAll(MachineInstr *MI) {
297   if (LiveVirtRegs.empty()) return;
298   isBulkSpilling = true;
299   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
300   // of spilling here is deterministic, if arbitrary.
301   for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
302        i != e; ++i)
303     spillVirtReg(MI, i);
304   LiveVirtRegs.clear();
305   isBulkSpilling = false;
306 }
307
308 /// usePhysReg - Handle the direct use of a physical register.
309 /// Check that the register is not used by a virtreg.
310 /// Kill the physreg, marking it free.
311 /// This may add implicit kills to MO->getParent() and invalidate MO.
312 void RAFast::usePhysReg(MachineOperand &MO) {
313   unsigned PhysReg = MO.getReg();
314   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
315          "Bad usePhysReg operand");
316
317   switch (PhysRegState[PhysReg]) {
318   case regDisabled:
319     break;
320   case regReserved:
321     PhysRegState[PhysReg] = regFree;
322     // Fall through
323   case regFree:
324     UsedInInstr.set(PhysReg);
325     MO.setIsKill();
326     return;
327   default:
328     // The physreg was allocated to a virtual register. That means to value we
329     // wanted has been clobbered.
330     llvm_unreachable("Instruction uses an allocated register");
331   }
332
333   // Maybe a superregister is reserved?
334   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
335        unsigned Alias = *AS; ++AS) {
336     switch (PhysRegState[Alias]) {
337     case regDisabled:
338       break;
339     case regReserved:
340       assert(TRI->isSuperRegister(PhysReg, Alias) &&
341              "Instruction is not using a subregister of a reserved register");
342       // Leave the superregister in the working set.
343       PhysRegState[Alias] = regFree;
344       UsedInInstr.set(Alias);
345       MO.getParent()->addRegisterKilled(Alias, TRI, true);
346       return;
347     case regFree:
348       if (TRI->isSuperRegister(PhysReg, Alias)) {
349         // Leave the superregister in the working set.
350         UsedInInstr.set(Alias);
351         MO.getParent()->addRegisterKilled(Alias, TRI, true);
352         return;
353       }
354       // Some other alias was in the working set - clear it.
355       PhysRegState[Alias] = regDisabled;
356       break;
357     default:
358       llvm_unreachable("Instruction uses an alias of an allocated register");
359     }
360   }
361
362   // All aliases are disabled, bring register into working set.
363   PhysRegState[PhysReg] = regFree;
364   UsedInInstr.set(PhysReg);
365   MO.setIsKill();
366 }
367
368 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
369 /// virtregs. This is very similar to defineVirtReg except the physreg is
370 /// reserved instead of allocated.
371 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
372                            RegState NewState) {
373   UsedInInstr.set(PhysReg);
374   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
375   case regDisabled:
376     break;
377   default:
378     spillVirtReg(MI, VirtReg);
379     // Fall through.
380   case regFree:
381   case regReserved:
382     PhysRegState[PhysReg] = NewState;
383     return;
384   }
385
386   // This is a disabled register, disable all aliases.
387   PhysRegState[PhysReg] = NewState;
388   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
389        unsigned Alias = *AS; ++AS) {
390     UsedInInstr.set(Alias);
391     switch (unsigned VirtReg = PhysRegState[Alias]) {
392     case regDisabled:
393       break;
394     default:
395       spillVirtReg(MI, VirtReg);
396       // Fall through.
397     case regFree:
398     case regReserved:
399       PhysRegState[Alias] = regDisabled;
400       if (TRI->isSuperRegister(PhysReg, Alias))
401         return;
402       break;
403     }
404   }
405 }
406
407
408 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
409 // aliases so it is free for allocation.
410 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
411 // can be allocated directly.
412 // Returns spillImpossible when PhysReg or an alias can't be spilled.
413 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
414   if (UsedInInstr.test(PhysReg))
415     return spillImpossible;
416   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
417   case regDisabled:
418     break;
419   case regFree:
420     return 0;
421   case regReserved:
422     return spillImpossible;
423   default:
424     return LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
425   }
426
427   // This is a disabled register, add up const of aliases.
428   unsigned Cost = 0;
429   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
430        unsigned Alias = *AS; ++AS) {
431     if (UsedInInstr.test(Alias))
432       return spillImpossible;
433     switch (unsigned VirtReg = PhysRegState[Alias]) {
434     case regDisabled:
435       break;
436     case regFree:
437       ++Cost;
438       break;
439     case regReserved:
440       return spillImpossible;
441     default:
442       Cost += LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
443       break;
444     }
445   }
446   return Cost;
447 }
448
449
450 /// assignVirtToPhysReg - This method updates local state so that we know
451 /// that PhysReg is the proper container for VirtReg now.  The physical
452 /// register must not be used for anything else when this is called.
453 ///
454 void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
455   DEBUG(dbgs() << "Assigning %reg" << LRE.first << " to "
456                << TRI->getName(PhysReg) << "\n");
457   PhysRegState[PhysReg] = LRE.first;
458   assert(!LRE.second.PhysReg && "Already assigned a physreg");
459   LRE.second.PhysReg = PhysReg;
460 }
461
462 /// allocVirtReg - Allocate a physical register for VirtReg.
463 void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
464   const unsigned VirtReg = LRE.first;
465
466   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
467          "Can only allocate virtual registers");
468
469   const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
470
471   // Ignore invalid hints.
472   if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
473                !RC->contains(Hint) || !Allocatable.test(Hint)))
474     Hint = 0;
475
476   // Take hint when possible.
477   if (Hint) {
478     switch(calcSpillCost(Hint)) {
479     default:
480       definePhysReg(MI, Hint, regFree);
481       // Fall through.
482     case 0:
483       return assignVirtToPhysReg(LRE, Hint);
484     case spillImpossible:
485       break;
486     }
487   }
488
489   TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
490   TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
491
492   // First try to find a completely free register.
493   for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
494     unsigned PhysReg = *I;
495     if (PhysRegState[PhysReg] == regFree && !UsedInInstr.test(PhysReg))
496       return assignVirtToPhysReg(LRE, PhysReg);
497   }
498
499   DEBUG(dbgs() << "Allocating %reg" << VirtReg << " from " << RC->getName()
500                << "\n");
501
502   unsigned BestReg = 0, BestCost = spillImpossible;
503   for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
504     unsigned Cost = calcSpillCost(*I);
505     // Cost is 0 when all aliases are already disabled.
506     if (Cost == 0)
507       return assignVirtToPhysReg(LRE, *I);
508     if (Cost < BestCost)
509       BestReg = *I, BestCost = Cost;
510   }
511
512   if (BestReg) {
513     definePhysReg(MI, BestReg, regFree);
514     return assignVirtToPhysReg(LRE, BestReg);
515   }
516
517   // Nothing we can do.
518   std::string msg;
519   raw_string_ostream Msg(msg);
520   Msg << "Ran out of registers during register allocation!";
521   if (MI->isInlineAsm()) {
522     Msg << "\nPlease check your inline asm statement for "
523         << "invalid constraints:\n";
524     MI->print(Msg, TM);
525   }
526   report_fatal_error(Msg.str());
527 }
528
529 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
530 RAFast::LiveRegMap::iterator
531 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
532                       unsigned VirtReg, unsigned Hint) {
533   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
534          "Not a virtual register");
535   LiveRegMap::iterator LRI;
536   bool New;
537   tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
538   LiveReg &LR = LRI->second;
539   if (New) {
540     // If there is no hint, peek at the only use of this register.
541     if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
542         MRI->hasOneNonDBGUse(VirtReg)) {
543       const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
544       // It's a copy, use the destination register as a hint.
545       if (UseMI.isCopyLike())
546         Hint = UseMI.getOperand(0).getReg();
547     }
548     allocVirtReg(MI, *LRI, Hint);
549   } else if (LR.LastUse) {
550     // Redefining a live register - kill at the last use, unless it is this
551     // instruction defining VirtReg multiple times.
552     if (LR.LastUse != MI || LR.LastUse->getOperand(LR.LastOpNum).isUse())
553       addKillFlag(LR);
554   }
555   assert(LR.PhysReg && "Register not assigned");
556   LR.LastUse = MI;
557   LR.LastOpNum = OpNum;
558   LR.Dirty = true;
559   UsedInInstr.set(LR.PhysReg);
560   return LRI;
561 }
562
563 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
564 RAFast::LiveRegMap::iterator
565 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
566                       unsigned VirtReg, unsigned Hint) {
567   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
568          "Not a virtual register");
569   LiveRegMap::iterator LRI;
570   bool New;
571   tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
572   LiveReg &LR = LRI->second;
573   MachineOperand &MO = MI->getOperand(OpNum);
574   if (New) {
575     allocVirtReg(MI, *LRI, Hint);
576     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
577     int FrameIndex = getStackSpaceFor(VirtReg, RC);
578     DEBUG(dbgs() << "Reloading %reg" << VirtReg << " into "
579                  << TRI->getName(LR.PhysReg) << "\n");
580     TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
581     ++NumLoads;
582   } else if (LR.Dirty) {
583     if (isLastUseOfLocalReg(MO)) {
584       DEBUG(dbgs() << "Killing last use: " << MO << "\n");
585       if (MO.isUse())
586         MO.setIsKill();
587       else
588         MO.setIsDead();
589     } else if (MO.isKill()) {
590       DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
591       MO.setIsKill(false);
592     } else if (MO.isDead()) {
593       DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
594       MO.setIsDead(false);
595     }
596   } else if (MO.isKill()) {
597     // We must remove kill flags from uses of reloaded registers because the
598     // register would be killed immediately, and there might be a second use:
599     //   %foo = OR %x<kill>, %x
600     // This would cause a second reload of %x into a different register.
601     DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
602     MO.setIsKill(false);
603   } else if (MO.isDead()) {
604     DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
605     MO.setIsDead(false);
606   }
607   assert(LR.PhysReg && "Register not assigned");
608   LR.LastUse = MI;
609   LR.LastOpNum = OpNum;
610   UsedInInstr.set(LR.PhysReg);
611   return LRI;
612 }
613
614 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
615 // subregs. This may invalidate any operand pointers.
616 // Return true if the operand kills its register.
617 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
618   MachineOperand &MO = MI->getOperand(OpNum);
619   if (!MO.getSubReg()) {
620     MO.setReg(PhysReg);
621     return MO.isKill() || MO.isDead();
622   }
623
624   // Handle subregister index.
625   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
626   MO.setSubReg(0);
627
628   // A kill flag implies killing the full register. Add corresponding super
629   // register kill.
630   if (MO.isKill()) {
631     MI->addRegisterKilled(PhysReg, TRI, true);
632     return true;
633   }
634   return MO.isDead();
635 }
636
637 // Handle special instruction operand like early clobbers and tied ops when
638 // there are additional physreg defines.
639 void RAFast::handleThroughOperands(MachineInstr *MI,
640                                    SmallVectorImpl<unsigned> &VirtDead) {
641   DEBUG(dbgs() << "Scanning for through registers:");
642   SmallSet<unsigned, 8> ThroughRegs;
643   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
644     MachineOperand &MO = MI->getOperand(i);
645     if (!MO.isReg()) continue;
646     unsigned Reg = MO.getReg();
647     if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
648     if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
649         (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
650       if (ThroughRegs.insert(Reg))
651         DEBUG(dbgs() << " %reg" << Reg);
652     }
653   }
654
655   // If any physreg defines collide with preallocated through registers,
656   // we must spill and reallocate.
657   DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
658   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
659     MachineOperand &MO = MI->getOperand(i);
660     if (!MO.isReg() || !MO.isDef()) continue;
661     unsigned Reg = MO.getReg();
662     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
663     UsedInInstr.set(Reg);
664     if (ThroughRegs.count(PhysRegState[Reg]))
665       definePhysReg(MI, Reg, regFree);
666     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
667       UsedInInstr.set(*AS);
668       if (ThroughRegs.count(PhysRegState[*AS]))
669         definePhysReg(MI, *AS, regFree);
670     }
671   }
672
673   SmallVector<unsigned, 8> PartialDefs;
674   DEBUG(dbgs() << "Allocating tied uses and early clobbers.\n");
675   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
676     MachineOperand &MO = MI->getOperand(i);
677     if (!MO.isReg()) continue;
678     unsigned Reg = MO.getReg();
679     if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
680     if (MO.isUse()) {
681       unsigned DefIdx = 0;
682       if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
683       DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
684         << DefIdx << ".\n");
685       LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
686       unsigned PhysReg = LRI->second.PhysReg;
687       setPhysReg(MI, i, PhysReg);
688       // Note: we don't update the def operand yet. That would cause the normal
689       // def-scan to attempt spilling.
690     } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
691       DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
692       // Reload the register, but don't assign to the operand just yet.
693       // That would confuse the later phys-def processing pass.
694       LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
695       PartialDefs.push_back(LRI->second.PhysReg);
696     } else if (MO.isEarlyClobber()) {
697       // Note: defineVirtReg may invalidate MO.
698       LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
699       unsigned PhysReg = LRI->second.PhysReg;
700       if (setPhysReg(MI, i, PhysReg))
701         VirtDead.push_back(Reg);
702     }
703   }
704
705   // Restore UsedInInstr to a state usable for allocating normal virtual uses.
706   UsedInInstr.reset();
707   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
708     MachineOperand &MO = MI->getOperand(i);
709     if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
710     unsigned Reg = MO.getReg();
711     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
712     UsedInInstr.set(Reg);
713     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
714       UsedInInstr.set(*AS);
715   }
716
717   // Also mark PartialDefs as used to avoid reallocation.
718   for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
719     UsedInInstr.set(PartialDefs[i]);
720 }
721
722 void RAFast::AllocateBasicBlock() {
723   DEBUG(dbgs() << "\nAllocating " << *MBB);
724
725   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
726   assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
727
728   MachineBasicBlock::iterator MII = MBB->begin();
729
730   // Add live-in registers as live.
731   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
732          E = MBB->livein_end(); I != E; ++I)
733     definePhysReg(MII, *I, regReserved);
734
735   SmallVector<unsigned, 8> VirtDead;
736   SmallVector<MachineInstr*, 32> Coalesced;
737
738   // Otherwise, sequentially allocate each instruction in the MBB.
739   while (MII != MBB->end()) {
740     MachineInstr *MI = MII++;
741     const TargetInstrDesc &TID = MI->getDesc();
742     DEBUG({
743         dbgs() << "\n>> " << *MI << "Regs:";
744         for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
745           if (PhysRegState[Reg] == regDisabled) continue;
746           dbgs() << " " << TRI->getName(Reg);
747           switch(PhysRegState[Reg]) {
748           case regFree:
749             break;
750           case regReserved:
751             dbgs() << "*";
752             break;
753           default:
754             dbgs() << "=%reg" << PhysRegState[Reg];
755             if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
756               dbgs() << "*";
757             assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
758                    "Bad inverse map");
759             break;
760           }
761         }
762         dbgs() << '\n';
763         // Check that LiveVirtRegs is the inverse.
764         for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
765              e = LiveVirtRegs.end(); i != e; ++i) {
766            assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
767                   "Bad map key");
768            assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
769                   "Bad map value");
770            assert(PhysRegState[i->second.PhysReg] == i->first &&
771                   "Bad inverse map");
772         }
773       });
774
775     // Debug values are not allowed to change codegen in any way.
776     if (MI->isDebugValue()) {
777       bool ScanDbgValue = true;
778       while (ScanDbgValue) {
779         ScanDbgValue = false;
780         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
781           MachineOperand &MO = MI->getOperand(i);
782           if (!MO.isReg()) continue;
783           unsigned Reg = MO.getReg();
784           if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
785           LiveDbgValueMap[Reg] = MI;
786           LiveRegMap::iterator LRI = LiveVirtRegs.find(Reg);
787           if (LRI != LiveVirtRegs.end())
788             setPhysReg(MI, i, LRI->second.PhysReg);
789           else {
790             int SS = StackSlotForVirtReg[Reg];
791             if (SS == -1)
792               MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
793             else {
794               // Modify DBG_VALUE now that the value is in a spill slot.
795               int64_t Offset = MI->getOperand(1).getImm();
796               const MDNode *MDPtr = 
797                 MI->getOperand(MI->getNumOperands()-1).getMetadata();
798               DebugLoc DL = MI->getDebugLoc();
799               if (MachineInstr *NewDV = 
800                   TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
801                 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
802                 MachineBasicBlock *MBB = MI->getParent();
803                 MBB->insert(MBB->erase(MI), NewDV);
804                 // Scan NewDV operands from the beginning.
805                 MI = NewDV;
806                 ScanDbgValue = true;
807                 break;
808               } else
809                 MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
810             }
811           }
812         }
813       }
814       // Next instruction.
815       continue;
816     }
817
818     // If this is a copy, we may be able to coalesce.
819     unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
820     if (MI->isCopy()) {
821       CopyDst = MI->getOperand(0).getReg();
822       CopySrc = MI->getOperand(1).getReg();
823       CopyDstSub = MI->getOperand(0).getSubReg();
824       CopySrcSub = MI->getOperand(1).getSubReg();
825     }
826
827     // Track registers used by instruction.
828     UsedInInstr.reset();
829
830     // First scan.
831     // Mark physreg uses and early clobbers as used.
832     // Find the end of the virtreg operands
833     unsigned VirtOpEnd = 0;
834     bool hasTiedOps = false;
835     bool hasEarlyClobbers = false;
836     bool hasPartialRedefs = false;
837     bool hasPhysDefs = false;
838     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
839       MachineOperand &MO = MI->getOperand(i);
840       if (!MO.isReg()) continue;
841       unsigned Reg = MO.getReg();
842       if (!Reg) continue;
843       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
844         VirtOpEnd = i+1;
845         if (MO.isUse()) {
846           hasTiedOps = hasTiedOps ||
847                                 TID.getOperandConstraint(i, TOI::TIED_TO) != -1;
848         } else {
849           if (MO.isEarlyClobber())
850             hasEarlyClobbers = true;
851           if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
852             hasPartialRedefs = true;
853         }
854         continue;
855       }
856       if (!Allocatable.test(Reg)) continue;
857       if (MO.isUse()) {
858         usePhysReg(MO);
859       } else if (MO.isEarlyClobber()) {
860         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
861                                regFree : regReserved);
862         hasEarlyClobbers = true;
863       } else
864         hasPhysDefs = true;
865     }
866
867     // The instruction may have virtual register operands that must be allocated
868     // the same register at use-time and def-time: early clobbers and tied
869     // operands. If there are also physical defs, these registers must avoid
870     // both physical defs and uses, making them more constrained than normal
871     // operands.
872     // Similarly, if there are multiple defs and tied operands, we must make sure
873     // the same register is allocated to uses and defs.
874     // We didn't detect inline asm tied operands above, so just make this extra
875     // pass for all inline asm.
876     if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
877         (hasTiedOps && (hasPhysDefs || TID.getNumDefs() > 1))) {
878       handleThroughOperands(MI, VirtDead);
879       // Don't attempt coalescing when we have funny stuff going on.
880       CopyDst = 0;
881       // Pretend we have early clobbers so the use operands get marked below.
882       // This is not necessary for the common case of a single tied use.
883       hasEarlyClobbers = true;
884     }
885
886     // Second scan.
887     // Allocate virtreg uses.
888     for (unsigned i = 0; i != VirtOpEnd; ++i) {
889       MachineOperand &MO = MI->getOperand(i);
890       if (!MO.isReg()) continue;
891       unsigned Reg = MO.getReg();
892       if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
893       if (MO.isUse()) {
894         LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
895         unsigned PhysReg = LRI->second.PhysReg;
896         CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
897         if (setPhysReg(MI, i, PhysReg))
898           killVirtReg(LRI);
899       }
900     }
901
902     MRI->addPhysRegsUsed(UsedInInstr);
903
904     // Track registers defined by instruction - early clobbers and tied uses at
905     // this point.
906     UsedInInstr.reset();
907     if (hasEarlyClobbers) {
908       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
909         MachineOperand &MO = MI->getOperand(i);
910         if (!MO.isReg()) continue;
911         unsigned Reg = MO.getReg();
912         if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
913         // Look for physreg defs and tied uses.
914         if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
915         UsedInInstr.set(Reg);
916         for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
917           UsedInInstr.set(*AS);
918       }
919     }
920
921     unsigned DefOpEnd = MI->getNumOperands();
922     if (TID.isCall()) {
923       // Spill all virtregs before a call. This serves two purposes: 1. If an
924       // exception is thrown, the landing pad is going to expect to find registers
925       // in their spill slots, and 2. we don't have to wade through all the
926       // <imp-def> operands on the call instruction.
927       DefOpEnd = VirtOpEnd;
928       DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
929       spillAll(MI);
930
931       // The imp-defs are skipped below, but we still need to mark those
932       // registers as used by the function.
933       SkippedInstrs.insert(&TID);
934     }
935
936     // Third scan.
937     // Allocate defs and collect dead defs.
938     for (unsigned i = 0; i != DefOpEnd; ++i) {
939       MachineOperand &MO = MI->getOperand(i);
940       if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
941         continue;
942       unsigned Reg = MO.getReg();
943
944       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
945         if (!Allocatable.test(Reg)) continue;
946         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
947                                regFree : regReserved);
948         continue;
949       }
950       LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
951       unsigned PhysReg = LRI->second.PhysReg;
952       if (setPhysReg(MI, i, PhysReg)) {
953         VirtDead.push_back(Reg);
954         CopyDst = 0; // cancel coalescing;
955       } else
956         CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
957     }
958
959     // Kill dead defs after the scan to ensure that multiple defs of the same
960     // register are allocated identically. We didn't need to do this for uses
961     // because we are crerating our own kill flags, and they are always at the
962     // last use.
963     for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
964       killVirtReg(VirtDead[i]);
965     VirtDead.clear();
966
967     MRI->addPhysRegsUsed(UsedInInstr);
968
969     if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
970       DEBUG(dbgs() << "-- coalescing: " << *MI);
971       Coalesced.push_back(MI);
972     } else {
973       DEBUG(dbgs() << "<< " << *MI);
974     }
975   }
976
977   // Spill all physical registers holding virtual registers now.
978   DEBUG(dbgs() << "Spilling live registers at end of block.\n");
979   spillAll(MBB->getFirstTerminator());
980
981   // Erase all the coalesced copies. We are delaying it until now because
982   // LiveVirtRegs might refer to the instrs.
983   for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
984     MBB->erase(Coalesced[i]);
985   NumCopies += Coalesced.size();
986
987   DEBUG(MBB->dump());
988 }
989
990 /// runOnMachineFunction - Register allocate the whole function
991 ///
992 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
993   DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
994                << "********** Function: "
995                << ((Value*)Fn.getFunction())->getName() << '\n');
996   MF = &Fn;
997   MRI = &MF->getRegInfo();
998   TM = &Fn.getTarget();
999   TRI = TM->getRegisterInfo();
1000   TII = TM->getInstrInfo();
1001
1002   UsedInInstr.resize(TRI->getNumRegs());
1003   Allocatable = TRI->getAllocatableSet(*MF);
1004
1005   // initialize the virtual->physical register map to have a 'null'
1006   // mapping for all virtual registers
1007   unsigned LastVirtReg = MRI->getLastVirtReg();
1008   StackSlotForVirtReg.grow(LastVirtReg);
1009
1010   // Loop over all of the basic blocks, eliminating virtual register references
1011   for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1012        MBBi != MBBe; ++MBBi) {
1013     MBB = &*MBBi;
1014     AllocateBasicBlock();
1015   }
1016
1017   // Make sure the set of used physregs is closed under subreg operations.
1018   MRI->closePhysRegsUsed(*TRI);
1019
1020   // Add the clobber lists for all the instructions we skipped earlier.
1021   for (SmallPtrSet<const TargetInstrDesc*, 4>::const_iterator
1022        I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1023     if (const unsigned *Defs = (*I)->getImplicitDefs())
1024       while (*Defs)
1025         MRI->setPhysRegUsed(*Defs++);
1026
1027   SkippedInstrs.clear();
1028   StackSlotForVirtReg.clear();
1029   LiveDbgValueMap.clear();
1030   return true;
1031 }
1032
1033 FunctionPass *llvm::createFastRegisterAllocator() {
1034   return new RAFast();
1035 }