1 //===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file This register allocator allocates registers to a basic block at a
10 /// time, attempting to keep values in registers and reusing registers as
11 /// appropriate.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/IndexedMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/SparseSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegAllocRegistry.h"
31 #include "llvm/CodeGen/RegisterClassInfo.h"
32 #include "llvm/CodeGen/TargetInstrInfo.h"
33 #include "llvm/CodeGen/TargetOpcodes.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/TargetSubtargetInfo.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/MC/MCInstrDesc.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <cassert>
48 #include <tuple>
49 #include <vector>
50 
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "regalloc"
54 
55 STATISTIC(NumStores, "Number of stores added");
56 STATISTIC(NumLoads , "Number of loads added");
57 STATISTIC(NumCoalesced, "Number of copies coalesced");
58 
59 static RegisterRegAlloc
60   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
61 
62 namespace {
63 
64   class RegAllocFast : public MachineFunctionPass {
65   public:
66     static char ID;
67 
68     RegAllocFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1) {}
69 
70   private:
71     MachineFrameInfo *MFI;
72     MachineRegisterInfo *MRI;
73     const TargetRegisterInfo *TRI;
74     const TargetInstrInfo *TII;
75     RegisterClassInfo RegClassInfo;
76 
77     /// Basic block currently being allocated.
78     MachineBasicBlock *MBB;
79 
80     /// Maps virtual regs to the frame index where these values are spilled.
81     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
82 
83     /// Everything we know about a live virtual register.
84     struct LiveReg {
85       MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
86       Register VirtReg;                ///< Virtual register number.
87       MCPhysReg PhysReg = 0;           ///< Currently held here.
88       unsigned short LastOpNum = 0;    ///< OpNum on LastUse.
89       bool Dirty = false;              ///< Register needs spill.
90 
91       explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
92 
93       unsigned getSparseSetIndex() const {
94         return Register::virtReg2Index(VirtReg);
95       }
96     };
97 
98     using LiveRegMap = SparseSet<LiveReg>;
99     /// This map contains entries for each virtual register that is currently
100     /// available in a physical register.
101     LiveRegMap LiveVirtRegs;
102 
103     DenseMap<unsigned, SmallVector<MachineInstr *, 2>> LiveDbgValueMap;
104 
105     /// Has a bit set for every virtual register for which it was determined
106     /// that it is alive across blocks.
107     BitVector MayLiveAcrossBlocks;
108 
109     /// State of a physical register.
110     enum RegState {
111       /// A disabled register is not available for allocation, but an alias may
112       /// be in use. A register can only be moved out of the disabled state if
113       /// all aliases are disabled.
114       regDisabled,
115 
116       /// A free register is not currently in use and can be allocated
117       /// immediately without checking aliases.
118       regFree,
119 
120       /// A reserved register has been assigned explicitly (e.g., setting up a
121       /// call parameter), and it remains reserved until it is used.
122       regReserved
123 
124       /// A register state may also be a virtual register number, indication
125       /// that the physical register is currently allocated to a virtual
126       /// register. In that case, LiveVirtRegs contains the inverse mapping.
127     };
128 
129     /// Maps each physical register to a RegState enum or a virtual register.
130     std::vector<unsigned> PhysRegState;
131 
132     SmallVector<Register, 16> VirtDead;
133     SmallVector<MachineInstr *, 32> Coalesced;
134 
135     using RegUnitSet = SparseSet<uint16_t, identity<uint16_t>>;
136     /// Set of register units that are used in the current instruction, and so
137     /// cannot be allocated.
138     RegUnitSet UsedInInstr;
139 
140     void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
141 
142     /// Mark a physreg as used in this instruction.
143     void markRegUsedInInstr(MCPhysReg PhysReg) {
144       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
145         UsedInInstr.insert(*Units);
146     }
147 
148     /// Check if a physreg or any of its aliases are used in this instruction.
149     bool isRegUsedInInstr(MCPhysReg PhysReg) const {
150       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
151         if (UsedInInstr.count(*Units))
152           return true;
153       return false;
154     }
155 
156     enum : unsigned {
157       spillClean = 50,
158       spillDirty = 100,
159       spillPrefBonus = 20,
160       spillImpossible = ~0u
161     };
162 
163   public:
164     StringRef getPassName() const override { return "Fast Register Allocator"; }
165 
166     void getAnalysisUsage(AnalysisUsage &AU) const override {
167       AU.setPreservesCFG();
168       MachineFunctionPass::getAnalysisUsage(AU);
169     }
170 
171     MachineFunctionProperties getRequiredProperties() const override {
172       return MachineFunctionProperties().set(
173           MachineFunctionProperties::Property::NoPHIs);
174     }
175 
176     MachineFunctionProperties getSetProperties() const override {
177       return MachineFunctionProperties().set(
178           MachineFunctionProperties::Property::NoVRegs);
179     }
180 
181   private:
182     bool runOnMachineFunction(MachineFunction &MF) override;
183 
184     void allocateBasicBlock(MachineBasicBlock &MBB);
185     void allocateInstruction(MachineInstr &MI);
186     void handleDebugValue(MachineInstr &MI);
187     void handleThroughOperands(MachineInstr &MI,
188                                SmallVectorImpl<Register> &VirtDead);
189     bool isLastUseOfLocalReg(const MachineOperand &MO) const;
190 
191     void addKillFlag(const LiveReg &LRI);
192     void killVirtReg(LiveReg &LR);
193     void killVirtReg(Register VirtReg);
194     void spillVirtReg(MachineBasicBlock::iterator MI, LiveReg &LR);
195     void spillVirtReg(MachineBasicBlock::iterator MI, Register VirtReg);
196 
197     void usePhysReg(MachineOperand &MO);
198     void definePhysReg(MachineBasicBlock::iterator MI, MCPhysReg PhysReg,
199                        RegState NewState);
200     unsigned calcSpillCost(MCPhysReg PhysReg) const;
201     void assignVirtToPhysReg(LiveReg &, MCPhysReg PhysReg);
202 
203     LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
204       return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
205     }
206 
207     LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
208       return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
209     }
210 
211     void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint);
212     void allocVirtRegUndef(MachineOperand &MO);
213     MCPhysReg defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
214                             Register Hint);
215     LiveReg &reloadVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
216                            Register Hint);
217     void spillAll(MachineBasicBlock::iterator MI, bool OnlyLiveOut);
218     bool setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
219 
220     Register traceCopies(Register VirtReg) const;
221     Register traceCopyChain(Register Reg) const;
222 
223     int getStackSpaceFor(Register VirtReg);
224     void spill(MachineBasicBlock::iterator Before, Register VirtReg,
225                MCPhysReg AssignedReg, bool Kill);
226     void reload(MachineBasicBlock::iterator Before, Register VirtReg,
227                 MCPhysReg PhysReg);
228 
229     bool mayLiveOut(Register VirtReg);
230     bool mayLiveIn(Register VirtReg);
231 
232     void dumpState();
233   };
234 
235 } // end anonymous namespace
236 
237 char RegAllocFast::ID = 0;
238 
239 INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
240                 false)
241 
242 void RegAllocFast::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
243   PhysRegState[PhysReg] = NewState;
244 }
245 
246 /// This allocates space for the specified virtual register to be held on the
247 /// stack.
248 int RegAllocFast::getStackSpaceFor(Register VirtReg) {
249   // Find the location Reg would belong...
250   int SS = StackSlotForVirtReg[VirtReg];
251   // Already has space allocated?
252   if (SS != -1)
253     return SS;
254 
255   // Allocate a new stack object for this spill location...
256   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
257   unsigned Size = TRI->getSpillSize(RC);
258   Align Alignment = TRI->getSpillAlign(RC);
259   int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
260 
261   // Assign the slot.
262   StackSlotForVirtReg[VirtReg] = FrameIdx;
263   return FrameIdx;
264 }
265 
266 static bool dominates(MachineBasicBlock &MBB,
267                       MachineBasicBlock::const_iterator A,
268                       MachineBasicBlock::const_iterator B) {
269   auto MBBEnd = MBB.end();
270   if (B == MBBEnd)
271     return true;
272 
273   MachineBasicBlock::const_iterator I = MBB.begin();
274   for (; &*I != A && &*I != B; ++I)
275     ;
276 
277   return &*I == A;
278 }
279 
280 /// Returns false if \p VirtReg is known to not live out of the current block.
281 bool RegAllocFast::mayLiveOut(Register VirtReg) {
282   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
283     // Cannot be live-out if there are no successors.
284     return !MBB->succ_empty();
285   }
286 
287   const MachineInstr *SelfLoopDef = nullptr;
288 
289   // If this block loops back to itself, it is necessary to check whether the
290   // use comes after the def.
291   if (MBB->isSuccessor(MBB)) {
292     SelfLoopDef = MRI->getUniqueVRegDef(VirtReg);
293     if (!SelfLoopDef) {
294       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
295       return true;
296     }
297   }
298 
299   // See if the first \p Limit uses of the register are all in the current
300   // block.
301   static const unsigned Limit = 8;
302   unsigned C = 0;
303   for (const MachineInstr &UseInst : MRI->reg_nodbg_instructions(VirtReg)) {
304     if (UseInst.getParent() != MBB || ++C >= Limit) {
305       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
306       // Cannot be live-out if there are no successors.
307       return !MBB->succ_empty();
308     }
309 
310     if (SelfLoopDef) {
311       // Try to handle some simple cases to avoid spilling and reloading every
312       // value inside a self looping block.
313       if (SelfLoopDef == &UseInst ||
314           !dominates(*MBB, SelfLoopDef->getIterator(), UseInst.getIterator())) {
315         MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
316         return true;
317       }
318     }
319   }
320 
321   return false;
322 }
323 
324 /// Returns false if \p VirtReg is known to not be live into the current block.
325 bool RegAllocFast::mayLiveIn(Register VirtReg) {
326   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
327     return !MBB->pred_empty();
328 
329   // See if the first \p Limit def of the register are all in the current block.
330   static const unsigned Limit = 8;
331   unsigned C = 0;
332   for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
333     if (DefInst.getParent() != MBB || ++C >= Limit) {
334       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
335       return !MBB->pred_empty();
336     }
337   }
338 
339   return false;
340 }
341 
342 /// Insert spill instruction for \p AssignedReg before \p Before. Update
343 /// DBG_VALUEs with \p VirtReg operands with the stack slot.
344 void RegAllocFast::spill(MachineBasicBlock::iterator Before, Register VirtReg,
345                          MCPhysReg AssignedReg, bool Kill) {
346   LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI)
347                     << " in " << printReg(AssignedReg, TRI));
348   int FI = getStackSpaceFor(VirtReg);
349   LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
350 
351   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
352   TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI);
353   ++NumStores;
354 
355   // If this register is used by DBG_VALUE then insert new DBG_VALUE to
356   // identify spilled location as the place to find corresponding variable's
357   // value.
358   SmallVectorImpl<MachineInstr *> &LRIDbgValues = LiveDbgValueMap[VirtReg];
359   for (MachineInstr *DBG : LRIDbgValues) {
360     MachineInstr *NewDV = buildDbgValueForSpill(*MBB, Before, *DBG, FI);
361     assert(NewDV->getParent() == MBB && "dangling parent pointer");
362     (void)NewDV;
363     LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
364   }
365   // Now this register is spilled there is should not be any DBG_VALUE
366   // pointing to this register because they are all pointing to spilled value
367   // now.
368   LRIDbgValues.clear();
369 }
370 
371 /// Insert reload instruction for \p PhysReg before \p Before.
372 void RegAllocFast::reload(MachineBasicBlock::iterator Before, Register VirtReg,
373                           MCPhysReg PhysReg) {
374   LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
375                     << printReg(PhysReg, TRI) << '\n');
376   int FI = getStackSpaceFor(VirtReg);
377   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
378   TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI);
379   ++NumLoads;
380 }
381 
382 /// Return true if MO is the only remaining reference to its virtual register,
383 /// and it is guaranteed to be a block-local register.
384 bool RegAllocFast::isLastUseOfLocalReg(const MachineOperand &MO) const {
385   // If the register has ever been spilled or reloaded, we conservatively assume
386   // it is a global register used in multiple blocks.
387   if (StackSlotForVirtReg[MO.getReg()] != -1)
388     return false;
389 
390   // Check that the use/def chain has exactly one operand - MO.
391   MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
392   if (&*I != &MO)
393     return false;
394   return ++I == MRI->reg_nodbg_end();
395 }
396 
397 /// Set kill flags on last use of a virtual register.
398 void RegAllocFast::addKillFlag(const LiveReg &LR) {
399   if (!LR.LastUse) return;
400   MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
401   if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
402     if (MO.getReg() == LR.PhysReg)
403       MO.setIsKill();
404     // else, don't do anything we are problably redefining a
405     // subreg of this register and given we don't track which
406     // lanes are actually dead, we cannot insert a kill flag here.
407     // Otherwise we may end up in a situation like this:
408     // ... = (MO) physreg:sub1, implicit killed physreg
409     // ... <== Here we would allow later pass to reuse physreg:sub1
410     //         which is potentially wrong.
411     // LR:sub0 = ...
412     // ... = LR.sub1 <== This is going to use physreg:sub1
413   }
414 }
415 
416 /// Mark virtreg as no longer available.
417 void RegAllocFast::killVirtReg(LiveReg &LR) {
418   addKillFlag(LR);
419   assert(PhysRegState[LR.PhysReg] == LR.VirtReg &&
420          "Broken RegState mapping");
421   setPhysRegState(LR.PhysReg, regFree);
422   LR.PhysReg = 0;
423 }
424 
425 /// Mark virtreg as no longer available.
426 void RegAllocFast::killVirtReg(Register VirtReg) {
427   assert(Register::isVirtualRegister(VirtReg) &&
428          "killVirtReg needs a virtual register");
429   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
430   if (LRI != LiveVirtRegs.end() && LRI->PhysReg)
431     killVirtReg(*LRI);
432 }
433 
434 /// This method spills the value specified by VirtReg into the corresponding
435 /// stack slot if needed.
436 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI,
437                                 Register VirtReg) {
438   assert(Register::isVirtualRegister(VirtReg) &&
439          "Spilling a physical register is illegal!");
440   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
441   assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
442          "Spilling unmapped virtual register");
443   spillVirtReg(MI, *LRI);
444 }
445 
446 /// Do the actual work of spilling.
447 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI, LiveReg &LR) {
448   assert(PhysRegState[LR.PhysReg] == LR.VirtReg && "Broken RegState mapping");
449 
450   if (LR.Dirty) {
451     // If this physreg is used by the instruction, we want to kill it on the
452     // instruction, not on the spill.
453     bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI;
454     LR.Dirty = false;
455 
456     spill(MI, LR.VirtReg, LR.PhysReg, SpillKill);
457 
458     if (SpillKill)
459       LR.LastUse = nullptr; // Don't kill register again
460   }
461   killVirtReg(LR);
462 }
463 
464 /// Spill all dirty virtregs without killing them.
465 void RegAllocFast::spillAll(MachineBasicBlock::iterator MI, bool OnlyLiveOut) {
466   if (LiveVirtRegs.empty())
467     return;
468   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
469   // of spilling here is deterministic, if arbitrary.
470   for (LiveReg &LR : LiveVirtRegs) {
471     if (!LR.PhysReg)
472       continue;
473     if (OnlyLiveOut && !mayLiveOut(LR.VirtReg))
474       continue;
475     spillVirtReg(MI, LR);
476   }
477   LiveVirtRegs.clear();
478 }
479 
480 /// Handle the direct use of a physical register.  Check that the register is
481 /// not used by a virtreg. Kill the physreg, marking it free. This may add
482 /// implicit kills to MO->getParent() and invalidate MO.
483 void RegAllocFast::usePhysReg(MachineOperand &MO) {
484   // Ignore undef uses.
485   if (MO.isUndef())
486     return;
487 
488   Register PhysReg = MO.getReg();
489   assert(PhysReg.isPhysical() && "Bad usePhysReg operand");
490 
491   markRegUsedInInstr(PhysReg);
492   switch (PhysRegState[PhysReg]) {
493   case regDisabled:
494     break;
495   case regReserved:
496     PhysRegState[PhysReg] = regFree;
497     LLVM_FALLTHROUGH;
498   case regFree:
499     MO.setIsKill();
500     return;
501   default:
502     // The physreg was allocated to a virtual register. That means the value we
503     // wanted has been clobbered.
504     llvm_unreachable("Instruction uses an allocated register");
505   }
506 
507   // Maybe a superregister is reserved?
508   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
509     MCPhysReg Alias = *AI;
510     switch (PhysRegState[Alias]) {
511     case regDisabled:
512       break;
513     case regReserved:
514       // Either PhysReg is a subregister of Alias and we mark the
515       // whole register as free, or PhysReg is the superregister of
516       // Alias and we mark all the aliases as disabled before freeing
517       // PhysReg.
518       // In the latter case, since PhysReg was disabled, this means that
519       // its value is defined only by physical sub-registers. This check
520       // is performed by the assert of the default case in this loop.
521       // Note: The value of the superregister may only be partial
522       // defined, that is why regDisabled is a valid state for aliases.
523       assert((TRI->isSuperRegister(PhysReg, Alias) ||
524               TRI->isSuperRegister(Alias, PhysReg)) &&
525              "Instruction is not using a subregister of a reserved register");
526       LLVM_FALLTHROUGH;
527     case regFree:
528       if (TRI->isSuperRegister(PhysReg, Alias)) {
529         // Leave the superregister in the working set.
530         setPhysRegState(Alias, regFree);
531         MO.getParent()->addRegisterKilled(Alias, TRI, true);
532         return;
533       }
534       // Some other alias was in the working set - clear it.
535       setPhysRegState(Alias, regDisabled);
536       break;
537     default:
538       llvm_unreachable("Instruction uses an alias of an allocated register");
539     }
540   }
541 
542   // All aliases are disabled, bring register into working set.
543   setPhysRegState(PhysReg, regFree);
544   MO.setIsKill();
545 }
546 
547 /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
548 /// similar to defineVirtReg except the physreg is reserved instead of
549 /// allocated.
550 void RegAllocFast::definePhysReg(MachineBasicBlock::iterator MI,
551                                  MCPhysReg PhysReg, RegState NewState) {
552   markRegUsedInInstr(PhysReg);
553   switch (Register VirtReg = PhysRegState[PhysReg]) {
554   case regDisabled:
555     break;
556   default:
557     spillVirtReg(MI, VirtReg);
558     LLVM_FALLTHROUGH;
559   case regFree:
560   case regReserved:
561     setPhysRegState(PhysReg, NewState);
562     return;
563   }
564 
565   // This is a disabled register, disable all aliases.
566   setPhysRegState(PhysReg, NewState);
567   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
568     MCPhysReg Alias = *AI;
569     switch (Register VirtReg = PhysRegState[Alias]) {
570     case regDisabled:
571       break;
572     default:
573       spillVirtReg(MI, VirtReg);
574       LLVM_FALLTHROUGH;
575     case regFree:
576     case regReserved:
577       setPhysRegState(Alias, regDisabled);
578       if (TRI->isSuperRegister(PhysReg, Alias))
579         return;
580       break;
581     }
582   }
583 }
584 
585 /// Return the cost of spilling clearing out PhysReg and aliases so it is free
586 /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
587 /// disabled - it can be allocated directly.
588 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
589 unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
590   if (isRegUsedInInstr(PhysReg)) {
591     LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI)
592                       << " is already used in instr.\n");
593     return spillImpossible;
594   }
595   switch (Register VirtReg = PhysRegState[PhysReg]) {
596   case regDisabled:
597     break;
598   case regFree:
599     return 0;
600   case regReserved:
601     LLVM_DEBUG(dbgs() << printReg(VirtReg, TRI) << " corresponding "
602                       << printReg(PhysReg, TRI) << " is reserved already.\n");
603     return spillImpossible;
604   default: {
605     LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
606     assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
607            "Missing VirtReg entry");
608     return LRI->Dirty ? spillDirty : spillClean;
609   }
610   }
611 
612   // This is a disabled register, add up cost of aliases.
613   LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is disabled.\n");
614   unsigned Cost = 0;
615   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
616     MCPhysReg Alias = *AI;
617     switch (Register VirtReg = PhysRegState[Alias]) {
618     case regDisabled:
619       break;
620     case regFree:
621       ++Cost;
622       break;
623     case regReserved:
624       return spillImpossible;
625     default: {
626       LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
627       assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
628              "Missing VirtReg entry");
629       Cost += LRI->Dirty ? spillDirty : spillClean;
630       break;
631     }
632     }
633   }
634   return Cost;
635 }
636 
637 /// This method updates local state so that we know that PhysReg is the
638 /// proper container for VirtReg now.  The physical register must not be used
639 /// for anything else when this is called.
640 void RegAllocFast::assignVirtToPhysReg(LiveReg &LR, MCPhysReg PhysReg) {
641   Register VirtReg = LR.VirtReg;
642   LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
643                     << printReg(PhysReg, TRI) << '\n');
644   assert(LR.PhysReg == 0 && "Already assigned a physreg");
645   assert(PhysReg != 0 && "Trying to assign no register");
646   LR.PhysReg = PhysReg;
647   setPhysRegState(PhysReg, VirtReg);
648 }
649 
650 static bool isCoalescable(const MachineInstr &MI) {
651   return MI.isFullCopy();
652 }
653 
654 Register RegAllocFast::traceCopyChain(Register Reg) const {
655   static const unsigned ChainLengthLimit = 3;
656   unsigned C = 0;
657   do {
658     if (Reg.isPhysical())
659       return Reg;
660     assert(Reg.isVirtual());
661 
662     MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
663     if (!VRegDef || !isCoalescable(*VRegDef))
664       return 0;
665     Reg = VRegDef->getOperand(1).getReg();
666   } while (++C <= ChainLengthLimit);
667   return 0;
668 }
669 
670 /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
671 /// chain of copies to check whether we reach a physical register we can
672 /// coalesce with.
673 Register RegAllocFast::traceCopies(Register VirtReg) const {
674   static const unsigned DefLimit = 3;
675   unsigned C = 0;
676   for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
677     if (isCoalescable(MI)) {
678       Register Reg = MI.getOperand(1).getReg();
679       Reg = traceCopyChain(Reg);
680       if (Reg.isValid())
681         return Reg;
682     }
683 
684     if (++C >= DefLimit)
685       break;
686   }
687   return Register();
688 }
689 
690 /// Allocates a physical register for VirtReg.
691 void RegAllocFast::allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint0) {
692   const Register VirtReg = LR.VirtReg;
693 
694   assert(Register::isVirtualRegister(VirtReg) &&
695          "Can only allocate virtual registers");
696 
697   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
698   LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
699                     << " in class " << TRI->getRegClassName(&RC)
700                     << " with hint " << printReg(Hint0, TRI) << '\n');
701 
702   // Take hint when possible.
703   if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) &&
704       RC.contains(Hint0)) {
705     // Ignore the hint if we would have to spill a dirty register.
706     unsigned Cost = calcSpillCost(Hint0);
707     if (Cost < spillDirty) {
708       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
709                         << '\n');
710       if (Cost)
711         definePhysReg(MI, Hint0, regFree);
712       assignVirtToPhysReg(LR, Hint0);
713       return;
714     } else {
715       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
716                         << "occupied\n");
717     }
718   } else {
719     Hint0 = Register();
720   }
721 
722   // Try other hint.
723   Register Hint1 = traceCopies(VirtReg);
724   if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) &&
725       RC.contains(Hint1) && !isRegUsedInInstr(Hint1)) {
726     // Ignore the hint if we would have to spill a dirty register.
727     unsigned Cost = calcSpillCost(Hint1);
728     if (Cost < spillDirty) {
729       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
730                         << '\n');
731       if (Cost)
732         definePhysReg(MI, Hint1, regFree);
733       assignVirtToPhysReg(LR, Hint1);
734       return;
735     } else {
736       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
737                         << "occupied\n");
738     }
739   } else {
740     Hint1 = Register();
741   }
742 
743   MCPhysReg BestReg = 0;
744   unsigned BestCost = spillImpossible;
745   ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
746   for (MCPhysReg PhysReg : AllocationOrder) {
747     LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
748     unsigned Cost = calcSpillCost(PhysReg);
749     LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
750     // Immediate take a register with cost 0.
751     if (Cost == 0) {
752       assignVirtToPhysReg(LR, PhysReg);
753       return;
754     }
755 
756     if (PhysReg == Hint1 || PhysReg == Hint0)
757       Cost -= spillPrefBonus;
758 
759     if (Cost < BestCost) {
760       BestReg = PhysReg;
761       BestCost = Cost;
762     }
763   }
764 
765   if (!BestReg) {
766     // Nothing we can do: Report an error and keep going with an invalid
767     // allocation.
768     if (MI.isInlineAsm())
769       MI.emitError("inline assembly requires more registers than available");
770     else
771       MI.emitError("ran out of registers during register allocation");
772     definePhysReg(MI, *AllocationOrder.begin(), regFree);
773     assignVirtToPhysReg(LR, *AllocationOrder.begin());
774     return;
775   }
776 
777   definePhysReg(MI, BestReg, regFree);
778   assignVirtToPhysReg(LR, BestReg);
779 }
780 
781 void RegAllocFast::allocVirtRegUndef(MachineOperand &MO) {
782   assert(MO.isUndef() && "expected undef use");
783   Register VirtReg = MO.getReg();
784   assert(Register::isVirtualRegister(VirtReg) && "Expected virtreg");
785 
786   LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
787   MCPhysReg PhysReg;
788   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
789     PhysReg = LRI->PhysReg;
790   } else {
791     const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
792     ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
793     assert(!AllocationOrder.empty() && "Allocation order must not be empty");
794     PhysReg = AllocationOrder[0];
795   }
796 
797   unsigned SubRegIdx = MO.getSubReg();
798   if (SubRegIdx != 0) {
799     PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
800     MO.setSubReg(0);
801   }
802   MO.setReg(PhysReg);
803   MO.setIsRenamable(true);
804 }
805 
806 /// Allocates a register for VirtReg and mark it as dirty.
807 MCPhysReg RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum,
808                                       Register VirtReg, Register Hint) {
809   assert(Register::isVirtualRegister(VirtReg) && "Not a virtual register");
810   LiveRegMap::iterator LRI;
811   bool New;
812   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
813   if (!LRI->PhysReg) {
814     // If there is no hint, peek at the only use of this register.
815     if ((!Hint || !Hint.isPhysical()) &&
816         MRI->hasOneNonDBGUse(VirtReg)) {
817       const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
818       // It's a copy, use the destination register as a hint.
819       if (UseMI.isCopyLike())
820         Hint = UseMI.getOperand(0).getReg();
821     }
822     allocVirtReg(MI, *LRI, Hint);
823   } else if (LRI->LastUse) {
824     // Redefining a live register - kill at the last use, unless it is this
825     // instruction defining VirtReg multiple times.
826     if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
827       addKillFlag(*LRI);
828   }
829   assert(LRI->PhysReg && "Register not assigned");
830   LRI->LastUse = &MI;
831   LRI->LastOpNum = OpNum;
832   LRI->Dirty = true;
833   markRegUsedInInstr(LRI->PhysReg);
834   return LRI->PhysReg;
835 }
836 
837 /// Make sure VirtReg is available in a physreg and return it.
838 RegAllocFast::LiveReg &RegAllocFast::reloadVirtReg(MachineInstr &MI,
839                                                    unsigned OpNum,
840                                                    Register VirtReg,
841                                                    Register Hint) {
842   assert(Register::isVirtualRegister(VirtReg) && "Not a virtual register");
843   LiveRegMap::iterator LRI;
844   bool New;
845   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
846   MachineOperand &MO = MI.getOperand(OpNum);
847   if (!LRI->PhysReg) {
848     allocVirtReg(MI, *LRI, Hint);
849     reload(MI, VirtReg, LRI->PhysReg);
850   } else if (LRI->Dirty) {
851     if (isLastUseOfLocalReg(MO)) {
852       LLVM_DEBUG(dbgs() << "Killing last use: " << MO << '\n');
853       if (MO.isUse())
854         MO.setIsKill();
855       else
856         MO.setIsDead();
857     } else if (MO.isKill()) {
858       LLVM_DEBUG(dbgs() << "Clearing dubious kill: " << MO << '\n');
859       MO.setIsKill(false);
860     } else if (MO.isDead()) {
861       LLVM_DEBUG(dbgs() << "Clearing dubious dead: " << MO << '\n');
862       MO.setIsDead(false);
863     }
864   } else if (MO.isKill()) {
865     // We must remove kill flags from uses of reloaded registers because the
866     // register would be killed immediately, and there might be a second use:
867     //   %foo = OR killed %x, %x
868     // This would cause a second reload of %x into a different register.
869     LLVM_DEBUG(dbgs() << "Clearing clean kill: " << MO << '\n');
870     MO.setIsKill(false);
871   } else if (MO.isDead()) {
872     LLVM_DEBUG(dbgs() << "Clearing clean dead: " << MO << '\n');
873     MO.setIsDead(false);
874   }
875   assert(LRI->PhysReg && "Register not assigned");
876   LRI->LastUse = &MI;
877   LRI->LastOpNum = OpNum;
878   markRegUsedInInstr(LRI->PhysReg);
879   return *LRI;
880 }
881 
882 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
883 /// may invalidate any operand pointers.  Return true if the operand kills its
884 /// register.
885 bool RegAllocFast::setPhysReg(MachineInstr &MI, MachineOperand &MO,
886                               MCPhysReg PhysReg) {
887   bool Dead = MO.isDead();
888   if (!MO.getSubReg()) {
889     MO.setReg(PhysReg);
890     MO.setIsRenamable(true);
891     return MO.isKill() || Dead;
892   }
893 
894   // Handle subregister index.
895   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : Register());
896   MO.setIsRenamable(true);
897   MO.setSubReg(0);
898 
899   // A kill flag implies killing the full register. Add corresponding super
900   // register kill.
901   if (MO.isKill()) {
902     MI.addRegisterKilled(PhysReg, TRI, true);
903     return true;
904   }
905 
906   // A <def,read-undef> of a sub-register requires an implicit def of the full
907   // register.
908   if (MO.isDef() && MO.isUndef())
909     MI.addRegisterDefined(PhysReg, TRI);
910 
911   return Dead;
912 }
913 
914 // Handles special instruction operand like early clobbers and tied ops when
915 // there are additional physreg defines.
916 void RegAllocFast::handleThroughOperands(MachineInstr &MI,
917                                          SmallVectorImpl<Register> &VirtDead) {
918   LLVM_DEBUG(dbgs() << "Scanning for through registers:");
919   SmallSet<Register, 8> ThroughRegs;
920   for (const MachineOperand &MO : MI.operands()) {
921     if (!MO.isReg()) continue;
922     Register Reg = MO.getReg();
923     if (!Reg.isVirtual())
924       continue;
925     if (MO.isEarlyClobber() || (MO.isUse() && MO.isTied()) ||
926         (MO.getSubReg() && MI.readsVirtualRegister(Reg))) {
927       if (ThroughRegs.insert(Reg).second)
928         LLVM_DEBUG(dbgs() << ' ' << printReg(Reg));
929     }
930   }
931 
932   // If any physreg defines collide with preallocated through registers,
933   // we must spill and reallocate.
934   LLVM_DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
935   for (const MachineOperand &MO : MI.operands()) {
936     if (!MO.isReg() || !MO.isDef()) continue;
937     Register Reg = MO.getReg();
938     if (!Reg || !Reg.isPhysical())
939       continue;
940     markRegUsedInInstr(Reg);
941     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
942       if (ThroughRegs.count(PhysRegState[*AI]))
943         definePhysReg(MI, *AI, regFree);
944     }
945   }
946 
947   SmallVector<Register, 8> PartialDefs;
948   LLVM_DEBUG(dbgs() << "Allocating tied uses.\n");
949   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
950     MachineOperand &MO = MI.getOperand(I);
951     if (!MO.isReg()) continue;
952     Register Reg = MO.getReg();
953     if (!Register::isVirtualRegister(Reg))
954       continue;
955     if (MO.isUse()) {
956       if (!MO.isTied()) continue;
957       LLVM_DEBUG(dbgs() << "Operand " << I << "(" << MO
958                         << ") is tied to operand " << MI.findTiedOperandIdx(I)
959                         << ".\n");
960       LiveReg &LR = reloadVirtReg(MI, I, Reg, 0);
961       MCPhysReg PhysReg = LR.PhysReg;
962       setPhysReg(MI, MO, PhysReg);
963       // Note: we don't update the def operand yet. That would cause the normal
964       // def-scan to attempt spilling.
965     } else if (MO.getSubReg() && MI.readsVirtualRegister(Reg)) {
966       LLVM_DEBUG(dbgs() << "Partial redefine: " << MO << '\n');
967       // Reload the register, but don't assign to the operand just yet.
968       // That would confuse the later phys-def processing pass.
969       LiveReg &LR = reloadVirtReg(MI, I, Reg, 0);
970       PartialDefs.push_back(LR.PhysReg);
971     }
972   }
973 
974   LLVM_DEBUG(dbgs() << "Allocating early clobbers.\n");
975   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
976     const MachineOperand &MO = MI.getOperand(I);
977     if (!MO.isReg()) continue;
978     Register Reg = MO.getReg();
979     if (!Register::isVirtualRegister(Reg))
980       continue;
981     if (!MO.isEarlyClobber())
982       continue;
983     // Note: defineVirtReg may invalidate MO.
984     MCPhysReg PhysReg = defineVirtReg(MI, I, Reg, 0);
985     if (setPhysReg(MI, MI.getOperand(I), PhysReg))
986       VirtDead.push_back(Reg);
987   }
988 
989   // Restore UsedInInstr to a state usable for allocating normal virtual uses.
990   UsedInInstr.clear();
991   for (const MachineOperand &MO : MI.operands()) {
992     if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
993     Register Reg = MO.getReg();
994     if (!Reg || !Reg.isPhysical())
995       continue;
996     LLVM_DEBUG(dbgs() << "\tSetting " << printReg(Reg, TRI)
997                       << " as used in instr\n");
998     markRegUsedInInstr(Reg);
999   }
1000 
1001   // Also mark PartialDefs as used to avoid reallocation.
1002   for (Register PartialDef : PartialDefs)
1003     markRegUsedInInstr(PartialDef);
1004 }
1005 
1006 #ifndef NDEBUG
1007 void RegAllocFast::dumpState() {
1008   for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
1009     if (PhysRegState[Reg] == regDisabled) continue;
1010     dbgs() << " " << printReg(Reg, TRI);
1011     switch(PhysRegState[Reg]) {
1012     case regFree:
1013       break;
1014     case regReserved:
1015       dbgs() << "*";
1016       break;
1017     default: {
1018       dbgs() << '=' << printReg(PhysRegState[Reg]);
1019       LiveRegMap::iterator LRI = findLiveVirtReg(PhysRegState[Reg]);
1020       assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
1021              "Missing VirtReg entry");
1022       if (LRI->Dirty)
1023         dbgs() << "*";
1024       assert(LRI->PhysReg == Reg && "Bad inverse map");
1025       break;
1026     }
1027     }
1028   }
1029   dbgs() << '\n';
1030   // Check that LiveVirtRegs is the inverse.
1031   for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
1032        e = LiveVirtRegs.end(); i != e; ++i) {
1033     if (!i->PhysReg)
1034       continue;
1035     assert(i->VirtReg.isVirtual() && "Bad map key");
1036     assert(Register::isPhysicalRegister(i->PhysReg) && "Bad map value");
1037     assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
1038   }
1039 }
1040 #endif
1041 
1042 void RegAllocFast::allocateInstruction(MachineInstr &MI) {
1043   const MCInstrDesc &MCID = MI.getDesc();
1044 
1045   // If this is a copy, we may be able to coalesce.
1046   Register CopySrcReg;
1047   Register CopyDstReg;
1048   unsigned CopySrcSub = 0;
1049   unsigned CopyDstSub = 0;
1050   if (MI.isCopy()) {
1051     CopyDstReg = MI.getOperand(0).getReg();
1052     CopySrcReg = MI.getOperand(1).getReg();
1053     CopyDstSub = MI.getOperand(0).getSubReg();
1054     CopySrcSub = MI.getOperand(1).getSubReg();
1055   }
1056 
1057   // Track registers used by instruction.
1058   UsedInInstr.clear();
1059 
1060   // First scan.
1061   // Mark physreg uses and early clobbers as used.
1062   // Find the end of the virtreg operands
1063   unsigned VirtOpEnd = 0;
1064   bool hasTiedOps = false;
1065   bool hasEarlyClobbers = false;
1066   bool hasPartialRedefs = false;
1067   bool hasPhysDefs = false;
1068   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1069     MachineOperand &MO = MI.getOperand(i);
1070     // Make sure MRI knows about registers clobbered by regmasks.
1071     if (MO.isRegMask()) {
1072       MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
1073       continue;
1074     }
1075     if (!MO.isReg()) continue;
1076     Register Reg = MO.getReg();
1077     if (!Reg) continue;
1078     if (Register::isVirtualRegister(Reg)) {
1079       VirtOpEnd = i+1;
1080       if (MO.isUse()) {
1081         hasTiedOps = hasTiedOps ||
1082                             MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
1083       } else {
1084         if (MO.isEarlyClobber())
1085           hasEarlyClobbers = true;
1086         if (MO.getSubReg() && MI.readsVirtualRegister(Reg))
1087           hasPartialRedefs = true;
1088       }
1089       continue;
1090     }
1091     if (!MRI->isAllocatable(Reg)) continue;
1092     if (MO.isUse()) {
1093       usePhysReg(MO);
1094     } else if (MO.isEarlyClobber()) {
1095       definePhysReg(MI, Reg,
1096                     (MO.isImplicit() || MO.isDead()) ? regFree : regReserved);
1097       hasEarlyClobbers = true;
1098     } else
1099       hasPhysDefs = true;
1100   }
1101 
1102   // The instruction may have virtual register operands that must be allocated
1103   // the same register at use-time and def-time: early clobbers and tied
1104   // operands. If there are also physical defs, these registers must avoid
1105   // both physical defs and uses, making them more constrained than normal
1106   // operands.
1107   // Similarly, if there are multiple defs and tied operands, we must make
1108   // sure the same register is allocated to uses and defs.
1109   // We didn't detect inline asm tied operands above, so just make this extra
1110   // pass for all inline asm.
1111   if (MI.isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
1112       (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
1113     handleThroughOperands(MI, VirtDead);
1114     // Don't attempt coalescing when we have funny stuff going on.
1115     CopyDstReg = Register();
1116     // Pretend we have early clobbers so the use operands get marked below.
1117     // This is not necessary for the common case of a single tied use.
1118     hasEarlyClobbers = true;
1119   }
1120 
1121   // Second scan.
1122   // Allocate virtreg uses.
1123   bool HasUndefUse = false;
1124   for (unsigned I = 0; I != VirtOpEnd; ++I) {
1125     MachineOperand &MO = MI.getOperand(I);
1126     if (!MO.isReg()) continue;
1127     Register Reg = MO.getReg();
1128     if (!Reg.isVirtual())
1129       continue;
1130     if (MO.isUse()) {
1131       if (MO.isUndef()) {
1132         HasUndefUse = true;
1133         // There is no need to allocate a register for an undef use.
1134         continue;
1135       }
1136 
1137       // Populate MayLiveAcrossBlocks in case the use block is allocated before
1138       // the def block (removing the vreg uses).
1139       mayLiveIn(Reg);
1140 
1141       LiveReg &LR = reloadVirtReg(MI, I, Reg, CopyDstReg);
1142       MCPhysReg PhysReg = LR.PhysReg;
1143       CopySrcReg = (CopySrcReg == Reg || CopySrcReg == PhysReg) ? PhysReg : 0;
1144       if (setPhysReg(MI, MO, PhysReg))
1145         killVirtReg(LR);
1146     }
1147   }
1148 
1149   // Allocate undef operands. This is a separate step because in a situation
1150   // like  ` = OP undef %X, %X`    both operands need the same register assign
1151   // so we should perform the normal assignment first.
1152   if (HasUndefUse) {
1153     for (MachineOperand &MO : MI.uses()) {
1154       if (!MO.isReg() || !MO.isUse())
1155         continue;
1156       Register Reg = MO.getReg();
1157       if (!Reg.isVirtual())
1158         continue;
1159 
1160       assert(MO.isUndef() && "Should only have undef virtreg uses left");
1161       allocVirtRegUndef(MO);
1162     }
1163   }
1164 
1165   // Track registers defined by instruction - early clobbers and tied uses at
1166   // this point.
1167   UsedInInstr.clear();
1168   if (hasEarlyClobbers) {
1169     for (const MachineOperand &MO : MI.operands()) {
1170       if (!MO.isReg()) continue;
1171       Register Reg = MO.getReg();
1172       if (!Reg || !Reg.isPhysical())
1173         continue;
1174       // Look for physreg defs and tied uses.
1175       if (!MO.isDef() && !MO.isTied()) continue;
1176       markRegUsedInInstr(Reg);
1177     }
1178   }
1179 
1180   unsigned DefOpEnd = MI.getNumOperands();
1181   if (MI.isCall()) {
1182     // Spill all virtregs before a call. This serves one purpose: If an
1183     // exception is thrown, the landing pad is going to expect to find
1184     // registers in their spill slots.
1185     // Note: although this is appealing to just consider all definitions
1186     // as call-clobbered, this is not correct because some of those
1187     // definitions may be used later on and we do not want to reuse
1188     // those for virtual registers in between.
1189     LLVM_DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
1190     spillAll(MI, /*OnlyLiveOut*/ false);
1191   }
1192 
1193   // Third scan.
1194   // Mark all physreg defs as used before allocating virtreg defs.
1195   for (unsigned I = 0; I != DefOpEnd; ++I) {
1196     const MachineOperand &MO = MI.getOperand(I);
1197     if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1198       continue;
1199     Register Reg = MO.getReg();
1200 
1201     if (!Reg || !Reg.isPhysical() || !MRI->isAllocatable(Reg))
1202       continue;
1203     definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
1204   }
1205 
1206   // Fourth scan.
1207   // Allocate defs and collect dead defs.
1208   for (unsigned I = 0; I != DefOpEnd; ++I) {
1209     const MachineOperand &MO = MI.getOperand(I);
1210     if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1211       continue;
1212     Register Reg = MO.getReg();
1213 
1214     // We have already dealt with phys regs in the previous scan.
1215     if (Reg.isPhysical())
1216       continue;
1217     MCPhysReg PhysReg = defineVirtReg(MI, I, Reg, CopySrcReg);
1218     if (setPhysReg(MI, MI.getOperand(I), PhysReg)) {
1219       VirtDead.push_back(Reg);
1220       CopyDstReg = Register(); // cancel coalescing;
1221     } else
1222       CopyDstReg = (CopyDstReg == Reg || CopyDstReg == PhysReg) ? PhysReg : 0;
1223   }
1224 
1225   // Kill dead defs after the scan to ensure that multiple defs of the same
1226   // register are allocated identically. We didn't need to do this for uses
1227   // because we are creating our own kill flags, and they are always at the last
1228   // use.
1229   for (Register VirtReg : VirtDead)
1230     killVirtReg(VirtReg);
1231   VirtDead.clear();
1232 
1233   LLVM_DEBUG(dbgs() << "<< " << MI);
1234   if (CopyDstReg && CopyDstReg == CopySrcReg && CopyDstSub == CopySrcSub) {
1235     LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
1236     Coalesced.push_back(&MI);
1237   }
1238 }
1239 
1240 void RegAllocFast::handleDebugValue(MachineInstr &MI) {
1241   MachineOperand &MO = MI.getDebugOperand(0);
1242 
1243   // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1244   // mostly constants and frame indices.
1245   if (!MO.isReg())
1246     return;
1247   Register Reg = MO.getReg();
1248   if (!Register::isVirtualRegister(Reg))
1249     return;
1250 
1251   // See if this virtual register has already been allocated to a physical
1252   // register or spilled to a stack slot.
1253   LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1254   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1255     setPhysReg(MI, MO, LRI->PhysReg);
1256   } else {
1257     int SS = StackSlotForVirtReg[Reg];
1258     if (SS != -1) {
1259       // Modify DBG_VALUE now that the value is in a spill slot.
1260       updateDbgValueForSpill(MI, SS);
1261       LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << MI);
1262       return;
1263     }
1264 
1265     // We can't allocate a physreg for a DebugValue, sorry!
1266     LLVM_DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
1267     MO.setReg(Register());
1268   }
1269 
1270   // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1271   // that future spills of Reg will have DBG_VALUEs.
1272   LiveDbgValueMap[Reg].push_back(&MI);
1273 }
1274 
1275 void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
1276   this->MBB = &MBB;
1277   LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1278 
1279   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
1280   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1281 
1282   MachineBasicBlock::iterator MII = MBB.begin();
1283 
1284   // Add live-in registers as live.
1285   for (const MachineBasicBlock::RegisterMaskPair &LI : MBB.liveins())
1286     if (MRI->isAllocatable(LI.PhysReg))
1287       definePhysReg(MII, LI.PhysReg, regReserved);
1288 
1289   VirtDead.clear();
1290   Coalesced.clear();
1291 
1292   // Otherwise, sequentially allocate each instruction in the MBB.
1293   for (MachineInstr &MI : MBB) {
1294     LLVM_DEBUG(
1295       dbgs() << "\n>> " << MI << "Regs:";
1296       dumpState()
1297     );
1298 
1299     // Special handling for debug values. Note that they are not allowed to
1300     // affect codegen of the other instructions in any way.
1301     if (MI.isDebugValue()) {
1302       handleDebugValue(MI);
1303       continue;
1304     }
1305 
1306     allocateInstruction(MI);
1307   }
1308 
1309   // Spill all physical registers holding virtual registers now.
1310   LLVM_DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1311   spillAll(MBB.getFirstTerminator(), /*OnlyLiveOut*/ true);
1312 
1313   // Erase all the coalesced copies. We are delaying it until now because
1314   // LiveVirtRegs might refer to the instrs.
1315   for (MachineInstr *MI : Coalesced)
1316     MBB.erase(MI);
1317   NumCoalesced += Coalesced.size();
1318 
1319   LLVM_DEBUG(MBB.dump());
1320 }
1321 
1322 bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
1323   LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1324                     << "********** Function: " << MF.getName() << '\n');
1325   MRI = &MF.getRegInfo();
1326   const TargetSubtargetInfo &STI = MF.getSubtarget();
1327   TRI = STI.getRegisterInfo();
1328   TII = STI.getInstrInfo();
1329   MFI = &MF.getFrameInfo();
1330   MRI->freezeReservedRegs(MF);
1331   RegClassInfo.runOnMachineFunction(MF);
1332   UsedInInstr.clear();
1333   UsedInInstr.setUniverse(TRI->getNumRegUnits());
1334 
1335   // initialize the virtual->physical register map to have a 'null'
1336   // mapping for all virtual registers
1337   unsigned NumVirtRegs = MRI->getNumVirtRegs();
1338   StackSlotForVirtReg.resize(NumVirtRegs);
1339   LiveVirtRegs.setUniverse(NumVirtRegs);
1340   MayLiveAcrossBlocks.clear();
1341   MayLiveAcrossBlocks.resize(NumVirtRegs);
1342 
1343   // Loop over all of the basic blocks, eliminating virtual register references
1344   for (MachineBasicBlock &MBB : MF)
1345     allocateBasicBlock(MBB);
1346 
1347   // All machine operands and other references to virtual registers have been
1348   // replaced. Remove the virtual registers.
1349   MRI->clearVirtRegs();
1350 
1351   StackSlotForVirtReg.clear();
1352   LiveDbgValueMap.clear();
1353   return true;
1354 }
1355 
1356 FunctionPass *llvm::createFastRegisterAllocator() {
1357   return new RegAllocFast();
1358 }
1359