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