LCOV - code coverage report
Current view: top level - lib/CodeGen - LiveVariables.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 312 335 93.1 %
Date: 2018-02-23 15:42:53 Functions: 25 25 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements the LiveVariable analysis pass.  For each machine
      11             : // instruction in the function, this pass calculates the set of registers that
      12             : // are immediately dead after the instruction (i.e., the instruction calculates
      13             : // the value, but it is never used) and the set of registers that are used by
      14             : // the instruction, but are never used after the instruction (i.e., they are
      15             : // killed).
      16             : //
      17             : // This class computes live variables using a sparse implementation based on
      18             : // the machine code SSA form.  This class computes live variable information for
      19             : // each virtual and _register allocatable_ physical register in a function.  It
      20             : // uses the dominance properties of SSA form to efficiently compute live
      21             : // variables for virtual registers, and assumes that physical registers are only
      22             : // live within a single basic block (allowing it to do a single local analysis
      23             : // to resolve physical register lifetimes in each basic block).  If a physical
      24             : // register is not register allocatable, it is not tracked.  This is useful for
      25             : // things like the stack pointer and condition codes.
      26             : //
      27             : //===----------------------------------------------------------------------===//
      28             : 
      29             : #include "llvm/CodeGen/LiveVariables.h"
      30             : #include "llvm/ADT/DepthFirstIterator.h"
      31             : #include "llvm/ADT/STLExtras.h"
      32             : #include "llvm/ADT/SmallPtrSet.h"
      33             : #include "llvm/ADT/SmallSet.h"
      34             : #include "llvm/CodeGen/MachineInstr.h"
      35             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      36             : #include "llvm/CodeGen/Passes.h"
      37             : #include "llvm/Support/Debug.h"
      38             : #include "llvm/Support/ErrorHandling.h"
      39             : #include "llvm/Support/raw_ostream.h"
      40             : #include <algorithm>
      41             : using namespace llvm;
      42             : 
      43             : char LiveVariables::ID = 0;
      44             : char &llvm::LiveVariablesID = LiveVariables::ID;
      45       22315 : INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
      46             :                 "Live Variable Analysis", false, false)
      47       22315 : INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
      48      208002 : INITIALIZE_PASS_END(LiveVariables, "livevars",
      49             :                 "Live Variable Analysis", false, false)
      50             : 
      51             : 
      52       18342 : void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
      53       18342 :   AU.addRequiredID(UnreachableMachineBlockElimID);
      54             :   AU.setPreservesAll();
      55       18342 :   MachineFunctionPass::getAnalysisUsage(AU);
      56       18342 : }
      57             : 
      58             : MachineInstr *
      59      428747 : LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
      60      871397 :   for (unsigned i = 0, e = Kills.size(); i != e; ++i)
      61      855642 :     if (Kills[i]->getParent() == MBB)
      62             :       return Kills[i];
      63             :   return nullptr;
      64             : }
      65             : 
      66             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
      67             : LLVM_DUMP_METHOD void LiveVariables::VarInfo::dump() const {
      68             :   dbgs() << "  Alive in blocks: ";
      69             :   for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
      70             :            E = AliveBlocks.end(); I != E; ++I)
      71             :     dbgs() << *I << ", ";
      72             :   dbgs() << "\n  Killed by:";
      73             :   if (Kills.empty())
      74             :     dbgs() << " No instructions.\n";
      75             :   else {
      76             :     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
      77             :       dbgs() << "\n    #" << i << ": " << *Kills[i];
      78             :     dbgs() << "\n";
      79             :   }
      80             : }
      81             : #endif
      82             : 
      83             : /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
      84     6461005 : LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
      85             :   assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
      86             :          "getVarInfo: not a virtual register!");
      87     6461005 :   VirtRegInfo.grow(RegIdx);
      88     6461005 :   return VirtRegInfo[RegIdx];
      89             : }
      90             : 
      91     1806780 : void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
      92             :                                             MachineBasicBlock *DefBlock,
      93             :                                             MachineBasicBlock *MBB,
      94             :                                     std::vector<MachineBasicBlock*> &WorkList) {
      95     1806780 :   unsigned BBNum = MBB->getNumber();
      96             : 
      97             :   // Check to see if this basic block is one of the killing blocks.  If so,
      98             :   // remove it.
      99     8252783 :   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
     100     9729218 :     if (VRInfo.Kills[i]->getParent() == MBB) {
     101      225386 :       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
     102      225386 :       break;
     103             :     }
     104             : 
     105     1806780 :   if (MBB == DefBlock) return;  // Terminate recursion
     106             : 
     107     1590116 :   if (VRInfo.AliveBlocks.test(BBNum))
     108             :     return;  // We already know the block is live
     109             : 
     110             :   // Mark the variable known alive in this bb
     111      917978 :   VRInfo.AliveBlocks.set(BBNum);
     112             : 
     113             :   assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
     114      917978 :   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
     115             : }
     116             : 
     117      602016 : void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
     118             :                                             MachineBasicBlock *DefBlock,
     119             :                                             MachineBasicBlock *MBB) {
     120             :   std::vector<MachineBasicBlock*> WorkList;
     121      602016 :   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
     122             : 
     123     3011544 :   while (!WorkList.empty()) {
     124     1204764 :     MachineBasicBlock *Pred = WorkList.back();
     125             :     WorkList.pop_back();
     126     1204764 :     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
     127             :   }
     128      602016 : }
     129             : 
     130     2862753 : void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
     131             :                                      MachineInstr &MI) {
     132             :   assert(MRI->getVRegDef(reg) && "Register use before def!");
     133             : 
     134     2862753 :   unsigned BBNum = MBB->getNumber();
     135             : 
     136     2862753 :   VarInfo& VRInfo = getVarInfo(reg);
     137             : 
     138             :   // Check to see if this basic block is already a kill block.
     139     2862753 :   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
     140             :     // Yes, this register is killed in this basic block already. Increase the
     141             :     // live range by updating the kill instruction.
     142     2477313 :     VRInfo.Kills.back() = &MI;
     143     2477313 :     return;
     144             :   }
     145             : 
     146             : #ifndef NDEBUG
     147             :   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
     148             :     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
     149             : #endif
     150             : 
     151             :   // This situation can occur:
     152             :   //
     153             :   //     ,------.
     154             :   //     |      |
     155             :   //     |      v
     156             :   //     |   t2 = phi ... t1 ...
     157             :   //     |      |
     158             :   //     |      v
     159             :   //     |   t1 = ...
     160             :   //     |  ... = ... t1 ...
     161             :   //     |      |
     162             :   //     `------'
     163             :   //
     164             :   // where there is a use in a PHI node that's a predecessor to the defining
     165             :   // block. We don't want to mark all predecessors as having the value "alive"
     166             :   // in this case.
     167      385440 :   if (MBB == MRI->getVRegDef(reg)->getParent()) return;
     168             : 
     169             :   // Add a new kill entry for this basic block. If this virtual register is
     170             :   // already marked as alive in this basic block, that means it is alive in at
     171             :   // least one of the successor blocks, it's not a kill.
     172      385439 :   if (!VRInfo.AliveBlocks.test(BBNum))
     173      320612 :     VRInfo.Kills.push_back(&MI);
     174             : 
     175             :   // Update all dominating blocks to mark them as "known live".
     176             :   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
     177      912074 :          E = MBB->pred_end(); PI != E; ++PI)
     178      526635 :     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
     179             : }
     180             : 
     181     1893901 : void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr &MI) {
     182     1893901 :   VarInfo &VRInfo = getVarInfo(Reg);
     183             : 
     184     1893901 :   if (VRInfo.AliveBlocks.empty())
     185             :     // If vr is not alive in any block, then defaults to dead.
     186     3787802 :     VRInfo.Kills.push_back(&MI);
     187     1893901 : }
     188             : 
     189             : /// FindLastPartialDef - Return the last partial def of the specified register.
     190             : /// Also returns the sub-registers that're defined by the instruction.
     191      287481 : MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
     192             :                                             SmallSet<unsigned,4> &PartDefRegs) {
     193      287481 :   unsigned LastDefReg = 0;
     194             :   unsigned LastDefDist = 0;
     195             :   MachineInstr *LastDef = nullptr;
     196      977807 :   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     197             :     unsigned SubReg = *SubRegs;
     198      805690 :     MachineInstr *Def = PhysRegDef[SubReg];
     199      402845 :     if (!Def)
     200      402833 :       continue;
     201          24 :     unsigned Dist = DistanceMap[Def];
     202          12 :     if (Dist > LastDefDist) {
     203           3 :       LastDefReg  = SubReg;
     204           3 :       LastDef     = Def;
     205             :       LastDefDist = Dist;
     206             :     }
     207             :   }
     208             : 
     209      287481 :   if (!LastDef)
     210             :     return nullptr;
     211             : 
     212           3 :   PartDefRegs.insert(LastDefReg);
     213          12 :   for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
     214           9 :     MachineOperand &MO = LastDef->getOperand(i);
     215          18 :     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
     216           3 :       continue;
     217             :     unsigned DefReg = MO.getReg();
     218          12 :     if (TRI->isSubRegister(Reg, DefReg)) {
     219           3 :       for (MCSubRegIterator SubRegs(DefReg, TRI, /*IncludeSelf=*/true);
     220          15 :            SubRegs.isValid(); ++SubRegs)
     221          12 :         PartDefRegs.insert(*SubRegs);
     222             :     }
     223             :   }
     224             :   return LastDef;
     225             : }
     226             : 
     227             : /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
     228             : /// implicit defs to a machine instruction if there was an earlier def of its
     229             : /// super-register.
     230      971980 : void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr &MI) {
     231     1943960 :   MachineInstr *LastDef = PhysRegDef[Reg];
     232             :   // If there was a previous use or a "full" def all is well.
     233     1259495 :   if (!LastDef && !PhysRegUse[Reg]) {
     234             :     // Otherwise, the last sub-register def implicitly defines this register.
     235             :     // e.g.
     236             :     // AH =
     237             :     // AL = ... implicit-def EAX, implicit killed AH
     238             :     //    = AH
     239             :     // ...
     240             :     //    = EAX
     241             :     // All of the sub-registers must have been defined before the use of Reg!
     242      287481 :     SmallSet<unsigned, 4> PartDefRegs;
     243      287481 :     MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
     244             :     // If LastPartialDef is NULL, it must be using a livein register.
     245      287481 :     if (LastPartialDef) {
     246           3 :       LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
     247             :                                                            true/*IsImp*/));
     248           6 :       PhysRegDef[Reg] = LastPartialDef;
     249           3 :       SmallSet<unsigned, 8> Processed;
     250          18 :       for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     251          12 :         unsigned SubReg = *SubRegs;
     252          12 :         if (Processed.count(SubReg))
     253          12 :           continue;
     254          12 :         if (PartDefRegs.count(SubReg))
     255          12 :           continue;
     256             :         // This part of Reg was defined before the last partial def. It's killed
     257             :         // here.
     258           0 :         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
     259             :                                                              false/*IsDef*/,
     260             :                                                              true/*IsImp*/));
     261           0 :         PhysRegDef[SubReg] = LastPartialDef;
     262           0 :         for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
     263           0 :           Processed.insert(*SS);
     264             :       }
     265             :     }
     266     2736686 :   } else if (LastDef && !PhysRegUse[Reg] &&
     267             :              !LastDef->findRegisterDefOperand(Reg))
     268             :     // Last def defines the super register, add an implicit def of reg.
     269         204 :     LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
     270             :                                                   true/*IsImp*/));
     271             : 
     272             :   // Remember this use.
     273      971980 :   for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
     274     3579581 :        SubRegs.isValid(); ++SubRegs)
     275     5215202 :     PhysRegUse[*SubRegs] = &MI;
     276      971980 : }
     277             : 
     278             : /// FindLastRefOrPartRef - Return the last reference or partial reference of
     279             : /// the specified register.
     280         336 : MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) {
     281         672 :   MachineInstr *LastDef = PhysRegDef[Reg];
     282         672 :   MachineInstr *LastUse = PhysRegUse[Reg];
     283         336 :   if (!LastDef && !LastUse)
     284             :     return nullptr;
     285             : 
     286         336 :   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
     287         672 :   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
     288             :   unsigned LastPartDefDist = 0;
     289         829 :   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     290             :     unsigned SubReg = *SubRegs;
     291         314 :     MachineInstr *Def = PhysRegDef[SubReg];
     292         157 :     if (Def && Def != LastDef) {
     293             :       // There was a def of this sub-register in between. This is a partial
     294             :       // def, keep track of the last one.
     295          82 :       unsigned Dist = DistanceMap[Def];
     296          82 :       if (Dist > LastPartDefDist)
     297             :         LastPartDefDist = Dist;
     298         150 :     } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
     299          75 :       unsigned Dist = DistanceMap[Use];
     300          75 :       if (Dist > LastRefOrPartRefDist) {
     301             :         LastRefOrPartRefDist = Dist;
     302           0 :         LastRefOrPartRef = Use;
     303             :       }
     304             :     }
     305             :   }
     306             : 
     307         336 :   return LastRefOrPartRef;
     308             : }
     309             : 
     310     7983264 : bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
     311    15966528 :   MachineInstr *LastDef = PhysRegDef[Reg];
     312    15966528 :   MachineInstr *LastUse = PhysRegUse[Reg];
     313     7983264 :   if (!LastDef && !LastUse)
     314             :     return false;
     315             : 
     316     7180273 :   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
     317    14360546 :   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
     318             :   // The whole register is used.
     319             :   // AL =
     320             :   // AH =
     321             :   //
     322             :   //    = AX
     323             :   //    = AL, implicit killed AX
     324             :   // AX =
     325             :   //
     326             :   // Or whole register is defined, but not used at all.
     327             :   // dead AX =
     328             :   // ...
     329             :   // AX =
     330             :   //
     331             :   // Or whole register is defined, but only partly used.
     332             :   // dead AX = implicit-def AL
     333             :   //    = killed AL
     334             :   // AX =
     335             :   MachineInstr *LastPartDef = nullptr;
     336             :   unsigned LastPartDefDist = 0;
     337     7180274 :   SmallSet<unsigned, 8> PartUses;
     338    23534681 :   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     339             :     unsigned SubReg = *SubRegs;
     340    18348268 :     MachineInstr *Def = PhysRegDef[SubReg];
     341     9174134 :     if (Def && Def != LastDef) {
     342             :       // There was a def of this sub-register in between. This is a partial
     343             :       // def, keep track of the last one.
     344      332089 :       unsigned Dist = DistanceMap[Def];
     345      332089 :       if (Dist > LastPartDefDist) {
     346             :         LastPartDefDist = Dist;
     347      115239 :         LastPartDef = Def;
     348             :       }
     349      332089 :       continue;
     350             :     }
     351    17684090 :     if (MachineInstr *Use = PhysRegUse[SubReg]) {
     352    32608391 :       for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true); SS.isValid();
     353             :            ++SS)
     354    15298798 :         PartUses.insert(*SS);
     355     8654798 :       unsigned Dist = DistanceMap[Use];
     356     8654798 :       if (Dist > LastRefOrPartRefDist) {
     357             :         LastRefOrPartRefDist = Dist;
     358         336 :         LastRefOrPartRef = Use;
     359             :       }
     360             :     }
     361             :   }
     362             : 
     363    14360548 :   if (!PhysRegUse[Reg]) {
     364             :     // Partial uses. Mark register def dead and add implicit def of
     365             :     // sub-registers which are used.
     366             :     // dead EAX  = op  implicit-def AL
     367             :     // That is, EAX def is dead but AL def extends pass it.
     368     1989914 :     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
     369     2180443 :     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     370      190529 :       unsigned SubReg = *SubRegs;
     371      190529 :       if (!PartUses.count(SubReg))
     372      190193 :         continue;
     373             :       bool NeedDef = true;
     374        1008 :       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
     375             :         MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
     376         336 :         if (MO) {
     377             :           NeedDef = false;
     378             :           assert(!MO->isDead());
     379             :         }
     380             :       }
     381             :       if (NeedDef)
     382           0 :         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
     383           0 :                                                  true/*IsDef*/, true/*IsImp*/));
     384         336 :       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
     385         336 :       if (LastSubRef)
     386         336 :         LastSubRef->addRegisterKilled(SubReg, TRI, true);
     387             :       else {
     388           0 :         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
     389           0 :         for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
     390           0 :              SS.isValid(); ++SS)
     391           0 :           PhysRegUse[*SS] = LastRefOrPartRef;
     392             :       }
     393         829 :       for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
     394         157 :         PartUses.erase(*SS);
     395             :     }
     396    12370634 :   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
     397           0 :     if (LastPartDef)
     398             :       // The last partial def kills the register.
     399           0 :       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
     400             :                                                 true/*IsImp*/, true/*IsKill*/));
     401             :     else {
     402             :       MachineOperand *MO =
     403           0 :         LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI);
     404           0 :       bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
     405             :       // If the last reference is the last def, then it's not used at all.
     406             :       // That is, unless we are currently processing the last reference itself.
     407           0 :       LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
     408           0 :       if (NeedEC) {
     409             :         // If we are adding a subreg def and the superreg def is marked early
     410             :         // clobber, add an early clobber marker to the subreg def.
     411           0 :         MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
     412           0 :         if (MO)
     413             :           MO->setIsEarlyClobber();
     414             :       }
     415             :     }
     416             :   } else
     417     6185317 :     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
     418             :   return true;
     419             : }
     420             : 
     421      194678 : void LiveVariables::HandleRegMask(const MachineOperand &MO) {
     422             :   // Call HandlePhysRegKill() for all live registers clobbered by Mask.
     423             :   // Clobbered registers are always dead, sp there is no need to use
     424             :   // HandlePhysRegDef().
     425    51069570 :   for (unsigned Reg = 1, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg) {
     426             :     // Skip dead regs.
     427   150672251 :     if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
     428    48752434 :       continue;
     429             :     // Skip mask-preserved regs.
     430     2122458 :     if (!MO.clobbersPhysReg(Reg))
     431      341423 :       continue;
     432             :     // Kill the largest clobbered super-register.
     433             :     // This avoids needless implicit operands.
     434             :     unsigned Super = Reg;
     435     6663323 :     for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
     436     9555797 :       if ((PhysRegDef[*SR] || PhysRegUse[*SR]) && MO.clobbersPhysReg(*SR))
     437             :         Super = *SR;
     438     1781035 :     HandlePhysRegKill(Super, nullptr);
     439             :   }
     440      194678 : }
     441             : 
     442     3570856 : void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
     443             :                                      SmallVectorImpl<unsigned> &Defs) {
     444             :   // What parts of the register are previously defined?
     445     3570856 :   SmallSet<unsigned, 32> Live;
     446     8562295 :   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
     447     5535728 :     for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
     448     8160764 :          SubRegs.isValid(); ++SubRegs)
     449     5392900 :       Live.insert(*SubRegs);
     450             :   } else {
     451     3623186 :     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     452     1214210 :       unsigned SubReg = *SubRegs;
     453             :       // If a register isn't itself defined, but all parts that make up of it
     454             :       // are defined, then consider it also defined.
     455             :       // e.g.
     456             :       // AL =
     457             :       // AH =
     458             :       //    = AX
     459     1214210 :       if (Live.count(SubReg))
     460        2574 :         continue;
     461     3633993 :       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
     462        3765 :         for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
     463       10152 :              SS.isValid(); ++SS)
     464        6387 :           Live.insert(*SS);
     465             :       }
     466             :     }
     467             :   }
     468             : 
     469             :   // Start from the largest piece, find the last time any part of the register
     470             :   // is referenced.
     471     3570856 :   HandlePhysRegKill(Reg, MI);
     472             :   // Only some of the sub-registers are used.
     473    10980958 :   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     474     3839246 :     unsigned SubReg = *SubRegs;
     475     3839246 :     if (!Live.count(SubReg))
     476             :       // Skip if this sub-register isn't defined.
     477     1207871 :       continue;
     478     2631375 :     HandlePhysRegKill(SubReg, MI);
     479             :   }
     480             : 
     481     3570856 :   if (MI)
     482     1351487 :     Defs.push_back(Reg);  // Remember this def.
     483     3570856 : }
     484             : 
     485     4131815 : void LiveVariables::UpdatePhysRegDefs(MachineInstr &MI,
     486             :                                       SmallVectorImpl<unsigned> &Defs) {
     487     6834789 :   while (!Defs.empty()) {
     488     1351487 :     unsigned Reg = Defs.back();
     489             :     Defs.pop_back();
     490     1351487 :     for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
     491     3993435 :          SubRegs.isValid(); ++SubRegs) {
     492             :       unsigned SubReg = *SubRegs;
     493     5283896 :       PhysRegDef[SubReg] = &MI;
     494     5283896 :       PhysRegUse[SubReg]  = nullptr;
     495             :     }
     496             :   }
     497     4131815 : }
     498             : 
     499     4131815 : void LiveVariables::runOnInstr(MachineInstr &MI,
     500             :                                SmallVectorImpl<unsigned> &Defs) {
     501             :   assert(!MI.isDebugValue());
     502             :   // Process all of the operands of the instruction...
     503     4131815 :   unsigned NumOperandsToProcess = MI.getNumOperands();
     504             : 
     505             :   // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
     506             :   // of the uses.  They will be handled in other basic blocks.
     507             :   if (MI.isPHI())
     508             :     NumOperandsToProcess = 1;
     509             : 
     510             :   // Clear kill and dead markers. LV will recompute them.
     511             :   SmallVector<unsigned, 4> UseRegs;
     512             :   SmallVector<unsigned, 4> DefRegs;
     513             :   SmallVector<unsigned, 1> RegMasks;
     514    21496730 :   for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
     515    17364915 :     MachineOperand &MO = MI.getOperand(i);
     516    17559593 :     if (MO.isRegMask()) {
     517      194678 :       RegMasks.push_back(i);
     518     7413063 :       continue;
     519             :     }
     520    24193944 :     if (!MO.isReg() || MO.getReg() == 0)
     521     7023707 :       continue;
     522    10146530 :     unsigned MOReg = MO.getReg();
     523    10146530 :     if (MO.isUse()) {
     524     8470210 :       if (!(TargetRegisterInfo::isPhysicalRegister(MOReg) &&
     525     2787923 :             MRI->isReserved(MOReg)))
     526             :         MO.setIsKill(false);
     527             :       if (MO.readsReg())
     528     5649009 :         UseRegs.push_back(MOReg);
     529             :     } else {
     530             :       assert(MO.isDef());
     531             :       // FIXME: We should not remove any dead flags. However the MIPS RDDSP
     532             :       // instruction needs it at the moment: http://llvm.org/PR27116.
     533     7034585 :       if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
     534     2570342 :           !MRI->isReserved(MOReg))
     535             :         MO.setIsDead(false);
     536     4464243 :       DefRegs.push_back(MOReg);
     537             :     }
     538             :   }
     539             : 
     540     4131815 :   MachineBasicBlock *MBB = MI.getParent();
     541             :   // Process all uses.
     542     9780823 :   for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
     543    11298018 :     unsigned MOReg = UseRegs[i];
     544     5649009 :     if (TargetRegisterInfo::isVirtualRegister(MOReg))
     545     2862753 :       HandleVirtRegUse(MOReg, MBB, MI);
     546     5572512 :     else if (!MRI->isReserved(MOReg))
     547      971980 :       HandlePhysRegUse(MOReg, MI);
     548             :   }
     549             : 
     550             :   // Process all masked registers. (Call clobbers).
     551     4326492 :   for (unsigned i = 0, e = RegMasks.size(); i != e; ++i)
     552      584034 :     HandleRegMask(MI.getOperand(RegMasks[i]));
     553             : 
     554             :   // Process all defs.
     555     8596057 :   for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
     556     8928486 :     unsigned MOReg = DefRegs[i];
     557     4464243 :     if (TargetRegisterInfo::isVirtualRegister(MOReg))
     558     1893901 :       HandleVirtRegDef(MOReg, MI);
     559     5140684 :     else if (!MRI->isReserved(MOReg))
     560     1351487 :       HandlePhysRegDef(MOReg, &MI, Defs);
     561             :   }
     562     4131814 :   UpdatePhysRegDefs(MI, Defs);
     563     4131815 : }
     564             : 
     565      323533 : void LiveVariables::runOnBlock(MachineBasicBlock *MBB, const unsigned NumRegs) {
     566             :   // Mark live-in registers as live-in.
     567             :   SmallVector<unsigned, 4> Defs;
     568      633741 :   for (const auto &LI : MBB->liveins()) {
     569             :     assert(TargetRegisterInfo::isPhysicalRegister(LI.PhysReg) &&
     570             :            "Cannot have a live-in virtual register!");
     571      310208 :     HandlePhysRegDef(LI.PhysReg, nullptr, Defs);
     572             :   }
     573             : 
     574             :   // Loop over all of the instructions, processing them.
     575      323533 :   DistanceMap.clear();
     576             :   unsigned Dist = 0;
     577     4805588 :   for (MachineInstr &MI : *MBB) {
     578     4158531 :     if (MI.isDebugValue())
     579       26716 :       continue;
     580     8263629 :     DistanceMap.insert(std::make_pair(&MI, Dist++));
     581             : 
     582     4131814 :     runOnInstr(MI, Defs);
     583             :   }
     584             : 
     585             :   // Handle any virtual assignments from PHI nodes which might be at the
     586             :   // bottom of this basic block.  We check all of our successor blocks to see
     587             :   // if they have PHI nodes, and if so, we simulate an assignment at the end
     588             :   // of the current block.
     589      647048 :   if (!PHIVarInfo[MBB->getNumber()].empty()) {
     590             :     SmallVectorImpl<unsigned> &VarInfoVec = PHIVarInfo[MBB->getNumber()];
     591             : 
     592       75381 :     for (SmallVectorImpl<unsigned>::iterator I = VarInfoVec.begin(),
     593      131406 :            E = VarInfoVec.end(); I != E; ++I)
     594             :       // Mark it alive only in the block we are representing.
     595       75381 :       MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
     596             :                               MBB);
     597             :   }
     598             : 
     599             :   // MachineCSE may CSE instructions which write to non-allocatable physical
     600             :   // registers across MBBs. Remember if any reserved register is liveout.
     601      323533 :   SmallSet<unsigned, 4> LiveOuts;
     602             :   for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
     603      541934 :          SE = MBB->succ_end(); SI != SE; ++SI) {
     604      218410 :     MachineBasicBlock *SuccMBB = *SI;
     605      218410 :     if (SuccMBB->isEHPad())
     606       27211 :       continue;
     607      191686 :     for (const auto &LI : SuccMBB->liveins()) {
     608         974 :       if (!TRI->isInAllocatableClass(LI.PhysReg))
     609             :         // Ignore other live-ins, e.g. those that are live into landing pads.
     610         479 :         LiveOuts.insert(LI.PhysReg);
     611             :     }
     612             :   }
     613             : 
     614             :   // Loop over PhysRegDef / PhysRegUse, killing any registers that are
     615             :   // available at the end of the basic block.
     616   156952473 :   for (unsigned i = 0; i != NumRegs; ++i)
     617   468513613 :     if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
     618     1909161 :       HandlePhysRegDef(i, nullptr, Defs);
     619      323533 : }
     620             : 
     621      166937 : bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
     622      166937 :   MF = &mf;
     623      166937 :   MRI = &mf.getRegInfo();
     624      166937 :   TRI = MF->getSubtarget().getRegisterInfo();
     625             : 
     626      166937 :   const unsigned NumRegs = TRI->getNumRegs();
     627      333874 :   PhysRegDef.assign(NumRegs, nullptr);
     628      333874 :   PhysRegUse.assign(NumRegs, nullptr);
     629      333874 :   PHIVarInfo.resize(MF->getNumBlockIDs());
     630             :   PHIJoins.clear();
     631             : 
     632             :   // FIXME: LiveIntervals will be updated to remove its dependence on
     633             :   // LiveVariables to improve compilation time and eliminate bizarre pass
     634             :   // dependencies. Until then, we can't change much in -O0.
     635      333874 :   if (!MRI->isSSA())
     636           0 :     report_fatal_error("regalloc=... not currently supported with -O0");
     637             : 
     638      166937 :   analyzePHINodes(mf);
     639             : 
     640             :   // Calculate live variable information in depth first order on the CFG of the
     641             :   // function.  This guarantees that we will see the definition of a virtual
     642             :   // register before its uses due to dominance properties of SSA (except for PHI
     643             :   // nodes, which are treated as a special case).
     644      333872 :   MachineBasicBlock *Entry = &MF->front();
     645             :   df_iterator_default_set<MachineBasicBlock*,16> Visited;
     646             : 
     647     1147876 :   for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
     648      323533 :     runOnBlock(MBB, NumRegs);
     649             : 
     650      647066 :     PhysRegDef.assign(NumRegs, nullptr);
     651      647066 :     PhysRegUse.assign(NumRegs, nullptr);
     652             :   }
     653             : 
     654             :   // Convert and transfer the dead / killed information we have gathered into
     655             :   // VirtRegInfo onto MI's.
     656     2620417 :   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
     657             :     const unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
     658     6735781 :     for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
     659     5486463 :       if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
     660       23050 :         VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
     661             :       else
     662     3634592 :         VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
     663             :   }
     664             : 
     665             :   // Check to make sure there are no unreachable blocks in the MC CFG for the
     666             :   // function.  If so, it is due to a bug in the instruction selector or some
     667             :   // other part of the code generator if this happens.
     668             : #ifndef NDEBUG
     669             :   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
     670             :     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
     671             : #endif
     672             : 
     673             :   PhysRegDef.clear();
     674             :   PhysRegUse.clear();
     675      166937 :   PHIVarInfo.clear();
     676             : 
     677      166937 :   return false;
     678             : }
     679             : 
     680             : /// replaceKillInstruction - Update register kill info by replacing a kill
     681             : /// instruction with a new one.
     682      106621 : void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr &OldMI,
     683             :                                            MachineInstr &NewMI) {
     684      106621 :   VarInfo &VI = getVarInfo(Reg);
     685             :   std::replace(VI.Kills.begin(), VI.Kills.end(), &OldMI, &NewMI);
     686      106621 : }
     687             : 
     688             : /// removeVirtualRegistersKilled - Remove all killed info for the specified
     689             : /// instruction.
     690       34486 : void LiveVariables::removeVirtualRegistersKilled(MachineInstr &MI) {
     691      219634 :   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
     692      185148 :     MachineOperand &MO = MI.getOperand(i);
     693      294965 :     if (MO.isReg() && MO.isKill()) {
     694             :       MO.setIsKill(false);
     695           0 :       unsigned Reg = MO.getReg();
     696           0 :       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
     697           0 :         bool removed = getVarInfo(Reg).removeKill(MI);
     698             :         assert(removed && "kill not in register's VarInfo?");
     699             :         (void)removed;
     700             :       }
     701             :     }
     702             :   }
     703       34486 : }
     704             : 
     705             : /// analyzePHINodes - Gather information about the PHI nodes in here. In
     706             : /// particular, we want to map the variable information of a virtual register
     707             : /// which is used in a PHI node. We map that to the BB the vreg is coming from.
     708             : ///
     709      166938 : void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
     710      490469 :   for (const auto &MBB : Fn)
     711      682304 :     for (const auto &BBI : MBB) {
     712             :       if (!BBI.isPHI())
     713             :         break;
     714      112177 :       for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
     715       76936 :         if (BBI.getOperand(i).readsReg())
     716      150762 :           PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
     717       75381 :             .push_back(BBI.getOperand(i).getReg());
     718             :     }
     719      166937 : }
     720             : 
     721        2677 : bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
     722             :                                       unsigned Reg,
     723             :                                       MachineRegisterInfo &MRI) {
     724        2677 :   unsigned Num = MBB.getNumber();
     725             : 
     726             :   // Reg is live-through.
     727        2677 :   if (AliveBlocks.test(Num))
     728             :     return true;
     729             : 
     730             :   // Registers defined in MBB cannot be live in.
     731        1982 :   const MachineInstr *Def = MRI.getVRegDef(Reg);
     732        1982 :   if (Def && Def->getParent() == &MBB)
     733             :     return false;
     734             : 
     735             :  // Reg was not defined in MBB, was it killed here?
     736        1980 :   return findKill(&MBB);
     737             : }
     738             : 
     739       79969 : bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
     740       79969 :   LiveVariables::VarInfo &VI = getVarInfo(Reg);
     741             : 
     742             :   SmallPtrSet<const MachineBasicBlock *, 8> Kills;
     743      168494 :   for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
     744       17112 :     Kills.insert(VI.Kills[i]->getParent());
     745             : 
     746             :   // Loop over all of the successors of the basic block, checking to see if
     747             :   // the value is either live in the block, or if it is killed in the block.
     748      180251 :   for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
     749             :     // Is it alive in this successor?
     750      106360 :     unsigned SuccIdx = SuccMBB->getNumber();
     751      106360 :     if (VI.AliveBlocks.test(SuccIdx))
     752             :       return true;
     753             :     // Or is it live because there is a use in a successor that kills it?
     754      102561 :     if (Kills.count(SuccMBB))
     755             :       return true;
     756             :   }
     757             : 
     758             :   return false;
     759             : }
     760             : 
     761             : /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
     762             : /// variables that are live out of DomBB will be marked as passing live through
     763             : /// BB.
     764        1858 : void LiveVariables::addNewBlock(MachineBasicBlock *BB,
     765             :                                 MachineBasicBlock *DomBB,
     766             :                                 MachineBasicBlock *SuccBB) {
     767        1858 :   const unsigned NumNew = BB->getNumber();
     768             : 
     769             :   DenseSet<unsigned> Defs, Kills;
     770             : 
     771        1858 :   MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
     772        4697 :   for (; BBI != BBE && BBI->isPHI(); ++BBI) {
     773             :     // Record the def of the PHI node.
     774        5678 :     Defs.insert(BBI->getOperand(0).getReg());
     775             : 
     776             :     // All registers used by PHI nodes in SuccBB must be live through BB.
     777       14884 :     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
     778       24090 :       if (BBI->getOperand(i+1).getMBB() == BB)
     779        2845 :         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
     780             :   }
     781             : 
     782             :   // Record all vreg defs and kills of all instructions in SuccBB.
     783       15269 :   for (; BBI != BBE; ++BBI) {
     784       65315 :     for (MachineInstr::mop_iterator I = BBI->operands_begin(),
     785       78726 :          E = BBI->operands_end(); I != E; ++I) {
     786       87237 :       if (I->isReg() && TargetRegisterInfo::isVirtualRegister(I->getReg())) {
     787       15920 :         if (I->isDef())
     788        9898 :           Defs.insert(I->getReg());
     789       10971 :         else if (I->isKill())
     790       12584 :           Kills.insert(I->getReg());
     791             :       }
     792             :     }
     793             :   }
     794             : 
     795             :   // Update info for all live variables
     796      799238 :   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
     797      397761 :     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
     798             : 
     799             :     // If the Defs is defined in the successor it can't be live in BB.
     800        7788 :     if (Defs.count(Reg))
     801        7788 :       continue;
     802             : 
     803             :     // If the register is either killed in or live through SuccBB it's also live
     804             :     // through BB.
     805      389973 :     VarInfo &VI = getVarInfo(Reg);
     806      388994 :     if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
     807        9688 :       VI.AliveBlocks.set(NumNew);
     808             :   }
     809        1858 : }

Generated by: LCOV version 1.13