For PR1284:
[oota-llvm.git] / lib / CodeGen / TwoAddressInstructionPass.cpp
1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the TwoAddress instruction pass which is used
11 // by most register allocators. Two-Address instructions are rewritten
12 // from:
13 //
14 //     A = B op C
15 //
16 // to:
17 //
18 //     A = B
19 //     A op= C
20 //
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
23 // virtual registers.
24 //
25 // It is also worth noting that the duplicate operand of the two
26 // address instruction is removed.
27 //
28 //===----------------------------------------------------------------------===//
29
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/SSARegMap.h"
37 #include "llvm/Target/MRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/STLExtras.h"
44 using namespace llvm;
45
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
50 namespace {
51   struct VISIBILITY_HIDDEN TwoAddressInstructionPass
52    : public MachineFunctionPass {
53     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
54
55     /// runOnMachineFunction - pass entry point
56     bool runOnMachineFunction(MachineFunction&);
57   };
58
59   RegisterPass<TwoAddressInstructionPass>
60   X("twoaddressinstruction", "Two-Address instruction pass");
61 }
62
63 const PassInfo *llvm::TwoAddressInstructionPassID = X.getPassInfo();
64
65 void TwoAddressInstructionPass::getAnalysisUsage(AnalysisUsage &AU) const {
66   AU.addRequired<LiveVariables>();
67   AU.addPreserved<LiveVariables>();
68   AU.addPreservedID(PHIEliminationID);
69   MachineFunctionPass::getAnalysisUsage(AU);
70 }
71
72 /// runOnMachineFunction - Reduce two-address instructions to two
73 /// operands.
74 ///
75 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
76   DOUT << "Machine Function\n";
77   const TargetMachine &TM = MF.getTarget();
78   const TargetInstrInfo &TII = *TM.getInstrInfo();
79   const MRegisterInfo &MRI = *TM.getRegisterInfo();
80   LiveVariables &LV = getAnalysis<LiveVariables>();
81
82   bool MadeChange = false;
83
84   DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
85   DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
86
87   for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
88        mbbi != mbbe; ++mbbi) {
89     for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
90          mi != me; ++mi) {
91       const TargetInstrDescriptor *TID = mi->getInstrDescriptor();
92
93       bool FirstTied = true;
94       for (unsigned si = 1, e = TID->numOperands; si < e; ++si) {
95         int ti = TID->getOperandConstraint(si, TOI::TIED_TO);
96         if (ti == -1)
97           continue;
98
99         if (FirstTied) {
100           ++NumTwoAddressInstrs;
101           DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
102         }
103         FirstTied = false;
104
105         assert(mi->getOperand(si).isRegister() && mi->getOperand(si).getReg() &&
106                mi->getOperand(si).isUse() && "two address instruction invalid");
107
108         // if the two operands are the same we just remove the use
109         // and mark the def as def&use, otherwise we have to insert a copy.
110         if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
111           // rewrite:
112           //     a = b op c
113           // to:
114           //     a = b
115           //     a = a op c
116           unsigned regA = mi->getOperand(ti).getReg();
117           unsigned regB = mi->getOperand(si).getReg();
118
119           assert(MRegisterInfo::isVirtualRegister(regA) &&
120                  MRegisterInfo::isVirtualRegister(regB) &&
121                  "cannot update physical register live information");
122
123 #ifndef NDEBUG
124           // First, verify that we don't have a use of a in the instruction (a =
125           // b + a for example) because our transformation will not work. This
126           // should never occur because we are in SSA form.
127           for (unsigned i = 0; i != mi->getNumOperands(); ++i)
128             assert((int)i == ti ||
129                    !mi->getOperand(i).isRegister() ||
130                    mi->getOperand(i).getReg() != regA);
131 #endif
132
133           // If this instruction is not the killing user of B, see if we can
134           // rearrange the code to make it so.  Making it the killing user will
135           // allow us to coalesce A and B together, eliminating the copy we are
136           // about to insert.
137           if (!LV.KillsRegister(mi, regB)) {
138             // If this instruction is commutative, check to see if C dies.  If
139             // so, swap the B and C operands.  This makes the live ranges of A
140             // and C joinable.
141             // FIXME: This code also works for A := B op C instructions.
142             if ((TID->Flags & M_COMMUTABLE) && mi->getNumOperands() == 3) {
143               assert(mi->getOperand(3-si).isRegister() &&
144                      "Not a proper commutative instruction!");
145               unsigned regC = mi->getOperand(3-si).getReg();
146               if (LV.KillsRegister(mi, regC)) {
147                 DOUT << "2addr: COMMUTING  : " << *mi;
148                 MachineInstr *NewMI = TII.commuteInstruction(mi);
149                 if (NewMI == 0) {
150                   DOUT << "2addr: COMMUTING FAILED!\n";
151                 } else {
152                   DOUT << "2addr: COMMUTED TO: " << *NewMI;
153                   // If the instruction changed to commute it, update livevar.
154                   if (NewMI != mi) {
155                     LV.instructionChanged(mi, NewMI);  // Update live variables
156                     mbbi->insert(mi, NewMI);           // Insert the new inst
157                     mbbi->erase(mi);                   // Nuke the old inst.
158                     mi = NewMI;
159                   }
160
161                   ++NumCommuted;
162                   regB = regC;
163                   goto InstructionRearranged;
164                 }
165               }
166             }
167
168             // If this instruction is potentially convertible to a true
169             // three-address instruction,
170             if (TID->Flags & M_CONVERTIBLE_TO_3_ADDR)
171               // FIXME: This assumes there are no more operands which are tied
172               // to another register.
173 #ifndef NDEBUG
174               for (unsigned i = si+1, e = TID->numOperands; i < e; ++i)
175                 assert(TID->getOperandConstraint(i, TOI::TIED_TO) == -1);
176 #endif
177
178               if (MachineInstr *New = TII.convertToThreeAddress(mbbi, mi, LV)) {
179                 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
180                 DOUT << "2addr:         TO 3-ADDR: " << *New;
181                 mbbi->erase(mi);                 // Nuke the old inst.
182                 mi = New;
183                 ++NumConvertedTo3Addr;
184                 // Done with this instruction.
185                 break;
186               }
187           }
188
189         InstructionRearranged:
190           const TargetRegisterClass* rc = MF.getSSARegMap()->getRegClass(regA);
191           MRI.copyRegToReg(*mbbi, mi, regA, regB, rc);
192
193           MachineBasicBlock::iterator prevMi = prior(mi);
194           DOUT << "\t\tprepend:\t"; DEBUG(prevMi->print(*cerr.stream(), &TM));
195
196           // Update live variables for regA
197           LiveVariables::VarInfo& varInfo = LV.getVarInfo(regA);
198           varInfo.DefInst = prevMi;
199
200           // update live variables for regB
201           LiveVariables::VarInfo& varInfoB = LV.getVarInfo(regB);
202           // regB is used in this BB.
203           varInfoB.UsedBlocks[mbbi->getNumber()] = true;
204           if (LV.removeVirtualRegisterKilled(regB, mbbi, mi))
205             LV.addVirtualRegisterKilled(regB, prevMi);
206
207           if (LV.removeVirtualRegisterDead(regB, mbbi, mi))
208             LV.addVirtualRegisterDead(regB, prevMi);
209
210           // replace all occurences of regB with regA
211           for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
212             if (mi->getOperand(i).isRegister() &&
213                 mi->getOperand(i).getReg() == regB)
214               mi->getOperand(i).setReg(regA);
215           }
216         }
217
218         assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
219         mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
220         MadeChange = true;
221
222         DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
223       }
224     }
225   }
226
227   return MadeChange;
228 }