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 // FIXME: Remove this switch when all testcases are fixed!
60 static cl::opt<bool> IgnoreMissingDefs("rafast-ignore-missing-defs",
61                                        cl::Hidden);
62 
63 static RegisterRegAlloc
64   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
65 
66 namespace {
67 
68   class RegAllocFast : public MachineFunctionPass {
69   public:
70     static char ID;
71 
72     RegAllocFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1) {}
73 
74   private:
75     MachineFrameInfo *MFI;
76     MachineRegisterInfo *MRI;
77     const TargetRegisterInfo *TRI;
78     const TargetInstrInfo *TII;
79     RegisterClassInfo RegClassInfo;
80 
81     /// Basic block currently being allocated.
82     MachineBasicBlock *MBB;
83 
84     /// Maps virtual regs to the frame index where these values are spilled.
85     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
86 
87     /// Everything we know about a live virtual register.
88     struct LiveReg {
89       MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
90       Register VirtReg;                ///< Virtual register number.
91       MCPhysReg PhysReg = 0;           ///< Currently held here.
92       bool LiveOut = false;            ///< Register is possibly live out.
93       bool Reloaded = false;           ///< Register was reloaded.
94       bool Error = false;              ///< Could not allocate.
95 
96       explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
97 
98       unsigned getSparseSetIndex() const {
99         return Register::virtReg2Index(VirtReg);
100       }
101     };
102 
103     using LiveRegMap = SparseSet<LiveReg>;
104     /// This map contains entries for each virtual register that is currently
105     /// available in a physical register.
106     LiveRegMap LiveVirtRegs;
107 
108     DenseMap<unsigned, SmallVector<MachineInstr *, 2>> LiveDbgValueMap;
109     /// List of DBG_VALUE that we encountered without the vreg being assigned
110     /// because they were placed after the last use of the vreg.
111     DenseMap<unsigned, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
112 
113     /// Has a bit set for every virtual register for which it was determined
114     /// that it is alive across blocks.
115     BitVector MayLiveAcrossBlocks;
116 
117     /// State of a register unit.
118     enum RegUnitState {
119       /// A free register is not currently in use and can be allocated
120       /// immediately without checking aliases.
121       regFree,
122 
123       /// A pre-assigned register has been assigned before register allocation
124       /// (e.g., setting up a call parameter).
125       regPreAssigned,
126 
127       /// Used temporarily in reloadAtBegin() to mark register units that are
128       /// live-in to the basic block.
129       regLiveIn,
130 
131       /// A register state may also be a virtual register number, indication
132       /// that the physical register is currently allocated to a virtual
133       /// register. In that case, LiveVirtRegs contains the inverse mapping.
134     };
135 
136     /// Maps each physical register to a RegUnitState enum or virtual register.
137     std::vector<unsigned> RegUnitStates;
138 
139     SmallVector<MachineInstr *, 32> Coalesced;
140 
141     using RegUnitSet = SparseSet<uint16_t, identity<uint16_t>>;
142     /// Set of register units that are used in the current instruction, and so
143     /// cannot be allocated.
144     RegUnitSet UsedInInstr;
145     RegUnitSet PhysRegUses;
146     SmallVector<uint16_t, 8> DefOperandIndexes;
147 
148     void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
149     bool isPhysRegFree(MCPhysReg PhysReg) const;
150 
151     /// Mark a physreg as used in this instruction.
152     void markRegUsedInInstr(MCPhysReg PhysReg) {
153       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
154         UsedInInstr.insert(*Units);
155     }
156 
157     /// Check if a physreg or any of its aliases are used in this instruction.
158     bool isRegUsedInInstr(MCPhysReg PhysReg, bool LookAtPhysRegUses) const {
159       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
160         if (UsedInInstr.count(*Units))
161           return true;
162         if (LookAtPhysRegUses && PhysRegUses.count(*Units))
163           return true;
164       }
165       return false;
166     }
167 
168     /// Mark physical register as being used in a register use operand.
169     /// This is only used by the special livethrough handling code.
170     void markPhysRegUsedInInstr(MCPhysReg PhysReg) {
171       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
172         PhysRegUses.insert(*Units);
173     }
174 
175     /// Remove mark of physical register being used in the instruction.
176     void unmarkRegUsedInInstr(MCPhysReg PhysReg) {
177       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
178         UsedInInstr.erase(*Units);
179     }
180 
181     enum : unsigned {
182       spillClean = 50,
183       spillDirty = 100,
184       spillPrefBonus = 20,
185       spillImpossible = ~0u
186     };
187 
188   public:
189     StringRef getPassName() const override { return "Fast Register Allocator"; }
190 
191     void getAnalysisUsage(AnalysisUsage &AU) const override {
192       AU.setPreservesCFG();
193       MachineFunctionPass::getAnalysisUsage(AU);
194     }
195 
196     MachineFunctionProperties getRequiredProperties() const override {
197       return MachineFunctionProperties().set(
198           MachineFunctionProperties::Property::NoPHIs);
199     }
200 
201     MachineFunctionProperties getSetProperties() const override {
202       return MachineFunctionProperties().set(
203           MachineFunctionProperties::Property::NoVRegs);
204     }
205 
206   private:
207     bool runOnMachineFunction(MachineFunction &MF) override;
208 
209     void allocateBasicBlock(MachineBasicBlock &MBB);
210 
211     void addRegClassDefCounts(std::vector<unsigned> &RegClassDefCounts,
212                               Register Reg) const;
213 
214     void allocateInstruction(MachineInstr &MI);
215     void handleDebugValue(MachineInstr &MI);
216 #ifndef NDEBUG
217     bool verifyRegStateMapping(const LiveReg &LR) const;
218 #endif
219     bool usePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
220     bool definePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
221     bool displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
222     void freePhysReg(MCPhysReg PhysReg);
223 
224     unsigned calcSpillCost(MCPhysReg PhysReg) const;
225 
226     LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
227       return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
228     }
229 
230     LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
231       return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
232     }
233 
234     void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCPhysReg PhysReg);
235     void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
236                       bool LookAtPhysRegUses = false);
237     void allocVirtRegUndef(MachineOperand &MO);
238     void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
239                                    MCPhysReg Reg);
240     void defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
241                                   Register VirtReg);
242     void defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
243                        bool LookAtPhysRegUses = false);
244     void useVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg);
245 
246     MachineBasicBlock::iterator
247     getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
248                               SmallSet<Register, 2> &PrologLiveIns) const;
249 
250     void reloadAtBegin(MachineBasicBlock &MBB);
251     void setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
252 
253     Register traceCopies(Register VirtReg) const;
254     Register traceCopyChain(Register Reg) const;
255 
256     int getStackSpaceFor(Register VirtReg);
257     void spill(MachineBasicBlock::iterator Before, Register VirtReg,
258                MCPhysReg AssignedReg, bool Kill);
259     void reload(MachineBasicBlock::iterator Before, Register VirtReg,
260                 MCPhysReg PhysReg);
261 
262     bool mayLiveOut(Register VirtReg);
263     bool mayLiveIn(Register VirtReg);
264 
265     void dumpState() const;
266   };
267 
268 } // end anonymous namespace
269 
270 char RegAllocFast::ID = 0;
271 
272 INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
273                 false)
274 
275 void RegAllocFast::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
276   for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI)
277     RegUnitStates[*UI] = NewState;
278 }
279 
280 bool RegAllocFast::isPhysRegFree(MCPhysReg PhysReg) const {
281   for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
282     if (RegUnitStates[*UI] != regFree)
283       return false;
284   }
285   return true;
286 }
287 
288 /// This allocates space for the specified virtual register to be held on the
289 /// stack.
290 int RegAllocFast::getStackSpaceFor(Register VirtReg) {
291   // Find the location Reg would belong...
292   int SS = StackSlotForVirtReg[VirtReg];
293   // Already has space allocated?
294   if (SS != -1)
295     return SS;
296 
297   // Allocate a new stack object for this spill location...
298   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
299   unsigned Size = TRI->getSpillSize(RC);
300   Align Alignment = TRI->getSpillAlign(RC);
301   int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
302 
303   // Assign the slot.
304   StackSlotForVirtReg[VirtReg] = FrameIdx;
305   return FrameIdx;
306 }
307 
308 static bool dominates(MachineBasicBlock &MBB,
309                       MachineBasicBlock::const_iterator A,
310                       MachineBasicBlock::const_iterator B) {
311   auto MBBEnd = MBB.end();
312   if (B == MBBEnd)
313     return true;
314 
315   MachineBasicBlock::const_iterator I = MBB.begin();
316   for (; &*I != A && &*I != B; ++I)
317     ;
318 
319   return &*I == A;
320 }
321 
322 /// Returns false if \p VirtReg is known to not live out of the current block.
323 bool RegAllocFast::mayLiveOut(Register VirtReg) {
324   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
325     // Cannot be live-out if there are no successors.
326     return !MBB->succ_empty();
327   }
328 
329   const MachineInstr *SelfLoopDef = nullptr;
330 
331   // If this block loops back to itself, it is necessary to check whether the
332   // use comes after the def.
333   if (MBB->isSuccessor(MBB)) {
334     SelfLoopDef = MRI->getUniqueVRegDef(VirtReg);
335     if (!SelfLoopDef) {
336       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
337       return true;
338     }
339   }
340 
341   // See if the first \p Limit uses of the register are all in the current
342   // block.
343   static const unsigned Limit = 8;
344   unsigned C = 0;
345   for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
346     if (UseInst.getParent() != MBB || ++C >= Limit) {
347       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
348       // Cannot be live-out if there are no successors.
349       return !MBB->succ_empty();
350     }
351 
352     if (SelfLoopDef) {
353       // Try to handle some simple cases to avoid spilling and reloading every
354       // value inside a self looping block.
355       if (SelfLoopDef == &UseInst ||
356           !dominates(*MBB, SelfLoopDef->getIterator(), UseInst.getIterator())) {
357         MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
358         return true;
359       }
360     }
361   }
362 
363   return false;
364 }
365 
366 /// Returns false if \p VirtReg is known to not be live into the current block.
367 bool RegAllocFast::mayLiveIn(Register VirtReg) {
368   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
369     return !MBB->pred_empty();
370 
371   // See if the first \p Limit def of the register are all in the current block.
372   static const unsigned Limit = 8;
373   unsigned C = 0;
374   for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
375     if (DefInst.getParent() != MBB || ++C >= Limit) {
376       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
377       return !MBB->pred_empty();
378     }
379   }
380 
381   return false;
382 }
383 
384 /// Insert spill instruction for \p AssignedReg before \p Before. Update
385 /// DBG_VALUEs with \p VirtReg operands with the stack slot.
386 void RegAllocFast::spill(MachineBasicBlock::iterator Before, Register VirtReg,
387                          MCPhysReg AssignedReg, bool Kill) {
388   LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI)
389                     << " in " << printReg(AssignedReg, TRI));
390   int FI = getStackSpaceFor(VirtReg);
391   LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
392 
393   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
394   TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI);
395   ++NumStores;
396 
397   // When we spill a virtual register, we will have spill instructions behind
398   // every definition of it, meaning we can switch all the DBG_VALUEs over
399   // to just reference the stack slot.
400   SmallVectorImpl<MachineInstr *> &LRIDbgValues = LiveDbgValueMap[VirtReg];
401   for (MachineInstr *DBG : LRIDbgValues) {
402     MachineInstr *NewDV = buildDbgValueForSpill(*MBB, Before, *DBG, FI);
403     assert(NewDV->getParent() == MBB && "dangling parent pointer");
404     (void)NewDV;
405     LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
406     // Rewrite unassigned dbg_values to use the stack slot.
407     MachineOperand &MO = DBG->getOperand(0);
408     if (MO.isReg() && MO.getReg() == 0)
409       updateDbgValueForSpill(*DBG, FI);
410   }
411   // Now this register is spilled there is should not be any DBG_VALUE
412   // pointing to this register because they are all pointing to spilled value
413   // now.
414   LRIDbgValues.clear();
415 }
416 
417 /// Insert reload instruction for \p PhysReg before \p Before.
418 void RegAllocFast::reload(MachineBasicBlock::iterator Before, Register VirtReg,
419                           MCPhysReg PhysReg) {
420   LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
421                     << printReg(PhysReg, TRI) << '\n');
422   int FI = getStackSpaceFor(VirtReg);
423   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
424   TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI);
425   ++NumLoads;
426 }
427 
428 /// Get basic block begin insertion point.
429 /// This is not just MBB.begin() because surprisingly we have EH_LABEL
430 /// instructions marking the begin of a basic block. This means we must insert
431 /// new instructions after such labels...
432 MachineBasicBlock::iterator
433 RegAllocFast::getMBBBeginInsertionPoint(
434   MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
435   MachineBasicBlock::iterator I = MBB.begin();
436   while (I != MBB.end()) {
437     if (I->isLabel()) {
438       ++I;
439       continue;
440     }
441 
442     // Most reloads should be inserted after prolog instructions.
443     if (!TII->isBasicBlockPrologue(*I))
444       break;
445 
446     // However if a prolog instruction reads a register that needs to be
447     // reloaded, the reload should be inserted before the prolog.
448     for (MachineOperand &MO : I->operands()) {
449       if (MO.isReg())
450         PrologLiveIns.insert(MO.getReg());
451     }
452 
453     ++I;
454   }
455 
456   return I;
457 }
458 
459 /// Reload all currently assigned virtual registers.
460 void RegAllocFast::reloadAtBegin(MachineBasicBlock &MBB) {
461   if (LiveVirtRegs.empty())
462     return;
463 
464   for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
465     MCPhysReg Reg = P.PhysReg;
466     // Set state to live-in. This possibly overrides mappings to virtual
467     // registers but we don't care anymore at this point.
468     setPhysRegState(Reg, regLiveIn);
469   }
470 
471 
472   SmallSet<Register, 2> PrologLiveIns;
473 
474   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
475   // of spilling here is deterministic, if arbitrary.
476   MachineBasicBlock::iterator InsertBefore
477     = getMBBBeginInsertionPoint(MBB, PrologLiveIns);
478   for (const LiveReg &LR : LiveVirtRegs) {
479     MCPhysReg PhysReg = LR.PhysReg;
480     if (PhysReg == 0)
481       continue;
482 
483     unsigned FirstUnit = *MCRegUnitIterator(PhysReg, TRI);
484     if (RegUnitStates[FirstUnit] == regLiveIn)
485       continue;
486 
487     assert((&MBB != &MBB.getParent()->front() || IgnoreMissingDefs) &&
488            "no reload in start block. Missing vreg def?");
489 
490     if (PrologLiveIns.count(PhysReg)) {
491       // FIXME: Theoretically this should use an insert point skipping labels
492       // but I'm not sure how labels should interact with prolog instruction
493       // that need reloads.
494       reload(MBB.begin(), LR.VirtReg, PhysReg);
495     } else
496       reload(InsertBefore, LR.VirtReg, PhysReg);
497   }
498   LiveVirtRegs.clear();
499 }
500 
501 /// Handle the direct use of a physical register.  Check that the register is
502 /// not used by a virtreg. Kill the physreg, marking it free. This may add
503 /// implicit kills to MO->getParent() and invalidate MO.
504 bool RegAllocFast::usePhysReg(MachineInstr &MI, MCPhysReg Reg) {
505   assert(Register::isPhysicalRegister(Reg) && "expected physreg");
506   bool displacedAny = displacePhysReg(MI, Reg);
507   setPhysRegState(Reg, regPreAssigned);
508   markRegUsedInInstr(Reg);
509   return displacedAny;
510 }
511 
512 bool RegAllocFast::definePhysReg(MachineInstr &MI, MCPhysReg Reg) {
513   bool displacedAny = displacePhysReg(MI, Reg);
514   setPhysRegState(Reg, regPreAssigned);
515   return displacedAny;
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 bool RegAllocFast::displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg) {
522   bool displacedAny = false;
523 
524   for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
525     unsigned Unit = *UI;
526     switch (unsigned VirtReg = RegUnitStates[Unit]) {
527     default: {
528       LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
529       assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
530       MachineBasicBlock::iterator ReloadBefore =
531           std::next((MachineBasicBlock::iterator)MI.getIterator());
532       reload(ReloadBefore, VirtReg, LRI->PhysReg);
533 
534       setPhysRegState(LRI->PhysReg, regFree);
535       LRI->PhysReg = 0;
536       LRI->Reloaded = true;
537       displacedAny = true;
538       break;
539     }
540     case regPreAssigned:
541       RegUnitStates[Unit] = regFree;
542       displacedAny = true;
543       break;
544     case regFree:
545       break;
546     }
547   }
548   return displacedAny;
549 }
550 
551 void RegAllocFast::freePhysReg(MCPhysReg PhysReg) {
552   LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
553 
554   unsigned FirstUnit = *MCRegUnitIterator(PhysReg, TRI);
555   switch (unsigned VirtReg = RegUnitStates[FirstUnit]) {
556   case regFree:
557     LLVM_DEBUG(dbgs() << '\n');
558     return;
559   case regPreAssigned:
560     LLVM_DEBUG(dbgs() << '\n');
561     setPhysRegState(PhysReg, regFree);
562     return;
563   default: {
564       LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
565       assert(LRI != LiveVirtRegs.end());
566       LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
567       setPhysRegState(LRI->PhysReg, regFree);
568       LRI->PhysReg = 0;
569     }
570     return;
571   }
572 }
573 
574 /// Return the cost of spilling clearing out PhysReg and aliases so it is free
575 /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
576 /// disabled - it can be allocated directly.
577 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
578 unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
579   for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
580     switch (unsigned VirtReg = RegUnitStates[*UI]) {
581     case regFree:
582       break;
583     case regPreAssigned:
584       LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
585                         << printReg(PhysReg, TRI) << '\n');
586       return spillImpossible;
587     default: {
588       bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
589                        findLiveVirtReg(VirtReg)->LiveOut;
590       return SureSpill ? spillClean : spillDirty;
591     }
592     }
593   }
594   return 0;
595 }
596 
597 void RegAllocFast::assignDanglingDebugValues(MachineInstr &Definition,
598                                              Register VirtReg, MCPhysReg Reg) {
599   auto UDBGValIter = DanglingDbgValues.find(VirtReg);
600   if (UDBGValIter == DanglingDbgValues.end())
601     return;
602 
603   SmallVectorImpl<MachineInstr*> &Dangling = UDBGValIter->second;
604   for (MachineInstr *DbgValue : Dangling) {
605     assert(DbgValue->isDebugValue());
606     MachineOperand &MO = DbgValue->getOperand(0);
607     if (!MO.isReg())
608       continue;
609 
610     // Test whether the physreg survives from the definition to the DBG_VALUE.
611     MCPhysReg SetToReg = Reg;
612     unsigned Limit = 20;
613     for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
614          E = DbgValue->getIterator(); I != E; ++I) {
615       if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
616         LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
617                    << '\n');
618         SetToReg = 0;
619         break;
620       }
621     }
622     MO.setReg(SetToReg);
623     if (SetToReg != 0)
624       MO.setIsRenamable();
625   }
626   Dangling.clear();
627 }
628 
629 /// This method updates local state so that we know that PhysReg is the
630 /// proper container for VirtReg now.  The physical register must not be used
631 /// for anything else when this is called.
632 void RegAllocFast::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
633                                        MCPhysReg PhysReg) {
634   Register VirtReg = LR.VirtReg;
635   LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
636                     << printReg(PhysReg, TRI) << '\n');
637   assert(LR.PhysReg == 0 && "Already assigned a physreg");
638   assert(PhysReg != 0 && "Trying to assign no register");
639   LR.PhysReg = PhysReg;
640   setPhysRegState(PhysReg, VirtReg);
641 
642   assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
643 }
644 
645 static bool isCoalescable(const MachineInstr &MI) {
646   return MI.isFullCopy();
647 }
648 
649 Register RegAllocFast::traceCopyChain(Register Reg) const {
650   static const unsigned ChainLengthLimit = 3;
651   unsigned C = 0;
652   do {
653     if (Reg.isPhysical())
654       return Reg;
655     assert(Reg.isVirtual());
656 
657     MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
658     if (!VRegDef || !isCoalescable(*VRegDef))
659       return 0;
660     Reg = VRegDef->getOperand(1).getReg();
661   } while (++C <= ChainLengthLimit);
662   return 0;
663 }
664 
665 /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
666 /// chain of copies to check whether we reach a physical register we can
667 /// coalesce with.
668 Register RegAllocFast::traceCopies(Register VirtReg) const {
669   static const unsigned DefLimit = 3;
670   unsigned C = 0;
671   for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
672     if (isCoalescable(MI)) {
673       Register Reg = MI.getOperand(1).getReg();
674       Reg = traceCopyChain(Reg);
675       if (Reg.isValid())
676         return Reg;
677     }
678 
679     if (++C >= DefLimit)
680       break;
681   }
682   return Register();
683 }
684 
685 /// Allocates a physical register for VirtReg.
686 void RegAllocFast::allocVirtReg(MachineInstr &MI, LiveReg &LR,
687                                 Register Hint0, bool LookAtPhysRegUses) {
688   const Register VirtReg = LR.VirtReg;
689   assert(LR.PhysReg == 0);
690 
691   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
692   LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
693                     << " in class " << TRI->getRegClassName(&RC)
694                     << " with hint " << printReg(Hint0, TRI) << '\n');
695 
696   // Take hint when possible.
697   if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
698       !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
699     // Take hint if the register is currently free.
700     if (isPhysRegFree(Hint0)) {
701       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
702                         << '\n');
703       assignVirtToPhysReg(MI, LR, Hint0);
704       return;
705     } else {
706       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
707                         << " occupied\n");
708     }
709   } else {
710     Hint0 = Register();
711   }
712 
713 
714   // Try other hint.
715   Register Hint1 = traceCopies(VirtReg);
716   if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
717       !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
718     // Take hint if the register is currently free.
719     if (isPhysRegFree(Hint1)) {
720       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
721                  << '\n');
722       assignVirtToPhysReg(MI, LR, Hint1);
723       return;
724     } else {
725       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
726                  << " occupied\n");
727     }
728   } else {
729     Hint1 = Register();
730   }
731 
732   MCPhysReg BestReg = 0;
733   unsigned BestCost = spillImpossible;
734   ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
735   for (MCPhysReg PhysReg : AllocationOrder) {
736     LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
737     if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
738       LLVM_DEBUG(dbgs() << "already used in instr.\n");
739       continue;
740     }
741 
742     unsigned Cost = calcSpillCost(PhysReg);
743     LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
744     // Immediate take a register with cost 0.
745     if (Cost == 0) {
746       assignVirtToPhysReg(MI, LR, PhysReg);
747       return;
748     }
749 
750     if (PhysReg == Hint0 || PhysReg == Hint1)
751       Cost -= spillPrefBonus;
752 
753     if (Cost < BestCost) {
754       BestReg = PhysReg;
755       BestCost = Cost;
756     }
757   }
758 
759   if (!BestReg) {
760     // Nothing we can do: Report an error and keep going with an invalid
761     // allocation.
762     if (MI.isInlineAsm())
763       MI.emitError("inline assembly requires more registers than available");
764     else
765       MI.emitError("ran out of registers during register allocation");
766 
767     LR.Error = true;
768     LR.PhysReg = 0;
769     return;
770   }
771 
772   displacePhysReg(MI, BestReg);
773   assignVirtToPhysReg(MI, LR, BestReg);
774 }
775 
776 void RegAllocFast::allocVirtRegUndef(MachineOperand &MO) {
777   assert(MO.isUndef() && "expected undef use");
778   Register VirtReg = MO.getReg();
779   assert(Register::isVirtualRegister(VirtReg) && "Expected virtreg");
780 
781   LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
782   MCPhysReg PhysReg;
783   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
784     PhysReg = LRI->PhysReg;
785   } else {
786     const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
787     ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
788     assert(!AllocationOrder.empty() && "Allocation order must not be empty");
789     PhysReg = AllocationOrder[0];
790   }
791 
792   unsigned SubRegIdx = MO.getSubReg();
793   if (SubRegIdx != 0) {
794     PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
795     MO.setSubReg(0);
796   }
797   MO.setReg(PhysReg);
798   MO.setIsRenamable(true);
799 }
800 
801 /// Variation of defineVirtReg() with special handling for livethrough regs
802 /// (tied or earlyclobber) that may interfere with preassigned uses.
803 void RegAllocFast::defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
804                                             Register VirtReg) {
805   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
806   if (LRI != LiveVirtRegs.end()) {
807     MCPhysReg PrevReg = LRI->PhysReg;
808     if (PrevReg != 0 && isRegUsedInInstr(PrevReg, true)) {
809       LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
810                         << " (tied/earlyclobber resolution)\n");
811       freePhysReg(PrevReg);
812       LRI->PhysReg = 0;
813       allocVirtReg(MI, *LRI, 0, true);
814       MachineBasicBlock::iterator InsertBefore =
815         std::next((MachineBasicBlock::iterator)MI.getIterator());
816       LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
817                         << printReg(PrevReg, TRI) << '\n');
818       BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
819               TII->get(TargetOpcode::COPY), PrevReg)
820         .addReg(LRI->PhysReg, llvm::RegState::Kill);
821     }
822     MachineOperand &MO = MI.getOperand(OpNum);
823     if (MO.getSubReg() && !MO.isUndef()) {
824       LRI->LastUse = &MI;
825     }
826   }
827   return defineVirtReg(MI, OpNum, VirtReg, true);
828 }
829 
830 /// Allocates a register for VirtReg definition. Typically the register is
831 /// already assigned from a use of the virtreg, however we still need to
832 /// perform an allocation if:
833 /// - It is a dead definition without any uses.
834 /// - The value is live out and all uses are in different basic blocks.
835 void RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum,
836                                  Register VirtReg, bool LookAtPhysRegUses) {
837   assert(VirtReg.isVirtual() && "Not a virtual register");
838   MachineOperand &MO = MI.getOperand(OpNum);
839   LiveRegMap::iterator LRI;
840   bool New;
841   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
842   if (New) {
843     if (!MO.isDead()) {
844       if (mayLiveOut(VirtReg)) {
845         LRI->LiveOut = true;
846       } else {
847         // It is a dead def without the dead flag; add the flag now.
848         MO.setIsDead(true);
849       }
850     }
851   }
852   if (LRI->PhysReg == 0)
853     allocVirtReg(MI, *LRI, 0, LookAtPhysRegUses);
854   else {
855     assert(!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) &&
856            "TODO: preassign mismatch");
857     LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
858                       << " use existing assignment to "
859                       << printReg(LRI->PhysReg, TRI) << '\n');
860   }
861 
862   MCPhysReg PhysReg = LRI->PhysReg;
863   assert(PhysReg != 0 && "Register not assigned");
864   if (LRI->Reloaded || LRI->LiveOut) {
865     if (!MI.isImplicitDef()) {
866       MachineBasicBlock::iterator SpillBefore =
867           std::next((MachineBasicBlock::iterator)MI.getIterator());
868       LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut << " RL: "
869                         << LRI->Reloaded << '\n');
870       bool Kill = LRI->LastUse == nullptr;
871       spill(SpillBefore, VirtReg, PhysReg, Kill);
872       LRI->LastUse = nullptr;
873     }
874     LRI->LiveOut = false;
875     LRI->Reloaded = false;
876   }
877   markRegUsedInInstr(PhysReg);
878   setPhysReg(MI, MO, PhysReg);
879 }
880 
881 /// Allocates a register for a VirtReg use.
882 void RegAllocFast::useVirtReg(MachineInstr &MI, unsigned OpNum,
883                               Register VirtReg) {
884   assert(VirtReg.isVirtual() && "Not a virtual register");
885   MachineOperand &MO = MI.getOperand(OpNum);
886   LiveRegMap::iterator LRI;
887   bool New;
888   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
889   if (New) {
890     MachineOperand &MO = MI.getOperand(OpNum);
891     if (!MO.isKill()) {
892       if (mayLiveOut(VirtReg)) {
893         LRI->LiveOut = true;
894       } else {
895         // It is a last (killing) use without the kill flag; add the flag now.
896         MO.setIsKill(true);
897       }
898     }
899   } else {
900     assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
901   }
902 
903   // If necessary allocate a register.
904   if (LRI->PhysReg == 0) {
905     assert(!MO.isTied() && "tied op should be allocated");
906     Register Hint;
907     if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
908       Hint = MI.getOperand(0).getReg();
909       assert(Hint.isPhysical() &&
910              "Copy destination should already be assigned");
911     }
912     allocVirtReg(MI, *LRI, Hint, false);
913     if (LRI->Error) {
914       const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
915       ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
916       setPhysReg(MI, MO, *AllocationOrder.begin());
917       return;
918     }
919   }
920 
921   LRI->LastUse = &MI;
922   markRegUsedInInstr(LRI->PhysReg);
923   setPhysReg(MI, MO, LRI->PhysReg);
924 }
925 
926 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
927 /// may invalidate any operand pointers.  Return true if the operand kills its
928 /// register.
929 void RegAllocFast::setPhysReg(MachineInstr &MI, MachineOperand &MO,
930                               MCPhysReg PhysReg) {
931   if (!MO.getSubReg()) {
932     MO.setReg(PhysReg);
933     MO.setIsRenamable(true);
934     return;
935   }
936 
937   // Handle subregister index.
938   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : Register());
939   MO.setIsRenamable(true);
940   // Note: We leave the subreg number around a little longer in case of defs.
941   // This is so that the register freeing logic in allocateInstruction can still
942   // recognize this as subregister defs. The code there will clear the number.
943   if (!MO.isDef())
944     MO.setSubReg(0);
945 
946   // A kill flag implies killing the full register. Add corresponding super
947   // register kill.
948   if (MO.isKill()) {
949     MI.addRegisterKilled(PhysReg, TRI, true);
950     return;
951   }
952 
953   // A <def,read-undef> of a sub-register requires an implicit def of the full
954   // register.
955   if (MO.isDef() && MO.isUndef()) {
956     if (MO.isDead())
957       MI.addRegisterDead(PhysReg, TRI, true);
958     else
959       MI.addRegisterDefined(PhysReg, TRI);
960   }
961 }
962 
963 #ifndef NDEBUG
964 
965 void RegAllocFast::dumpState() const {
966   for (unsigned Unit = 1, UnitE = TRI->getNumRegUnits(); Unit != UnitE;
967        ++Unit) {
968     switch (unsigned VirtReg = RegUnitStates[Unit]) {
969     case regFree:
970       break;
971     case regPreAssigned:
972       dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
973       break;
974     case regLiveIn:
975       llvm_unreachable("Should not have regLiveIn in map");
976     default: {
977       dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
978       LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
979       assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
980       if (I->LiveOut || I->Reloaded) {
981         dbgs() << '[';
982         if (I->LiveOut) dbgs() << 'O';
983         if (I->Reloaded) dbgs() << 'R';
984         dbgs() << ']';
985       }
986       assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
987       break;
988     }
989     }
990   }
991   dbgs() << '\n';
992   // Check that LiveVirtRegs is the inverse.
993   for (const LiveReg &LR : LiveVirtRegs) {
994     Register VirtReg = LR.VirtReg;
995     assert(VirtReg.isVirtual() && "Bad map key");
996     MCPhysReg PhysReg = LR.PhysReg;
997     if (PhysReg != 0) {
998       assert(Register::isPhysicalRegister(PhysReg) &&
999              "mapped to physreg");
1000       for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
1001         assert(RegUnitStates[*UI] == VirtReg && "inverse map valid");
1002       }
1003     }
1004   }
1005 }
1006 #endif
1007 
1008 /// Count number of defs consumed from each register class by \p Reg
1009 void RegAllocFast::addRegClassDefCounts(std::vector<unsigned> &RegClassDefCounts,
1010                                         Register Reg) const {
1011   assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1012 
1013   if (Reg.isVirtual()) {
1014     const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1015     for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1016          RCIdx != RCIdxEnd; ++RCIdx) {
1017       const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1018       // FIXME: Consider aliasing sub/super registers.
1019       if (OpRC->hasSubClassEq(IdxRC))
1020         ++RegClassDefCounts[RCIdx];
1021     }
1022 
1023     return;
1024   }
1025 
1026   for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1027        RCIdx != RCIdxEnd; ++RCIdx) {
1028     const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1029     for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1030       if (IdxRC->contains(*Alias)) {
1031         ++RegClassDefCounts[RCIdx];
1032         break;
1033       }
1034     }
1035   }
1036 }
1037 
1038 void RegAllocFast::allocateInstruction(MachineInstr &MI) {
1039   // The basic algorithm here is:
1040   // 1. Mark registers of def operands as free
1041   // 2. Allocate registers to use operands and place reload instructions for
1042   //    registers displaced by the allocation.
1043   //
1044   // However we need to handle some corner cases:
1045   // - pre-assigned defs and uses need to be handled before the other def/use
1046   //   operands are processed to avoid the allocation heuristics clashing with
1047   //   the pre-assignment.
1048   // - The "free def operands" step has to come last instead of first for tied
1049   //   operands and early-clobbers.
1050 
1051   UsedInInstr.clear();
1052 
1053   // Scan for special cases; Apply pre-assigned register defs to state.
1054   bool HasPhysRegUse = false;
1055   bool HasRegMask = false;
1056   bool HasVRegDef = false;
1057   bool HasDef = false;
1058   bool HasEarlyClobber = false;
1059   bool NeedToAssignLiveThroughs = false;
1060   for (MachineOperand &MO : MI.operands()) {
1061     if (MO.isReg()) {
1062       Register Reg = MO.getReg();
1063       if (Reg.isVirtual()) {
1064         if (MO.isDef()) {
1065           HasDef = true;
1066           HasVRegDef = true;
1067           if (MO.isEarlyClobber()) {
1068             HasEarlyClobber = true;
1069             NeedToAssignLiveThroughs = true;
1070           }
1071           if (MO.isTied() || (MO.getSubReg() != 0 && !MO.isUndef()))
1072             NeedToAssignLiveThroughs = true;
1073         }
1074       } else if (Reg.isPhysical()) {
1075         if (!MRI->isReserved(Reg)) {
1076           if (MO.isDef()) {
1077             HasDef = true;
1078             bool displacedAny = definePhysReg(MI, Reg);
1079             if (MO.isEarlyClobber())
1080               HasEarlyClobber = true;
1081             if (!displacedAny)
1082               MO.setIsDead(true);
1083           }
1084           if (MO.readsReg())
1085             HasPhysRegUse = true;
1086         }
1087       }
1088     } else if (MO.isRegMask()) {
1089       HasRegMask = true;
1090     }
1091   }
1092 
1093   // Allocate virtreg defs.
1094   if (HasDef) {
1095     if (HasVRegDef) {
1096       // Special handling for early clobbers, tied operands or subregister defs:
1097       // Compared to "normal" defs these:
1098       // - Must not use a register that is pre-assigned for a use operand.
1099       // - In order to solve tricky inline assembly constraints we change the
1100       //   heuristic to figure out a good operand order before doing
1101       //   assignments.
1102       if (NeedToAssignLiveThroughs) {
1103         DefOperandIndexes.clear();
1104         PhysRegUses.clear();
1105 
1106         // Track number of defs which may consume a register from the class.
1107         std::vector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1108         assert(RegClassDefCounts[0] == 0);
1109 
1110         LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1111         for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1112           const MachineOperand &MO = MI.getOperand(I);
1113           if (!MO.isReg())
1114             continue;
1115           Register Reg = MO.getReg();
1116           if (MO.readsReg()) {
1117             if (Reg.isPhysical()) {
1118               LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI)
1119                                 << '\n');
1120               markPhysRegUsedInInstr(Reg);
1121             }
1122           }
1123 
1124           if (MO.isDef()) {
1125             if (Reg.isVirtual())
1126               DefOperandIndexes.push_back(I);
1127 
1128             addRegClassDefCounts(RegClassDefCounts, Reg);
1129           }
1130         }
1131 
1132         llvm::sort(DefOperandIndexes.begin(), DefOperandIndexes.end(),
1133                    [&](uint16_t I0, uint16_t I1) {
1134           const MachineOperand &MO0 = MI.getOperand(I0);
1135           const MachineOperand &MO1 = MI.getOperand(I1);
1136           Register Reg0 = MO0.getReg();
1137           Register Reg1 = MO1.getReg();
1138           const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1139           const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1140 
1141           // Identify regclass that are easy to use up completely just in this
1142           // instruction.
1143           unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
1144           unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
1145 
1146           bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1147           bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1148           if (SmallClass0 > SmallClass1)
1149             return true;
1150           if (SmallClass0 < SmallClass1)
1151             return false;
1152 
1153           // Allocate early clobbers and livethrough operands first.
1154           bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
1155                               (MO0.getSubReg() == 0 && !MO0.isUndef());
1156           bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
1157                               (MO1.getSubReg() == 0 && !MO1.isUndef());
1158           if (Livethrough0 > Livethrough1)
1159             return true;
1160           if (Livethrough0 < Livethrough1)
1161             return false;
1162 
1163           // Tie-break rule: operand index.
1164           return I0 < I1;
1165         });
1166 
1167         for (uint16_t OpIdx : DefOperandIndexes) {
1168           MachineOperand &MO = MI.getOperand(OpIdx);
1169           LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1170           unsigned Reg = MO.getReg();
1171           if (MO.isEarlyClobber() || MO.isTied() ||
1172               (MO.getSubReg() && !MO.isUndef())) {
1173             defineLiveThroughVirtReg(MI, OpIdx, Reg);
1174           } else {
1175             defineVirtReg(MI, OpIdx, Reg);
1176           }
1177         }
1178       } else {
1179         // Assign virtual register defs.
1180         for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1181           MachineOperand &MO = MI.getOperand(I);
1182           if (!MO.isReg() || !MO.isDef())
1183             continue;
1184           Register Reg = MO.getReg();
1185           if (Reg.isVirtual())
1186             defineVirtReg(MI, I, Reg);
1187         }
1188       }
1189     }
1190 
1191     // Free registers occupied by defs.
1192     // Iterate operands in reverse order, so we see the implicit super register
1193     // defs first (we added them earlier in case of <def,read-undef>).
1194     for (unsigned I = MI.getNumOperands(); I-- > 0;) {
1195       MachineOperand &MO = MI.getOperand(I);
1196       if (!MO.isReg() || !MO.isDef())
1197         continue;
1198 
1199       // subreg defs don't free the full register. We left the subreg number
1200       // around as a marker in setPhysReg() to recognize this case here.
1201       if (MO.getSubReg() != 0) {
1202         MO.setSubReg(0);
1203         continue;
1204       }
1205 
1206       // Do not free tied operands and early clobbers.
1207       if (MO.isTied() || MO.isEarlyClobber())
1208         continue;
1209       Register Reg = MO.getReg();
1210       if (!Reg)
1211         continue;
1212       assert(Reg.isPhysical());
1213       if (MRI->isReserved(Reg))
1214         continue;
1215       freePhysReg(Reg);
1216       unmarkRegUsedInInstr(Reg);
1217     }
1218   }
1219 
1220   // Displace clobbered registers.
1221   if (HasRegMask) {
1222     for (const MachineOperand &MO : MI.operands()) {
1223       if (MO.isRegMask()) {
1224         // MRI bookkeeping.
1225         MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
1226 
1227         // Displace clobbered registers.
1228         const uint32_t *Mask = MO.getRegMask();
1229         for (LiveRegMap::iterator LRI = LiveVirtRegs.begin(),
1230              LRIE = LiveVirtRegs.end(); LRI != LRIE; ++LRI) {
1231           MCPhysReg PhysReg = LRI->PhysReg;
1232           if (PhysReg != 0 && MachineOperand::clobbersPhysReg(Mask, PhysReg))
1233             displacePhysReg(MI, PhysReg);
1234         }
1235       }
1236     }
1237   }
1238 
1239   // Apply pre-assigned register uses to state.
1240   if (HasPhysRegUse) {
1241     for (MachineOperand &MO : MI.operands()) {
1242       if (!MO.isReg() || !MO.readsReg())
1243         continue;
1244       Register Reg = MO.getReg();
1245       if (!Reg.isPhysical())
1246         continue;
1247       if (MRI->isReserved(Reg))
1248         continue;
1249       bool displacedAny = usePhysReg(MI, Reg);
1250       if (!displacedAny && !MRI->isReserved(Reg))
1251         MO.setIsKill(true);
1252     }
1253   }
1254 
1255   // Allocate virtreg uses and insert reloads as necessary.
1256   bool HasUndefUse = false;
1257   for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
1258     MachineOperand &MO = MI.getOperand(I);
1259     if (!MO.isReg() || !MO.isUse())
1260       continue;
1261     Register Reg = MO.getReg();
1262     if (!Reg.isVirtual())
1263       continue;
1264 
1265     if (MO.isUndef()) {
1266       HasUndefUse = true;
1267       continue;
1268     }
1269 
1270 
1271     // Populate MayLiveAcrossBlocks in case the use block is allocated before
1272     // the def block (removing the vreg uses).
1273     mayLiveIn(Reg);
1274 
1275 
1276     assert(!MO.isInternalRead() && "Bundles not supported");
1277     assert(MO.readsReg() && "reading use");
1278     useVirtReg(MI, I, Reg);
1279   }
1280 
1281   // Allocate undef operands. This is a separate step because in a situation
1282   // like  ` = OP undef %X, %X`    both operands need the same register assign
1283   // so we should perform the normal assignment first.
1284   if (HasUndefUse) {
1285     for (MachineOperand &MO : MI.uses()) {
1286       if (!MO.isReg() || !MO.isUse())
1287         continue;
1288       Register Reg = MO.getReg();
1289       if (!Reg.isVirtual())
1290         continue;
1291 
1292       assert(MO.isUndef() && "Should only have undef virtreg uses left");
1293       allocVirtRegUndef(MO);
1294     }
1295   }
1296 
1297   // Free early clobbers.
1298   if (HasEarlyClobber) {
1299     for (unsigned I = MI.getNumOperands(); I-- > 0; ) {
1300       MachineOperand &MO = MI.getOperand(I);
1301       if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber())
1302         continue;
1303       // subreg defs don't free the full register. We left the subreg number
1304       // around as a marker in setPhysReg() to recognize this case here.
1305       if (MO.getSubReg() != 0) {
1306         MO.setSubReg(0);
1307         continue;
1308       }
1309 
1310       Register Reg = MO.getReg();
1311       if (!Reg)
1312         continue;
1313       assert(Reg.isPhysical() && "should have register assigned");
1314 
1315       // We sometimes get odd situations like:
1316       //    early-clobber %x0 = INSTRUCTION %x0
1317       // which is semantically questionable as the early-clobber should
1318       // apply before the use. But in practice we consider the use to
1319       // happen before the early clobber now. Don't free the early clobber
1320       // register in this case.
1321       if (MI.readsRegister(Reg, TRI))
1322         continue;
1323 
1324       freePhysReg(Reg);
1325     }
1326   }
1327 
1328   LLVM_DEBUG(dbgs() << "<< " << MI);
1329   if (MI.isCopy() && MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
1330       MI.getNumOperands() == 2) {
1331     LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
1332     Coalesced.push_back(&MI);
1333   }
1334 }
1335 
1336 void RegAllocFast::handleDebugValue(MachineInstr &MI) {
1337   MachineOperand &MO = MI.getDebugOperand(0);
1338 
1339   // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1340   // mostly constants and frame indices.
1341   if (!MO.isReg())
1342     return;
1343   Register Reg = MO.getReg();
1344   if (!Register::isVirtualRegister(Reg))
1345     return;
1346 
1347   // Already spilled to a stackslot?
1348   int SS = StackSlotForVirtReg[Reg];
1349   if (SS != -1) {
1350     // Modify DBG_VALUE now that the value is in a spill slot.
1351     updateDbgValueForSpill(MI, SS);
1352     LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1353     return;
1354   }
1355 
1356   // See if this virtual register has already been allocated to a physical
1357   // register or spilled to a stack slot.
1358   LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1359   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1360     setPhysReg(MI, MO, LRI->PhysReg);
1361   } else {
1362     DanglingDbgValues[Reg].push_back(&MI);
1363   }
1364 
1365   // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1366   // that future spills of Reg will have DBG_VALUEs.
1367   LiveDbgValueMap[Reg].push_back(&MI);
1368 }
1369 
1370 #ifndef NDEBUG
1371 bool RegAllocFast::verifyRegStateMapping(const LiveReg &LR) const {
1372   for (MCRegUnitIterator UI(LR.PhysReg, TRI); UI.isValid(); ++UI) {
1373     if (RegUnitStates[*UI] != LR.VirtReg)
1374       return false;
1375   }
1376 
1377   return true;
1378 }
1379 #endif
1380 
1381 void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
1382   this->MBB = &MBB;
1383   LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1384 
1385   RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1386   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1387 
1388   for (MachineBasicBlock *Succ : MBB.successors()) {
1389     for (const MachineBasicBlock::RegisterMaskPair &LI : Succ->liveins())
1390       setPhysRegState(LI.PhysReg, regPreAssigned);
1391   }
1392 
1393   Coalesced.clear();
1394 
1395   // Traverse block in reverse order allocating instructions one by one.
1396   for (MachineInstr &MI : reverse(MBB)) {
1397     LLVM_DEBUG(
1398       dbgs() << "\n>> " << MI << "Regs:";
1399       dumpState()
1400     );
1401 
1402     // Special handling for debug values. Note that they are not allowed to
1403     // affect codegen of the other instructions in any way.
1404     if (MI.isDebugValue()) {
1405       handleDebugValue(MI);
1406       continue;
1407     }
1408 
1409     allocateInstruction(MI);
1410   }
1411 
1412   LLVM_DEBUG(
1413     dbgs() << "Begin Regs:";
1414     dumpState()
1415   );
1416 
1417   // Spill all physical registers holding virtual registers now.
1418   LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1419   reloadAtBegin(MBB);
1420 
1421   // Erase all the coalesced copies. We are delaying it until now because
1422   // LiveVirtRegs might refer to the instrs.
1423   for (MachineInstr *MI : Coalesced)
1424     MBB.erase(MI);
1425   NumCoalesced += Coalesced.size();
1426 
1427   for (auto &UDBGPair : DanglingDbgValues) {
1428     for (MachineInstr *DbgValue : UDBGPair.second) {
1429       assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1430       MachineOperand &MO = DbgValue->getOperand(0);
1431       // Nothing to do if the vreg was spilled in the meantime.
1432       if (!MO.isReg())
1433         continue;
1434       LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1435                  << '\n');
1436       MO.setReg(0);
1437     }
1438   }
1439   DanglingDbgValues.clear();
1440 
1441   LLVM_DEBUG(MBB.dump());
1442 }
1443 
1444 bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
1445   LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1446                     << "********** Function: " << MF.getName() << '\n');
1447   MRI = &MF.getRegInfo();
1448   const TargetSubtargetInfo &STI = MF.getSubtarget();
1449   TRI = STI.getRegisterInfo();
1450   TII = STI.getInstrInfo();
1451   MFI = &MF.getFrameInfo();
1452   MRI->freezeReservedRegs(MF);
1453   RegClassInfo.runOnMachineFunction(MF);
1454   unsigned NumRegUnits = TRI->getNumRegUnits();
1455   UsedInInstr.clear();
1456   UsedInInstr.setUniverse(NumRegUnits);
1457   PhysRegUses.clear();
1458   PhysRegUses.setUniverse(NumRegUnits);
1459 
1460   // initialize the virtual->physical register map to have a 'null'
1461   // mapping for all virtual registers
1462   unsigned NumVirtRegs = MRI->getNumVirtRegs();
1463   StackSlotForVirtReg.resize(NumVirtRegs);
1464   LiveVirtRegs.setUniverse(NumVirtRegs);
1465   MayLiveAcrossBlocks.clear();
1466   MayLiveAcrossBlocks.resize(NumVirtRegs);
1467 
1468   // Loop over all of the basic blocks, eliminating virtual register references
1469   for (MachineBasicBlock &MBB : MF)
1470     allocateBasicBlock(MBB);
1471 
1472   // All machine operands and other references to virtual registers have been
1473   // replaced. Remove the virtual registers.
1474   MRI->clearVirtRegs();
1475 
1476   StackSlotForVirtReg.clear();
1477   LiveDbgValueMap.clear();
1478   return true;
1479 }
1480 
1481 FunctionPass *llvm::createFastRegisterAllocator() {
1482   return new RegAllocFast();
1483 }
1484