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/CommandLine.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/STLExtras.h"
48 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
49 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
50 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
51 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
54 EnableReMat("2-addr-remat", cl::init(false), cl::Hidden,
55 cl::desc("Two-addr conversion should remat when possible."));
58 class VISIBILITY_HIDDEN TwoAddressInstructionPass
59 : public MachineFunctionPass {
60 const TargetInstrInfo *TII;
61 const TargetRegisterInfo *TRI;
62 MachineRegisterInfo *MRI;
65 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
67 MachineBasicBlock::iterator OldPos);
69 static char ID; // Pass identification, replacement for typeid
70 TwoAddressInstructionPass() : MachineFunctionPass((intptr_t)&ID) {}
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequired<LiveVariables>();
74 AU.addPreserved<LiveVariables>();
75 AU.addPreservedID(MachineLoopInfoID);
76 AU.addPreservedID(MachineDominatorsID);
77 AU.addPreservedID(PHIEliminationID);
78 MachineFunctionPass::getAnalysisUsage(AU);
81 /// runOnMachineFunction - Pass entry point.
82 bool runOnMachineFunction(MachineFunction&);
86 char TwoAddressInstructionPass::ID = 0;
87 static RegisterPass<TwoAddressInstructionPass>
88 X("twoaddressinstruction", "Two-Address instruction pass");
90 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
92 /// Sink3AddrInstruction - A two-address instruction has been converted to a
93 /// three-address instruction to avoid clobbering a register. Try to sink it
94 /// past the instruction that would kill the above mentioned register to reduce
95 /// register pressure.
97 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
98 MachineInstr *MI, unsigned SavedReg,
99 MachineBasicBlock::iterator OldPos) {
100 // Check if it's safe to move this instruction.
101 bool SeenStore = true; // Be conservative.
102 if (!MI->isSafeToMove(TII, SeenStore))
106 SmallSet<unsigned, 4> UseRegs;
108 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
109 const MachineOperand &MO = MI->getOperand(i);
110 if (!MO.isRegister())
112 unsigned MOReg = MO.getReg();
115 if (MO.isUse() && MOReg != SavedReg)
116 UseRegs.insert(MO.getReg());
120 // Don't try to move it if it implicitly defines a register.
123 // For now, don't move any instructions that define multiple registers.
125 DefReg = MO.getReg();
128 // Find the instruction that kills SavedReg.
129 MachineInstr *KillMI = NULL;
131 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
132 UE = MRI->use_end(); UI != UE; ++UI) {
133 MachineOperand &UseMO = UI.getOperand();
136 KillMI = UseMO.getParent();
140 if (!KillMI || KillMI->getParent() != MBB)
143 // If any of the definitions are used by another instruction between the
144 // position and the kill use, then it's not safe to sink it.
146 // FIXME: This can be sped up if there is an easy way to query whether an
147 // instruction if before or after another instruction. Then we can use
148 // MachineRegisterInfo def / use instead.
149 MachineOperand *KillMO = NULL;
150 MachineBasicBlock::iterator KillPos = KillMI;
153 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
154 MachineInstr *OtherMI = I;
156 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
157 MachineOperand &MO = OtherMI->getOperand(i);
158 if (!MO.isRegister())
160 unsigned MOReg = MO.getReg();
167 if (OtherMI == KillMI && MOReg == SavedReg)
168 // Save the operand that kills the register. We want unset the kill
169 // marker is we can sink MI past it.
171 else if (UseRegs.count(MOReg))
172 // One of the uses is killed before the destination.
178 // Update kill and LV information.
179 KillMO->setIsKill(false);
180 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
181 KillMO->setIsKill(true);
182 LiveVariables::VarInfo& VarInfo = LV->getVarInfo(SavedReg);
183 VarInfo.removeKill(KillMI);
184 VarInfo.Kills.push_back(MI);
186 // Move instruction to its destination.
188 MBB->insert(KillPos, MI);
194 /// runOnMachineFunction - Reduce two-address instructions to two operands.
196 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
197 DOUT << "Machine Function\n";
198 const TargetMachine &TM = MF.getTarget();
199 MRI = &MF.getRegInfo();
200 TII = TM.getInstrInfo();
201 TRI = TM.getRegisterInfo();
202 LV = &getAnalysis<LiveVariables>();
204 bool MadeChange = false;
206 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
207 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
209 SmallPtrSet<MachineInstr*, 8> ReMattedInstrs;
211 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
212 mbbi != mbbe; ++mbbi) {
213 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
215 MachineBasicBlock::iterator nmi = next(mi);
216 const TargetInstrDesc &TID = mi->getDesc();
217 bool FirstTied = true;
219 for (unsigned si = 1, e = TID.getNumOperands(); si < e; ++si) {
220 int ti = TID.getOperandConstraint(si, TOI::TIED_TO);
225 ++NumTwoAddressInstrs;
226 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
231 assert(mi->getOperand(si).isRegister() && mi->getOperand(si).getReg() &&
232 mi->getOperand(si).isUse() && "two address instruction invalid");
234 // If the two operands are the same we just remove the use
235 // and mark the def as def&use, otherwise we have to insert a copy.
236 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
242 unsigned regA = mi->getOperand(ti).getReg();
243 unsigned regB = mi->getOperand(si).getReg();
245 assert(TargetRegisterInfo::isVirtualRegister(regA) &&
246 TargetRegisterInfo::isVirtualRegister(regB) &&
247 "cannot update physical register live information");
250 // First, verify that we don't have a use of a in the instruction (a =
251 // b + a for example) because our transformation will not work. This
252 // should never occur because we are in SSA form.
253 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
254 assert((int)i == ti ||
255 !mi->getOperand(i).isRegister() ||
256 mi->getOperand(i).getReg() != regA);
259 // If this instruction is not the killing user of B, see if we can
260 // rearrange the code to make it so. Making it the killing user will
261 // allow us to coalesce A and B together, eliminating the copy we are
263 if (!mi->killsRegister(regB)) {
264 // If this instruction is commutative, check to see if C dies. If
265 // so, swap the B and C operands. This makes the live ranges of A
267 // FIXME: This code also works for A := B op C instructions.
268 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
269 assert(mi->getOperand(3-si).isRegister() &&
270 "Not a proper commutative instruction!");
271 unsigned regC = mi->getOperand(3-si).getReg();
273 if (mi->killsRegister(regC)) {
274 DOUT << "2addr: COMMUTING : " << *mi;
275 MachineInstr *NewMI = TII->commuteInstruction(mi);
278 DOUT << "2addr: COMMUTING FAILED!\n";
280 DOUT << "2addr: COMMUTED TO: " << *NewMI;
281 // If the instruction changed to commute it, update livevar.
283 LV->instructionChanged(mi, NewMI); // Update live variables
284 mbbi->insert(mi, NewMI); // Insert the new inst
285 mbbi->erase(mi); // Nuke the old inst.
291 goto InstructionRearranged;
296 // If this instruction is potentially convertible to a true
297 // three-address instruction,
298 if (TID.isConvertibleTo3Addr()) {
299 // FIXME: This assumes there are no more operands which are tied
300 // to another register.
302 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
303 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
306 if (MachineInstr *New=TII->convertToThreeAddress(mbbi, mi, *LV)) {
307 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
308 DOUT << "2addr: TO 3-ADDR: " << *New;
311 if (New->findRegisterUseOperand(regB, false, TRI))
312 // FIXME: Temporary workaround. If the new instruction doesn't
313 // uses regB, convertToThreeAddress must have created more
314 // then one instruction.
315 Sunk = Sink3AddrInstruction(mbbi, New, regB, mi);
317 mbbi->erase(mi); // Nuke the old inst.
324 ++NumConvertedTo3Addr;
325 break; // Done with this instruction.
330 InstructionRearranged:
331 const TargetRegisterClass* rc = MF.getRegInfo().getRegClass(regA);
332 MachineInstr *Orig = MRI->getVRegDef(regB);
333 const TargetInstrDesc &OrigTID = Orig->getDesc();
334 bool SawStore = false;
336 if (EnableReMat && Orig && Orig->isSafeToMove(TII, SawStore) &&
337 OrigTID.isAsCheapAsAMove() && !OrigTID.mayLoad() &&
338 !OrigTID.isSimpleLoad()) {
339 DEBUG(cerr << "2addr: REMATTING : " << *Orig << "\n");
340 TII->reMaterialize(*mbbi, mi, regA, Orig);
341 ReMattedInstrs.insert(Orig);
343 TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
346 MachineBasicBlock::iterator prevMi = prior(mi);
347 DOUT << "\t\tprepend:\t"; DEBUG(prevMi->print(*cerr.stream(), &TM));
349 // Update live variables for regB.
350 LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
352 // regB is used in this BB.
353 varInfoB.UsedBlocks[mbbi->getNumber()] = true;
355 if (LV->removeVirtualRegisterKilled(regB, mbbi, mi))
356 LV->addVirtualRegisterKilled(regB, prevMi);
358 if (LV->removeVirtualRegisterDead(regB, mbbi, mi))
359 LV->addVirtualRegisterDead(regB, prevMi);
361 // Replace all occurences of regB with regA.
362 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
363 if (mi->getOperand(i).isRegister() &&
364 mi->getOperand(i).getReg() == regB)
365 mi->getOperand(i).setReg(regA);
369 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
370 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
373 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
381 // Check to see if the instructions that we rematerialized are now dead. If
382 // they are, expunge them here.
383 SmallPtrSet<MachineInstr*, 8>::iterator I = ReMattedInstrs.begin();
384 SmallPtrSet<MachineInstr*, 8>::iterator E = ReMattedInstrs.end();
386 for (; I != E; ++I) {
387 MachineInstr *MI = *I;
388 bool InstrDead = true;
390 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
391 const MachineOperand &MO = MI->getOperand(i);
392 if (!MO.isRegister())
394 unsigned MOReg = MO.getReg();
396 if (!MOReg || !MO.isDef() || (MO.isImplicit() && MO.isDead()))
399 if (MRI->use_begin(MOReg) != MRI->use_end()) {
406 MI->eraseFromParent();