1 //===- DeadMachineInstructionElim.cpp - Remove dead machine instructions --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is an extremely simple MachineInstr-level dead-code-elimination pass.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/Passes.h"
15 #include "llvm/Pass.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetMachine.h"
24 class VISIBILITY_HIDDEN DeadMachineInstructionElim :
25 public MachineFunctionPass {
26 virtual bool runOnMachineFunction(MachineFunction &MF);
29 static char ID; // Pass identification, replacement for typeid
30 DeadMachineInstructionElim() : MachineFunctionPass(&ID) {}
33 char DeadMachineInstructionElim::ID = 0;
35 static RegisterPass<DeadMachineInstructionElim>
36 Y("dead-mi-elimination",
37 "Remove dead machine instructions");
39 FunctionPass *llvm::createDeadMachineInstructionElimPass() {
40 return new DeadMachineInstructionElim();
43 bool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {
44 bool AnyChanges = false;
45 const MachineRegisterInfo &MRI = MF.getRegInfo();
46 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
49 // Loop over all instructions in all blocks, from bottom to top, so that it's
50 // more likely that chains of dependent but ultimately dead instructions will
52 for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
54 MachineBasicBlock *MBB = &*I;
55 for (MachineBasicBlock::reverse_iterator MII = MBB->rbegin(),
56 MIE = MBB->rend(); MII != MIE; ) {
57 MachineInstr *MI = &*MII;
59 // Don't delete instructions with side effects.
60 if (MI->isSafeToMove(&TII, SawStore)) {
61 // Examine each operand.
62 bool AllDefsDead = true;
63 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
64 const MachineOperand &MO = MI->getOperand(i);
65 if (MO.isRegister() && MO.isDef()) {
66 unsigned Reg = MO.getReg();
67 if ((!MO.isImplicit() &&
68 TargetRegisterInfo::isPhysicalRegister(Reg)) ||
69 !MRI.use_empty(Reg)) {
70 // This def has a use. Don't delete the instruction!
77 // If there are no defs with uses, the instruction is dead.
79 // Clear out the operands to take the registers out of their
81 while (unsigned Num = MI->getNumOperands())
82 MI->RemoveOperand(Num-1);
84 // Delete the actual instruction.
86 MI->eraseFromParent();
88 // MII is now pointing to the next instruction to process,
89 // so don't increment it.
93 // We didn't delete the current instruction, so increment MII to