xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/LiveVariables.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the LiveVariable analysis pass.  For each machine
100b57cec5SDimitry Andric // instruction in the function, this pass calculates the set of registers that
110b57cec5SDimitry Andric // are immediately dead after the instruction (i.e., the instruction calculates
120b57cec5SDimitry Andric // the value, but it is never used) and the set of registers that are used by
130b57cec5SDimitry Andric // the instruction, but are never used after the instruction (i.e., they are
140b57cec5SDimitry Andric // killed).
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric // This class computes live variables using a sparse implementation based on
170b57cec5SDimitry Andric // the machine code SSA form.  This class computes live variable information for
180b57cec5SDimitry Andric // each virtual and _register allocatable_ physical register in a function.  It
190b57cec5SDimitry Andric // uses the dominance properties of SSA form to efficiently compute live
200b57cec5SDimitry Andric // variables for virtual registers, and assumes that physical registers are only
210b57cec5SDimitry Andric // live within a single basic block (allowing it to do a single local analysis
220b57cec5SDimitry Andric // to resolve physical register lifetimes in each basic block).  If a physical
230b57cec5SDimitry Andric // register is not register allocatable, it is not tracked.  This is useful for
240b57cec5SDimitry Andric // things like the stack pointer and condition codes.
250b57cec5SDimitry Andric //
260b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric #include "llvm/CodeGen/LiveVariables.h"
298bcb0991SDimitry Andric #include "llvm/ADT/DenseSet.h"
300b57cec5SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
310b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
320b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
330b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
370b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
380b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
390b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
400b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
410b57cec5SDimitry Andric #include <algorithm>
420b57cec5SDimitry Andric using namespace llvm;
430b57cec5SDimitry Andric 
44*0fca6ea1SDimitry Andric AnalysisKey LiveVariablesAnalysis::Key;
45*0fca6ea1SDimitry Andric 
46*0fca6ea1SDimitry Andric LiveVariablesAnalysis::Result
47*0fca6ea1SDimitry Andric LiveVariablesAnalysis::run(MachineFunction &MF,
48*0fca6ea1SDimitry Andric                            MachineFunctionAnalysisManager &) {
49*0fca6ea1SDimitry Andric   return Result(MF);
50*0fca6ea1SDimitry Andric }
51*0fca6ea1SDimitry Andric 
52*0fca6ea1SDimitry Andric PreservedAnalyses
53*0fca6ea1SDimitry Andric LiveVariablesPrinterPass::run(MachineFunction &MF,
54*0fca6ea1SDimitry Andric                               MachineFunctionAnalysisManager &MFAM) {
55*0fca6ea1SDimitry Andric   OS << "Live variables in machine function: " << MF.getName() << '\n';
56*0fca6ea1SDimitry Andric   MFAM.getResult<LiveVariablesAnalysis>(MF).print(OS);
57*0fca6ea1SDimitry Andric   return PreservedAnalyses::all();
58*0fca6ea1SDimitry Andric }
59*0fca6ea1SDimitry Andric 
60*0fca6ea1SDimitry Andric char LiveVariablesWrapperPass::ID = 0;
61*0fca6ea1SDimitry Andric char &llvm::LiveVariablesID = LiveVariablesWrapperPass::ID;
62*0fca6ea1SDimitry Andric INITIALIZE_PASS_BEGIN(LiveVariablesWrapperPass, "livevars",
630b57cec5SDimitry Andric                       "Live Variable Analysis", false, false)
640b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
65*0fca6ea1SDimitry Andric INITIALIZE_PASS_END(LiveVariablesWrapperPass, "livevars",
660b57cec5SDimitry Andric                     "Live Variable Analysis", false, false)
670b57cec5SDimitry Andric 
68*0fca6ea1SDimitry Andric void LiveVariablesWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
690b57cec5SDimitry Andric   AU.addRequiredID(UnreachableMachineBlockElimID);
700b57cec5SDimitry Andric   AU.setPreservesAll();
710b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
720b57cec5SDimitry Andric }
730b57cec5SDimitry Andric 
74*0fca6ea1SDimitry Andric LiveVariables::LiveVariables(MachineFunction &MF)
75*0fca6ea1SDimitry Andric     : MF(&MF), MRI(&MF.getRegInfo()), TRI(MF.getSubtarget().getRegisterInfo()) {
76*0fca6ea1SDimitry Andric   analyze(MF);
77*0fca6ea1SDimitry Andric }
78*0fca6ea1SDimitry Andric 
79*0fca6ea1SDimitry Andric void LiveVariables::print(raw_ostream &OS) const {
80*0fca6ea1SDimitry Andric   for (size_t I = 0, E = VirtRegInfo.size(); I != E; ++I) {
81*0fca6ea1SDimitry Andric     const Register Reg = Register::index2VirtReg(I);
82*0fca6ea1SDimitry Andric     OS << "Virtual register '%" << I << "':\n";
83*0fca6ea1SDimitry Andric     VirtRegInfo[Reg].print(OS);
84*0fca6ea1SDimitry Andric   }
85*0fca6ea1SDimitry Andric }
86*0fca6ea1SDimitry Andric 
870b57cec5SDimitry Andric MachineInstr *
880b57cec5SDimitry Andric LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
894824e7fdSDimitry Andric   for (MachineInstr *MI : Kills)
904824e7fdSDimitry Andric     if (MI->getParent() == MBB)
914824e7fdSDimitry Andric       return MI;
920b57cec5SDimitry Andric   return nullptr;
930b57cec5SDimitry Andric }
940b57cec5SDimitry Andric 
95*0fca6ea1SDimitry Andric void LiveVariables::VarInfo::print(raw_ostream &OS) const {
96*0fca6ea1SDimitry Andric   OS << "  Alive in blocks: ";
97fe6060f1SDimitry Andric   for (unsigned AB : AliveBlocks)
98*0fca6ea1SDimitry Andric     OS << AB << ", ";
99*0fca6ea1SDimitry Andric   OS << "\n  Killed by:";
1000b57cec5SDimitry Andric   if (Kills.empty())
101*0fca6ea1SDimitry Andric     OS << " No instructions.\n\n";
1020b57cec5SDimitry Andric   else {
1030b57cec5SDimitry Andric     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
104*0fca6ea1SDimitry Andric       OS << "\n    #" << i << ": " << *Kills[i];
105*0fca6ea1SDimitry Andric     OS << "\n";
1060b57cec5SDimitry Andric   }
1070b57cec5SDimitry Andric }
108*0fca6ea1SDimitry Andric 
109*0fca6ea1SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
110*0fca6ea1SDimitry Andric LLVM_DUMP_METHOD void LiveVariables::VarInfo::dump() const { print(dbgs()); }
1110b57cec5SDimitry Andric #endif
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
114e8d8bef9SDimitry Andric LiveVariables::VarInfo &LiveVariables::getVarInfo(Register Reg) {
115e8d8bef9SDimitry Andric   assert(Reg.isVirtual() && "getVarInfo: not a virtual register!");
116e8d8bef9SDimitry Andric   VirtRegInfo.grow(Reg);
117e8d8bef9SDimitry Andric   return VirtRegInfo[Reg];
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
120e8d8bef9SDimitry Andric void LiveVariables::MarkVirtRegAliveInBlock(
121e8d8bef9SDimitry Andric     VarInfo &VRInfo, MachineBasicBlock *DefBlock, MachineBasicBlock *MBB,
122e8d8bef9SDimitry Andric     SmallVectorImpl<MachineBasicBlock *> &WorkList) {
1230b57cec5SDimitry Andric   unsigned BBNum = MBB->getNumber();
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // Check to see if this basic block is one of the killing blocks.  If so,
1260b57cec5SDimitry Andric   // remove it.
1270b57cec5SDimitry Andric   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
1280b57cec5SDimitry Andric     if (VRInfo.Kills[i]->getParent() == MBB) {
1290b57cec5SDimitry Andric       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
1300b57cec5SDimitry Andric       break;
1310b57cec5SDimitry Andric     }
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   if (MBB == DefBlock) return;  // Terminate recursion
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   if (VRInfo.AliveBlocks.test(BBNum))
1360b57cec5SDimitry Andric     return;  // We already know the block is live
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric   // Mark the variable known alive in this bb
1390b57cec5SDimitry Andric   VRInfo.AliveBlocks.set(BBNum);
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
1420b57cec5SDimitry Andric   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
1460b57cec5SDimitry Andric                                             MachineBasicBlock *DefBlock,
1470b57cec5SDimitry Andric                                             MachineBasicBlock *MBB) {
148e8d8bef9SDimitry Andric   SmallVector<MachineBasicBlock *, 16> WorkList;
1490b57cec5SDimitry Andric   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   while (!WorkList.empty()) {
152349cc55cSDimitry Andric     MachineBasicBlock *Pred = WorkList.pop_back_val();
1530b57cec5SDimitry Andric     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
1540b57cec5SDimitry Andric   }
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric 
157e8d8bef9SDimitry Andric void LiveVariables::HandleVirtRegUse(Register Reg, MachineBasicBlock *MBB,
1580b57cec5SDimitry Andric                                      MachineInstr &MI) {
159e8d8bef9SDimitry Andric   assert(MRI->getVRegDef(Reg) && "Register use before def!");
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   unsigned BBNum = MBB->getNumber();
1620b57cec5SDimitry Andric 
163e8d8bef9SDimitry Andric   VarInfo &VRInfo = getVarInfo(Reg);
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   // Check to see if this basic block is already a kill block.
1660b57cec5SDimitry Andric   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
1670b57cec5SDimitry Andric     // Yes, this register is killed in this basic block already. Increase the
1680b57cec5SDimitry Andric     // live range by updating the kill instruction.
1690b57cec5SDimitry Andric     VRInfo.Kills.back() = &MI;
1700b57cec5SDimitry Andric     return;
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric #ifndef NDEBUG
1740eae32dcSDimitry Andric   for (MachineInstr *Kill : VRInfo.Kills)
1750eae32dcSDimitry Andric     assert(Kill->getParent() != MBB && "entry should be at end!");
1760b57cec5SDimitry Andric #endif
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   // This situation can occur:
1790b57cec5SDimitry Andric   //
1800b57cec5SDimitry Andric   //     ,------.
1810b57cec5SDimitry Andric   //     |      |
1820b57cec5SDimitry Andric   //     |      v
1830b57cec5SDimitry Andric   //     |   t2 = phi ... t1 ...
1840b57cec5SDimitry Andric   //     |      |
1850b57cec5SDimitry Andric   //     |      v
1860b57cec5SDimitry Andric   //     |   t1 = ...
1870b57cec5SDimitry Andric   //     |  ... = ... t1 ...
1880b57cec5SDimitry Andric   //     |      |
1890b57cec5SDimitry Andric   //     `------'
1900b57cec5SDimitry Andric   //
1910b57cec5SDimitry Andric   // where there is a use in a PHI node that's a predecessor to the defining
1920b57cec5SDimitry Andric   // block. We don't want to mark all predecessors as having the value "alive"
1930b57cec5SDimitry Andric   // in this case.
194e8d8bef9SDimitry Andric   if (MBB == MRI->getVRegDef(Reg)->getParent())
195e8d8bef9SDimitry Andric     return;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   // Add a new kill entry for this basic block. If this virtual register is
1980b57cec5SDimitry Andric   // already marked as alive in this basic block, that means it is alive in at
1990b57cec5SDimitry Andric   // least one of the successor blocks, it's not a kill.
2000b57cec5SDimitry Andric   if (!VRInfo.AliveBlocks.test(BBNum))
2010b57cec5SDimitry Andric     VRInfo.Kills.push_back(&MI);
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric   // Update all dominating blocks to mark them as "known live".
204fe6060f1SDimitry Andric   for (MachineBasicBlock *Pred : MBB->predecessors())
205fe6060f1SDimitry Andric     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(Reg)->getParent(), Pred);
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric 
208e8d8bef9SDimitry Andric void LiveVariables::HandleVirtRegDef(Register Reg, MachineInstr &MI) {
2090b57cec5SDimitry Andric   VarInfo &VRInfo = getVarInfo(Reg);
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   if (VRInfo.AliveBlocks.empty())
2120b57cec5SDimitry Andric     // If vr is not alive in any block, then defaults to dead.
2130b57cec5SDimitry Andric     VRInfo.Kills.push_back(&MI);
2140b57cec5SDimitry Andric }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric /// FindLastPartialDef - Return the last partial def of the specified register.
2170b57cec5SDimitry Andric /// Also returns the sub-registers that're defined by the instruction.
218e8d8bef9SDimitry Andric MachineInstr *
219e8d8bef9SDimitry Andric LiveVariables::FindLastPartialDef(Register Reg,
2200b57cec5SDimitry Andric                                   SmallSet<unsigned, 4> &PartDefRegs) {
2210b57cec5SDimitry Andric   unsigned LastDefReg = 0;
2220b57cec5SDimitry Andric   unsigned LastDefDist = 0;
2230b57cec5SDimitry Andric   MachineInstr *LastDef = nullptr;
22406c3fb27SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs(Reg)) {
2250b57cec5SDimitry Andric     MachineInstr *Def = PhysRegDef[SubReg];
2260b57cec5SDimitry Andric     if (!Def)
2270b57cec5SDimitry Andric       continue;
2280b57cec5SDimitry Andric     unsigned Dist = DistanceMap[Def];
2290b57cec5SDimitry Andric     if (Dist > LastDefDist) {
2300b57cec5SDimitry Andric       LastDefReg  = SubReg;
2310b57cec5SDimitry Andric       LastDef     = Def;
2320b57cec5SDimitry Andric       LastDefDist = Dist;
2330b57cec5SDimitry Andric     }
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   if (!LastDef)
2370b57cec5SDimitry Andric     return nullptr;
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   PartDefRegs.insert(LastDefReg);
24006c3fb27SDimitry Andric   for (MachineOperand &MO : LastDef->all_defs()) {
24106c3fb27SDimitry Andric     if (MO.getReg() == 0)
2420b57cec5SDimitry Andric       continue;
2438bcb0991SDimitry Andric     Register DefReg = MO.getReg();
2440b57cec5SDimitry Andric     if (TRI->isSubRegister(Reg, DefReg)) {
24506c3fb27SDimitry Andric       for (MCPhysReg SubReg : TRI->subregs_inclusive(DefReg))
24606c3fb27SDimitry Andric         PartDefRegs.insert(SubReg);
2470b57cec5SDimitry Andric     }
2480b57cec5SDimitry Andric   }
2490b57cec5SDimitry Andric   return LastDef;
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
2530b57cec5SDimitry Andric /// implicit defs to a machine instruction if there was an earlier def of its
2540b57cec5SDimitry Andric /// super-register.
255e8d8bef9SDimitry Andric void LiveVariables::HandlePhysRegUse(Register Reg, MachineInstr &MI) {
2560b57cec5SDimitry Andric   MachineInstr *LastDef = PhysRegDef[Reg];
2570b57cec5SDimitry Andric   // If there was a previous use or a "full" def all is well.
2580b57cec5SDimitry Andric   if (!LastDef && !PhysRegUse[Reg]) {
2590b57cec5SDimitry Andric     // Otherwise, the last sub-register def implicitly defines this register.
2600b57cec5SDimitry Andric     // e.g.
2610b57cec5SDimitry Andric     // AH =
2620b57cec5SDimitry Andric     // AL = ... implicit-def EAX, implicit killed AH
2630b57cec5SDimitry Andric     //    = AH
2640b57cec5SDimitry Andric     // ...
2650b57cec5SDimitry Andric     //    = EAX
2660b57cec5SDimitry Andric     // All of the sub-registers must have been defined before the use of Reg!
2670b57cec5SDimitry Andric     SmallSet<unsigned, 4> PartDefRegs;
2680b57cec5SDimitry Andric     MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
2690b57cec5SDimitry Andric     // If LastPartialDef is NULL, it must be using a livein register.
2700b57cec5SDimitry Andric     if (LastPartialDef) {
2710b57cec5SDimitry Andric       LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
2720b57cec5SDimitry Andric                                                            true/*IsImp*/));
2730b57cec5SDimitry Andric       PhysRegDef[Reg] = LastPartialDef;
2740b57cec5SDimitry Andric       SmallSet<unsigned, 8> Processed;
27506c3fb27SDimitry Andric       for (MCPhysReg SubReg : TRI->subregs(Reg)) {
2760b57cec5SDimitry Andric         if (Processed.count(SubReg))
2770b57cec5SDimitry Andric           continue;
2780b57cec5SDimitry Andric         if (PartDefRegs.count(SubReg))
2790b57cec5SDimitry Andric           continue;
2800b57cec5SDimitry Andric         // This part of Reg was defined before the last partial def. It's killed
2810b57cec5SDimitry Andric         // here.
2820b57cec5SDimitry Andric         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
2830b57cec5SDimitry Andric                                                              false/*IsDef*/,
2840b57cec5SDimitry Andric                                                              true/*IsImp*/));
2850b57cec5SDimitry Andric         PhysRegDef[SubReg] = LastPartialDef;
28606c3fb27SDimitry Andric         for (MCPhysReg SS : TRI->subregs(SubReg))
28706c3fb27SDimitry Andric           Processed.insert(SS);
2880b57cec5SDimitry Andric       }
2890b57cec5SDimitry Andric     }
2900b57cec5SDimitry Andric   } else if (LastDef && !PhysRegUse[Reg] &&
291*0fca6ea1SDimitry Andric              !LastDef->findRegisterDefOperand(Reg, /*TRI=*/nullptr))
2920b57cec5SDimitry Andric     // Last def defines the super register, add an implicit def of reg.
2930b57cec5SDimitry Andric     LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
2940b57cec5SDimitry Andric                                                   true/*IsImp*/));
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   // Remember this use.
29706c3fb27SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
29806c3fb27SDimitry Andric     PhysRegUse[SubReg] = &MI;
2990b57cec5SDimitry Andric }
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric /// FindLastRefOrPartRef - Return the last reference or partial reference of
3020b57cec5SDimitry Andric /// the specified register.
303e8d8bef9SDimitry Andric MachineInstr *LiveVariables::FindLastRefOrPartRef(Register Reg) {
3040b57cec5SDimitry Andric   MachineInstr *LastDef = PhysRegDef[Reg];
3050b57cec5SDimitry Andric   MachineInstr *LastUse = PhysRegUse[Reg];
3060b57cec5SDimitry Andric   if (!LastDef && !LastUse)
3070b57cec5SDimitry Andric     return nullptr;
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
3100b57cec5SDimitry Andric   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
3110b57cec5SDimitry Andric   unsigned LastPartDefDist = 0;
31206c3fb27SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs(Reg)) {
3130b57cec5SDimitry Andric     MachineInstr *Def = PhysRegDef[SubReg];
3140b57cec5SDimitry Andric     if (Def && Def != LastDef) {
3150b57cec5SDimitry Andric       // There was a def of this sub-register in between. This is a partial
3160b57cec5SDimitry Andric       // def, keep track of the last one.
3170b57cec5SDimitry Andric       unsigned Dist = DistanceMap[Def];
3180b57cec5SDimitry Andric       if (Dist > LastPartDefDist)
3190b57cec5SDimitry Andric         LastPartDefDist = Dist;
3200b57cec5SDimitry Andric     } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
3210b57cec5SDimitry Andric       unsigned Dist = DistanceMap[Use];
3220b57cec5SDimitry Andric       if (Dist > LastRefOrPartRefDist) {
3230b57cec5SDimitry Andric         LastRefOrPartRefDist = Dist;
3240b57cec5SDimitry Andric         LastRefOrPartRef = Use;
3250b57cec5SDimitry Andric       }
3260b57cec5SDimitry Andric     }
3270b57cec5SDimitry Andric   }
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   return LastRefOrPartRef;
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric 
332e8d8bef9SDimitry Andric bool LiveVariables::HandlePhysRegKill(Register Reg, MachineInstr *MI) {
3330b57cec5SDimitry Andric   MachineInstr *LastDef = PhysRegDef[Reg];
3340b57cec5SDimitry Andric   MachineInstr *LastUse = PhysRegUse[Reg];
3350b57cec5SDimitry Andric   if (!LastDef && !LastUse)
3360b57cec5SDimitry Andric     return false;
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
3390b57cec5SDimitry Andric   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
3400b57cec5SDimitry Andric   // The whole register is used.
3410b57cec5SDimitry Andric   // AL =
3420b57cec5SDimitry Andric   // AH =
3430b57cec5SDimitry Andric   //
3440b57cec5SDimitry Andric   //    = AX
3450b57cec5SDimitry Andric   //    = AL, implicit killed AX
3460b57cec5SDimitry Andric   // AX =
3470b57cec5SDimitry Andric   //
3480b57cec5SDimitry Andric   // Or whole register is defined, but not used at all.
3490b57cec5SDimitry Andric   // dead AX =
3500b57cec5SDimitry Andric   // ...
3510b57cec5SDimitry Andric   // AX =
3520b57cec5SDimitry Andric   //
3530b57cec5SDimitry Andric   // Or whole register is defined, but only partly used.
3540b57cec5SDimitry Andric   // dead AX = implicit-def AL
3550b57cec5SDimitry Andric   //    = killed AL
3560b57cec5SDimitry Andric   // AX =
3570b57cec5SDimitry Andric   MachineInstr *LastPartDef = nullptr;
3580b57cec5SDimitry Andric   unsigned LastPartDefDist = 0;
3590b57cec5SDimitry Andric   SmallSet<unsigned, 8> PartUses;
36006c3fb27SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs(Reg)) {
3610b57cec5SDimitry Andric     MachineInstr *Def = PhysRegDef[SubReg];
3620b57cec5SDimitry Andric     if (Def && Def != LastDef) {
3630b57cec5SDimitry Andric       // There was a def of this sub-register in between. This is a partial
3640b57cec5SDimitry Andric       // def, keep track of the last one.
3650b57cec5SDimitry Andric       unsigned Dist = DistanceMap[Def];
3660b57cec5SDimitry Andric       if (Dist > LastPartDefDist) {
3670b57cec5SDimitry Andric         LastPartDefDist = Dist;
3680b57cec5SDimitry Andric         LastPartDef = Def;
3690b57cec5SDimitry Andric       }
3700b57cec5SDimitry Andric       continue;
3710b57cec5SDimitry Andric     }
3720b57cec5SDimitry Andric     if (MachineInstr *Use = PhysRegUse[SubReg]) {
37306c3fb27SDimitry Andric       for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
37406c3fb27SDimitry Andric         PartUses.insert(SS);
3750b57cec5SDimitry Andric       unsigned Dist = DistanceMap[Use];
3760b57cec5SDimitry Andric       if (Dist > LastRefOrPartRefDist) {
3770b57cec5SDimitry Andric         LastRefOrPartRefDist = Dist;
3780b57cec5SDimitry Andric         LastRefOrPartRef = Use;
3790b57cec5SDimitry Andric       }
3800b57cec5SDimitry Andric     }
3810b57cec5SDimitry Andric   }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   if (!PhysRegUse[Reg]) {
3840b57cec5SDimitry Andric     // Partial uses. Mark register def dead and add implicit def of
3850b57cec5SDimitry Andric     // sub-registers which are used.
3860b57cec5SDimitry Andric     // dead EAX  = op  implicit-def AL
3870b57cec5SDimitry Andric     // That is, EAX def is dead but AL def extends pass it.
3880b57cec5SDimitry Andric     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
38906c3fb27SDimitry Andric     for (MCPhysReg SubReg : TRI->subregs(Reg)) {
3900b57cec5SDimitry Andric       if (!PartUses.count(SubReg))
3910b57cec5SDimitry Andric         continue;
3920b57cec5SDimitry Andric       bool NeedDef = true;
3930b57cec5SDimitry Andric       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
394*0fca6ea1SDimitry Andric         MachineOperand *MO =
395*0fca6ea1SDimitry Andric             PhysRegDef[Reg]->findRegisterDefOperand(SubReg, /*TRI=*/nullptr);
3960b57cec5SDimitry Andric         if (MO) {
3970b57cec5SDimitry Andric           NeedDef = false;
3980b57cec5SDimitry Andric           assert(!MO->isDead());
3990b57cec5SDimitry Andric         }
4000b57cec5SDimitry Andric       }
4010b57cec5SDimitry Andric       if (NeedDef)
4020b57cec5SDimitry Andric         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
4030b57cec5SDimitry Andric                                                  true/*IsDef*/, true/*IsImp*/));
4040b57cec5SDimitry Andric       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
4050b57cec5SDimitry Andric       if (LastSubRef)
4060b57cec5SDimitry Andric         LastSubRef->addRegisterKilled(SubReg, TRI, true);
4070b57cec5SDimitry Andric       else {
4080b57cec5SDimitry Andric         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
40906c3fb27SDimitry Andric         for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
41006c3fb27SDimitry Andric           PhysRegUse[SS] = LastRefOrPartRef;
4110b57cec5SDimitry Andric       }
41206c3fb27SDimitry Andric       for (MCPhysReg SS : TRI->subregs(SubReg))
41306c3fb27SDimitry Andric         PartUses.erase(SS);
4140b57cec5SDimitry Andric     }
4150b57cec5SDimitry Andric   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
4160b57cec5SDimitry Andric     if (LastPartDef)
4170b57cec5SDimitry Andric       // The last partial def kills the register.
4180b57cec5SDimitry Andric       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
4190b57cec5SDimitry Andric                                                 true/*IsImp*/, true/*IsKill*/));
4200b57cec5SDimitry Andric     else {
4210b57cec5SDimitry Andric       MachineOperand *MO =
422*0fca6ea1SDimitry Andric           LastRefOrPartRef->findRegisterDefOperand(Reg, TRI, false, false);
4230b57cec5SDimitry Andric       bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
4240b57cec5SDimitry Andric       // If the last reference is the last def, then it's not used at all.
4250b57cec5SDimitry Andric       // That is, unless we are currently processing the last reference itself.
4260b57cec5SDimitry Andric       LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
4270b57cec5SDimitry Andric       if (NeedEC) {
4280b57cec5SDimitry Andric         // If we are adding a subreg def and the superreg def is marked early
4290b57cec5SDimitry Andric         // clobber, add an early clobber marker to the subreg def.
430*0fca6ea1SDimitry Andric         MO = LastRefOrPartRef->findRegisterDefOperand(Reg, /*TRI=*/nullptr);
4310b57cec5SDimitry Andric         if (MO)
4320b57cec5SDimitry Andric           MO->setIsEarlyClobber();
4330b57cec5SDimitry Andric       }
4340b57cec5SDimitry Andric     }
4350b57cec5SDimitry Andric   } else
4360b57cec5SDimitry Andric     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
4370b57cec5SDimitry Andric   return true;
4380b57cec5SDimitry Andric }
4390b57cec5SDimitry Andric 
4405f757f3fSDimitry Andric void LiveVariables::HandleRegMask(const MachineOperand &MO, unsigned NumRegs) {
4410b57cec5SDimitry Andric   // Call HandlePhysRegKill() for all live registers clobbered by Mask.
4420b57cec5SDimitry Andric   // Clobbered registers are always dead, sp there is no need to use
4430b57cec5SDimitry Andric   // HandlePhysRegDef().
4445f757f3fSDimitry Andric   for (unsigned Reg = 1; Reg != NumRegs; ++Reg) {
4450b57cec5SDimitry Andric     // Skip dead regs.
4460b57cec5SDimitry Andric     if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
4470b57cec5SDimitry Andric       continue;
4480b57cec5SDimitry Andric     // Skip mask-preserved regs.
4490b57cec5SDimitry Andric     if (!MO.clobbersPhysReg(Reg))
4500b57cec5SDimitry Andric       continue;
4510b57cec5SDimitry Andric     // Kill the largest clobbered super-register.
4520b57cec5SDimitry Andric     // This avoids needless implicit operands.
4530b57cec5SDimitry Andric     unsigned Super = Reg;
45406c3fb27SDimitry Andric     for (MCPhysReg SR : TRI->superregs(Reg))
4555f757f3fSDimitry Andric       if (SR < NumRegs && (PhysRegDef[SR] || PhysRegUse[SR]) &&
4565f757f3fSDimitry Andric           MO.clobbersPhysReg(SR))
45706c3fb27SDimitry Andric         Super = SR;
4580b57cec5SDimitry Andric     HandlePhysRegKill(Super, nullptr);
4590b57cec5SDimitry Andric   }
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric 
462e8d8bef9SDimitry Andric void LiveVariables::HandlePhysRegDef(Register Reg, MachineInstr *MI,
4630b57cec5SDimitry Andric                                      SmallVectorImpl<unsigned> &Defs) {
4640b57cec5SDimitry Andric   // What parts of the register are previously defined?
4650b57cec5SDimitry Andric   SmallSet<unsigned, 32> Live;
4660b57cec5SDimitry Andric   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
46706c3fb27SDimitry Andric     for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
46806c3fb27SDimitry Andric       Live.insert(SubReg);
4690b57cec5SDimitry Andric   } else {
47006c3fb27SDimitry Andric     for (MCPhysReg SubReg : TRI->subregs(Reg)) {
4710b57cec5SDimitry Andric       // If a register isn't itself defined, but all parts that make up of it
4720b57cec5SDimitry Andric       // are defined, then consider it also defined.
4730b57cec5SDimitry Andric       // e.g.
4740b57cec5SDimitry Andric       // AL =
4750b57cec5SDimitry Andric       // AH =
4760b57cec5SDimitry Andric       //    = AX
4770b57cec5SDimitry Andric       if (Live.count(SubReg))
4780b57cec5SDimitry Andric         continue;
4790b57cec5SDimitry Andric       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
48006c3fb27SDimitry Andric         for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
48106c3fb27SDimitry Andric           Live.insert(SS);
4820b57cec5SDimitry Andric       }
4830b57cec5SDimitry Andric     }
4840b57cec5SDimitry Andric   }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   // Start from the largest piece, find the last time any part of the register
4870b57cec5SDimitry Andric   // is referenced.
4880b57cec5SDimitry Andric   HandlePhysRegKill(Reg, MI);
4890b57cec5SDimitry Andric   // Only some of the sub-registers are used.
49006c3fb27SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs(Reg)) {
4910b57cec5SDimitry Andric     if (!Live.count(SubReg))
4920b57cec5SDimitry Andric       // Skip if this sub-register isn't defined.
4930b57cec5SDimitry Andric       continue;
4940b57cec5SDimitry Andric     HandlePhysRegKill(SubReg, MI);
4950b57cec5SDimitry Andric   }
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   if (MI)
4980b57cec5SDimitry Andric     Defs.push_back(Reg);  // Remember this def.
4990b57cec5SDimitry Andric }
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric void LiveVariables::UpdatePhysRegDefs(MachineInstr &MI,
5020b57cec5SDimitry Andric                                       SmallVectorImpl<unsigned> &Defs) {
5030b57cec5SDimitry Andric   while (!Defs.empty()) {
504349cc55cSDimitry Andric     Register Reg = Defs.pop_back_val();
50506c3fb27SDimitry Andric     for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg)) {
5060b57cec5SDimitry Andric       PhysRegDef[SubReg] = &MI;
5070b57cec5SDimitry Andric       PhysRegUse[SubReg]  = nullptr;
5080b57cec5SDimitry Andric     }
5090b57cec5SDimitry Andric   }
5100b57cec5SDimitry Andric }
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric void LiveVariables::runOnInstr(MachineInstr &MI,
5135f757f3fSDimitry Andric                                SmallVectorImpl<unsigned> &Defs,
5145f757f3fSDimitry Andric                                unsigned NumRegs) {
515fe6060f1SDimitry Andric   assert(!MI.isDebugOrPseudoInstr());
5160b57cec5SDimitry Andric   // Process all of the operands of the instruction...
5170b57cec5SDimitry Andric   unsigned NumOperandsToProcess = MI.getNumOperands();
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
5200b57cec5SDimitry Andric   // of the uses.  They will be handled in other basic blocks.
5210b57cec5SDimitry Andric   if (MI.isPHI())
5220b57cec5SDimitry Andric     NumOperandsToProcess = 1;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   // Clear kill and dead markers. LV will recompute them.
5250b57cec5SDimitry Andric   SmallVector<unsigned, 4> UseRegs;
5260b57cec5SDimitry Andric   SmallVector<unsigned, 4> DefRegs;
5270b57cec5SDimitry Andric   SmallVector<unsigned, 1> RegMasks;
5280b57cec5SDimitry Andric   for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
5290b57cec5SDimitry Andric     MachineOperand &MO = MI.getOperand(i);
5300b57cec5SDimitry Andric     if (MO.isRegMask()) {
5310b57cec5SDimitry Andric       RegMasks.push_back(i);
5320b57cec5SDimitry Andric       continue;
5330b57cec5SDimitry Andric     }
5340b57cec5SDimitry Andric     if (!MO.isReg() || MO.getReg() == 0)
5350b57cec5SDimitry Andric       continue;
5368bcb0991SDimitry Andric     Register MOReg = MO.getReg();
5370b57cec5SDimitry Andric     if (MO.isUse()) {
538bdd1243dSDimitry Andric       if (!(MOReg.isPhysical() && MRI->isReserved(MOReg)))
5390b57cec5SDimitry Andric         MO.setIsKill(false);
5400b57cec5SDimitry Andric       if (MO.readsReg())
5410b57cec5SDimitry Andric         UseRegs.push_back(MOReg);
5420b57cec5SDimitry Andric     } else {
5430b57cec5SDimitry Andric       assert(MO.isDef());
5440b57cec5SDimitry Andric       // FIXME: We should not remove any dead flags. However the MIPS RDDSP
5450b57cec5SDimitry Andric       // instruction needs it at the moment: http://llvm.org/PR27116.
546bdd1243dSDimitry Andric       if (MOReg.isPhysical() && !MRI->isReserved(MOReg))
5470b57cec5SDimitry Andric         MO.setIsDead(false);
5480b57cec5SDimitry Andric       DefRegs.push_back(MOReg);
5490b57cec5SDimitry Andric     }
5500b57cec5SDimitry Andric   }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
5530b57cec5SDimitry Andric   // Process all uses.
5540eae32dcSDimitry Andric   for (unsigned MOReg : UseRegs) {
5558bcb0991SDimitry Andric     if (Register::isVirtualRegister(MOReg))
5560b57cec5SDimitry Andric       HandleVirtRegUse(MOReg, MBB, MI);
5570b57cec5SDimitry Andric     else if (!MRI->isReserved(MOReg))
5580b57cec5SDimitry Andric       HandlePhysRegUse(MOReg, MI);
5590b57cec5SDimitry Andric   }
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric   // Process all masked registers. (Call clobbers).
5620eae32dcSDimitry Andric   for (unsigned Mask : RegMasks)
5635f757f3fSDimitry Andric     HandleRegMask(MI.getOperand(Mask), NumRegs);
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   // Process all defs.
5660eae32dcSDimitry Andric   for (unsigned MOReg : DefRegs) {
5678bcb0991SDimitry Andric     if (Register::isVirtualRegister(MOReg))
5680b57cec5SDimitry Andric       HandleVirtRegDef(MOReg, MI);
5690b57cec5SDimitry Andric     else if (!MRI->isReserved(MOReg))
5700b57cec5SDimitry Andric       HandlePhysRegDef(MOReg, &MI, Defs);
5710b57cec5SDimitry Andric   }
5720b57cec5SDimitry Andric   UpdatePhysRegDefs(MI, Defs);
5730b57cec5SDimitry Andric }
5740b57cec5SDimitry Andric 
5755f757f3fSDimitry Andric void LiveVariables::runOnBlock(MachineBasicBlock *MBB, unsigned NumRegs) {
5760b57cec5SDimitry Andric   // Mark live-in registers as live-in.
5770b57cec5SDimitry Andric   SmallVector<unsigned, 4> Defs;
5780b57cec5SDimitry Andric   for (const auto &LI : MBB->liveins()) {
5798bcb0991SDimitry Andric     assert(Register::isPhysicalRegister(LI.PhysReg) &&
5800b57cec5SDimitry Andric            "Cannot have a live-in virtual register!");
5810b57cec5SDimitry Andric     HandlePhysRegDef(LI.PhysReg, nullptr, Defs);
5820b57cec5SDimitry Andric   }
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   // Loop over all of the instructions, processing them.
5850b57cec5SDimitry Andric   DistanceMap.clear();
5860b57cec5SDimitry Andric   unsigned Dist = 0;
5870b57cec5SDimitry Andric   for (MachineInstr &MI : *MBB) {
588fe6060f1SDimitry Andric     if (MI.isDebugOrPseudoInstr())
5890b57cec5SDimitry Andric       continue;
5900b57cec5SDimitry Andric     DistanceMap.insert(std::make_pair(&MI, Dist++));
5910b57cec5SDimitry Andric 
5925f757f3fSDimitry Andric     runOnInstr(MI, Defs, NumRegs);
5930b57cec5SDimitry Andric   }
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   // Handle any virtual assignments from PHI nodes which might be at the
5960b57cec5SDimitry Andric   // bottom of this basic block.  We check all of our successor blocks to see
5970b57cec5SDimitry Andric   // if they have PHI nodes, and if so, we simulate an assignment at the end
5980b57cec5SDimitry Andric   // of the current block.
5990b57cec5SDimitry Andric   if (!PHIVarInfo[MBB->getNumber()].empty()) {
6000b57cec5SDimitry Andric     SmallVectorImpl<unsigned> &VarInfoVec = PHIVarInfo[MBB->getNumber()];
6010b57cec5SDimitry Andric 
602fe6060f1SDimitry Andric     for (unsigned I : VarInfoVec)
6030b57cec5SDimitry Andric       // Mark it alive only in the block we are representing.
604fe6060f1SDimitry Andric       MarkVirtRegAliveInBlock(getVarInfo(I), MRI->getVRegDef(I)->getParent(),
6050b57cec5SDimitry Andric                               MBB);
6060b57cec5SDimitry Andric   }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   // MachineCSE may CSE instructions which write to non-allocatable physical
6090b57cec5SDimitry Andric   // registers across MBBs. Remember if any reserved register is liveout.
6100b57cec5SDimitry Andric   SmallSet<unsigned, 4> LiveOuts;
611fe6060f1SDimitry Andric   for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
6120b57cec5SDimitry Andric     if (SuccMBB->isEHPad())
6130b57cec5SDimitry Andric       continue;
6140b57cec5SDimitry Andric     for (const auto &LI : SuccMBB->liveins()) {
6150b57cec5SDimitry Andric       if (!TRI->isInAllocatableClass(LI.PhysReg))
6160b57cec5SDimitry Andric         // Ignore other live-ins, e.g. those that are live into landing pads.
6170b57cec5SDimitry Andric         LiveOuts.insert(LI.PhysReg);
6180b57cec5SDimitry Andric     }
6190b57cec5SDimitry Andric   }
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric   // Loop over PhysRegDef / PhysRegUse, killing any registers that are
6220b57cec5SDimitry Andric   // available at the end of the basic block.
6230b57cec5SDimitry Andric   for (unsigned i = 0; i != NumRegs; ++i)
6240b57cec5SDimitry Andric     if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
6250b57cec5SDimitry Andric       HandlePhysRegDef(i, nullptr, Defs);
6260b57cec5SDimitry Andric }
6270b57cec5SDimitry Andric 
628*0fca6ea1SDimitry Andric void LiveVariables::analyze(MachineFunction &mf) {
6290b57cec5SDimitry Andric   MF = &mf;
6300b57cec5SDimitry Andric   MRI = &mf.getRegInfo();
6310b57cec5SDimitry Andric   TRI = MF->getSubtarget().getRegisterInfo();
6320b57cec5SDimitry Andric 
6335f757f3fSDimitry Andric   const unsigned NumRegs = TRI->getNumSupportedRegs(mf);
6340b57cec5SDimitry Andric   PhysRegDef.assign(NumRegs, nullptr);
6350b57cec5SDimitry Andric   PhysRegUse.assign(NumRegs, nullptr);
6360b57cec5SDimitry Andric   PHIVarInfo.resize(MF->getNumBlockIDs());
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   // FIXME: LiveIntervals will be updated to remove its dependence on
6390b57cec5SDimitry Andric   // LiveVariables to improve compilation time and eliminate bizarre pass
6400b57cec5SDimitry Andric   // dependencies. Until then, we can't change much in -O0.
6410b57cec5SDimitry Andric   if (!MRI->isSSA())
6420b57cec5SDimitry Andric     report_fatal_error("regalloc=... not currently supported with -O0");
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   analyzePHINodes(mf);
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric   // Calculate live variable information in depth first order on the CFG of the
6470b57cec5SDimitry Andric   // function.  This guarantees that we will see the definition of a virtual
6480b57cec5SDimitry Andric   // register before its uses due to dominance properties of SSA (except for PHI
6490b57cec5SDimitry Andric   // nodes, which are treated as a special case).
6500b57cec5SDimitry Andric   MachineBasicBlock *Entry = &MF->front();
6510b57cec5SDimitry Andric   df_iterator_default_set<MachineBasicBlock*,16> Visited;
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric   for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
6540b57cec5SDimitry Andric     runOnBlock(MBB, NumRegs);
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric     PhysRegDef.assign(NumRegs, nullptr);
6570b57cec5SDimitry Andric     PhysRegUse.assign(NumRegs, nullptr);
6580b57cec5SDimitry Andric   }
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric   // Convert and transfer the dead / killed information we have gathered into
6610b57cec5SDimitry Andric   // VirtRegInfo onto MI's.
6620b57cec5SDimitry Andric   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
663e8d8bef9SDimitry Andric     const Register Reg = Register::index2VirtReg(i);
6640b57cec5SDimitry Andric     for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
6650b57cec5SDimitry Andric       if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
6660b57cec5SDimitry Andric         VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
6670b57cec5SDimitry Andric       else
6680b57cec5SDimitry Andric         VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
6690b57cec5SDimitry Andric   }
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   // Check to make sure there are no unreachable blocks in the MC CFG for the
6720b57cec5SDimitry Andric   // function.  If so, it is due to a bug in the instruction selector or some
6730b57cec5SDimitry Andric   // other part of the code generator if this happens.
6740b57cec5SDimitry Andric #ifndef NDEBUG
675fe6060f1SDimitry Andric   for (const MachineBasicBlock &MBB : *MF)
676fe6060f1SDimitry Andric     assert(Visited.contains(&MBB) && "unreachable basic block found");
6770b57cec5SDimitry Andric #endif
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   PhysRegDef.clear();
6800b57cec5SDimitry Andric   PhysRegUse.clear();
6810b57cec5SDimitry Andric   PHIVarInfo.clear();
6820b57cec5SDimitry Andric }
6830b57cec5SDimitry Andric 
684349cc55cSDimitry Andric void LiveVariables::recomputeForSingleDefVirtReg(Register Reg) {
685349cc55cSDimitry Andric   assert(Reg.isVirtual());
686349cc55cSDimitry Andric 
687349cc55cSDimitry Andric   VarInfo &VI = getVarInfo(Reg);
688349cc55cSDimitry Andric   VI.AliveBlocks.clear();
689349cc55cSDimitry Andric   VI.Kills.clear();
690349cc55cSDimitry Andric 
691349cc55cSDimitry Andric   MachineInstr &DefMI = *MRI->getUniqueVRegDef(Reg);
692349cc55cSDimitry Andric   MachineBasicBlock &DefBB = *DefMI.getParent();
693349cc55cSDimitry Andric 
694349cc55cSDimitry Andric   // Initialize a worklist of BBs that Reg is live-to-end of. (Here
695349cc55cSDimitry Andric   // "live-to-end" means Reg is live at the end of a block even if it is only
696349cc55cSDimitry Andric   // live because of phi uses in a successor. This is different from isLiveOut()
697349cc55cSDimitry Andric   // which does not consider phi uses.)
698349cc55cSDimitry Andric   SmallVector<MachineBasicBlock *> LiveToEndBlocks;
699349cc55cSDimitry Andric   SparseBitVector<> UseBlocks;
7005f757f3fSDimitry Andric   unsigned NumRealUses = 0;
701349cc55cSDimitry Andric   for (auto &UseMO : MRI->use_nodbg_operands(Reg)) {
702349cc55cSDimitry Andric     UseMO.setIsKill(false);
7035f757f3fSDimitry Andric     if (!UseMO.readsReg())
7045f757f3fSDimitry Andric       continue;
7055f757f3fSDimitry Andric     ++NumRealUses;
706349cc55cSDimitry Andric     MachineInstr &UseMI = *UseMO.getParent();
707349cc55cSDimitry Andric     MachineBasicBlock &UseBB = *UseMI.getParent();
708349cc55cSDimitry Andric     UseBlocks.set(UseBB.getNumber());
709349cc55cSDimitry Andric     if (UseMI.isPHI()) {
710349cc55cSDimitry Andric       // If Reg is used in a phi then it is live-to-end of the corresponding
711349cc55cSDimitry Andric       // predecessor.
71206c3fb27SDimitry Andric       unsigned Idx = UseMO.getOperandNo();
713349cc55cSDimitry Andric       LiveToEndBlocks.push_back(UseMI.getOperand(Idx + 1).getMBB());
714349cc55cSDimitry Andric     } else if (&UseBB == &DefBB) {
715349cc55cSDimitry Andric       // A non-phi use in the same BB as the single def must come after the def.
716349cc55cSDimitry Andric     } else {
717349cc55cSDimitry Andric       // Otherwise Reg must be live-to-end of all predecessors.
718349cc55cSDimitry Andric       LiveToEndBlocks.append(UseBB.pred_begin(), UseBB.pred_end());
719349cc55cSDimitry Andric     }
720349cc55cSDimitry Andric   }
721349cc55cSDimitry Andric 
7225f757f3fSDimitry Andric   // Handle the case where all uses have been removed.
7235f757f3fSDimitry Andric   if (NumRealUses == 0) {
7245f757f3fSDimitry Andric     VI.Kills.push_back(&DefMI);
7255f757f3fSDimitry Andric     DefMI.addRegisterDead(Reg, nullptr);
7265f757f3fSDimitry Andric     return;
7275f757f3fSDimitry Andric   }
7285f757f3fSDimitry Andric   DefMI.clearRegisterDeads(Reg);
7295f757f3fSDimitry Andric 
730349cc55cSDimitry Andric   // Iterate over the worklist adding blocks to AliveBlocks.
731349cc55cSDimitry Andric   bool LiveToEndOfDefBB = false;
732349cc55cSDimitry Andric   while (!LiveToEndBlocks.empty()) {
733349cc55cSDimitry Andric     MachineBasicBlock &BB = *LiveToEndBlocks.pop_back_val();
734349cc55cSDimitry Andric     if (&BB == &DefBB) {
735349cc55cSDimitry Andric       LiveToEndOfDefBB = true;
736349cc55cSDimitry Andric       continue;
737349cc55cSDimitry Andric     }
738349cc55cSDimitry Andric     if (VI.AliveBlocks.test(BB.getNumber()))
739349cc55cSDimitry Andric       continue;
740349cc55cSDimitry Andric     VI.AliveBlocks.set(BB.getNumber());
741349cc55cSDimitry Andric     LiveToEndBlocks.append(BB.pred_begin(), BB.pred_end());
742349cc55cSDimitry Andric   }
743349cc55cSDimitry Andric 
744349cc55cSDimitry Andric   // Recompute kill flags. For each block in which Reg is used but is not
745349cc55cSDimitry Andric   // live-through, find the last instruction that uses Reg. Ignore phi nodes
746349cc55cSDimitry Andric   // because they should not be included in Kills.
747349cc55cSDimitry Andric   for (unsigned UseBBNum : UseBlocks) {
748349cc55cSDimitry Andric     if (VI.AliveBlocks.test(UseBBNum))
749349cc55cSDimitry Andric       continue;
750349cc55cSDimitry Andric     MachineBasicBlock &UseBB = *MF->getBlockNumbered(UseBBNum);
751349cc55cSDimitry Andric     if (&UseBB == &DefBB && LiveToEndOfDefBB)
752349cc55cSDimitry Andric       continue;
753349cc55cSDimitry Andric     for (auto &MI : reverse(UseBB)) {
754349cc55cSDimitry Andric       if (MI.isDebugOrPseudoInstr())
755349cc55cSDimitry Andric         continue;
756349cc55cSDimitry Andric       if (MI.isPHI())
757349cc55cSDimitry Andric         break;
7585f757f3fSDimitry Andric       if (MI.readsVirtualRegister(Reg)) {
759*0fca6ea1SDimitry Andric         assert(!MI.killsRegister(Reg, /*TRI=*/nullptr));
760349cc55cSDimitry Andric         MI.addRegisterKilled(Reg, nullptr);
761349cc55cSDimitry Andric         VI.Kills.push_back(&MI);
762349cc55cSDimitry Andric         break;
763349cc55cSDimitry Andric       }
764349cc55cSDimitry Andric     }
765349cc55cSDimitry Andric   }
766349cc55cSDimitry Andric }
767349cc55cSDimitry Andric 
7680b57cec5SDimitry Andric /// replaceKillInstruction - Update register kill info by replacing a kill
7690b57cec5SDimitry Andric /// instruction with a new one.
770e8d8bef9SDimitry Andric void LiveVariables::replaceKillInstruction(Register Reg, MachineInstr &OldMI,
7710b57cec5SDimitry Andric                                            MachineInstr &NewMI) {
7720b57cec5SDimitry Andric   VarInfo &VI = getVarInfo(Reg);
7730b57cec5SDimitry Andric   std::replace(VI.Kills.begin(), VI.Kills.end(), &OldMI, &NewMI);
7740b57cec5SDimitry Andric }
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric /// removeVirtualRegistersKilled - Remove all killed info for the specified
7770b57cec5SDimitry Andric /// instruction.
7780b57cec5SDimitry Andric void LiveVariables::removeVirtualRegistersKilled(MachineInstr &MI) {
779fcaf7f86SDimitry Andric   for (MachineOperand &MO : MI.operands()) {
7800b57cec5SDimitry Andric     if (MO.isReg() && MO.isKill()) {
7810b57cec5SDimitry Andric       MO.setIsKill(false);
7828bcb0991SDimitry Andric       Register Reg = MO.getReg();
783bdd1243dSDimitry Andric       if (Reg.isVirtual()) {
7840b57cec5SDimitry Andric         bool removed = getVarInfo(Reg).removeKill(MI);
7850b57cec5SDimitry Andric         assert(removed && "kill not in register's VarInfo?");
7860b57cec5SDimitry Andric         (void)removed;
7870b57cec5SDimitry Andric       }
7880b57cec5SDimitry Andric     }
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric }
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric /// analyzePHINodes - Gather information about the PHI nodes in here. In
7930b57cec5SDimitry Andric /// particular, we want to map the variable information of a virtual register
7940b57cec5SDimitry Andric /// which is used in a PHI node. We map that to the BB the vreg is coming from.
7950b57cec5SDimitry Andric ///
7960b57cec5SDimitry Andric void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
7970b57cec5SDimitry Andric   for (const auto &MBB : Fn)
7980b57cec5SDimitry Andric     for (const auto &BBI : MBB) {
7990b57cec5SDimitry Andric       if (!BBI.isPHI())
8000b57cec5SDimitry Andric         break;
8010b57cec5SDimitry Andric       for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
8020b57cec5SDimitry Andric         if (BBI.getOperand(i).readsReg())
8030b57cec5SDimitry Andric           PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
8040b57cec5SDimitry Andric             .push_back(BBI.getOperand(i).getReg());
8050b57cec5SDimitry Andric     }
8060b57cec5SDimitry Andric }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
809e8d8bef9SDimitry Andric                                       Register Reg, MachineRegisterInfo &MRI) {
8100b57cec5SDimitry Andric   unsigned Num = MBB.getNumber();
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   // Reg is live-through.
8130b57cec5SDimitry Andric   if (AliveBlocks.test(Num))
8140b57cec5SDimitry Andric     return true;
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   // Registers defined in MBB cannot be live in.
8170b57cec5SDimitry Andric   const MachineInstr *Def = MRI.getVRegDef(Reg);
8180b57cec5SDimitry Andric   if (Def && Def->getParent() == &MBB)
8190b57cec5SDimitry Andric     return false;
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric  // Reg was not defined in MBB, was it killed here?
8220b57cec5SDimitry Andric   return findKill(&MBB);
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric 
825e8d8bef9SDimitry Andric bool LiveVariables::isLiveOut(Register Reg, const MachineBasicBlock &MBB) {
8260b57cec5SDimitry Andric   LiveVariables::VarInfo &VI = getVarInfo(Reg);
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 8> Kills;
8294824e7fdSDimitry Andric   for (MachineInstr *MI : VI.Kills)
8304824e7fdSDimitry Andric     Kills.insert(MI->getParent());
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   // Loop over all of the successors of the basic block, checking to see if
8330b57cec5SDimitry Andric   // the value is either live in the block, or if it is killed in the block.
8340b57cec5SDimitry Andric   for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
8350b57cec5SDimitry Andric     // Is it alive in this successor?
8360b57cec5SDimitry Andric     unsigned SuccIdx = SuccMBB->getNumber();
8370b57cec5SDimitry Andric     if (VI.AliveBlocks.test(SuccIdx))
8380b57cec5SDimitry Andric       return true;
8390b57cec5SDimitry Andric     // Or is it live because there is a use in a successor that kills it?
8400b57cec5SDimitry Andric     if (Kills.count(SuccMBB))
8410b57cec5SDimitry Andric       return true;
8420b57cec5SDimitry Andric   }
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric   return false;
8450b57cec5SDimitry Andric }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
8480b57cec5SDimitry Andric /// variables that are live out of DomBB will be marked as passing live through
8490b57cec5SDimitry Andric /// BB.
8500b57cec5SDimitry Andric void LiveVariables::addNewBlock(MachineBasicBlock *BB,
8510b57cec5SDimitry Andric                                 MachineBasicBlock *DomBB,
8520b57cec5SDimitry Andric                                 MachineBasicBlock *SuccBB) {
8530b57cec5SDimitry Andric   const unsigned NumNew = BB->getNumber();
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric   DenseSet<unsigned> Defs, Kills;
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric   MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
8580b57cec5SDimitry Andric   for (; BBI != BBE && BBI->isPHI(); ++BBI) {
8590b57cec5SDimitry Andric     // Record the def of the PHI node.
8600b57cec5SDimitry Andric     Defs.insert(BBI->getOperand(0).getReg());
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric     // All registers used by PHI nodes in SuccBB must be live through BB.
8630b57cec5SDimitry Andric     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
8640b57cec5SDimitry Andric       if (BBI->getOperand(i+1).getMBB() == BB)
8650b57cec5SDimitry Andric         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
8660b57cec5SDimitry Andric   }
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric   // Record all vreg defs and kills of all instructions in SuccBB.
8690b57cec5SDimitry Andric   for (; BBI != BBE; ++BBI) {
870fe6060f1SDimitry Andric     for (const MachineOperand &Op : BBI->operands()) {
871bdd1243dSDimitry Andric       if (Op.isReg() && Op.getReg().isVirtual()) {
872fe6060f1SDimitry Andric         if (Op.isDef())
873fe6060f1SDimitry Andric           Defs.insert(Op.getReg());
874fe6060f1SDimitry Andric         else if (Op.isKill())
875fe6060f1SDimitry Andric           Kills.insert(Op.getReg());
8760b57cec5SDimitry Andric       }
8770b57cec5SDimitry Andric     }
8780b57cec5SDimitry Andric   }
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric   // Update info for all live variables
8810b57cec5SDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
882e8d8bef9SDimitry Andric     Register Reg = Register::index2VirtReg(i);
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric     // If the Defs is defined in the successor it can't be live in BB.
8850b57cec5SDimitry Andric     if (Defs.count(Reg))
8860b57cec5SDimitry Andric       continue;
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric     // If the register is either killed in or live through SuccBB it's also live
8890b57cec5SDimitry Andric     // through BB.
8900b57cec5SDimitry Andric     VarInfo &VI = getVarInfo(Reg);
8910b57cec5SDimitry Andric     if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
8920b57cec5SDimitry Andric       VI.AliveBlocks.set(NumNew);
8930b57cec5SDimitry Andric   }
8940b57cec5SDimitry Andric }
8955ffd83dbSDimitry Andric 
8965ffd83dbSDimitry Andric /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
8975ffd83dbSDimitry Andric /// variables that are live out of DomBB will be marked as passing live through
8985ffd83dbSDimitry Andric /// BB. LiveInSets[BB] is *not* updated (because it is not needed during
8995ffd83dbSDimitry Andric /// PHIElimination).
9005ffd83dbSDimitry Andric void LiveVariables::addNewBlock(MachineBasicBlock *BB,
9015ffd83dbSDimitry Andric                                 MachineBasicBlock *DomBB,
9025ffd83dbSDimitry Andric                                 MachineBasicBlock *SuccBB,
9035ffd83dbSDimitry Andric                                 std::vector<SparseBitVector<>> &LiveInSets) {
9045ffd83dbSDimitry Andric   const unsigned NumNew = BB->getNumber();
9055ffd83dbSDimitry Andric 
9065ffd83dbSDimitry Andric   SparseBitVector<> &BV = LiveInSets[SuccBB->getNumber()];
907fe6060f1SDimitry Andric   for (unsigned R : BV) {
908fe6060f1SDimitry Andric     Register VirtReg = Register::index2VirtReg(R);
9095ffd83dbSDimitry Andric     LiveVariables::VarInfo &VI = getVarInfo(VirtReg);
9105ffd83dbSDimitry Andric     VI.AliveBlocks.set(NumNew);
9115ffd83dbSDimitry Andric   }
9125ffd83dbSDimitry Andric   // All registers used by PHI nodes in SuccBB must be live through BB.
9135ffd83dbSDimitry Andric   for (MachineBasicBlock::iterator BBI = SuccBB->begin(),
9145ffd83dbSDimitry Andric          BBE = SuccBB->end();
9155ffd83dbSDimitry Andric        BBI != BBE && BBI->isPHI(); ++BBI) {
9165ffd83dbSDimitry Andric     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
9175ffd83dbSDimitry Andric       if (BBI->getOperand(i + 1).getMBB() == BB &&
9185ffd83dbSDimitry Andric           BBI->getOperand(i).readsReg())
9195ffd83dbSDimitry Andric         getVarInfo(BBI->getOperand(i).getReg())
9205ffd83dbSDimitry Andric           .AliveBlocks.set(NumNew);
9215ffd83dbSDimitry Andric   }
9225ffd83dbSDimitry Andric }
923