1009b1c42SEd Schouten //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements the LiveVariable analysis pass. For each machine
10009b1c42SEd Schouten // instruction in the function, this pass calculates the set of registers that
11009b1c42SEd Schouten // are immediately dead after the instruction (i.e., the instruction calculates
12009b1c42SEd Schouten // the value, but it is never used) and the set of registers that are used by
13009b1c42SEd Schouten // the instruction, but are never used after the instruction (i.e., they are
14009b1c42SEd Schouten // killed).
15009b1c42SEd Schouten //
1663faed5bSDimitry Andric // This class computes live variables using a sparse implementation based on
17009b1c42SEd Schouten // the machine code SSA form. This class computes live variable information for
18009b1c42SEd Schouten // each virtual and _register allocatable_ physical register in a function. It
19009b1c42SEd Schouten // uses the dominance properties of SSA form to efficiently compute live
20009b1c42SEd Schouten // variables for virtual registers, and assumes that physical registers are only
21009b1c42SEd Schouten // live within a single basic block (allowing it to do a single local analysis
22009b1c42SEd Schouten // to resolve physical register lifetimes in each basic block). If a physical
23009b1c42SEd Schouten // register is not register allocatable, it is not tracked. This is useful for
24009b1c42SEd Schouten // things like the stack pointer and condition codes.
25009b1c42SEd Schouten //
26009b1c42SEd Schouten //===----------------------------------------------------------------------===//
27009b1c42SEd Schouten
28009b1c42SEd Schouten #include "llvm/CodeGen/LiveVariables.h"
291d5ae102SDimitry Andric #include "llvm/ADT/DenseSet.h"
304a16efa3SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
314a16efa3SDimitry Andric #include "llvm/ADT/STLExtras.h"
324a16efa3SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
334a16efa3SDimitry Andric #include "llvm/ADT/SmallSet.h"
34009b1c42SEd Schouten #include "llvm/CodeGen/MachineInstr.h"
35009b1c42SEd Schouten #include "llvm/CodeGen/MachineRegisterInfo.h"
36009b1c42SEd Schouten #include "llvm/CodeGen/Passes.h"
37eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
38829000e0SRoman Divacky #include "llvm/Support/Debug.h"
394a16efa3SDimitry Andric #include "llvm/Support/ErrorHandling.h"
405a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
41009b1c42SEd Schouten #include <algorithm>
42009b1c42SEd Schouten using namespace llvm;
43009b1c42SEd Schouten
44ac9a064cSDimitry Andric AnalysisKey LiveVariablesAnalysis::Key;
45ac9a064cSDimitry Andric
46ac9a064cSDimitry Andric LiveVariablesAnalysis::Result
run(MachineFunction & MF,MachineFunctionAnalysisManager &)47ac9a064cSDimitry Andric LiveVariablesAnalysis::run(MachineFunction &MF,
48ac9a064cSDimitry Andric MachineFunctionAnalysisManager &) {
49ac9a064cSDimitry Andric return Result(MF);
50ac9a064cSDimitry Andric }
51ac9a064cSDimitry Andric
52ac9a064cSDimitry Andric PreservedAnalyses
run(MachineFunction & MF,MachineFunctionAnalysisManager & MFAM)53ac9a064cSDimitry Andric LiveVariablesPrinterPass::run(MachineFunction &MF,
54ac9a064cSDimitry Andric MachineFunctionAnalysisManager &MFAM) {
55ac9a064cSDimitry Andric OS << "Live variables in machine function: " << MF.getName() << '\n';
56ac9a064cSDimitry Andric MFAM.getResult<LiveVariablesAnalysis>(MF).print(OS);
57ac9a064cSDimitry Andric return PreservedAnalyses::all();
58ac9a064cSDimitry Andric }
59ac9a064cSDimitry Andric
60ac9a064cSDimitry Andric char LiveVariablesWrapperPass::ID = 0;
61ac9a064cSDimitry Andric char &llvm::LiveVariablesID = LiveVariablesWrapperPass::ID;
62ac9a064cSDimitry Andric INITIALIZE_PASS_BEGIN(LiveVariablesWrapperPass, "livevars",
63cf099d11SDimitry Andric "Live Variable Analysis", false, false)
INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)64cf099d11SDimitry Andric INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
65ac9a064cSDimitry Andric INITIALIZE_PASS_END(LiveVariablesWrapperPass, "livevars",
66cf099d11SDimitry Andric "Live Variable Analysis", false, false)
67009b1c42SEd Schouten
68ac9a064cSDimitry Andric void LiveVariablesWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
69009b1c42SEd Schouten AU.addRequiredID(UnreachableMachineBlockElimID);
70009b1c42SEd Schouten AU.setPreservesAll();
7159850d08SRoman Divacky MachineFunctionPass::getAnalysisUsage(AU);
72009b1c42SEd Schouten }
73009b1c42SEd Schouten
LiveVariables(MachineFunction & MF)74ac9a064cSDimitry Andric LiveVariables::LiveVariables(MachineFunction &MF)
75ac9a064cSDimitry Andric : MF(&MF), MRI(&MF.getRegInfo()), TRI(MF.getSubtarget().getRegisterInfo()) {
76ac9a064cSDimitry Andric analyze(MF);
77ac9a064cSDimitry Andric }
78ac9a064cSDimitry Andric
print(raw_ostream & OS) const79ac9a064cSDimitry Andric void LiveVariables::print(raw_ostream &OS) const {
80ac9a064cSDimitry Andric for (size_t I = 0, E = VirtRegInfo.size(); I != E; ++I) {
81ac9a064cSDimitry Andric const Register Reg = Register::index2VirtReg(I);
82ac9a064cSDimitry Andric OS << "Virtual register '%" << I << "':\n";
83ac9a064cSDimitry Andric VirtRegInfo[Reg].print(OS);
84ac9a064cSDimitry Andric }
85ac9a064cSDimitry Andric }
86ac9a064cSDimitry Andric
87907da171SRoman Divacky MachineInstr *
findKill(const MachineBasicBlock * MBB) const88907da171SRoman Divacky LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
89f65dcba8SDimitry Andric for (MachineInstr *MI : Kills)
90f65dcba8SDimitry Andric if (MI->getParent() == MBB)
91f65dcba8SDimitry Andric return MI;
925ca98fd9SDimitry Andric return nullptr;
93907da171SRoman Divacky }
94907da171SRoman Divacky
print(raw_ostream & OS) const95ac9a064cSDimitry Andric void LiveVariables::VarInfo::print(raw_ostream &OS) const {
96ac9a064cSDimitry Andric OS << " Alive in blocks: ";
97344a3780SDimitry Andric for (unsigned AB : AliveBlocks)
98ac9a064cSDimitry Andric OS << AB << ", ";
99ac9a064cSDimitry Andric OS << "\n Killed by:";
100009b1c42SEd Schouten if (Kills.empty())
101ac9a064cSDimitry Andric OS << " No instructions.\n\n";
102009b1c42SEd Schouten else {
103009b1c42SEd Schouten for (unsigned i = 0, e = Kills.size(); i != e; ++i)
104ac9a064cSDimitry Andric OS << "\n #" << i << ": " << *Kills[i];
105ac9a064cSDimitry Andric OS << "\n";
106009b1c42SEd Schouten }
107009b1c42SEd Schouten }
108ac9a064cSDimitry Andric
109ac9a064cSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const110ac9a064cSDimitry Andric LLVM_DUMP_METHOD void LiveVariables::VarInfo::dump() const { print(dbgs()); }
11171d5a254SDimitry Andric #endif
112009b1c42SEd Schouten
113009b1c42SEd Schouten /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
getVarInfo(Register Reg)114b60736ecSDimitry Andric LiveVariables::VarInfo &LiveVariables::getVarInfo(Register Reg) {
115b60736ecSDimitry Andric assert(Reg.isVirtual() && "getVarInfo: not a virtual register!");
116b60736ecSDimitry Andric VirtRegInfo.grow(Reg);
117b60736ecSDimitry Andric return VirtRegInfo[Reg];
118009b1c42SEd Schouten }
119009b1c42SEd Schouten
MarkVirtRegAliveInBlock(VarInfo & VRInfo,MachineBasicBlock * DefBlock,MachineBasicBlock * MBB,SmallVectorImpl<MachineBasicBlock * > & WorkList)120b60736ecSDimitry Andric void LiveVariables::MarkVirtRegAliveInBlock(
121b60736ecSDimitry Andric VarInfo &VRInfo, MachineBasicBlock *DefBlock, MachineBasicBlock *MBB,
122b60736ecSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &WorkList) {
123009b1c42SEd Schouten unsigned BBNum = MBB->getNumber();
124009b1c42SEd Schouten
125009b1c42SEd Schouten // Check to see if this basic block is one of the killing blocks. If so,
126009b1c42SEd Schouten // remove it.
127009b1c42SEd Schouten for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
128009b1c42SEd Schouten if (VRInfo.Kills[i]->getParent() == MBB) {
129009b1c42SEd Schouten VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
130009b1c42SEd Schouten break;
131009b1c42SEd Schouten }
132009b1c42SEd Schouten
133009b1c42SEd Schouten if (MBB == DefBlock) return; // Terminate recursion
134009b1c42SEd Schouten
135009b1c42SEd Schouten if (VRInfo.AliveBlocks.test(BBNum))
136009b1c42SEd Schouten return; // We already know the block is live
137009b1c42SEd Schouten
138009b1c42SEd Schouten // Mark the variable known alive in this bb
139009b1c42SEd Schouten VRInfo.AliveBlocks.set(BBNum);
140009b1c42SEd Schouten
14163faed5bSDimitry Andric assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
1426b943ff3SDimitry Andric WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
143009b1c42SEd Schouten }
144009b1c42SEd Schouten
MarkVirtRegAliveInBlock(VarInfo & VRInfo,MachineBasicBlock * DefBlock,MachineBasicBlock * MBB)145009b1c42SEd Schouten void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
146009b1c42SEd Schouten MachineBasicBlock *DefBlock,
147009b1c42SEd Schouten MachineBasicBlock *MBB) {
148b60736ecSDimitry Andric SmallVector<MachineBasicBlock *, 16> WorkList;
149009b1c42SEd Schouten MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
150009b1c42SEd Schouten
151009b1c42SEd Schouten while (!WorkList.empty()) {
152c0981da4SDimitry Andric MachineBasicBlock *Pred = WorkList.pop_back_val();
153009b1c42SEd Schouten MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
154009b1c42SEd Schouten }
155009b1c42SEd Schouten }
156009b1c42SEd Schouten
HandleVirtRegUse(Register Reg,MachineBasicBlock * MBB,MachineInstr & MI)157b60736ecSDimitry Andric void LiveVariables::HandleVirtRegUse(Register Reg, MachineBasicBlock *MBB,
15801095a5dSDimitry Andric MachineInstr &MI) {
159b60736ecSDimitry Andric assert(MRI->getVRegDef(Reg) && "Register use before def!");
160009b1c42SEd Schouten
161009b1c42SEd Schouten unsigned BBNum = MBB->getNumber();
162009b1c42SEd Schouten
163b60736ecSDimitry Andric VarInfo &VRInfo = getVarInfo(Reg);
164009b1c42SEd Schouten
165009b1c42SEd Schouten // Check to see if this basic block is already a kill block.
166009b1c42SEd Schouten if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
167009b1c42SEd Schouten // Yes, this register is killed in this basic block already. Increase the
168009b1c42SEd Schouten // live range by updating the kill instruction.
16901095a5dSDimitry Andric VRInfo.Kills.back() = &MI;
170009b1c42SEd Schouten return;
171009b1c42SEd Schouten }
172009b1c42SEd Schouten
173009b1c42SEd Schouten #ifndef NDEBUG
17477fc4c14SDimitry Andric for (MachineInstr *Kill : VRInfo.Kills)
17577fc4c14SDimitry Andric assert(Kill->getParent() != MBB && "entry should be at end!");
176009b1c42SEd Schouten #endif
177009b1c42SEd Schouten
178009b1c42SEd Schouten // This situation can occur:
179009b1c42SEd Schouten //
180009b1c42SEd Schouten // ,------.
181009b1c42SEd Schouten // | |
182009b1c42SEd Schouten // | v
183009b1c42SEd Schouten // | t2 = phi ... t1 ...
184009b1c42SEd Schouten // | |
185009b1c42SEd Schouten // | v
186009b1c42SEd Schouten // | t1 = ...
187009b1c42SEd Schouten // | ... = ... t1 ...
188009b1c42SEd Schouten // | |
189009b1c42SEd Schouten // `------'
190009b1c42SEd Schouten //
191009b1c42SEd Schouten // where there is a use in a PHI node that's a predecessor to the defining
192009b1c42SEd Schouten // block. We don't want to mark all predecessors as having the value "alive"
193009b1c42SEd Schouten // in this case.
194b60736ecSDimitry Andric if (MBB == MRI->getVRegDef(Reg)->getParent())
195b60736ecSDimitry Andric return;
196009b1c42SEd Schouten
197009b1c42SEd Schouten // Add a new kill entry for this basic block. If this virtual register is
198009b1c42SEd Schouten // already marked as alive in this basic block, that means it is alive in at
199009b1c42SEd Schouten // least one of the successor blocks, it's not a kill.
200009b1c42SEd Schouten if (!VRInfo.AliveBlocks.test(BBNum))
20101095a5dSDimitry Andric VRInfo.Kills.push_back(&MI);
202009b1c42SEd Schouten
203009b1c42SEd Schouten // Update all dominating blocks to mark them as "known live".
204344a3780SDimitry Andric for (MachineBasicBlock *Pred : MBB->predecessors())
205344a3780SDimitry Andric MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(Reg)->getParent(), Pred);
206009b1c42SEd Schouten }
207009b1c42SEd Schouten
HandleVirtRegDef(Register Reg,MachineInstr & MI)208b60736ecSDimitry Andric void LiveVariables::HandleVirtRegDef(Register Reg, MachineInstr &MI) {
209009b1c42SEd Schouten VarInfo &VRInfo = getVarInfo(Reg);
210009b1c42SEd Schouten
211009b1c42SEd Schouten if (VRInfo.AliveBlocks.empty())
212009b1c42SEd Schouten // If vr is not alive in any block, then defaults to dead.
21301095a5dSDimitry Andric VRInfo.Kills.push_back(&MI);
214009b1c42SEd Schouten }
215009b1c42SEd Schouten
216009b1c42SEd Schouten /// FindLastPartialDef - Return the last partial def of the specified register.
21759850d08SRoman Divacky /// Also returns the sub-registers that're defined by the instruction.
218b60736ecSDimitry Andric MachineInstr *
FindLastPartialDef(Register Reg,SmallSet<unsigned,4> & PartDefRegs)219b60736ecSDimitry Andric LiveVariables::FindLastPartialDef(Register Reg,
22059850d08SRoman Divacky SmallSet<unsigned, 4> &PartDefRegs) {
221009b1c42SEd Schouten unsigned LastDefReg = 0;
222009b1c42SEd Schouten unsigned LastDefDist = 0;
2235ca98fd9SDimitry Andric MachineInstr *LastDef = nullptr;
2247fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs(Reg)) {
225009b1c42SEd Schouten MachineInstr *Def = PhysRegDef[SubReg];
226009b1c42SEd Schouten if (!Def)
227009b1c42SEd Schouten continue;
228009b1c42SEd Schouten unsigned Dist = DistanceMap[Def];
229009b1c42SEd Schouten if (Dist > LastDefDist) {
230009b1c42SEd Schouten LastDefReg = SubReg;
231009b1c42SEd Schouten LastDef = Def;
232009b1c42SEd Schouten LastDefDist = Dist;
233009b1c42SEd Schouten }
234009b1c42SEd Schouten }
23559850d08SRoman Divacky
23659850d08SRoman Divacky if (!LastDef)
2375ca98fd9SDimitry Andric return nullptr;
23859850d08SRoman Divacky
23959850d08SRoman Divacky PartDefRegs.insert(LastDefReg);
2407fa27ce4SDimitry Andric for (MachineOperand &MO : LastDef->all_defs()) {
2417fa27ce4SDimitry Andric if (MO.getReg() == 0)
24259850d08SRoman Divacky continue;
2431d5ae102SDimitry Andric Register DefReg = MO.getReg();
24459850d08SRoman Divacky if (TRI->isSubRegister(Reg, DefReg)) {
2457fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs_inclusive(DefReg))
2467fa27ce4SDimitry Andric PartDefRegs.insert(SubReg);
24759850d08SRoman Divacky }
24859850d08SRoman Divacky }
249009b1c42SEd Schouten return LastDef;
250009b1c42SEd Schouten }
251009b1c42SEd Schouten
252009b1c42SEd Schouten /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
253009b1c42SEd Schouten /// implicit defs to a machine instruction if there was an earlier def of its
254009b1c42SEd Schouten /// super-register.
HandlePhysRegUse(Register Reg,MachineInstr & MI)255b60736ecSDimitry Andric void LiveVariables::HandlePhysRegUse(Register Reg, MachineInstr &MI) {
256907da171SRoman Divacky MachineInstr *LastDef = PhysRegDef[Reg];
257009b1c42SEd Schouten // If there was a previous use or a "full" def all is well.
258907da171SRoman Divacky if (!LastDef && !PhysRegUse[Reg]) {
259009b1c42SEd Schouten // Otherwise, the last sub-register def implicitly defines this register.
260009b1c42SEd Schouten // e.g.
261009b1c42SEd Schouten // AH =
262044eb2f6SDimitry Andric // AL = ... implicit-def EAX, implicit killed AH
263009b1c42SEd Schouten // = AH
264009b1c42SEd Schouten // ...
265009b1c42SEd Schouten // = EAX
266009b1c42SEd Schouten // All of the sub-registers must have been defined before the use of Reg!
26759850d08SRoman Divacky SmallSet<unsigned, 4> PartDefRegs;
26859850d08SRoman Divacky MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
269009b1c42SEd Schouten // If LastPartialDef is NULL, it must be using a livein register.
270009b1c42SEd Schouten if (LastPartialDef) {
271009b1c42SEd Schouten LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
272009b1c42SEd Schouten true/*IsImp*/));
273009b1c42SEd Schouten PhysRegDef[Reg] = LastPartialDef;
274009b1c42SEd Schouten SmallSet<unsigned, 8> Processed;
2757fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs(Reg)) {
276009b1c42SEd Schouten if (Processed.count(SubReg))
277009b1c42SEd Schouten continue;
27859850d08SRoman Divacky if (PartDefRegs.count(SubReg))
279009b1c42SEd Schouten continue;
280009b1c42SEd Schouten // This part of Reg was defined before the last partial def. It's killed
281009b1c42SEd Schouten // here.
282009b1c42SEd Schouten LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
283009b1c42SEd Schouten false/*IsDef*/,
284009b1c42SEd Schouten true/*IsImp*/));
285009b1c42SEd Schouten PhysRegDef[SubReg] = LastPartialDef;
2867fa27ce4SDimitry Andric for (MCPhysReg SS : TRI->subregs(SubReg))
2877fa27ce4SDimitry Andric Processed.insert(SS);
288009b1c42SEd Schouten }
289009b1c42SEd Schouten }
29063faed5bSDimitry Andric } else if (LastDef && !PhysRegUse[Reg] &&
291ac9a064cSDimitry Andric !LastDef->findRegisterDefOperand(Reg, /*TRI=*/nullptr))
292907da171SRoman Divacky // Last def defines the super register, add an implicit def of reg.
29363faed5bSDimitry Andric LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
29463faed5bSDimitry Andric true/*IsImp*/));
295009b1c42SEd Schouten
296009b1c42SEd Schouten // Remember this use.
2977fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
2987fa27ce4SDimitry Andric PhysRegUse[SubReg] = &MI;
299009b1c42SEd Schouten }
300009b1c42SEd Schouten
30106f9d401SRoman Divacky /// FindLastRefOrPartRef - Return the last reference or partial reference of
30206f9d401SRoman Divacky /// the specified register.
FindLastRefOrPartRef(Register Reg)303b60736ecSDimitry Andric MachineInstr *LiveVariables::FindLastRefOrPartRef(Register Reg) {
30406f9d401SRoman Divacky MachineInstr *LastDef = PhysRegDef[Reg];
30506f9d401SRoman Divacky MachineInstr *LastUse = PhysRegUse[Reg];
30606f9d401SRoman Divacky if (!LastDef && !LastUse)
3075ca98fd9SDimitry Andric return nullptr;
30806f9d401SRoman Divacky
30906f9d401SRoman Divacky MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
31006f9d401SRoman Divacky unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
31106f9d401SRoman Divacky unsigned LastPartDefDist = 0;
3127fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs(Reg)) {
31306f9d401SRoman Divacky MachineInstr *Def = PhysRegDef[SubReg];
31406f9d401SRoman Divacky if (Def && Def != LastDef) {
31506f9d401SRoman Divacky // There was a def of this sub-register in between. This is a partial
31606f9d401SRoman Divacky // def, keep track of the last one.
31706f9d401SRoman Divacky unsigned Dist = DistanceMap[Def];
318829000e0SRoman Divacky if (Dist > LastPartDefDist)
31906f9d401SRoman Divacky LastPartDefDist = Dist;
320829000e0SRoman Divacky } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
32106f9d401SRoman Divacky unsigned Dist = DistanceMap[Use];
32206f9d401SRoman Divacky if (Dist > LastRefOrPartRefDist) {
32306f9d401SRoman Divacky LastRefOrPartRefDist = Dist;
32406f9d401SRoman Divacky LastRefOrPartRef = Use;
32506f9d401SRoman Divacky }
32606f9d401SRoman Divacky }
32706f9d401SRoman Divacky }
32806f9d401SRoman Divacky
32906f9d401SRoman Divacky return LastRefOrPartRef;
33006f9d401SRoman Divacky }
33106f9d401SRoman Divacky
HandlePhysRegKill(Register Reg,MachineInstr * MI)332b60736ecSDimitry Andric bool LiveVariables::HandlePhysRegKill(Register Reg, MachineInstr *MI) {
33359850d08SRoman Divacky MachineInstr *LastDef = PhysRegDef[Reg];
33459850d08SRoman Divacky MachineInstr *LastUse = PhysRegUse[Reg];
33559850d08SRoman Divacky if (!LastDef && !LastUse)
336009b1c42SEd Schouten return false;
337009b1c42SEd Schouten
33859850d08SRoman Divacky MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
339009b1c42SEd Schouten unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
340009b1c42SEd Schouten // The whole register is used.
341009b1c42SEd Schouten // AL =
342009b1c42SEd Schouten // AH =
343009b1c42SEd Schouten //
344009b1c42SEd Schouten // = AX
345044eb2f6SDimitry Andric // = AL, implicit killed AX
346009b1c42SEd Schouten // AX =
347009b1c42SEd Schouten //
348009b1c42SEd Schouten // Or whole register is defined, but not used at all.
349044eb2f6SDimitry Andric // dead AX =
350009b1c42SEd Schouten // ...
351009b1c42SEd Schouten // AX =
352009b1c42SEd Schouten //
353009b1c42SEd Schouten // Or whole register is defined, but only partly used.
354044eb2f6SDimitry Andric // dead AX = implicit-def AL
355044eb2f6SDimitry Andric // = killed AL
356009b1c42SEd Schouten // AX =
3575ca98fd9SDimitry Andric MachineInstr *LastPartDef = nullptr;
35859850d08SRoman Divacky unsigned LastPartDefDist = 0;
359009b1c42SEd Schouten SmallSet<unsigned, 8> PartUses;
3607fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs(Reg)) {
36159850d08SRoman Divacky MachineInstr *Def = PhysRegDef[SubReg];
36259850d08SRoman Divacky if (Def && Def != LastDef) {
36359850d08SRoman Divacky // There was a def of this sub-register in between. This is a partial
36459850d08SRoman Divacky // def, keep track of the last one.
36559850d08SRoman Divacky unsigned Dist = DistanceMap[Def];
36659850d08SRoman Divacky if (Dist > LastPartDefDist) {
36759850d08SRoman Divacky LastPartDefDist = Dist;
36859850d08SRoman Divacky LastPartDef = Def;
36959850d08SRoman Divacky }
37059850d08SRoman Divacky continue;
37159850d08SRoman Divacky }
372009b1c42SEd Schouten if (MachineInstr *Use = PhysRegUse[SubReg]) {
3737fa27ce4SDimitry Andric for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
3747fa27ce4SDimitry Andric PartUses.insert(SS);
375009b1c42SEd Schouten unsigned Dist = DistanceMap[Use];
376009b1c42SEd Schouten if (Dist > LastRefOrPartRefDist) {
377009b1c42SEd Schouten LastRefOrPartRefDist = Dist;
378009b1c42SEd Schouten LastRefOrPartRef = Use;
379009b1c42SEd Schouten }
380009b1c42SEd Schouten }
381009b1c42SEd Schouten }
382009b1c42SEd Schouten
383f5a3459aSRoman Divacky if (!PhysRegUse[Reg]) {
384b2f21fb0SEd Schouten // Partial uses. Mark register def dead and add implicit def of
385b2f21fb0SEd Schouten // sub-registers which are used.
386044eb2f6SDimitry Andric // dead EAX = op implicit-def AL
387b2f21fb0SEd Schouten // That is, EAX def is dead but AL def extends pass it.
388009b1c42SEd Schouten PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
3897fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs(Reg)) {
39059850d08SRoman Divacky if (!PartUses.count(SubReg))
39159850d08SRoman Divacky continue;
39259850d08SRoman Divacky bool NeedDef = true;
39359850d08SRoman Divacky if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
394ac9a064cSDimitry Andric MachineOperand *MO =
395ac9a064cSDimitry Andric PhysRegDef[Reg]->findRegisterDefOperand(SubReg, /*TRI=*/nullptr);
39659850d08SRoman Divacky if (MO) {
39759850d08SRoman Divacky NeedDef = false;
39859850d08SRoman Divacky assert(!MO->isDead());
39959850d08SRoman Divacky }
40059850d08SRoman Divacky }
40159850d08SRoman Divacky if (NeedDef)
402009b1c42SEd Schouten PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
40359850d08SRoman Divacky true/*IsDef*/, true/*IsImp*/));
40406f9d401SRoman Divacky MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
40506f9d401SRoman Divacky if (LastSubRef)
40606f9d401SRoman Divacky LastSubRef->addRegisterKilled(SubReg, TRI, true);
40706f9d401SRoman Divacky else {
408009b1c42SEd Schouten LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
4097fa27ce4SDimitry Andric for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
4107fa27ce4SDimitry Andric PhysRegUse[SS] = LastRefOrPartRef;
41106f9d401SRoman Divacky }
4127fa27ce4SDimitry Andric for (MCPhysReg SS : TRI->subregs(SubReg))
4137fa27ce4SDimitry Andric PartUses.erase(SS);
414009b1c42SEd Schouten }
415f5a3459aSRoman Divacky } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
416f5a3459aSRoman Divacky if (LastPartDef)
417f5a3459aSRoman Divacky // The last partial def kills the register.
418f5a3459aSRoman Divacky LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
419f5a3459aSRoman Divacky true/*IsImp*/, true/*IsKill*/));
420f5a3459aSRoman Divacky else {
421f5a3459aSRoman Divacky MachineOperand *MO =
422ac9a064cSDimitry Andric LastRefOrPartRef->findRegisterDefOperand(Reg, TRI, false, false);
423f5a3459aSRoman Divacky bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
424f5a3459aSRoman Divacky // If the last reference is the last def, then it's not used at all.
425f5a3459aSRoman Divacky // That is, unless we are currently processing the last reference itself.
426f5a3459aSRoman Divacky LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
427f5a3459aSRoman Divacky if (NeedEC) {
428f5a3459aSRoman Divacky // If we are adding a subreg def and the superreg def is marked early
429f5a3459aSRoman Divacky // clobber, add an early clobber marker to the subreg def.
430ac9a064cSDimitry Andric MO = LastRefOrPartRef->findRegisterDefOperand(Reg, /*TRI=*/nullptr);
431f5a3459aSRoman Divacky if (MO)
432f5a3459aSRoman Divacky MO->setIsEarlyClobber();
433f5a3459aSRoman Divacky }
434f5a3459aSRoman Divacky }
43559850d08SRoman Divacky } else
436009b1c42SEd Schouten LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
437009b1c42SEd Schouten return true;
438009b1c42SEd Schouten }
439009b1c42SEd Schouten
HandleRegMask(const MachineOperand & MO,unsigned NumRegs)440b1c73532SDimitry Andric void LiveVariables::HandleRegMask(const MachineOperand &MO, unsigned NumRegs) {
44163faed5bSDimitry Andric // Call HandlePhysRegKill() for all live registers clobbered by Mask.
44263faed5bSDimitry Andric // Clobbered registers are always dead, sp there is no need to use
44363faed5bSDimitry Andric // HandlePhysRegDef().
444b1c73532SDimitry Andric for (unsigned Reg = 1; Reg != NumRegs; ++Reg) {
44563faed5bSDimitry Andric // Skip dead regs.
44663faed5bSDimitry Andric if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
44763faed5bSDimitry Andric continue;
44863faed5bSDimitry Andric // Skip mask-preserved regs.
44963faed5bSDimitry Andric if (!MO.clobbersPhysReg(Reg))
45063faed5bSDimitry Andric continue;
45163faed5bSDimitry Andric // Kill the largest clobbered super-register.
45263faed5bSDimitry Andric // This avoids needless implicit operands.
45363faed5bSDimitry Andric unsigned Super = Reg;
4547fa27ce4SDimitry Andric for (MCPhysReg SR : TRI->superregs(Reg))
455b1c73532SDimitry Andric if (SR < NumRegs && (PhysRegDef[SR] || PhysRegUse[SR]) &&
456b1c73532SDimitry Andric MO.clobbersPhysReg(SR))
4577fa27ce4SDimitry Andric Super = SR;
4585ca98fd9SDimitry Andric HandlePhysRegKill(Super, nullptr);
45963faed5bSDimitry Andric }
46063faed5bSDimitry Andric }
46163faed5bSDimitry Andric
HandlePhysRegDef(Register Reg,MachineInstr * MI,SmallVectorImpl<unsigned> & Defs)462b60736ecSDimitry Andric void LiveVariables::HandlePhysRegDef(Register Reg, MachineInstr *MI,
463f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &Defs) {
464009b1c42SEd Schouten // What parts of the register are previously defined?
465009b1c42SEd Schouten SmallSet<unsigned, 32> Live;
466009b1c42SEd Schouten if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
4677fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
4687fa27ce4SDimitry Andric Live.insert(SubReg);
469009b1c42SEd Schouten } else {
4707fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs(Reg)) {
471009b1c42SEd Schouten // If a register isn't itself defined, but all parts that make up of it
472009b1c42SEd Schouten // are defined, then consider it also defined.
473009b1c42SEd Schouten // e.g.
474009b1c42SEd Schouten // AL =
475009b1c42SEd Schouten // AH =
476009b1c42SEd Schouten // = AX
47759850d08SRoman Divacky if (Live.count(SubReg))
47859850d08SRoman Divacky continue;
479009b1c42SEd Schouten if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
4807fa27ce4SDimitry Andric for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
4817fa27ce4SDimitry Andric Live.insert(SS);
482009b1c42SEd Schouten }
483009b1c42SEd Schouten }
484009b1c42SEd Schouten }
485009b1c42SEd Schouten
486009b1c42SEd Schouten // Start from the largest piece, find the last time any part of the register
487009b1c42SEd Schouten // is referenced.
48859850d08SRoman Divacky HandlePhysRegKill(Reg, MI);
489009b1c42SEd Schouten // Only some of the sub-registers are used.
4907fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs(Reg)) {
491009b1c42SEd Schouten if (!Live.count(SubReg))
492009b1c42SEd Schouten // Skip if this sub-register isn't defined.
493009b1c42SEd Schouten continue;
49459850d08SRoman Divacky HandlePhysRegKill(SubReg, MI);
495009b1c42SEd Schouten }
496009b1c42SEd Schouten
49759850d08SRoman Divacky if (MI)
49859850d08SRoman Divacky Defs.push_back(Reg); // Remember this def.
499009b1c42SEd Schouten }
500009b1c42SEd Schouten
UpdatePhysRegDefs(MachineInstr & MI,SmallVectorImpl<unsigned> & Defs)50101095a5dSDimitry Andric void LiveVariables::UpdatePhysRegDefs(MachineInstr &MI,
502f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &Defs) {
50359850d08SRoman Divacky while (!Defs.empty()) {
504c0981da4SDimitry Andric Register Reg = Defs.pop_back_val();
5057fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg)) {
50601095a5dSDimitry Andric PhysRegDef[SubReg] = &MI;
5075ca98fd9SDimitry Andric PhysRegUse[SubReg] = nullptr;
508009b1c42SEd Schouten }
509009b1c42SEd Schouten }
510009b1c42SEd Schouten }
511009b1c42SEd Schouten
runOnInstr(MachineInstr & MI,SmallVectorImpl<unsigned> & Defs,unsigned NumRegs)51201095a5dSDimitry Andric void LiveVariables::runOnInstr(MachineInstr &MI,
513b1c73532SDimitry Andric SmallVectorImpl<unsigned> &Defs,
514b1c73532SDimitry Andric unsigned NumRegs) {
515344a3780SDimitry Andric assert(!MI.isDebugOrPseudoInstr());
516009b1c42SEd Schouten // Process all of the operands of the instruction...
51701095a5dSDimitry Andric unsigned NumOperandsToProcess = MI.getNumOperands();
518009b1c42SEd Schouten
519009b1c42SEd Schouten // Unless it is a PHI node. In this case, ONLY process the DEF, not any
520009b1c42SEd Schouten // of the uses. They will be handled in other basic blocks.
52101095a5dSDimitry Andric if (MI.isPHI())
522009b1c42SEd Schouten NumOperandsToProcess = 1;
523009b1c42SEd Schouten
524104bd817SRoman Divacky // Clear kill and dead markers. LV will recompute them.
525009b1c42SEd Schouten SmallVector<unsigned, 4> UseRegs;
526009b1c42SEd Schouten SmallVector<unsigned, 4> DefRegs;
52763faed5bSDimitry Andric SmallVector<unsigned, 1> RegMasks;
528009b1c42SEd Schouten for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
52901095a5dSDimitry Andric MachineOperand &MO = MI.getOperand(i);
53063faed5bSDimitry Andric if (MO.isRegMask()) {
53163faed5bSDimitry Andric RegMasks.push_back(i);
53263faed5bSDimitry Andric continue;
53363faed5bSDimitry Andric }
534009b1c42SEd Schouten if (!MO.isReg() || MO.getReg() == 0)
535009b1c42SEd Schouten continue;
5361d5ae102SDimitry Andric Register MOReg = MO.getReg();
537104bd817SRoman Divacky if (MO.isUse()) {
538e3b55780SDimitry Andric if (!(MOReg.isPhysical() && MRI->isReserved(MOReg)))
539104bd817SRoman Divacky MO.setIsKill(false);
54058b69754SDimitry Andric if (MO.readsReg())
541009b1c42SEd Schouten UseRegs.push_back(MOReg);
54201095a5dSDimitry Andric } else {
54301095a5dSDimitry Andric assert(MO.isDef());
54401095a5dSDimitry Andric // FIXME: We should not remove any dead flags. However the MIPS RDDSP
54501095a5dSDimitry Andric // instruction needs it at the moment: http://llvm.org/PR27116.
546e3b55780SDimitry Andric if (MOReg.isPhysical() && !MRI->isReserved(MOReg))
547104bd817SRoman Divacky MO.setIsDead(false);
548009b1c42SEd Schouten DefRegs.push_back(MOReg);
549009b1c42SEd Schouten }
550104bd817SRoman Divacky }
551009b1c42SEd Schouten
55201095a5dSDimitry Andric MachineBasicBlock *MBB = MI.getParent();
553009b1c42SEd Schouten // Process all uses.
55477fc4c14SDimitry Andric for (unsigned MOReg : UseRegs) {
5551d5ae102SDimitry Andric if (Register::isVirtualRegister(MOReg))
556009b1c42SEd Schouten HandleVirtRegUse(MOReg, MBB, MI);
557522600a2SDimitry Andric else if (!MRI->isReserved(MOReg))
558009b1c42SEd Schouten HandlePhysRegUse(MOReg, MI);
559009b1c42SEd Schouten }
560009b1c42SEd Schouten
56163faed5bSDimitry Andric // Process all masked registers. (Call clobbers).
56277fc4c14SDimitry Andric for (unsigned Mask : RegMasks)
563b1c73532SDimitry Andric HandleRegMask(MI.getOperand(Mask), NumRegs);
56463faed5bSDimitry Andric
565009b1c42SEd Schouten // Process all defs.
56677fc4c14SDimitry Andric for (unsigned MOReg : DefRegs) {
5671d5ae102SDimitry Andric if (Register::isVirtualRegister(MOReg))
568009b1c42SEd Schouten HandleVirtRegDef(MOReg, MI);
569522600a2SDimitry Andric else if (!MRI->isReserved(MOReg))
57001095a5dSDimitry Andric HandlePhysRegDef(MOReg, &MI, Defs);
571009b1c42SEd Schouten }
57259850d08SRoman Divacky UpdatePhysRegDefs(MI, Defs);
573009b1c42SEd Schouten }
574009b1c42SEd Schouten
runOnBlock(MachineBasicBlock * MBB,unsigned NumRegs)575b1c73532SDimitry Andric void LiveVariables::runOnBlock(MachineBasicBlock *MBB, unsigned NumRegs) {
57667c32a98SDimitry Andric // Mark live-in registers as live-in.
57767c32a98SDimitry Andric SmallVector<unsigned, 4> Defs;
578dd58ef01SDimitry Andric for (const auto &LI : MBB->liveins()) {
5791d5ae102SDimitry Andric assert(Register::isPhysicalRegister(LI.PhysReg) &&
58067c32a98SDimitry Andric "Cannot have a live-in virtual register!");
581dd58ef01SDimitry Andric HandlePhysRegDef(LI.PhysReg, nullptr, Defs);
58267c32a98SDimitry Andric }
58367c32a98SDimitry Andric
58467c32a98SDimitry Andric // Loop over all of the instructions, processing them.
58567c32a98SDimitry Andric DistanceMap.clear();
58667c32a98SDimitry Andric unsigned Dist = 0;
58701095a5dSDimitry Andric for (MachineInstr &MI : *MBB) {
588344a3780SDimitry Andric if (MI.isDebugOrPseudoInstr())
58967c32a98SDimitry Andric continue;
59001095a5dSDimitry Andric DistanceMap.insert(std::make_pair(&MI, Dist++));
59167c32a98SDimitry Andric
592b1c73532SDimitry Andric runOnInstr(MI, Defs, NumRegs);
59367c32a98SDimitry Andric }
59467c32a98SDimitry Andric
595009b1c42SEd Schouten // Handle any virtual assignments from PHI nodes which might be at the
596009b1c42SEd Schouten // bottom of this basic block. We check all of our successor blocks to see
597009b1c42SEd Schouten // if they have PHI nodes, and if so, we simulate an assignment at the end
598009b1c42SEd Schouten // of the current block.
599009b1c42SEd Schouten if (!PHIVarInfo[MBB->getNumber()].empty()) {
600f8af5cf6SDimitry Andric SmallVectorImpl<unsigned> &VarInfoVec = PHIVarInfo[MBB->getNumber()];
601009b1c42SEd Schouten
602344a3780SDimitry Andric for (unsigned I : VarInfoVec)
603009b1c42SEd Schouten // Mark it alive only in the block we are representing.
604344a3780SDimitry Andric MarkVirtRegAliveInBlock(getVarInfo(I), MRI->getVRegDef(I)->getParent(),
605009b1c42SEd Schouten MBB);
606009b1c42SEd Schouten }
607009b1c42SEd Schouten
60863faed5bSDimitry Andric // MachineCSE may CSE instructions which write to non-allocatable physical
60963faed5bSDimitry Andric // registers across MBBs. Remember if any reserved register is liveout.
61063faed5bSDimitry Andric SmallSet<unsigned, 4> LiveOuts;
611344a3780SDimitry Andric for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
612dd58ef01SDimitry Andric if (SuccMBB->isEHPad())
61363faed5bSDimitry Andric continue;
614dd58ef01SDimitry Andric for (const auto &LI : SuccMBB->liveins()) {
615dd58ef01SDimitry Andric if (!TRI->isInAllocatableClass(LI.PhysReg))
61663faed5bSDimitry Andric // Ignore other live-ins, e.g. those that are live into landing pads.
617dd58ef01SDimitry Andric LiveOuts.insert(LI.PhysReg);
61863faed5bSDimitry Andric }
61963faed5bSDimitry Andric }
62063faed5bSDimitry Andric
621009b1c42SEd Schouten // Loop over PhysRegDef / PhysRegUse, killing any registers that are
622009b1c42SEd Schouten // available at the end of the basic block.
623009b1c42SEd Schouten for (unsigned i = 0; i != NumRegs; ++i)
62463faed5bSDimitry Andric if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
6255ca98fd9SDimitry Andric HandlePhysRegDef(i, nullptr, Defs);
62667c32a98SDimitry Andric }
627009b1c42SEd Schouten
analyze(MachineFunction & mf)628ac9a064cSDimitry Andric void LiveVariables::analyze(MachineFunction &mf) {
62967c32a98SDimitry Andric MF = &mf;
63067c32a98SDimitry Andric MRI = &mf.getRegInfo();
63167c32a98SDimitry Andric TRI = MF->getSubtarget().getRegisterInfo();
63267c32a98SDimitry Andric
633b1c73532SDimitry Andric const unsigned NumRegs = TRI->getNumSupportedRegs(mf);
63467c32a98SDimitry Andric PhysRegDef.assign(NumRegs, nullptr);
63567c32a98SDimitry Andric PhysRegUse.assign(NumRegs, nullptr);
63667c32a98SDimitry Andric PHIVarInfo.resize(MF->getNumBlockIDs());
63767c32a98SDimitry Andric
63867c32a98SDimitry Andric // FIXME: LiveIntervals will be updated to remove its dependence on
63967c32a98SDimitry Andric // LiveVariables to improve compilation time and eliminate bizarre pass
64067c32a98SDimitry Andric // dependencies. Until then, we can't change much in -O0.
64167c32a98SDimitry Andric if (!MRI->isSSA())
64267c32a98SDimitry Andric report_fatal_error("regalloc=... not currently supported with -O0");
64367c32a98SDimitry Andric
64467c32a98SDimitry Andric analyzePHINodes(mf);
64567c32a98SDimitry Andric
64667c32a98SDimitry Andric // Calculate live variable information in depth first order on the CFG of the
64767c32a98SDimitry Andric // function. This guarantees that we will see the definition of a virtual
64867c32a98SDimitry Andric // register before its uses due to dominance properties of SSA (except for PHI
64967c32a98SDimitry Andric // nodes, which are treated as a special case).
650dd58ef01SDimitry Andric MachineBasicBlock *Entry = &MF->front();
651b915e9e0SDimitry Andric df_iterator_default_set<MachineBasicBlock*,16> Visited;
65267c32a98SDimitry Andric
65367c32a98SDimitry Andric for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
65467c32a98SDimitry Andric runOnBlock(MBB, NumRegs);
65567c32a98SDimitry Andric
65667c32a98SDimitry Andric PhysRegDef.assign(NumRegs, nullptr);
65767c32a98SDimitry Andric PhysRegUse.assign(NumRegs, nullptr);
658009b1c42SEd Schouten }
659009b1c42SEd Schouten
660009b1c42SEd Schouten // Convert and transfer the dead / killed information we have gathered into
661009b1c42SEd Schouten // VirtRegInfo onto MI's.
662cf099d11SDimitry Andric for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
663b60736ecSDimitry Andric const Register Reg = Register::index2VirtReg(i);
664cf099d11SDimitry Andric for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
665cf099d11SDimitry Andric if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
666cf099d11SDimitry Andric VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
667009b1c42SEd Schouten else
668cf099d11SDimitry Andric VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
669cf099d11SDimitry Andric }
670009b1c42SEd Schouten
671009b1c42SEd Schouten // Check to make sure there are no unreachable blocks in the MC CFG for the
672009b1c42SEd Schouten // function. If so, it is due to a bug in the instruction selector or some
673009b1c42SEd Schouten // other part of the code generator if this happens.
674009b1c42SEd Schouten #ifndef NDEBUG
675344a3780SDimitry Andric for (const MachineBasicBlock &MBB : *MF)
676344a3780SDimitry Andric assert(Visited.contains(&MBB) && "unreachable basic block found");
677009b1c42SEd Schouten #endif
678009b1c42SEd Schouten
67967c32a98SDimitry Andric PhysRegDef.clear();
68067c32a98SDimitry Andric PhysRegUse.clear();
68167c32a98SDimitry Andric PHIVarInfo.clear();
682009b1c42SEd Schouten }
683009b1c42SEd Schouten
recomputeForSingleDefVirtReg(Register Reg)684c0981da4SDimitry Andric void LiveVariables::recomputeForSingleDefVirtReg(Register Reg) {
685c0981da4SDimitry Andric assert(Reg.isVirtual());
686c0981da4SDimitry Andric
687c0981da4SDimitry Andric VarInfo &VI = getVarInfo(Reg);
688c0981da4SDimitry Andric VI.AliveBlocks.clear();
689c0981da4SDimitry Andric VI.Kills.clear();
690c0981da4SDimitry Andric
691c0981da4SDimitry Andric MachineInstr &DefMI = *MRI->getUniqueVRegDef(Reg);
692c0981da4SDimitry Andric MachineBasicBlock &DefBB = *DefMI.getParent();
693c0981da4SDimitry Andric
694c0981da4SDimitry Andric // Initialize a worklist of BBs that Reg is live-to-end of. (Here
695c0981da4SDimitry Andric // "live-to-end" means Reg is live at the end of a block even if it is only
696c0981da4SDimitry Andric // live because of phi uses in a successor. This is different from isLiveOut()
697c0981da4SDimitry Andric // which does not consider phi uses.)
698c0981da4SDimitry Andric SmallVector<MachineBasicBlock *> LiveToEndBlocks;
699c0981da4SDimitry Andric SparseBitVector<> UseBlocks;
700b1c73532SDimitry Andric unsigned NumRealUses = 0;
701c0981da4SDimitry Andric for (auto &UseMO : MRI->use_nodbg_operands(Reg)) {
702c0981da4SDimitry Andric UseMO.setIsKill(false);
703b1c73532SDimitry Andric if (!UseMO.readsReg())
704b1c73532SDimitry Andric continue;
705b1c73532SDimitry Andric ++NumRealUses;
706c0981da4SDimitry Andric MachineInstr &UseMI = *UseMO.getParent();
707c0981da4SDimitry Andric MachineBasicBlock &UseBB = *UseMI.getParent();
708c0981da4SDimitry Andric UseBlocks.set(UseBB.getNumber());
709c0981da4SDimitry Andric if (UseMI.isPHI()) {
710c0981da4SDimitry Andric // If Reg is used in a phi then it is live-to-end of the corresponding
711c0981da4SDimitry Andric // predecessor.
7127fa27ce4SDimitry Andric unsigned Idx = UseMO.getOperandNo();
713c0981da4SDimitry Andric LiveToEndBlocks.push_back(UseMI.getOperand(Idx + 1).getMBB());
714c0981da4SDimitry Andric } else if (&UseBB == &DefBB) {
715c0981da4SDimitry Andric // A non-phi use in the same BB as the single def must come after the def.
716c0981da4SDimitry Andric } else {
717c0981da4SDimitry Andric // Otherwise Reg must be live-to-end of all predecessors.
718c0981da4SDimitry Andric LiveToEndBlocks.append(UseBB.pred_begin(), UseBB.pred_end());
719c0981da4SDimitry Andric }
720c0981da4SDimitry Andric }
721c0981da4SDimitry Andric
722b1c73532SDimitry Andric // Handle the case where all uses have been removed.
723b1c73532SDimitry Andric if (NumRealUses == 0) {
724b1c73532SDimitry Andric VI.Kills.push_back(&DefMI);
725b1c73532SDimitry Andric DefMI.addRegisterDead(Reg, nullptr);
726b1c73532SDimitry Andric return;
727b1c73532SDimitry Andric }
728b1c73532SDimitry Andric DefMI.clearRegisterDeads(Reg);
729b1c73532SDimitry Andric
730c0981da4SDimitry Andric // Iterate over the worklist adding blocks to AliveBlocks.
731c0981da4SDimitry Andric bool LiveToEndOfDefBB = false;
732c0981da4SDimitry Andric while (!LiveToEndBlocks.empty()) {
733c0981da4SDimitry Andric MachineBasicBlock &BB = *LiveToEndBlocks.pop_back_val();
734c0981da4SDimitry Andric if (&BB == &DefBB) {
735c0981da4SDimitry Andric LiveToEndOfDefBB = true;
736c0981da4SDimitry Andric continue;
737c0981da4SDimitry Andric }
738c0981da4SDimitry Andric if (VI.AliveBlocks.test(BB.getNumber()))
739c0981da4SDimitry Andric continue;
740c0981da4SDimitry Andric VI.AliveBlocks.set(BB.getNumber());
741c0981da4SDimitry Andric LiveToEndBlocks.append(BB.pred_begin(), BB.pred_end());
742c0981da4SDimitry Andric }
743c0981da4SDimitry Andric
744c0981da4SDimitry Andric // Recompute kill flags. For each block in which Reg is used but is not
745c0981da4SDimitry Andric // live-through, find the last instruction that uses Reg. Ignore phi nodes
746c0981da4SDimitry Andric // because they should not be included in Kills.
747c0981da4SDimitry Andric for (unsigned UseBBNum : UseBlocks) {
748c0981da4SDimitry Andric if (VI.AliveBlocks.test(UseBBNum))
749c0981da4SDimitry Andric continue;
750c0981da4SDimitry Andric MachineBasicBlock &UseBB = *MF->getBlockNumbered(UseBBNum);
751c0981da4SDimitry Andric if (&UseBB == &DefBB && LiveToEndOfDefBB)
752c0981da4SDimitry Andric continue;
753c0981da4SDimitry Andric for (auto &MI : reverse(UseBB)) {
754c0981da4SDimitry Andric if (MI.isDebugOrPseudoInstr())
755c0981da4SDimitry Andric continue;
756c0981da4SDimitry Andric if (MI.isPHI())
757c0981da4SDimitry Andric break;
758b1c73532SDimitry Andric if (MI.readsVirtualRegister(Reg)) {
759ac9a064cSDimitry Andric assert(!MI.killsRegister(Reg, /*TRI=*/nullptr));
760c0981da4SDimitry Andric MI.addRegisterKilled(Reg, nullptr);
761c0981da4SDimitry Andric VI.Kills.push_back(&MI);
762c0981da4SDimitry Andric break;
763c0981da4SDimitry Andric }
764c0981da4SDimitry Andric }
765c0981da4SDimitry Andric }
766c0981da4SDimitry Andric }
767c0981da4SDimitry Andric
768009b1c42SEd Schouten /// replaceKillInstruction - Update register kill info by replacing a kill
769009b1c42SEd Schouten /// instruction with a new one.
replaceKillInstruction(Register Reg,MachineInstr & OldMI,MachineInstr & NewMI)770b60736ecSDimitry Andric void LiveVariables::replaceKillInstruction(Register Reg, MachineInstr &OldMI,
77101095a5dSDimitry Andric MachineInstr &NewMI) {
772009b1c42SEd Schouten VarInfo &VI = getVarInfo(Reg);
77301095a5dSDimitry Andric std::replace(VI.Kills.begin(), VI.Kills.end(), &OldMI, &NewMI);
774009b1c42SEd Schouten }
775009b1c42SEd Schouten
776009b1c42SEd Schouten /// removeVirtualRegistersKilled - Remove all killed info for the specified
777009b1c42SEd Schouten /// instruction.
removeVirtualRegistersKilled(MachineInstr & MI)77801095a5dSDimitry Andric void LiveVariables::removeVirtualRegistersKilled(MachineInstr &MI) {
7794b4fe385SDimitry Andric for (MachineOperand &MO : MI.operands()) {
780009b1c42SEd Schouten if (MO.isReg() && MO.isKill()) {
781009b1c42SEd Schouten MO.setIsKill(false);
7821d5ae102SDimitry Andric Register Reg = MO.getReg();
783e3b55780SDimitry Andric if (Reg.isVirtual()) {
784009b1c42SEd Schouten bool removed = getVarInfo(Reg).removeKill(MI);
785009b1c42SEd Schouten assert(removed && "kill not in register's VarInfo?");
78630815c53SDimitry Andric (void)removed;
787009b1c42SEd Schouten }
788009b1c42SEd Schouten }
789009b1c42SEd Schouten }
790009b1c42SEd Schouten }
791009b1c42SEd Schouten
792009b1c42SEd Schouten /// analyzePHINodes - Gather information about the PHI nodes in here. In
793009b1c42SEd Schouten /// particular, we want to map the variable information of a virtual register
794009b1c42SEd Schouten /// which is used in a PHI node. We map that to the BB the vreg is coming from.
795009b1c42SEd Schouten ///
analyzePHINodes(const MachineFunction & Fn)796009b1c42SEd Schouten void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
7975ca98fd9SDimitry Andric for (const auto &MBB : Fn)
7985ca98fd9SDimitry Andric for (const auto &BBI : MBB) {
7995ca98fd9SDimitry Andric if (!BBI.isPHI())
8005ca98fd9SDimitry Andric break;
8015ca98fd9SDimitry Andric for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
8025ca98fd9SDimitry Andric if (BBI.getOperand(i).readsReg())
8035ca98fd9SDimitry Andric PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
8045ca98fd9SDimitry Andric .push_back(BBI.getOperand(i).getReg());
8055ca98fd9SDimitry Andric }
806009b1c42SEd Schouten }
807907da171SRoman Divacky
isLiveIn(const MachineBasicBlock & MBB,Register Reg,MachineRegisterInfo & MRI)80806f9d401SRoman Divacky bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
809b60736ecSDimitry Andric Register Reg, MachineRegisterInfo &MRI) {
81006f9d401SRoman Divacky unsigned Num = MBB.getNumber();
81106f9d401SRoman Divacky
81206f9d401SRoman Divacky // Reg is live-through.
81306f9d401SRoman Divacky if (AliveBlocks.test(Num))
81406f9d401SRoman Divacky return true;
81506f9d401SRoman Divacky
81606f9d401SRoman Divacky // Registers defined in MBB cannot be live in.
81706f9d401SRoman Divacky const MachineInstr *Def = MRI.getVRegDef(Reg);
81806f9d401SRoman Divacky if (Def && Def->getParent() == &MBB)
81906f9d401SRoman Divacky return false;
82006f9d401SRoman Divacky
82106f9d401SRoman Divacky // Reg was not defined in MBB, was it killed here?
82206f9d401SRoman Divacky return findKill(&MBB);
82306f9d401SRoman Divacky }
82406f9d401SRoman Divacky
isLiveOut(Register Reg,const MachineBasicBlock & MBB)825b60736ecSDimitry Andric bool LiveVariables::isLiveOut(Register Reg, const MachineBasicBlock &MBB) {
826571945e6SRoman Divacky LiveVariables::VarInfo &VI = getVarInfo(Reg);
827571945e6SRoman Divacky
8283a0822f0SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> Kills;
829f65dcba8SDimitry Andric for (MachineInstr *MI : VI.Kills)
830f65dcba8SDimitry Andric Kills.insert(MI->getParent());
8313a0822f0SDimitry Andric
832571945e6SRoman Divacky // Loop over all of the successors of the basic block, checking to see if
833571945e6SRoman Divacky // the value is either live in the block, or if it is killed in the block.
8343a0822f0SDimitry Andric for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
835571945e6SRoman Divacky // Is it alive in this successor?
836571945e6SRoman Divacky unsigned SuccIdx = SuccMBB->getNumber();
837571945e6SRoman Divacky if (VI.AliveBlocks.test(SuccIdx))
838571945e6SRoman Divacky return true;
8393a0822f0SDimitry Andric // Or is it live because there is a use in a successor that kills it?
8403a0822f0SDimitry Andric if (Kills.count(SuccMBB))
8413a0822f0SDimitry Andric return true;
842571945e6SRoman Divacky }
843571945e6SRoman Divacky
844571945e6SRoman Divacky return false;
845571945e6SRoman Divacky }
846571945e6SRoman Divacky
847907da171SRoman Divacky /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
848907da171SRoman Divacky /// variables that are live out of DomBB will be marked as passing live through
849907da171SRoman Divacky /// BB.
addNewBlock(MachineBasicBlock * BB,MachineBasicBlock * DomBB,MachineBasicBlock * SuccBB)850907da171SRoman Divacky void LiveVariables::addNewBlock(MachineBasicBlock *BB,
85106f9d401SRoman Divacky MachineBasicBlock *DomBB,
85206f9d401SRoman Divacky MachineBasicBlock *SuccBB) {
853907da171SRoman Divacky const unsigned NumNew = BB->getNumber();
85406f9d401SRoman Divacky
8556b3f41edSDimitry Andric DenseSet<unsigned> Defs, Kills;
856522600a2SDimitry Andric
857522600a2SDimitry Andric MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
858522600a2SDimitry Andric for (; BBI != BBE && BBI->isPHI(); ++BBI) {
859522600a2SDimitry Andric // Record the def of the PHI node.
860522600a2SDimitry Andric Defs.insert(BBI->getOperand(0).getReg());
861522600a2SDimitry Andric
86206f9d401SRoman Divacky // All registers used by PHI nodes in SuccBB must be live through BB.
86306f9d401SRoman Divacky for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
86406f9d401SRoman Divacky if (BBI->getOperand(i+1).getMBB() == BB)
86506f9d401SRoman Divacky getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
866522600a2SDimitry Andric }
867522600a2SDimitry Andric
868522600a2SDimitry Andric // Record all vreg defs and kills of all instructions in SuccBB.
869522600a2SDimitry Andric for (; BBI != BBE; ++BBI) {
870344a3780SDimitry Andric for (const MachineOperand &Op : BBI->operands()) {
871e3b55780SDimitry Andric if (Op.isReg() && Op.getReg().isVirtual()) {
872344a3780SDimitry Andric if (Op.isDef())
873344a3780SDimitry Andric Defs.insert(Op.getReg());
874344a3780SDimitry Andric else if (Op.isKill())
875344a3780SDimitry Andric Kills.insert(Op.getReg());
876522600a2SDimitry Andric }
877522600a2SDimitry Andric }
878522600a2SDimitry Andric }
879907da171SRoman Divacky
880907da171SRoman Divacky // Update info for all live variables
881cf099d11SDimitry Andric for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
882b60736ecSDimitry Andric Register Reg = Register::index2VirtReg(i);
883522600a2SDimitry Andric
884522600a2SDimitry Andric // If the Defs is defined in the successor it can't be live in BB.
885522600a2SDimitry Andric if (Defs.count(Reg))
886522600a2SDimitry Andric continue;
887522600a2SDimitry Andric
888522600a2SDimitry Andric // If the register is either killed in or live through SuccBB it's also live
889522600a2SDimitry Andric // through BB.
890907da171SRoman Divacky VarInfo &VI = getVarInfo(Reg);
891522600a2SDimitry Andric if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
892907da171SRoman Divacky VI.AliveBlocks.set(NumNew);
893907da171SRoman Divacky }
894907da171SRoman Divacky }
895cfca06d7SDimitry Andric
896cfca06d7SDimitry Andric /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
897cfca06d7SDimitry Andric /// variables that are live out of DomBB will be marked as passing live through
898cfca06d7SDimitry Andric /// BB. LiveInSets[BB] is *not* updated (because it is not needed during
899cfca06d7SDimitry Andric /// PHIElimination).
addNewBlock(MachineBasicBlock * BB,MachineBasicBlock * DomBB,MachineBasicBlock * SuccBB,std::vector<SparseBitVector<>> & LiveInSets)900cfca06d7SDimitry Andric void LiveVariables::addNewBlock(MachineBasicBlock *BB,
901cfca06d7SDimitry Andric MachineBasicBlock *DomBB,
902cfca06d7SDimitry Andric MachineBasicBlock *SuccBB,
903cfca06d7SDimitry Andric std::vector<SparseBitVector<>> &LiveInSets) {
904cfca06d7SDimitry Andric const unsigned NumNew = BB->getNumber();
905cfca06d7SDimitry Andric
906cfca06d7SDimitry Andric SparseBitVector<> &BV = LiveInSets[SuccBB->getNumber()];
907344a3780SDimitry Andric for (unsigned R : BV) {
908344a3780SDimitry Andric Register VirtReg = Register::index2VirtReg(R);
909cfca06d7SDimitry Andric LiveVariables::VarInfo &VI = getVarInfo(VirtReg);
910cfca06d7SDimitry Andric VI.AliveBlocks.set(NumNew);
911cfca06d7SDimitry Andric }
912cfca06d7SDimitry Andric // All registers used by PHI nodes in SuccBB must be live through BB.
913cfca06d7SDimitry Andric for (MachineBasicBlock::iterator BBI = SuccBB->begin(),
914cfca06d7SDimitry Andric BBE = SuccBB->end();
915cfca06d7SDimitry Andric BBI != BBE && BBI->isPHI(); ++BBI) {
916cfca06d7SDimitry Andric for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
917cfca06d7SDimitry Andric if (BBI->getOperand(i + 1).getMBB() == BB &&
918cfca06d7SDimitry Andric BBI->getOperand(i).readsReg())
919cfca06d7SDimitry Andric getVarInfo(BBI->getOperand(i).getReg())
920cfca06d7SDimitry Andric .AliveBlocks.set(NumNew);
921cfca06d7SDimitry Andric }
922cfca06d7SDimitry Andric }
923