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 return VirtRegInfo[RegIdx];
74 /// registerOverlap - Returns true if register 1 is equal to register 2
75 /// or if register 1 is equal to any of alias of register 2.
76 static bool registerOverlap(unsigned Reg1, unsigned Reg2,
77 const MRegisterInfo *RegInfo) {
78 bool isVirt1 = MRegisterInfo::isVirtualRegister(Reg1);
79 bool isVirt2 = MRegisterInfo::isVirtualRegister(Reg2);
80 if (isVirt1 != isVirt2)
86 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg2);
87 unsigned Alias = *AliasSet; ++AliasSet) {
94 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
95 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
96 MachineOperand &MO = MI->getOperand(i);
97 if (MO.isReg() && MO.isKill()) {
98 if (registerOverlap(Reg, MO.getReg(), RegInfo))
105 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
106 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
107 MachineOperand &MO = MI->getOperand(i);
108 if (MO.isReg() && MO.isDead())
109 if (registerOverlap(Reg, MO.getReg(), RegInfo))
115 bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
116 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
117 MachineOperand &MO = MI->getOperand(i);
118 if (MO.isReg() && MO.isDef()) {
119 if (registerOverlap(Reg, MO.getReg(), RegInfo))
126 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
127 MachineBasicBlock *MBB) {
128 unsigned BBNum = MBB->getNumber();
130 // Check to see if this basic block is one of the killing blocks. If so,
132 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
133 if (VRInfo.Kills[i]->getParent() == MBB) {
134 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
138 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
140 if (VRInfo.AliveBlocks.size() <= BBNum)
141 VRInfo.AliveBlocks.resize(BBNum+1); // Make space...
143 if (VRInfo.AliveBlocks[BBNum])
144 return; // We already know the block is live
146 // Mark the variable known alive in this bb
147 VRInfo.AliveBlocks[BBNum] = true;
149 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
150 E = MBB->pred_end(); PI != E; ++PI)
151 MarkVirtRegAliveInBlock(VRInfo, *PI);
154 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
156 assert(VRInfo.DefInst && "Register use before def!");
158 // Check to see if this basic block is already a kill block...
159 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
160 // Yes, this register is killed in this basic block already. Increase the
161 // live range by updating the kill instruction.
162 VRInfo.Kills.back() = MI;
167 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
168 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
171 assert(MBB != VRInfo.DefInst->getParent() &&
172 "Should have kill for defblock!");
174 // Add a new kill entry for this basic block.
175 VRInfo.Kills.push_back(MI);
177 // Update all dominating blocks to mark them known live.
178 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
179 E = MBB->pred_end(); PI != E; ++PI)
180 MarkVirtRegAliveInBlock(VRInfo, *PI);
183 void LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI) {
184 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
185 MachineOperand &MO = MI->getOperand(i);
186 if (MO.isReg() && MO.isUse() && MO.getReg() == IncomingReg) {
193 void LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI) {
194 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
195 MachineOperand &MO = MI->getOperand(i);
196 if (MO.isReg() && MO.isDef() && MO.getReg() == IncomingReg) {
203 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
204 PhysRegInfo[Reg] = MI;
205 PhysRegUsed[Reg] = true;
207 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
208 unsigned Alias = *AliasSet; ++AliasSet) {
209 PhysRegInfo[Alias] = MI;
210 PhysRegUsed[Alias] = true;
214 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
215 // Does this kill a previous version of this register?
216 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
217 if (PhysRegUsed[Reg])
218 addRegisterKilled(Reg, LastUse);
220 addRegisterDead(Reg, LastUse);
222 PhysRegInfo[Reg] = MI;
223 PhysRegUsed[Reg] = false;
225 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
226 unsigned Alias = *AliasSet; ++AliasSet) {
227 if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
228 if (PhysRegUsed[Alias])
229 addRegisterKilled(Alias, LastUse);
231 addRegisterDead(Alias, LastUse);
233 PhysRegInfo[Alias] = MI;
234 PhysRegUsed[Alias] = false;
238 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
239 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
240 RegInfo = MF.getTarget().getRegisterInfo();
241 assert(RegInfo && "Target doesn't have register information?");
243 AllocatablePhysicalRegisters = RegInfo->getAllocatableSet(MF);
245 // PhysRegInfo - Keep track of which instruction was the last use of a
246 // physical register. This is a purely local property, because all physical
247 // register references as presumed dead across basic blocks.
249 PhysRegInfo = (MachineInstr**)alloca(sizeof(MachineInstr*) *
250 RegInfo->getNumRegs());
251 PhysRegUsed = (bool*)alloca(sizeof(bool)*RegInfo->getNumRegs());
252 std::fill(PhysRegInfo, PhysRegInfo+RegInfo->getNumRegs(), (MachineInstr*)0);
254 /// Get some space for a respectable number of registers...
255 VirtRegInfo.resize(64);
259 // Calculate live variable information in depth first order on the CFG of the
260 // function. This guarantees that we will see the definition of a virtual
261 // register before its uses due to dominance properties of SSA (except for PHI
262 // nodes, which are treated as a special case).
264 MachineBasicBlock *Entry = MF.begin();
265 std::set<MachineBasicBlock*> Visited;
266 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
267 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
268 MachineBasicBlock *MBB = *DFI;
270 // Mark live-in registers as live-in.
271 for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(),
272 EE = MBB->livein_end(); II != EE; ++II) {
273 assert(MRegisterInfo::isPhysicalRegister(*II) &&
274 "Cannot have a live-in virtual register!");
275 HandlePhysRegDef(*II, 0);
278 // Loop over all of the instructions, processing them.
279 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
281 MachineInstr *MI = I;
283 // Process all of the operands of the instruction...
284 unsigned NumOperandsToProcess = MI->getNumOperands();
286 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
287 // of the uses. They will be handled in other basic blocks.
288 if (MI->getOpcode() == TargetInstrInfo::PHI)
289 NumOperandsToProcess = 1;
291 // Process all uses...
292 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
293 MachineOperand &MO = MI->getOperand(i);
294 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
295 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
296 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
297 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
298 AllocatablePhysicalRegisters[MO.getReg()]) {
299 HandlePhysRegUse(MO.getReg(), MI);
304 // Process all defs...
305 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
306 MachineOperand &MO = MI->getOperand(i);
307 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
308 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
309 VarInfo &VRInfo = getVarInfo(MO.getReg());
311 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
314 VRInfo.Kills.push_back(MI);
315 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
316 AllocatablePhysicalRegisters[MO.getReg()]) {
317 HandlePhysRegDef(MO.getReg(), MI);
323 // Handle any virtual assignments from PHI nodes which might be at the
324 // bottom of this basic block. We check all of our successor blocks to see
325 // if they have PHI nodes, and if so, we simulate an assignment at the end
326 // of the current block.
327 if (!PHIVarInfo[MBB].empty()) {
328 std::vector<unsigned>& VarInfoVec = PHIVarInfo[MBB];
330 for (std::vector<unsigned>::iterator I = VarInfoVec.begin(),
331 E = VarInfoVec.end(); I != E; ++I) {
332 VarInfo& VRInfo = getVarInfo(*I);
333 assert(VRInfo.DefInst && "Register use before def (or no def)!");
335 // Only mark it alive only in the block we are representing.
336 MarkVirtRegAliveInBlock(VRInfo, MBB);
340 // Finally, if the last instruction in the block is a return, make sure to mark
341 // it as using all of the live-out values in the function.
342 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
343 MachineInstr *Ret = &MBB->back();
344 for (MachineFunction::liveout_iterator I = MF.liveout_begin(),
345 E = MF.liveout_end(); I != E; ++I) {
346 assert(MRegisterInfo::isPhysicalRegister(*I) &&
347 "Cannot have a live-in virtual register!");
348 HandlePhysRegUse(*I, Ret);
349 // Add live-out registers as implicit uses.
350 Ret->addRegOperand(*I, false, true);
354 // Loop over PhysRegInfo, killing any registers that are available at the
355 // end of the basic block. This also resets the PhysRegInfo map.
356 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
358 HandlePhysRegDef(i, 0);
361 // Convert and transfer the dead / killed information we have gathered into
362 // VirtRegInfo onto MI's.
364 for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
365 for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
366 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
367 addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
368 VirtRegInfo[i].Kills[j]);
370 addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
371 VirtRegInfo[i].Kills[j]);
374 // Check to make sure there are no unreachable blocks in the MC CFG for the
375 // function. If so, it is due to a bug in the instruction selector or some
376 // other part of the code generator if this happens.
378 for(MachineFunction::iterator i = MF.begin(), e = MF.end(); i != e; ++i)
379 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
386 /// instructionChanged - When the address of an instruction changes, this
387 /// method should be called so that live variables can update its internal
388 /// data structures. This removes the records for OldMI, transfering them to
389 /// the records for NewMI.
390 void LiveVariables::instructionChanged(MachineInstr *OldMI,
391 MachineInstr *NewMI) {
392 // If the instruction defines any virtual registers, update the VarInfo,
393 // kill and dead information for the instruction.
394 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
395 MachineOperand &MO = OldMI->getOperand(i);
396 if (MO.isRegister() && MO.getReg() &&
397 MRegisterInfo::isVirtualRegister(MO.getReg())) {
398 unsigned Reg = MO.getReg();
399 VarInfo &VI = getVarInfo(Reg);
403 addVirtualRegisterDead(Reg, NewMI);
405 // Update the defining instruction.
406 if (VI.DefInst == OldMI)
412 addVirtualRegisterKilled(Reg, NewMI);
414 // If this is a kill of the value, update the VI kills list.
415 if (VI.removeKill(OldMI))
416 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
422 /// removeVirtualRegistersKilled - Remove all killed info for the specified
424 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
425 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
426 MachineOperand &MO = MI->getOperand(i);
427 if (MO.isReg() && MO.isKill()) {
429 unsigned Reg = MO.getReg();
430 if (MRegisterInfo::isVirtualRegister(Reg)) {
431 bool removed = getVarInfo(Reg).removeKill(MI);
432 assert(removed && "kill not in register's VarInfo?");
438 /// removeVirtualRegistersDead - Remove all of the dead registers for the
439 /// specified instruction from the live variable information.
440 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
441 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
442 MachineOperand &MO = MI->getOperand(i);
443 if (MO.isReg() && MO.isDead()) {
445 unsigned Reg = MO.getReg();
446 if (MRegisterInfo::isVirtualRegister(Reg)) {
447 bool removed = getVarInfo(Reg).removeKill(MI);
448 assert(removed && "kill not in register's VarInfo?");
454 /// analyzePHINodes - Gather information about the PHI nodes in here. In
455 /// particular, we want to map the variable information of a virtual
456 /// register which is used in a PHI node. We map that to the BB the vreg is
459 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
460 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
462 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
463 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
464 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
465 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()].
466 push_back(BBI->getOperand(i).getReg());