1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
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 file implements the TwoAddress instruction pass which is used
11 // by most register allocators. Two-Address instructions are rewritten
21 // Note that if a register allocator chooses to use this pass, that it
22 // has to be capable of handling the non-SSA nature of these rewritten
25 // It is also worth noting that the duplicate operand of the two
26 // address instruction is removed.
28 //===----------------------------------------------------------------------===//
30 #define DEBUG_TYPE "twoaddrinstr"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Function.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/STLExtras.h"
46 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
47 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
48 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
49 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
52 class VISIBILITY_HIDDEN TwoAddressInstructionPass
53 : public MachineFunctionPass {
54 const TargetInstrInfo *TII;
55 const TargetRegisterInfo *TRI;
56 MachineRegisterInfo *MRI;
59 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
61 MachineBasicBlock::iterator OldPos);
63 static char ID; // Pass identification, replacement for typeid
64 TwoAddressInstructionPass() : MachineFunctionPass((intptr_t)&ID) {}
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<LiveVariables>();
68 AU.addPreserved<LiveVariables>();
69 AU.addPreservedID(MachineLoopInfoID);
70 AU.addPreservedID(MachineDominatorsID);
71 AU.addPreservedID(PHIEliminationID);
72 MachineFunctionPass::getAnalysisUsage(AU);
75 /// runOnMachineFunction - Pass entry point.
76 bool runOnMachineFunction(MachineFunction&);
80 char TwoAddressInstructionPass::ID = 0;
81 static RegisterPass<TwoAddressInstructionPass>
82 X("twoaddressinstruction", "Two-Address instruction pass");
84 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
86 /// Sink3AddrInstruction - A two-address instruction has been converted to a
87 /// three-address instruction to avoid clobbering a register. Try to sink it
88 /// past the instruction that would kill the above mentioned register to reduce
89 /// register pressure.
91 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
92 MachineInstr *MI, unsigned SavedReg,
93 MachineBasicBlock::iterator OldPos) {
94 // Check if it's safe to move this instruction.
95 bool SeenStore = true; // Be conservative.
96 if (!MI->isSafeToMove(TII, SeenStore))
100 SmallSet<unsigned, 4> UseRegs;
102 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
103 const MachineOperand &MO = MI->getOperand(i);
104 if (!MO.isRegister())
106 unsigned MOReg = MO.getReg();
109 if (MO.isUse() && MOReg != SavedReg)
110 UseRegs.insert(MO.getReg());
114 // Don't try to move it if it implicitly defines a register.
117 // For now, don't move any instructions that define multiple registers.
119 DefReg = MO.getReg();
122 // Find the instruction that kills SavedReg.
123 MachineInstr *KillMI = NULL;
125 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
126 UE = MRI->use_end(); UI != UE; ++UI) {
127 MachineOperand &UseMO = UI.getOperand();
130 KillMI = UseMO.getParent();
134 if (!KillMI || KillMI->getParent() != MBB)
137 // If any of the definitions are used by another instruction between the
138 // position and the kill use, then it's not safe to sink it.
140 // FIXME: This can be sped up if there is an easy way to query whether an
141 // instruction if before or after another instruction. Then we can use
142 // MachineRegisterInfo def / use instead.
143 MachineOperand *KillMO = NULL;
144 MachineBasicBlock::iterator KillPos = KillMI;
147 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
148 MachineInstr *OtherMI = I;
150 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
151 MachineOperand &MO = OtherMI->getOperand(i);
152 if (!MO.isRegister())
154 unsigned MOReg = MO.getReg();
161 if (OtherMI == KillMI && MOReg == SavedReg)
162 // Save the operand that kills the register. We want unset the kill
163 // marker is we can sink MI past it.
165 else if (UseRegs.count(MOReg))
166 // One of the uses is killed before the destination.
172 // Update kill and LV information.
173 KillMO->setIsKill(false);
174 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
175 KillMO->setIsKill(true);
176 LiveVariables::VarInfo& VarInfo = LV->getVarInfo(SavedReg);
177 VarInfo.removeKill(KillMI);
178 VarInfo.Kills.push_back(MI);
180 // Move instruction to its destination.
182 MBB->insert(KillPos, MI);
188 /// runOnMachineFunction - Reduce two-address instructions to two operands.
190 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
191 DOUT << "Machine Function\n";
192 const TargetMachine &TM = MF.getTarget();
193 MRI = &MF.getRegInfo();
194 TII = TM.getInstrInfo();
195 TRI = TM.getRegisterInfo();
196 LV = &getAnalysis<LiveVariables>();
198 bool MadeChange = false;
200 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
201 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
203 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
204 mbbi != mbbe; ++mbbi) {
205 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
207 MachineBasicBlock::iterator nmi = next(mi);
208 const TargetInstrDesc &TID = mi->getDesc();
209 bool FirstTied = true;
211 for (unsigned si = 1, e = TID.getNumOperands(); si < e; ++si) {
212 int ti = TID.getOperandConstraint(si, TOI::TIED_TO);
217 ++NumTwoAddressInstrs;
218 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
223 assert(mi->getOperand(si).isRegister() && mi->getOperand(si).getReg() &&
224 mi->getOperand(si).isUse() && "two address instruction invalid");
226 // If the two operands are the same we just remove the use
227 // and mark the def as def&use, otherwise we have to insert a copy.
228 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
234 unsigned regA = mi->getOperand(ti).getReg();
235 unsigned regB = mi->getOperand(si).getReg();
237 assert(TargetRegisterInfo::isVirtualRegister(regA) &&
238 TargetRegisterInfo::isVirtualRegister(regB) &&
239 "cannot update physical register live information");
242 // First, verify that we don't have a use of a in the instruction (a =
243 // b + a for example) because our transformation will not work. This
244 // should never occur because we are in SSA form.
245 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
246 assert((int)i == ti ||
247 !mi->getOperand(i).isRegister() ||
248 mi->getOperand(i).getReg() != regA);
251 // If this instruction is not the killing user of B, see if we can
252 // rearrange the code to make it so. Making it the killing user will
253 // allow us to coalesce A and B together, eliminating the copy we are
255 if (!mi->killsRegister(regB)) {
256 // If this instruction is commutative, check to see if C dies. If
257 // so, swap the B and C operands. This makes the live ranges of A
259 // FIXME: This code also works for A := B op C instructions.
260 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
261 assert(mi->getOperand(3-si).isRegister() &&
262 "Not a proper commutative instruction!");
263 unsigned regC = mi->getOperand(3-si).getReg();
265 if (mi->killsRegister(regC)) {
266 DOUT << "2addr: COMMUTING : " << *mi;
267 MachineInstr *NewMI = TII->commuteInstruction(mi);
270 DOUT << "2addr: COMMUTING FAILED!\n";
272 DOUT << "2addr: COMMUTED TO: " << *NewMI;
273 // If the instruction changed to commute it, update livevar.
275 LV->instructionChanged(mi, NewMI); // Update live variables
276 mbbi->insert(mi, NewMI); // Insert the new inst
277 mbbi->erase(mi); // Nuke the old inst.
283 goto InstructionRearranged;
288 // If this instruction is potentially convertible to a true
289 // three-address instruction,
290 if (TID.isConvertibleTo3Addr()) {
291 // FIXME: This assumes there are no more operands which are tied
292 // to another register.
294 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
295 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
298 if (MachineInstr *New=TII->convertToThreeAddress(mbbi, mi, *LV)) {
299 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
300 DOUT << "2addr: TO 3-ADDR: " << *New;
303 if (New->findRegisterUseOperand(regB, false, TRI))
304 // FIXME: Temporary workaround. If the new instruction doesn't
305 // uses regB, convertToThreeAddress must have created more
306 // then one instruction.
307 Sunk = Sink3AddrInstruction(mbbi, New, regB, mi);
309 mbbi->erase(mi); // Nuke the old inst.
316 ++NumConvertedTo3Addr;
317 break; // Done with this instruction.
322 InstructionRearranged:
323 const TargetRegisterClass* rc = MF.getRegInfo().getRegClass(regA);
324 TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
326 MachineBasicBlock::iterator prevMi = prior(mi);
327 DOUT << "\t\tprepend:\t"; DEBUG(prevMi->print(*cerr.stream(), &TM));
329 // Update live variables for regB.
330 LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
332 // regB is used in this BB.
333 varInfoB.UsedBlocks[mbbi->getNumber()] = true;
335 if (LV->removeVirtualRegisterKilled(regB, mbbi, mi))
336 LV->addVirtualRegisterKilled(regB, prevMi);
338 if (LV->removeVirtualRegisterDead(regB, mbbi, mi))
339 LV->addVirtualRegisterDead(regB, prevMi);
341 // Replace all occurences of regB with regA.
342 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
343 if (mi->getOperand(i).isRegister() &&
344 mi->getOperand(i).getReg() == regB)
345 mi->getOperand(i).setReg(regA);
349 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
350 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
353 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));