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 char LiveVariables::ID = 0;
41 static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
43 void LiveVariables::VarInfo::dump() const {
44 cerr << "Register Defined by: ";
49 cerr << " Alive in blocks: ";
50 for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
51 if (AliveBlocks[i]) cerr << i << ", ";
52 cerr << "\n Killed by:";
54 cerr << " No instructions.\n";
56 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
57 cerr << "\n #" << i << ": " << *Kills[i];
62 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
63 assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
64 "getVarInfo: not a virtual register!");
65 RegIdx -= MRegisterInfo::FirstVirtualRegister;
66 if (RegIdx >= VirtRegInfo.size()) {
67 if (RegIdx >= 2*VirtRegInfo.size())
68 VirtRegInfo.resize(RegIdx*2);
70 VirtRegInfo.resize(2*VirtRegInfo.size());
72 VarInfo &VI = VirtRegInfo[RegIdx];
73 VI.AliveBlocks.resize(MF->getNumBlockIDs());
77 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
78 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
79 MachineOperand &MO = MI->getOperand(i);
80 if (MO.isReg() && MO.isKill()) {
81 if ((MO.getReg() == Reg) ||
82 (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
83 MRegisterInfo::isPhysicalRegister(Reg) &&
84 RegInfo->isSubRegister(MO.getReg(), Reg)))
91 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
92 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
93 MachineOperand &MO = MI->getOperand(i);
94 if (MO.isReg() && MO.isDead()) {
95 if ((MO.getReg() == Reg) ||
96 (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
97 MRegisterInfo::isPhysicalRegister(Reg) &&
98 RegInfo->isSubRegister(MO.getReg(), Reg)))
105 bool LiveVariables::ModifiesRegister(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.isDef() && MO.getReg() == Reg)
114 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
115 MachineBasicBlock *MBB,
116 std::vector<MachineBasicBlock*> &WorkList) {
117 unsigned BBNum = MBB->getNumber();
119 // Check to see if this basic block is one of the killing blocks. If so,
121 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
122 if (VRInfo.Kills[i]->getParent() == MBB) {
123 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
127 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
129 if (VRInfo.AliveBlocks[BBNum])
130 return; // We already know the block is live
132 // Mark the variable known alive in this bb
133 VRInfo.AliveBlocks[BBNum] = true;
135 for (MachineBasicBlock::const_pred_reverse_iterator PI = MBB->pred_rbegin(),
136 E = MBB->pred_rend(); PI != E; ++PI)
137 WorkList.push_back(*PI);
140 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
141 MachineBasicBlock *MBB) {
142 std::vector<MachineBasicBlock*> WorkList;
143 MarkVirtRegAliveInBlock(VRInfo, MBB, WorkList);
144 while (!WorkList.empty()) {
145 MachineBasicBlock *Pred = WorkList.back();
147 MarkVirtRegAliveInBlock(VRInfo, Pred, WorkList);
152 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
154 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 // If this virtual register is already marked as alive in this basic block,
176 // that means it is alive in at least one of the successor block, it's not
178 if (!VRInfo.AliveBlocks[MBB->getNumber()])
179 VRInfo.Kills.push_back(MI);
181 // Update all dominating blocks to mark them known live.
182 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
183 E = MBB->pred_end(); PI != E; ++PI)
184 MarkVirtRegAliveInBlock(VRInfo, *PI);
187 bool LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI,
188 bool AddIfNotFound) {
190 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
191 MachineOperand &MO = MI->getOperand(i);
192 if (MO.isReg() && MO.isUse()) {
193 unsigned Reg = MO.getReg();
196 if (Reg == IncomingReg) {
200 } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
201 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
202 RegInfo->isSuperRegister(IncomingReg, Reg) &&
204 // A super-register kill already exists.
209 // If not found, this means an alias of one of the operand is killed. Add a
210 // new implicit operand if required.
211 if (!Found && AddIfNotFound) {
212 MI->addRegOperand(IncomingReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
218 bool LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI,
219 bool AddIfNotFound) {
221 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
222 MachineOperand &MO = MI->getOperand(i);
223 if (MO.isReg() && MO.isDef()) {
224 unsigned Reg = MO.getReg();
227 if (Reg == IncomingReg) {
231 } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
232 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
233 RegInfo->isSuperRegister(IncomingReg, Reg) &&
235 // There exists a super-register that's marked dead.
240 // If not found, this means an alias of one of the operand is dead. Add a
241 // new implicit operand.
242 if (!Found && AddIfNotFound) {
243 MI->addRegOperand(IncomingReg, true/*IsDef*/,true/*IsImp*/,false/*IsKill*/,
250 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
251 // There is a now a proper use, forget about the last partial use.
252 PhysRegPartUse[Reg] = NULL;
254 // Turn previous partial def's into read/mod/write.
255 for (unsigned i = 0, e = PhysRegPartDef[Reg].size(); i != e; ++i) {
256 MachineInstr *Def = PhysRegPartDef[Reg][i];
257 // First one is just a def. This means the use is reading some undef bits.
259 Def->addRegOperand(Reg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
260 Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
262 PhysRegPartDef[Reg].clear();
264 // There was an earlier def of a super-register. Add implicit def to that MI.
267 // Add implicit def to A.
268 if (PhysRegInfo[Reg] && !PhysRegUsed[Reg]) {
269 MachineInstr *Def = PhysRegInfo[Reg];
270 if (!Def->findRegisterDefOperand(Reg))
271 Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
274 PhysRegInfo[Reg] = MI;
275 PhysRegUsed[Reg] = true;
277 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
278 unsigned SubReg = *SubRegs; ++SubRegs) {
279 PhysRegInfo[SubReg] = MI;
280 PhysRegUsed[SubReg] = true;
283 // Remember the partial uses.
284 for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
285 unsigned SuperReg = *SuperRegs; ++SuperRegs)
286 PhysRegPartUse[SuperReg] = MI;
289 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
290 // Does this kill a previous version of this register?
291 if (MachineInstr *LastRef = PhysRegInfo[Reg]) {
292 if (PhysRegUsed[Reg])
293 addRegisterKilled(Reg, LastRef);
294 else if (PhysRegPartUse[Reg])
295 // Add implicit use / kill to last use of a sub-register.
296 addRegisterKilled(Reg, PhysRegPartUse[Reg], true);
298 addRegisterDead(Reg, LastRef);
300 PhysRegInfo[Reg] = MI;
301 PhysRegUsed[Reg] = false;
302 PhysRegPartUse[Reg] = NULL;
304 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
305 unsigned SubReg = *SubRegs; ++SubRegs) {
306 if (MachineInstr *LastRef = PhysRegInfo[SubReg]) {
307 if (PhysRegUsed[SubReg])
308 addRegisterKilled(SubReg, LastRef);
309 else if (PhysRegPartUse[SubReg])
310 // Add implicit use / kill to last use of a sub-register.
311 addRegisterKilled(SubReg, PhysRegPartUse[SubReg], true);
313 addRegisterDead(SubReg, LastRef);
315 PhysRegInfo[SubReg] = MI;
316 PhysRegUsed[SubReg] = false;
320 for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
321 unsigned SuperReg = *SuperRegs; ++SuperRegs) {
322 if (PhysRegInfo[SuperReg]) {
323 // The larger register is previously defined. Now a smaller part is
324 // being re-defined. Treat it as read/mod/write.
326 // AX = EAX<imp-use,kill>, EAX<imp-def>
327 MI->addRegOperand(SuperReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
328 MI->addRegOperand(SuperReg, true/*IsDef*/,true/*IsImp*/);
329 PhysRegInfo[SuperReg] = MI;
330 PhysRegUsed[SuperReg] = false;
332 // Remember this partial def.
333 PhysRegPartDef[SuperReg].push_back(MI);
338 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
340 const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
341 RegInfo = MF->getTarget().getRegisterInfo();
342 assert(RegInfo && "Target doesn't have register information?");
344 ReservedRegisters = RegInfo->getReservedRegs(mf);
346 unsigned NumRegs = RegInfo->getNumRegs();
347 PhysRegInfo = new MachineInstr*[NumRegs];
348 PhysRegUsed = new bool[NumRegs];
349 PhysRegPartUse = new MachineInstr*[NumRegs];
350 PhysRegPartDef = new SmallVector<MachineInstr*,4>[NumRegs];
351 PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
352 std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
353 std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
354 std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
356 /// Get some space for a respectable number of registers...
357 VirtRegInfo.resize(64);
361 // Calculate live variable information in depth first order on the CFG of the
362 // function. This guarantees that we will see the definition of a virtual
363 // register before its uses due to dominance properties of SSA (except for PHI
364 // nodes, which are treated as a special case).
366 MachineBasicBlock *Entry = MF->begin();
367 std::set<MachineBasicBlock*> Visited;
368 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
369 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
370 MachineBasicBlock *MBB = *DFI;
372 // Mark live-in registers as live-in.
373 for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
374 EE = MBB->livein_end(); II != EE; ++II) {
375 assert(MRegisterInfo::isPhysicalRegister(*II) &&
376 "Cannot have a live-in virtual register!");
377 HandlePhysRegDef(*II, 0);
380 // Loop over all of the instructions, processing them.
381 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
383 MachineInstr *MI = I;
385 // Process all of the operands of the instruction...
386 unsigned NumOperandsToProcess = MI->getNumOperands();
388 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
389 // of the uses. They will be handled in other basic blocks.
390 if (MI->getOpcode() == TargetInstrInfo::PHI)
391 NumOperandsToProcess = 1;
393 // Process all uses...
394 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
395 MachineOperand &MO = MI->getOperand(i);
396 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
397 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
398 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
399 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
400 !ReservedRegisters[MO.getReg()]) {
401 HandlePhysRegUse(MO.getReg(), MI);
406 // Process all defs...
407 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
408 MachineOperand &MO = MI->getOperand(i);
409 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
410 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
411 VarInfo &VRInfo = getVarInfo(MO.getReg());
413 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
416 VRInfo.Kills.push_back(MI);
417 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
418 !ReservedRegisters[MO.getReg()]) {
419 HandlePhysRegDef(MO.getReg(), MI);
425 // Handle any virtual assignments from PHI nodes which might be at the
426 // bottom of this basic block. We check all of our successor blocks to see
427 // if they have PHI nodes, and if so, we simulate an assignment at the end
428 // of the current block.
429 if (!PHIVarInfo[MBB->getNumber()].empty()) {
430 SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
432 for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
433 E = VarInfoVec.end(); I != E; ++I) {
434 VarInfo& VRInfo = getVarInfo(*I);
435 assert(VRInfo.DefInst && "Register use before def (or no def)!");
437 // Only mark it alive only in the block we are representing.
438 MarkVirtRegAliveInBlock(VRInfo, MBB);
442 // Finally, if the last instruction in the block is a return, make sure to mark
443 // it as using all of the live-out values in the function.
444 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
445 MachineInstr *Ret = &MBB->back();
446 for (MachineFunction::liveout_iterator I = MF->liveout_begin(),
447 E = MF->liveout_end(); I != E; ++I) {
448 assert(MRegisterInfo::isPhysicalRegister(*I) &&
449 "Cannot have a live-in virtual register!");
450 HandlePhysRegUse(*I, Ret);
451 // Add live-out registers as implicit uses.
452 if (Ret->findRegisterUseOperandIdx(*I) == -1)
453 Ret->addRegOperand(*I, false, true);
457 // Loop over PhysRegInfo, killing any registers that are available at the
458 // end of the basic block. This also resets the PhysRegInfo map.
459 for (unsigned i = 0; i != NumRegs; ++i)
461 HandlePhysRegDef(i, 0);
463 // Clear some states between BB's. These are purely local information.
464 for (unsigned i = 0; i != NumRegs; ++i)
465 PhysRegPartDef[i].clear();
466 std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
469 // Convert and transfer the dead / killed information we have gathered into
470 // VirtRegInfo onto MI's.
472 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
473 for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j) {
474 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
475 addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
476 VirtRegInfo[i].Kills[j]);
478 addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
479 VirtRegInfo[i].Kills[j]);
482 // Check to make sure there are no unreachable blocks in the MC CFG for the
483 // function. If so, it is due to a bug in the instruction selector or some
484 // other part of the code generator if this happens.
486 for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
487 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
490 delete[] PhysRegInfo;
491 delete[] PhysRegUsed;
492 delete[] PhysRegPartUse;
493 delete[] PhysRegPartDef;
499 /// instructionChanged - When the address of an instruction changes, this
500 /// method should be called so that live variables can update its internal
501 /// data structures. This removes the records for OldMI, transfering them to
502 /// the records for NewMI.
503 void LiveVariables::instructionChanged(MachineInstr *OldMI,
504 MachineInstr *NewMI) {
505 // If the instruction defines any virtual registers, update the VarInfo,
506 // kill and dead information for the instruction.
507 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
508 MachineOperand &MO = OldMI->getOperand(i);
509 if (MO.isRegister() && MO.getReg() &&
510 MRegisterInfo::isVirtualRegister(MO.getReg())) {
511 unsigned Reg = MO.getReg();
512 VarInfo &VI = getVarInfo(Reg);
516 addVirtualRegisterDead(Reg, NewMI);
518 // Update the defining instruction.
519 if (VI.DefInst == OldMI)
525 addVirtualRegisterKilled(Reg, NewMI);
527 // If this is a kill of the value, update the VI kills list.
528 if (VI.removeKill(OldMI))
529 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
535 /// removeVirtualRegistersKilled - Remove all killed info for the specified
537 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
538 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
539 MachineOperand &MO = MI->getOperand(i);
540 if (MO.isReg() && MO.isKill()) {
542 unsigned Reg = MO.getReg();
543 if (MRegisterInfo::isVirtualRegister(Reg)) {
544 bool removed = getVarInfo(Reg).removeKill(MI);
545 assert(removed && "kill not in register's VarInfo?");
551 /// removeVirtualRegistersDead - Remove all of the dead registers for the
552 /// specified instruction from the live variable information.
553 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
554 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
555 MachineOperand &MO = MI->getOperand(i);
556 if (MO.isReg() && MO.isDead()) {
558 unsigned Reg = MO.getReg();
559 if (MRegisterInfo::isVirtualRegister(Reg)) {
560 bool removed = getVarInfo(Reg).removeKill(MI);
561 assert(removed && "kill not in register's VarInfo?");
567 /// analyzePHINodes - Gather information about the PHI nodes in here. In
568 /// particular, we want to map the variable information of a virtual
569 /// register which is used in a PHI node. We map that to the BB the vreg is
572 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
573 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
575 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
576 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
577 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
578 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()->getNumber()].
579 push_back(BBI->getOperand(i).getReg());