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