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