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 ((MO.getReg() == Reg) ||
81 (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
82 MRegisterInfo::isPhysicalRegister(Reg) &&
83 RegInfo->isSubRegister(MO.getReg(), Reg)))
90 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
91 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
92 MachineOperand &MO = MI->getOperand(i);
93 if (MO.isReg() && MO.isDead()) {
94 if ((MO.getReg() == Reg) ||
95 (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
96 MRegisterInfo::isPhysicalRegister(Reg) &&
97 RegInfo->isSubRegister(MO.getReg(), Reg)))
104 bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
105 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
106 MachineOperand &MO = MI->getOperand(i);
107 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
113 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
114 MachineBasicBlock *MBB) {
115 unsigned BBNum = MBB->getNumber();
117 // Check to see if this basic block is one of the killing blocks. If so,
119 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
120 if (VRInfo.Kills[i]->getParent() == MBB) {
121 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
125 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
127 if (VRInfo.AliveBlocks[BBNum])
128 return; // We already know the block is live
130 // Mark the variable known alive in this bb
131 VRInfo.AliveBlocks[BBNum] = true;
133 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
134 E = MBB->pred_end(); PI != E; ++PI)
135 MarkVirtRegAliveInBlock(VRInfo, *PI);
138 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
140 assert(VRInfo.DefInst && "Register use before def!");
144 // Check to see if this basic block is already a kill block...
145 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
146 // Yes, this register is killed in this basic block already. Increase the
147 // live range by updating the kill instruction.
148 VRInfo.Kills.back() = MI;
153 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
154 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
157 assert(MBB != VRInfo.DefInst->getParent() &&
158 "Should have kill for defblock!");
160 // Add a new kill entry for this basic block.
161 // If this virtual register is already marked as alive in this basic block,
162 // that means it is alive in at least one of the successor block, it's not
164 if (!VRInfo.AliveBlocks[MBB->getNumber()])
165 VRInfo.Kills.push_back(MI);
167 // Update all dominating blocks to mark them known live.
168 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
169 E = MBB->pred_end(); PI != E; ++PI)
170 MarkVirtRegAliveInBlock(VRInfo, *PI);
173 void LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI) {
175 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
176 MachineOperand &MO = MI->getOperand(i);
177 if (MO.isReg() && MO.isUse()) {
178 unsigned Reg = MO.getReg();
181 if (Reg == IncomingReg) {
185 } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
186 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
187 RegInfo->isSuperRegister(IncomingReg, Reg) &&
189 // A super-register kill already exists.
194 // If not found, this means an alias of one of the operand is killed. Add a
195 // new implicit operand.
197 MI->addRegOperand(IncomingReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
200 void LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI) {
202 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
203 MachineOperand &MO = MI->getOperand(i);
204 if (MO.isReg() && MO.isDef()) {
205 unsigned Reg = MO.getReg();
208 if (Reg == IncomingReg) {
212 } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
213 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
214 RegInfo->isSuperRegister(IncomingReg, Reg) &&
216 // There exists a super-register that's marked dead.
221 // If not found, this means an alias of one of the operand is dead. Add a
222 // new implicit operand.
224 MI->addRegOperand(IncomingReg, true/*IsDef*/,true/*IsImp*/,false/*IsKill*/,
228 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
229 // There is a now a proper use, forget about the last partial use.
230 PhysRegPartUse[Reg] = NULL;
232 // Turn previous partial def's into read/mod/write.
233 for (unsigned i = 0, e = PhysRegPartDef[Reg].size(); i != e; ++i) {
234 MachineInstr *Def = PhysRegPartDef[Reg][i];
235 // First one is just a def. This means the use is reading some undef bits.
237 Def->addRegOperand(Reg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
238 Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
240 PhysRegPartDef[Reg].clear();
242 // There was an earlier def of a super-register. Add implicit def to that MI.
245 // Add implicit def to A.
246 if (PhysRegInfo[Reg] && !PhysRegUsed[Reg]) {
247 MachineInstr *Def = PhysRegInfo[Reg];
248 if (!Def->findRegisterDefOperand(Reg))
249 Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
252 PhysRegInfo[Reg] = MI;
253 PhysRegUsed[Reg] = true;
255 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
256 unsigned SubReg = *SubRegs; ++SubRegs) {
257 PhysRegInfo[SubReg] = MI;
258 PhysRegUsed[SubReg] = true;
261 // Remember the partial uses.
262 for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
263 unsigned SuperReg = *SuperRegs; ++SuperRegs)
264 PhysRegPartUse[SuperReg] = MI;
267 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
268 // Does this kill a previous version of this register?
269 if (MachineInstr *LastRef = PhysRegInfo[Reg]) {
270 if (PhysRegUsed[Reg])
271 addRegisterKilled(Reg, LastRef);
272 else if (PhysRegPartUse[Reg])
273 // Add implicit use / kill to last use of a sub-register.
274 addRegisterKilled(Reg, PhysRegPartUse[Reg]);
276 addRegisterDead(Reg, LastRef);
278 PhysRegInfo[Reg] = MI;
279 PhysRegUsed[Reg] = false;
280 PhysRegPartUse[Reg] = NULL;
282 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
283 unsigned SubReg = *SubRegs; ++SubRegs) {
284 if (MachineInstr *LastRef = PhysRegInfo[SubReg]) {
285 if (PhysRegUsed[SubReg])
286 addRegisterKilled(SubReg, LastRef);
287 else if (PhysRegPartUse[SubReg])
288 // Add implicit use / kill to last use of a sub-register.
289 addRegisterKilled(SubReg, PhysRegPartUse[SubReg]);
291 addRegisterDead(SubReg, LastRef);
293 PhysRegInfo[SubReg] = MI;
294 PhysRegUsed[SubReg] = false;
298 for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
299 unsigned SuperReg = *SuperRegs; ++SuperRegs) {
300 if (PhysRegInfo[SuperReg]) {
301 // The larger register is previously defined. Now a smaller part is
302 // being re-defined. Treat it as read/mod/write.
304 // AX = EAX<imp-use,kill>, EAX<imp-def>
305 MI->addRegOperand(SuperReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
306 MI->addRegOperand(SuperReg, true/*IsDef*/,true/*IsImp*/);
307 PhysRegInfo[SuperReg] = MI;
308 PhysRegUsed[SuperReg] = false;
310 // Remember this partial def.
311 PhysRegPartDef[SuperReg].push_back(MI);
316 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
318 const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
319 RegInfo = MF->getTarget().getRegisterInfo();
320 assert(RegInfo && "Target doesn't have register information?");
322 ReservedRegisters = RegInfo->getReservedRegs(mf);
324 unsigned NumRegs = RegInfo->getNumRegs();
325 PhysRegInfo = new MachineInstr*[NumRegs];
326 PhysRegUsed = new bool[NumRegs];
327 PhysRegPartUse = new MachineInstr*[NumRegs];
328 PhysRegPartDef = new SmallVector<MachineInstr*,4>[NumRegs];
329 PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
330 std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
331 std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
332 std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
334 /// Get some space for a respectable number of registers...
335 VirtRegInfo.resize(64);
339 // Calculate live variable information in depth first order on the CFG of the
340 // function. This guarantees that we will see the definition of a virtual
341 // register before its uses due to dominance properties of SSA (except for PHI
342 // nodes, which are treated as a special case).
344 MachineBasicBlock *Entry = MF->begin();
345 std::set<MachineBasicBlock*> Visited;
346 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
347 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
348 MachineBasicBlock *MBB = *DFI;
350 // Mark live-in registers as live-in.
351 for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
352 EE = MBB->livein_end(); II != EE; ++II) {
353 assert(MRegisterInfo::isPhysicalRegister(*II) &&
354 "Cannot have a live-in virtual register!");
355 HandlePhysRegDef(*II, 0);
358 // Loop over all of the instructions, processing them.
359 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
361 MachineInstr *MI = I;
363 // Process all of the operands of the instruction...
364 unsigned NumOperandsToProcess = MI->getNumOperands();
366 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
367 // of the uses. They will be handled in other basic blocks.
368 if (MI->getOpcode() == TargetInstrInfo::PHI)
369 NumOperandsToProcess = 1;
371 // Process all uses...
372 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
373 MachineOperand &MO = MI->getOperand(i);
374 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
375 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
376 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
377 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
378 !ReservedRegisters[MO.getReg()]) {
379 HandlePhysRegUse(MO.getReg(), MI);
384 // Process all defs...
385 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
386 MachineOperand &MO = MI->getOperand(i);
387 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
388 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
389 VarInfo &VRInfo = getVarInfo(MO.getReg());
391 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
394 VRInfo.Kills.push_back(MI);
395 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
396 !ReservedRegisters[MO.getReg()]) {
397 HandlePhysRegDef(MO.getReg(), MI);
403 // Handle any virtual assignments from PHI nodes which might be at the
404 // bottom of this basic block. We check all of our successor blocks to see
405 // if they have PHI nodes, and if so, we simulate an assignment at the end
406 // of the current block.
407 if (!PHIVarInfo[MBB->getNumber()].empty()) {
408 SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
410 for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
411 E = VarInfoVec.end(); I != E; ++I) {
412 VarInfo& VRInfo = getVarInfo(*I);
413 assert(VRInfo.DefInst && "Register use before def (or no def)!");
415 // Only mark it alive only in the block we are representing.
416 MarkVirtRegAliveInBlock(VRInfo, MBB);
420 // Finally, if the last instruction in the block is a return, make sure to mark
421 // it as using all of the live-out values in the function.
422 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
423 MachineInstr *Ret = &MBB->back();
424 for (MachineFunction::liveout_iterator I = MF->liveout_begin(),
425 E = MF->liveout_end(); I != E; ++I) {
426 assert(MRegisterInfo::isPhysicalRegister(*I) &&
427 "Cannot have a live-in virtual register!");
428 HandlePhysRegUse(*I, Ret);
429 // Add live-out registers as implicit uses.
430 Ret->addRegOperand(*I, false, true);
434 // Loop over PhysRegInfo, killing any registers that are available at the
435 // end of the basic block. This also resets the PhysRegInfo map.
436 for (unsigned i = 0; i != NumRegs; ++i)
438 HandlePhysRegDef(i, 0);
440 // Clear some states between BB's. These are purely local information.
441 for (unsigned i = 0; i != NumRegs; ++i)
442 PhysRegPartDef[i].clear();
443 std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
446 // Convert and transfer the dead / killed information we have gathered into
447 // VirtRegInfo onto MI's.
449 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
450 for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j) {
451 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
452 addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
453 VirtRegInfo[i].Kills[j]);
455 addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
456 VirtRegInfo[i].Kills[j]);
459 // Check to make sure there are no unreachable blocks in the MC CFG for the
460 // function. If so, it is due to a bug in the instruction selector or some
461 // other part of the code generator if this happens.
463 for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
464 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
467 delete[] PhysRegInfo;
468 delete[] PhysRegUsed;
469 delete[] PhysRegPartUse;
470 delete[] PhysRegPartDef;
476 /// instructionChanged - When the address of an instruction changes, this
477 /// method should be called so that live variables can update its internal
478 /// data structures. This removes the records for OldMI, transfering them to
479 /// the records for NewMI.
480 void LiveVariables::instructionChanged(MachineInstr *OldMI,
481 MachineInstr *NewMI) {
482 // If the instruction defines any virtual registers, update the VarInfo,
483 // kill and dead information for the instruction.
484 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
485 MachineOperand &MO = OldMI->getOperand(i);
486 if (MO.isRegister() && MO.getReg() &&
487 MRegisterInfo::isVirtualRegister(MO.getReg())) {
488 unsigned Reg = MO.getReg();
489 VarInfo &VI = getVarInfo(Reg);
493 addVirtualRegisterDead(Reg, NewMI);
495 // Update the defining instruction.
496 if (VI.DefInst == OldMI)
502 addVirtualRegisterKilled(Reg, NewMI);
504 // If this is a kill of the value, update the VI kills list.
505 if (VI.removeKill(OldMI))
506 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
512 /// removeVirtualRegistersKilled - Remove all killed info for the specified
514 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
515 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
516 MachineOperand &MO = MI->getOperand(i);
517 if (MO.isReg() && MO.isKill()) {
519 unsigned Reg = MO.getReg();
520 if (MRegisterInfo::isVirtualRegister(Reg)) {
521 bool removed = getVarInfo(Reg).removeKill(MI);
522 assert(removed && "kill not in register's VarInfo?");
528 /// removeVirtualRegistersDead - Remove all of the dead registers for the
529 /// specified instruction from the live variable information.
530 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
531 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
532 MachineOperand &MO = MI->getOperand(i);
533 if (MO.isReg() && MO.isDead()) {
535 unsigned Reg = MO.getReg();
536 if (MRegisterInfo::isVirtualRegister(Reg)) {
537 bool removed = getVarInfo(Reg).removeKill(MI);
538 assert(removed && "kill not in register's VarInfo?");
544 /// analyzePHINodes - Gather information about the PHI nodes in here. In
545 /// particular, we want to map the variable information of a virtual
546 /// register which is used in a PHI node. We map that to the BB the vreg is
549 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
550 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
552 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
553 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
554 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
555 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()->getNumber()].
556 push_back(BBI->getOperand(i).getReg());