1 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
17 // This class computes live variables using are 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.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/CodeGen/LiveVariables.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/Target/MRegisterInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Config/alloca.h"
40 static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
42 void LiveVariables::VarInfo::dump() const {
43 cerr << "Register Defined by: ";
48 cerr << " Alive in blocks: ";
49 for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
50 if (AliveBlocks[i]) cerr << i << ", ";
51 cerr << "\n Killed by:";
53 cerr << " No instructions.\n";
55 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
56 cerr << "\n #" << i << ": " << *Kills[i];
61 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
62 assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
63 "getVarInfo: not a virtual register!");
64 RegIdx -= MRegisterInfo::FirstVirtualRegister;
65 if (RegIdx >= VirtRegInfo.size()) {
66 if (RegIdx >= 2*VirtRegInfo.size())
67 VirtRegInfo.resize(RegIdx*2);
69 VirtRegInfo.resize(2*VirtRegInfo.size());
71 VarInfo &VI = VirtRegInfo[RegIdx];
72 VI.AliveBlocks.resize(MF->getNumBlockIDs());
76 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
77 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
78 MachineOperand &MO = MI->getOperand(i);
79 if (MO.isReg() && MO.isKill()) {
80 if (RegInfo->regsOverlap(Reg, MO.getReg()))
87 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
88 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
89 MachineOperand &MO = MI->getOperand(i);
90 if (MO.isReg() && MO.isDead())
91 if (RegInfo->regsOverlap(Reg, MO.getReg()))
97 bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
98 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
99 MachineOperand &MO = MI->getOperand(i);
100 if (MO.isReg() && MO.isDef()) {
101 if (RegInfo->regsOverlap(Reg, MO.getReg()))
108 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
109 MachineBasicBlock *MBB) {
110 unsigned BBNum = MBB->getNumber();
112 // Check to see if this basic block is one of the killing blocks. If so,
114 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
115 if (VRInfo.Kills[i]->getParent() == MBB) {
116 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
120 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
122 if (VRInfo.AliveBlocks[BBNum])
123 return; // We already know the block is live
125 // Mark the variable known alive in this bb
126 VRInfo.AliveBlocks[BBNum] = true;
128 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
129 E = MBB->pred_end(); PI != E; ++PI)
130 MarkVirtRegAliveInBlock(VRInfo, *PI);
133 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
135 assert(VRInfo.DefInst && "Register use before def!");
139 // Check to see if this basic block is already a kill block...
140 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
141 // Yes, this register is killed in this basic block already. Increase the
142 // live range by updating the kill instruction.
143 VRInfo.Kills.back() = MI;
148 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
149 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
152 assert(MBB != VRInfo.DefInst->getParent() &&
153 "Should have kill for defblock!");
155 // Add a new kill entry for this basic block.
156 // If this virtual register is already marked as alive in this basic block,
157 // that means it is alive in at least one of the successor block, it's not
159 if (!VRInfo.AliveBlocks[MBB->getNumber()])
160 VRInfo.Kills.push_back(MI);
162 // Update all dominating blocks to mark them known live.
163 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
164 E = MBB->pred_end(); PI != E; ++PI)
165 MarkVirtRegAliveInBlock(VRInfo, *PI);
168 void LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI) {
169 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170 MachineOperand &MO = MI->getOperand(i);
171 if (MO.isReg() && MO.isUse() && MO.getReg() == IncomingReg) {
178 void LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI) {
179 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
180 MachineOperand &MO = MI->getOperand(i);
181 if (MO.isReg() && MO.isDef() && MO.getReg() == IncomingReg) {
188 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
189 PhysRegInfo[Reg] = MI;
190 PhysRegUsed[Reg] = true;
192 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
193 unsigned Alias = *AliasSet; ++AliasSet) {
194 PhysRegInfo[Alias] = MI;
195 PhysRegUsed[Alias] = true;
199 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
200 // Does this kill a previous version of this register?
201 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
202 if (PhysRegUsed[Reg])
203 addRegisterKilled(Reg, LastUse);
205 addRegisterDead(Reg, LastUse);
207 PhysRegInfo[Reg] = MI;
208 PhysRegUsed[Reg] = false;
210 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
211 unsigned Alias = *AliasSet; ++AliasSet) {
212 if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
213 if (PhysRegUsed[Alias])
214 addRegisterKilled(Alias, LastUse);
216 addRegisterDead(Alias, LastUse);
218 PhysRegInfo[Alias] = MI;
219 PhysRegUsed[Alias] = false;
223 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
225 const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
226 RegInfo = MF->getTarget().getRegisterInfo();
227 assert(RegInfo && "Target doesn't have register information?");
229 ReservedRegisters = RegInfo->getReservedRegs(mf);
231 // PhysRegInfo - Keep track of which instruction was the last use of a
232 // physical register. This is a purely local property, because all physical
233 // register references as presumed dead across basic blocks.
235 PhysRegInfo = (MachineInstr**)alloca(sizeof(MachineInstr*) *
236 RegInfo->getNumRegs());
237 PhysRegUsed = (bool*)alloca(sizeof(bool)*RegInfo->getNumRegs());
238 std::fill(PhysRegInfo, PhysRegInfo+RegInfo->getNumRegs(), (MachineInstr*)0);
240 /// Get some space for a respectable number of registers...
241 VirtRegInfo.resize(64);
245 // Calculate live variable information in depth first order on the CFG of the
246 // function. This guarantees that we will see the definition of a virtual
247 // register before its uses due to dominance properties of SSA (except for PHI
248 // nodes, which are treated as a special case).
250 MachineBasicBlock *Entry = MF->begin();
251 std::set<MachineBasicBlock*> Visited;
252 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
253 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
254 MachineBasicBlock *MBB = *DFI;
256 // Mark live-in registers as live-in.
257 for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
258 EE = MBB->livein_end(); II != EE; ++II) {
259 assert(MRegisterInfo::isPhysicalRegister(*II) &&
260 "Cannot have a live-in virtual register!");
261 HandlePhysRegDef(*II, 0);
264 // Loop over all of the instructions, processing them.
265 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
267 MachineInstr *MI = I;
269 // Process all of the operands of the instruction...
270 unsigned NumOperandsToProcess = MI->getNumOperands();
272 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
273 // of the uses. They will be handled in other basic blocks.
274 if (MI->getOpcode() == TargetInstrInfo::PHI)
275 NumOperandsToProcess = 1;
277 // Process all uses...
278 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
279 MachineOperand &MO = MI->getOperand(i);
280 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
281 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
282 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
283 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
284 !ReservedRegisters[MO.getReg()]) {
285 HandlePhysRegUse(MO.getReg(), MI);
290 // Process all defs...
291 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
292 MachineOperand &MO = MI->getOperand(i);
293 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
294 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
295 VarInfo &VRInfo = getVarInfo(MO.getReg());
297 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
300 VRInfo.Kills.push_back(MI);
301 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
302 !ReservedRegisters[MO.getReg()]) {
303 HandlePhysRegDef(MO.getReg(), MI);
309 // Handle any virtual assignments from PHI nodes which might be at the
310 // bottom of this basic block. We check all of our successor blocks to see
311 // if they have PHI nodes, and if so, we simulate an assignment at the end
312 // of the current block.
313 if (!PHIVarInfo[MBB].empty()) {
314 std::vector<unsigned>& VarInfoVec = PHIVarInfo[MBB];
316 for (std::vector<unsigned>::iterator I = VarInfoVec.begin(),
317 E = VarInfoVec.end(); I != E; ++I) {
318 VarInfo& VRInfo = getVarInfo(*I);
319 assert(VRInfo.DefInst && "Register use before def (or no def)!");
321 // Only mark it alive only in the block we are representing.
322 MarkVirtRegAliveInBlock(VRInfo, MBB);
326 // Finally, if the last instruction in the block is a return, make sure to mark
327 // it as using all of the live-out values in the function.
328 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
329 MachineInstr *Ret = &MBB->back();
330 for (MachineFunction::liveout_iterator I = MF->liveout_begin(),
331 E = MF->liveout_end(); I != E; ++I) {
332 assert(MRegisterInfo::isPhysicalRegister(*I) &&
333 "Cannot have a live-in virtual register!");
334 HandlePhysRegUse(*I, Ret);
335 // Add live-out registers as implicit uses.
336 Ret->addRegOperand(*I, false, true);
340 // Loop over PhysRegInfo, killing any registers that are available at the
341 // end of the basic block. This also resets the PhysRegInfo map.
342 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
344 HandlePhysRegDef(i, 0);
347 // Convert and transfer the dead / killed information we have gathered into
348 // VirtRegInfo onto MI's.
350 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
351 for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j) {
352 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
353 addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
354 VirtRegInfo[i].Kills[j]);
356 addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
357 VirtRegInfo[i].Kills[j]);
360 // Check to make sure there are no unreachable blocks in the MC CFG for the
361 // function. If so, it is due to a bug in the instruction selector or some
362 // other part of the code generator if this happens.
364 for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
365 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
372 /// instructionChanged - When the address of an instruction changes, this
373 /// method should be called so that live variables can update its internal
374 /// data structures. This removes the records for OldMI, transfering them to
375 /// the records for NewMI.
376 void LiveVariables::instructionChanged(MachineInstr *OldMI,
377 MachineInstr *NewMI) {
378 // If the instruction defines any virtual registers, update the VarInfo,
379 // kill and dead information for the instruction.
380 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
381 MachineOperand &MO = OldMI->getOperand(i);
382 if (MO.isRegister() && MO.getReg() &&
383 MRegisterInfo::isVirtualRegister(MO.getReg())) {
384 unsigned Reg = MO.getReg();
385 VarInfo &VI = getVarInfo(Reg);
389 addVirtualRegisterDead(Reg, NewMI);
391 // Update the defining instruction.
392 if (VI.DefInst == OldMI)
398 addVirtualRegisterKilled(Reg, NewMI);
400 // If this is a kill of the value, update the VI kills list.
401 if (VI.removeKill(OldMI))
402 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
408 /// removeVirtualRegistersKilled - Remove all killed info for the specified
410 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
411 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
412 MachineOperand &MO = MI->getOperand(i);
413 if (MO.isReg() && MO.isKill()) {
415 unsigned Reg = MO.getReg();
416 if (MRegisterInfo::isVirtualRegister(Reg)) {
417 bool removed = getVarInfo(Reg).removeKill(MI);
418 assert(removed && "kill not in register's VarInfo?");
424 /// removeVirtualRegistersDead - Remove all of the dead registers for the
425 /// specified instruction from the live variable information.
426 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
427 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
428 MachineOperand &MO = MI->getOperand(i);
429 if (MO.isReg() && MO.isDead()) {
431 unsigned Reg = MO.getReg();
432 if (MRegisterInfo::isVirtualRegister(Reg)) {
433 bool removed = getVarInfo(Reg).removeKill(MI);
434 assert(removed && "kill not in register's VarInfo?");
440 /// analyzePHINodes - Gather information about the PHI nodes in here. In
441 /// particular, we want to map the variable information of a virtual
442 /// register which is used in a PHI node. We map that to the BB the vreg is
445 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
446 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
448 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
449 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
450 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
451 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()].
452 push_back(BBI->getOperand(i).getReg());