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 bool LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI,
174 bool AddIfNotFound) {
176 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
177 MachineOperand &MO = MI->getOperand(i);
178 if (MO.isReg() && MO.isUse()) {
179 unsigned Reg = MO.getReg();
182 if (Reg == IncomingReg) {
186 } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
187 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
188 RegInfo->isSuperRegister(IncomingReg, Reg) &&
190 // A super-register kill already exists.
195 // If not found, this means an alias of one of the operand is killed. Add a
196 // new implicit operand if required.
197 if (!Found && AddIfNotFound) {
198 MI->addRegOperand(IncomingReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
204 bool LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI,
205 bool AddIfNotFound) {
207 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
208 MachineOperand &MO = MI->getOperand(i);
209 if (MO.isReg() && MO.isDef()) {
210 unsigned Reg = MO.getReg();
213 if (Reg == IncomingReg) {
217 } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
218 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
219 RegInfo->isSuperRegister(IncomingReg, Reg) &&
221 // There exists a super-register that's marked dead.
226 // If not found, this means an alias of one of the operand is dead. Add a
227 // new implicit operand.
228 if (!Found && AddIfNotFound) {
229 MI->addRegOperand(IncomingReg, true/*IsDef*/,true/*IsImp*/,false/*IsKill*/,
236 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
237 // There is a now a proper use, forget about the last partial use.
238 PhysRegPartUse[Reg] = NULL;
240 // Turn previous partial def's into read/mod/write.
241 for (unsigned i = 0, e = PhysRegPartDef[Reg].size(); i != e; ++i) {
242 MachineInstr *Def = PhysRegPartDef[Reg][i];
243 // First one is just a def. This means the use is reading some undef bits.
245 Def->addRegOperand(Reg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
246 Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
248 PhysRegPartDef[Reg].clear();
250 // There was an earlier def of a super-register. Add implicit def to that MI.
253 // Add implicit def to A.
254 if (PhysRegInfo[Reg] && !PhysRegUsed[Reg]) {
255 MachineInstr *Def = PhysRegInfo[Reg];
256 if (!Def->findRegisterDefOperand(Reg))
257 Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
260 PhysRegInfo[Reg] = MI;
261 PhysRegUsed[Reg] = true;
263 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
264 unsigned SubReg = *SubRegs; ++SubRegs) {
265 PhysRegInfo[SubReg] = MI;
266 PhysRegUsed[SubReg] = true;
269 // Remember the partial uses.
270 for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
271 unsigned SuperReg = *SuperRegs; ++SuperRegs)
272 PhysRegPartUse[SuperReg] = MI;
275 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
276 // Does this kill a previous version of this register?
277 if (MachineInstr *LastRef = PhysRegInfo[Reg]) {
278 if (PhysRegUsed[Reg])
279 addRegisterKilled(Reg, LastRef);
280 else if (PhysRegPartUse[Reg])
281 // Add implicit use / kill to last use of a sub-register.
282 addRegisterKilled(Reg, PhysRegPartUse[Reg], true);
284 addRegisterDead(Reg, LastRef);
286 PhysRegInfo[Reg] = MI;
287 PhysRegUsed[Reg] = false;
288 PhysRegPartUse[Reg] = NULL;
290 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
291 unsigned SubReg = *SubRegs; ++SubRegs) {
292 if (MachineInstr *LastRef = PhysRegInfo[SubReg]) {
293 if (PhysRegUsed[SubReg])
294 addRegisterKilled(SubReg, LastRef);
295 else if (PhysRegPartUse[SubReg])
296 // Add implicit use / kill to last use of a sub-register.
297 addRegisterKilled(SubReg, PhysRegPartUse[SubReg], true);
299 addRegisterDead(SubReg, LastRef);
301 PhysRegInfo[SubReg] = MI;
302 PhysRegUsed[SubReg] = false;
306 for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
307 unsigned SuperReg = *SuperRegs; ++SuperRegs) {
308 if (PhysRegInfo[SuperReg]) {
309 // The larger register is previously defined. Now a smaller part is
310 // being re-defined. Treat it as read/mod/write.
312 // AX = EAX<imp-use,kill>, EAX<imp-def>
313 MI->addRegOperand(SuperReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
314 MI->addRegOperand(SuperReg, true/*IsDef*/,true/*IsImp*/);
315 PhysRegInfo[SuperReg] = MI;
316 PhysRegUsed[SuperReg] = false;
318 // Remember this partial def.
319 PhysRegPartDef[SuperReg].push_back(MI);
324 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
326 const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
327 RegInfo = MF->getTarget().getRegisterInfo();
328 assert(RegInfo && "Target doesn't have register information?");
330 ReservedRegisters = RegInfo->getReservedRegs(mf);
332 unsigned NumRegs = RegInfo->getNumRegs();
333 PhysRegInfo = new MachineInstr*[NumRegs];
334 PhysRegUsed = new bool[NumRegs];
335 PhysRegPartUse = new MachineInstr*[NumRegs];
336 PhysRegPartDef = new SmallVector<MachineInstr*,4>[NumRegs];
337 PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
338 std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
339 std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
340 std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
342 /// Get some space for a respectable number of registers...
343 VirtRegInfo.resize(64);
347 // Calculate live variable information in depth first order on the CFG of the
348 // function. This guarantees that we will see the definition of a virtual
349 // register before its uses due to dominance properties of SSA (except for PHI
350 // nodes, which are treated as a special case).
352 MachineBasicBlock *Entry = MF->begin();
353 std::set<MachineBasicBlock*> Visited;
354 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
355 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
356 MachineBasicBlock *MBB = *DFI;
358 // Mark live-in registers as live-in.
359 for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
360 EE = MBB->livein_end(); II != EE; ++II) {
361 assert(MRegisterInfo::isPhysicalRegister(*II) &&
362 "Cannot have a live-in virtual register!");
363 HandlePhysRegDef(*II, 0);
366 // Loop over all of the instructions, processing them.
367 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
369 MachineInstr *MI = I;
371 // Process all of the operands of the instruction...
372 unsigned NumOperandsToProcess = MI->getNumOperands();
374 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
375 // of the uses. They will be handled in other basic blocks.
376 if (MI->getOpcode() == TargetInstrInfo::PHI)
377 NumOperandsToProcess = 1;
379 // Process all uses...
380 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
381 MachineOperand &MO = MI->getOperand(i);
382 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
383 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
384 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
385 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
386 !ReservedRegisters[MO.getReg()]) {
387 HandlePhysRegUse(MO.getReg(), MI);
392 // Process all defs...
393 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
394 MachineOperand &MO = MI->getOperand(i);
395 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
396 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
397 VarInfo &VRInfo = getVarInfo(MO.getReg());
399 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
402 VRInfo.Kills.push_back(MI);
403 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
404 !ReservedRegisters[MO.getReg()]) {
405 HandlePhysRegDef(MO.getReg(), MI);
411 // Handle any virtual assignments from PHI nodes which might be at the
412 // bottom of this basic block. We check all of our successor blocks to see
413 // if they have PHI nodes, and if so, we simulate an assignment at the end
414 // of the current block.
415 if (!PHIVarInfo[MBB->getNumber()].empty()) {
416 SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
418 for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
419 E = VarInfoVec.end(); I != E; ++I) {
420 VarInfo& VRInfo = getVarInfo(*I);
421 assert(VRInfo.DefInst && "Register use before def (or no def)!");
423 // Only mark it alive only in the block we are representing.
424 MarkVirtRegAliveInBlock(VRInfo, MBB);
428 // Finally, if the last instruction in the block is a return, make sure to mark
429 // it as using all of the live-out values in the function.
430 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
431 MachineInstr *Ret = &MBB->back();
432 for (MachineFunction::liveout_iterator I = MF->liveout_begin(),
433 E = MF->liveout_end(); I != E; ++I) {
434 assert(MRegisterInfo::isPhysicalRegister(*I) &&
435 "Cannot have a live-in virtual register!");
436 HandlePhysRegUse(*I, Ret);
437 // Add live-out registers as implicit uses.
438 if (Ret->findRegisterUseOperandIdx(*I) == -1)
439 Ret->addRegOperand(*I, false, true);
443 // Loop over PhysRegInfo, killing any registers that are available at the
444 // end of the basic block. This also resets the PhysRegInfo map.
445 for (unsigned i = 0; i != NumRegs; ++i)
447 HandlePhysRegDef(i, 0);
449 // Clear some states between BB's. These are purely local information.
450 for (unsigned i = 0; i != NumRegs; ++i)
451 PhysRegPartDef[i].clear();
452 std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
455 // Convert and transfer the dead / killed information we have gathered into
456 // VirtRegInfo onto MI's.
458 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
459 for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j) {
460 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
461 addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
462 VirtRegInfo[i].Kills[j]);
464 addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
465 VirtRegInfo[i].Kills[j]);
468 // Check to make sure there are no unreachable blocks in the MC CFG for the
469 // function. If so, it is due to a bug in the instruction selector or some
470 // other part of the code generator if this happens.
472 for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
473 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
476 delete[] PhysRegInfo;
477 delete[] PhysRegUsed;
478 delete[] PhysRegPartUse;
479 delete[] PhysRegPartDef;
485 /// instructionChanged - When the address of an instruction changes, this
486 /// method should be called so that live variables can update its internal
487 /// data structures. This removes the records for OldMI, transfering them to
488 /// the records for NewMI.
489 void LiveVariables::instructionChanged(MachineInstr *OldMI,
490 MachineInstr *NewMI) {
491 // If the instruction defines any virtual registers, update the VarInfo,
492 // kill and dead information for the instruction.
493 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
494 MachineOperand &MO = OldMI->getOperand(i);
495 if (MO.isRegister() && MO.getReg() &&
496 MRegisterInfo::isVirtualRegister(MO.getReg())) {
497 unsigned Reg = MO.getReg();
498 VarInfo &VI = getVarInfo(Reg);
502 addVirtualRegisterDead(Reg, NewMI);
504 // Update the defining instruction.
505 if (VI.DefInst == OldMI)
511 addVirtualRegisterKilled(Reg, NewMI);
513 // If this is a kill of the value, update the VI kills list.
514 if (VI.removeKill(OldMI))
515 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
521 /// removeVirtualRegistersKilled - Remove all killed info for the specified
523 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
524 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
525 MachineOperand &MO = MI->getOperand(i);
526 if (MO.isReg() && MO.isKill()) {
528 unsigned Reg = MO.getReg();
529 if (MRegisterInfo::isVirtualRegister(Reg)) {
530 bool removed = getVarInfo(Reg).removeKill(MI);
531 assert(removed && "kill not in register's VarInfo?");
537 /// removeVirtualRegistersDead - Remove all of the dead registers for the
538 /// specified instruction from the live variable information.
539 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
540 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
541 MachineOperand &MO = MI->getOperand(i);
542 if (MO.isReg() && MO.isDead()) {
544 unsigned Reg = MO.getReg();
545 if (MRegisterInfo::isVirtualRegister(Reg)) {
546 bool removed = getVarInfo(Reg).removeKill(MI);
547 assert(removed && "kill not in register's VarInfo?");
553 /// analyzePHINodes - Gather information about the PHI nodes in here. In
554 /// particular, we want to map the variable information of a virtual
555 /// register which is used in a PHI node. We map that to the BB the vreg is
558 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
559 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
561 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
562 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
563 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
564 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()->getNumber()].
565 push_back(BBI->getOperand(i).getReg());