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