Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:29

0001 //===-- llvm/CodeGen/LiveVariables.h - Live Variable Analysis ---*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file implements the LiveVariables analysis pass.  For each machine
0010 // instruction in the function, this pass calculates the set of registers that
0011 // are immediately dead after the instruction (i.e., the instruction calculates
0012 // the value, but it is never used) and the set of registers that are used by
0013 // the instruction, but are never used after the instruction (i.e., they are
0014 // killed).
0015 //
0016 // This class computes live variables using a sparse implementation based on
0017 // the machine code SSA form.  This class computes live variable information for
0018 // each virtual and _register allocatable_ physical register in a function.  It
0019 // uses the dominance properties of SSA form to efficiently compute live
0020 // variables for virtual registers, and assumes that physical registers are only
0021 // live within a single basic block (allowing it to do a single local analysis
0022 // to resolve physical register lifetimes in each basic block).  If a physical
0023 // register is not register allocatable, it is not tracked.  This is useful for
0024 // things like the stack pointer and condition codes.
0025 //
0026 //===----------------------------------------------------------------------===//
0027 
0028 #ifndef LLVM_CODEGEN_LIVEVARIABLES_H
0029 #define LLVM_CODEGEN_LIVEVARIABLES_H
0030 
0031 #include "llvm/ADT/DenseMap.h"
0032 #include "llvm/ADT/IndexedMap.h"
0033 #include "llvm/ADT/SmallSet.h"
0034 #include "llvm/ADT/SmallVector.h"
0035 #include "llvm/ADT/SparseBitVector.h"
0036 #include "llvm/CodeGen/MachineFunctionPass.h"
0037 #include "llvm/CodeGen/MachineInstr.h"
0038 #include "llvm/CodeGen/MachinePassManager.h"
0039 #include "llvm/CodeGen/TargetRegisterInfo.h"
0040 #include "llvm/InitializePasses.h"
0041 #include "llvm/PassRegistry.h"
0042 
0043 namespace llvm {
0044 
0045 class MachineBasicBlock;
0046 class MachineRegisterInfo;
0047 
0048 class LiveVariables {
0049   friend class LiveVariablesWrapperPass;
0050 
0051 public:
0052   /// VarInfo - This represents the regions where a virtual register is live in
0053   /// the program.  We represent this with three different pieces of
0054   /// information: the set of blocks in which the instruction is live
0055   /// throughout, the set of blocks in which the instruction is actually used,
0056   /// and the set of non-phi instructions that are the last users of the value.
0057   ///
0058   /// In the common case where a value is defined and killed in the same block,
0059   /// There is one killing instruction, and AliveBlocks is empty.
0060   ///
0061   /// Otherwise, the value is live out of the block.  If the value is live
0062   /// throughout any blocks, these blocks are listed in AliveBlocks.  Blocks
0063   /// where the liveness range ends are not included in AliveBlocks, instead
0064   /// being captured by the Kills set.  In these blocks, the value is live into
0065   /// the block (unless the value is defined and killed in the same block) and
0066   /// lives until the specified instruction.  Note that there cannot ever be a
0067   /// value whose Kills set contains two instructions from the same basic block.
0068   ///
0069   /// PHI nodes complicate things a bit.  If a PHI node is the last user of a
0070   /// value in one of its predecessor blocks, it is not listed in the kills set,
0071   /// but does include the predecessor block in the AliveBlocks set (unless that
0072   /// block also defines the value).  This leads to the (perfectly sensical)
0073   /// situation where a value is defined in a block, and the last use is a phi
0074   /// node in the successor.  In this case, AliveBlocks is empty (the value is
0075   /// not live across any  blocks) and Kills is empty (phi nodes are not
0076   /// included). This is sensical because the value must be live to the end of
0077   /// the block, but is not live in any successor blocks.
0078   struct VarInfo {
0079     /// AliveBlocks - Set of blocks in which this value is alive completely
0080     /// through.  This is a bit set which uses the basic block number as an
0081     /// index.
0082     ///
0083     SparseBitVector<> AliveBlocks;
0084 
0085     /// Kills - List of MachineInstruction's which are the last use of this
0086     /// virtual register (kill it) in their basic block.
0087     ///
0088     std::vector<MachineInstr*> Kills;
0089 
0090     /// removeKill - Delete a kill corresponding to the specified
0091     /// machine instruction. Returns true if there was a kill
0092     /// corresponding to this instruction, false otherwise.
0093     bool removeKill(MachineInstr &MI) {
0094       std::vector<MachineInstr *>::iterator I = find(Kills, &MI);
0095       if (I == Kills.end())
0096         return false;
0097       Kills.erase(I);
0098       return true;
0099     }
0100 
0101     /// findKill - Find a kill instruction in MBB. Return NULL if none is found.
0102     MachineInstr *findKill(const MachineBasicBlock *MBB) const;
0103 
0104     /// isLiveIn - Is Reg live in to MBB? This means that Reg is live through
0105     /// MBB, or it is killed in MBB. If Reg is only used by PHI instructions in
0106     /// MBB, it is not considered live in.
0107     bool isLiveIn(const MachineBasicBlock &MBB, Register Reg,
0108                   MachineRegisterInfo &MRI);
0109 
0110     void print(raw_ostream &OS) const;
0111 
0112     void dump() const;
0113   };
0114 
0115 private:
0116   /// VirtRegInfo - This list is a mapping from virtual register number to
0117   /// variable information.
0118   ///
0119   IndexedMap<VarInfo, VirtReg2IndexFunctor> VirtRegInfo;
0120 
0121 private:   // Intermediate data structures
0122   MachineFunction *MF = nullptr;
0123 
0124   MachineRegisterInfo *MRI = nullptr;
0125 
0126   const TargetRegisterInfo *TRI = nullptr;
0127 
0128   // PhysRegInfo - Keep track of which instruction was the last def of a
0129   // physical register. This is a purely local property, because all physical
0130   // register references are presumed dead across basic blocks.
0131   std::vector<MachineInstr *> PhysRegDef;
0132 
0133   // PhysRegInfo - Keep track of which instruction was the last use of a
0134   // physical register. This is a purely local property, because all physical
0135   // register references are presumed dead across basic blocks.
0136   std::vector<MachineInstr *> PhysRegUse;
0137 
0138   std::vector<SmallVector<unsigned, 4>> PHIVarInfo;
0139 
0140   // DistanceMap - Keep track the distance of a MI from the start of the
0141   // current basic block.
0142   DenseMap<MachineInstr*, unsigned> DistanceMap;
0143 
0144   // For legacy pass.
0145   LiveVariables() = default;
0146 
0147   void analyze(MachineFunction &MF);
0148 
0149   /// HandlePhysRegKill - Add kills of Reg and its sub-registers to the
0150   /// uses. Pay special attention to the sub-register uses which may come below
0151   /// the last use of the whole register.
0152   bool HandlePhysRegKill(Register Reg, MachineInstr *MI);
0153 
0154   /// HandleRegMask - Call HandlePhysRegKill for all registers clobbered by Mask.
0155   void HandleRegMask(const MachineOperand &, unsigned);
0156 
0157   void HandlePhysRegUse(Register Reg, MachineInstr &MI);
0158   void HandlePhysRegDef(Register Reg, MachineInstr *MI,
0159                         SmallVectorImpl<Register> &Defs);
0160   void UpdatePhysRegDefs(MachineInstr &MI, SmallVectorImpl<Register> &Defs);
0161 
0162   /// FindLastRefOrPartRef - Return the last reference or partial reference of
0163   /// the specified register.
0164   MachineInstr *FindLastRefOrPartRef(Register Reg);
0165 
0166   /// FindLastPartialDef - Return the last partial def of the specified
0167   /// register. Also returns the sub-registers that're defined by the
0168   /// instruction.
0169   MachineInstr *FindLastPartialDef(Register Reg,
0170                                    SmallSet<Register, 4> &PartDefRegs);
0171 
0172   /// analyzePHINodes - Gather information about the PHI nodes in here. In
0173   /// particular, we want to map the variable information of a virtual
0174   /// register which is used in a PHI node. We map that to the BB the vreg
0175   /// is coming from.
0176   void analyzePHINodes(const MachineFunction& Fn);
0177 
0178   void runOnInstr(MachineInstr &MI, SmallVectorImpl<Register> &Defs,
0179                   unsigned NumRegs);
0180 
0181   void runOnBlock(MachineBasicBlock *MBB, unsigned NumRegs);
0182 
0183 public:
0184   LiveVariables(MachineFunction &MF);
0185 
0186   void print(raw_ostream &OS) const;
0187 
0188   //===--------------------------------------------------------------------===//
0189   //  API to update live variable information
0190 
0191   /// Recompute liveness from scratch for a virtual register \p Reg that is
0192   /// known to have a single def that dominates all uses. This can be useful
0193   /// after removing some uses of \p Reg. It is not necessary for the whole
0194   /// machine function to be in SSA form.
0195   void recomputeForSingleDefVirtReg(Register Reg);
0196 
0197   /// replaceKillInstruction - Update register kill info by replacing a kill
0198   /// instruction with a new one.
0199   void replaceKillInstruction(Register Reg, MachineInstr &OldMI,
0200                               MachineInstr &NewMI);
0201 
0202   /// addVirtualRegisterKilled - Add information about the fact that the
0203   /// specified register is killed after being used by the specified
0204   /// instruction. If AddIfNotFound is true, add a implicit operand if it's
0205   /// not found.
0206   void addVirtualRegisterKilled(Register IncomingReg, MachineInstr &MI,
0207                                 bool AddIfNotFound = false) {
0208     if (MI.addRegisterKilled(IncomingReg, TRI, AddIfNotFound))
0209       getVarInfo(IncomingReg).Kills.push_back(&MI);
0210   }
0211 
0212   /// removeVirtualRegisterKilled - Remove the specified kill of the virtual
0213   /// register from the live variable information. Returns true if the
0214   /// variable was marked as killed by the specified instruction,
0215   /// false otherwise.
0216   bool removeVirtualRegisterKilled(Register Reg, MachineInstr &MI) {
0217     if (!getVarInfo(Reg).removeKill(MI))
0218       return false;
0219 
0220     bool Removed = false;
0221     for (MachineOperand &MO : MI.operands()) {
0222       if (MO.isReg() && MO.isKill() && MO.getReg() == Reg) {
0223         MO.setIsKill(false);
0224         Removed = true;
0225         break;
0226       }
0227     }
0228 
0229     assert(Removed && "Register is not used by this instruction!");
0230     (void)Removed;
0231     return true;
0232   }
0233 
0234   /// removeVirtualRegistersKilled - Remove all killed info for the specified
0235   /// instruction.
0236   void removeVirtualRegistersKilled(MachineInstr &MI);
0237 
0238   /// addVirtualRegisterDead - Add information about the fact that the specified
0239   /// register is dead after being used by the specified instruction. If
0240   /// AddIfNotFound is true, add a implicit operand if it's not found.
0241   void addVirtualRegisterDead(Register IncomingReg, MachineInstr &MI,
0242                               bool AddIfNotFound = false) {
0243     if (MI.addRegisterDead(IncomingReg, TRI, AddIfNotFound))
0244       getVarInfo(IncomingReg).Kills.push_back(&MI);
0245   }
0246 
0247   /// removeVirtualRegisterDead - Remove the specified kill of the virtual
0248   /// register from the live variable information. Returns true if the
0249   /// variable was marked dead at the specified instruction, false
0250   /// otherwise.
0251   bool removeVirtualRegisterDead(Register Reg, MachineInstr &MI) {
0252     if (!getVarInfo(Reg).removeKill(MI))
0253       return false;
0254 
0255     bool Removed = false;
0256     for (MachineOperand &MO : MI.all_defs()) {
0257       if (MO.getReg() == Reg) {
0258         MO.setIsDead(false);
0259         Removed = true;
0260         break;
0261       }
0262     }
0263     assert(Removed && "Register is not defined by this instruction!");
0264     (void)Removed;
0265     return true;
0266   }
0267 
0268   /// getVarInfo - Return the VarInfo structure for the specified VIRTUAL
0269   /// register.
0270   VarInfo &getVarInfo(Register Reg);
0271 
0272   void MarkVirtRegAliveInBlock(VarInfo& VRInfo, MachineBasicBlock* DefBlock,
0273                                MachineBasicBlock *BB);
0274   void MarkVirtRegAliveInBlock(VarInfo &VRInfo, MachineBasicBlock *DefBlock,
0275                                MachineBasicBlock *BB,
0276                                SmallVectorImpl<MachineBasicBlock *> &WorkList);
0277 
0278   void HandleVirtRegDef(Register reg, MachineInstr &MI);
0279   void HandleVirtRegUse(Register reg, MachineBasicBlock *MBB, MachineInstr &MI);
0280 
0281   bool isLiveIn(Register Reg, const MachineBasicBlock &MBB) {
0282     return getVarInfo(Reg).isLiveIn(MBB, Reg, *MRI);
0283   }
0284 
0285   /// isLiveOut - Determine if Reg is live out from MBB, when not considering
0286   /// PHI nodes. This means that Reg is either killed by a successor block or
0287   /// passed through one.
0288   bool isLiveOut(Register Reg, const MachineBasicBlock &MBB);
0289 
0290   /// addNewBlock - Add a new basic block BB between DomBB and SuccBB. All
0291   /// variables that are live out of DomBB and live into SuccBB will be marked
0292   /// as passing live through BB. This method assumes that the machine code is
0293   /// still in SSA form.
0294   void addNewBlock(MachineBasicBlock *BB,
0295                    MachineBasicBlock *DomBB,
0296                    MachineBasicBlock *SuccBB);
0297 
0298   void addNewBlock(MachineBasicBlock *BB,
0299                    MachineBasicBlock *DomBB,
0300                    MachineBasicBlock *SuccBB,
0301                    std::vector<SparseBitVector<>> &LiveInSets);
0302 };
0303 
0304 class LiveVariablesAnalysis : public AnalysisInfoMixin<LiveVariablesAnalysis> {
0305   friend AnalysisInfoMixin<LiveVariablesAnalysis>;
0306   static AnalysisKey Key;
0307 
0308 public:
0309   using Result = LiveVariables;
0310   Result run(MachineFunction &MF, MachineFunctionAnalysisManager &);
0311 };
0312 
0313 class LiveVariablesPrinterPass
0314     : public PassInfoMixin<LiveVariablesPrinterPass> {
0315   raw_ostream &OS;
0316 
0317 public:
0318   explicit LiveVariablesPrinterPass(raw_ostream &OS) : OS(OS) {}
0319   PreservedAnalyses run(MachineFunction &MF,
0320                         MachineFunctionAnalysisManager &MFAM);
0321   static bool isRequired() { return true; }
0322 };
0323 
0324 class LiveVariablesWrapperPass : public MachineFunctionPass {
0325   LiveVariables LV;
0326 
0327 public:
0328   static char ID; // Pass identification, replacement for typeid
0329 
0330   LiveVariablesWrapperPass() : MachineFunctionPass(ID) {
0331     initializeLiveVariablesWrapperPassPass(*PassRegistry::getPassRegistry());
0332   }
0333 
0334   bool runOnMachineFunction(MachineFunction &MF) override {
0335     LV.analyze(MF);
0336     return false;
0337   }
0338 
0339   void getAnalysisUsage(AnalysisUsage &AU) const override;
0340 
0341   void releaseMemory() override { LV.VirtRegInfo.clear(); }
0342 
0343   LiveVariables &getLV() { return LV; }
0344 };
0345 
0346 } // End llvm namespace
0347 
0348 #endif