Improve sub-register def handling in ProcessImplicitDefs.
[oota-llvm.git] / lib / CodeGen / ProcessImplicitDefs.cpp
1 //===---------------------- ProcessImplicitDefs.cpp -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "processimplicitdefs"
11
12 #include "llvm/CodeGen/ProcessImplicitDefs.h"
13
14 #include "llvm/ADT/DepthFirstIterator.h"
15 #include "llvm/ADT/SmallSet.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/CodeGen/LiveVariables.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24
25
26 using namespace llvm;
27
28 char ProcessImplicitDefs::ID = 0;
29 INITIALIZE_PASS_BEGIN(ProcessImplicitDefs, "processimpdefs",
30                 "Process Implicit Definitions", false, false)
31 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
32 INITIALIZE_PASS_END(ProcessImplicitDefs, "processimpdefs",
33                 "Process Implicit Definitions", false, false)
34
35 void ProcessImplicitDefs::getAnalysisUsage(AnalysisUsage &AU) const {
36   AU.setPreservesCFG();
37   AU.addPreserved<AliasAnalysis>();
38   AU.addPreserved<LiveVariables>();
39   AU.addRequired<LiveVariables>();
40   AU.addPreservedID(MachineLoopInfoID);
41   AU.addPreservedID(MachineDominatorsID);
42   AU.addPreservedID(TwoAddressInstructionPassID);
43   AU.addPreservedID(PHIEliminationID);
44   MachineFunctionPass::getAnalysisUsage(AU);
45 }
46
47 bool
48 ProcessImplicitDefs::CanTurnIntoImplicitDef(MachineInstr *MI,
49                                             unsigned Reg, unsigned OpIdx,
50                                             SmallSet<unsigned, 8> &ImpDefRegs) {
51   switch(OpIdx) {
52   case 1:
53     return MI->isCopy() && (!MI->getOperand(0).readsReg() ||
54                             ImpDefRegs.count(MI->getOperand(0).getReg()));
55   case 2:
56     return MI->isSubregToReg() && (!MI->getOperand(0).readsReg() ||
57                                   ImpDefRegs.count(MI->getOperand(0).getReg()));
58   default: return false;
59   }
60 }
61
62 static bool isUndefCopy(MachineInstr *MI, unsigned Reg,
63                         SmallSet<unsigned, 8> &ImpDefRegs) {
64   if (MI->isCopy()) {
65     MachineOperand &MO0 = MI->getOperand(0);
66     MachineOperand &MO1 = MI->getOperand(1);
67     if (MO1.getReg() != Reg)
68       return false;
69     if (!MO0.readsReg() || ImpDefRegs.count(MO0.getReg()))
70       return true;
71     return false;
72   }
73   return false;
74 }
75
76 /// processImplicitDefs - Process IMPLICIT_DEF instructions and make sure
77 /// there is one implicit_def for each use. Add isUndef marker to
78 /// implicit_def defs and their uses.
79 bool ProcessImplicitDefs::runOnMachineFunction(MachineFunction &fn) {
80
81   DEBUG(dbgs() << "********** PROCESS IMPLICIT DEFS **********\n"
82                << "********** Function: "
83                << ((Value*)fn.getFunction())->getName() << '\n');
84
85   bool Changed = false;
86
87   TII = fn.getTarget().getInstrInfo();
88   TRI = fn.getTarget().getRegisterInfo();
89   MRI = &fn.getRegInfo();
90   LV = &getAnalysis<LiveVariables>();
91
92   SmallSet<unsigned, 8> ImpDefRegs;
93   SmallVector<MachineInstr*, 8> ImpDefMIs;
94   SmallVector<MachineInstr*, 4> RUses;
95   SmallPtrSet<MachineBasicBlock*,16> Visited;
96   SmallPtrSet<MachineInstr*, 8> ModInsts;
97
98   MachineBasicBlock *Entry = fn.begin();
99   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
100          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
101        DFI != E; ++DFI) {
102     MachineBasicBlock *MBB = *DFI;
103     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
104          I != E; ) {
105       MachineInstr *MI = &*I;
106       ++I;
107       if (MI->isImplicitDef()) {
108         ImpDefMIs.push_back(MI);
109         // Is this a sub-register read-modify-write?
110         if (MI->getOperand(0).readsReg())
111           continue;
112         unsigned Reg = MI->getOperand(0).getReg();
113         ImpDefRegs.insert(Reg);
114         if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
115           for (const unsigned *SS = TRI->getSubRegisters(Reg); *SS; ++SS)
116             ImpDefRegs.insert(*SS);
117         }
118         continue;
119       }
120
121       // Eliminate %reg1032:sub<def> = COPY undef.
122       if (MI->isCopy() && MI->getOperand(0).readsReg()) {
123         MachineOperand &MO = MI->getOperand(1);
124         if (MO.isUndef() || ImpDefRegs.count(MO.getReg())) {
125           if (MO.isKill()) {
126             LiveVariables::VarInfo& vi = LV->getVarInfo(MO.getReg());
127             vi.removeKill(MI);
128           }
129           unsigned Reg = MI->getOperand(0).getReg();
130           MI->eraseFromParent();
131           Changed = true;
132
133           // A REG_SEQUENCE may have been expanded into partial definitions.
134           // If this was the last one, mark Reg as implicitly defined.
135           if (TargetRegisterInfo::isVirtualRegister(Reg) && MRI->def_empty(Reg))
136             ImpDefRegs.insert(Reg);
137           continue;
138         }
139       }
140
141       bool ChangedToImpDef = false;
142       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
143         MachineOperand& MO = MI->getOperand(i);
144         if (!MO.isReg() || !MO.readsReg())
145           continue;
146         unsigned Reg = MO.getReg();
147         if (!Reg)
148           continue;
149         if (!ImpDefRegs.count(Reg))
150           continue;
151         // Use is a copy, just turn it into an implicit_def.
152         if (CanTurnIntoImplicitDef(MI, Reg, i, ImpDefRegs)) {
153           bool isKill = MO.isKill();
154           MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
155           for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
156             MI->RemoveOperand(j);
157           if (isKill) {
158             ImpDefRegs.erase(Reg);
159             LiveVariables::VarInfo& vi = LV->getVarInfo(Reg);
160             vi.removeKill(MI);
161           }
162           ChangedToImpDef = true;
163           Changed = true;
164           break;
165         }
166
167         Changed = true;
168         MO.setIsUndef();
169         // This is a partial register redef of an implicit def.
170         // Make sure the whole register is defined by the instruction.
171         if (MO.isDef()) {
172           MI->addRegisterDefined(Reg);
173           continue;
174         }
175         if (MO.isKill() || MI->isRegTiedToDefOperand(i)) {
176           // Make sure other reads of Reg are also marked <undef>.
177           for (unsigned j = i+1; j != e; ++j) {
178             MachineOperand &MOJ = MI->getOperand(j);
179             if (MOJ.isReg() && MOJ.getReg() == Reg && MOJ.readsReg())
180               MOJ.setIsUndef();
181           }
182           ImpDefRegs.erase(Reg);
183         }
184       }
185
186       if (ChangedToImpDef) {
187         // Backtrack to process this new implicit_def.
188         --I;
189       } else {
190         for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
191           MachineOperand& MO = MI->getOperand(i);
192           if (!MO.isReg() || !MO.isDef())
193             continue;
194           ImpDefRegs.erase(MO.getReg());
195         }
196       }
197     }
198
199     // Any outstanding liveout implicit_def's?
200     for (unsigned i = 0, e = ImpDefMIs.size(); i != e; ++i) {
201       MachineInstr *MI = ImpDefMIs[i];
202       unsigned Reg = MI->getOperand(0).getReg();
203       if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
204           !ImpDefRegs.count(Reg)) {
205         // Delete all "local" implicit_def's. That include those which define
206         // physical registers since they cannot be liveout.
207         MI->eraseFromParent();
208         Changed = true;
209         continue;
210       }
211
212       // If there are multiple defs of the same register and at least one
213       // is not an implicit_def, do not insert implicit_def's before the
214       // uses.
215       bool Skip = false;
216       SmallVector<MachineInstr*, 4> DeadImpDefs;
217       for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
218              DE = MRI->def_end(); DI != DE; ++DI) {
219         MachineInstr *DeadImpDef = &*DI;
220         if (!DeadImpDef->isImplicitDef()) {
221           Skip = true;
222           break;
223         }
224         DeadImpDefs.push_back(DeadImpDef);
225       }
226       if (Skip)
227         continue;
228
229       // The only implicit_def which we want to keep are those that are live
230       // out of its block.
231       for (unsigned j = 0, ee = DeadImpDefs.size(); j != ee; ++j)
232         DeadImpDefs[j]->eraseFromParent();
233       Changed = true;
234
235       // Process each use instruction once.
236       for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
237              UE = MRI->use_end(); UI != UE; ++UI) {
238         if (UI.getOperand().isUndef())
239           continue;
240         MachineInstr *RMI = &*UI;
241         if (ModInsts.insert(RMI))
242           RUses.push_back(RMI);
243       }
244
245       for (unsigned i = 0, e = RUses.size(); i != e; ++i) {
246         MachineInstr *RMI = RUses[i];
247
248         // Turn a copy use into an implicit_def.
249         if (isUndefCopy(RMI, Reg, ImpDefRegs)) {
250           RMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
251
252           bool isKill = false;
253           SmallVector<unsigned, 4> Ops;
254           for (unsigned j = 0, ee = RMI->getNumOperands(); j != ee; ++j) {
255             MachineOperand &RRMO = RMI->getOperand(j);
256             if (RRMO.isReg() && RRMO.getReg() == Reg) {
257               Ops.push_back(j);
258               if (RRMO.isKill())
259                 isKill = true;
260             }
261           }
262           // Leave the other operands along.
263           for (unsigned j = 0, ee = Ops.size(); j != ee; ++j) {
264             unsigned OpIdx = Ops[j];
265             RMI->RemoveOperand(OpIdx-j);
266           }
267
268           // Update LiveVariables varinfo if the instruction is a kill.
269           if (isKill) {
270             LiveVariables::VarInfo& vi = LV->getVarInfo(Reg);
271             vi.removeKill(RMI);
272           }
273           continue;
274         }
275
276         // Replace Reg with a new vreg that's marked implicit.
277         const TargetRegisterClass* RC = MRI->getRegClass(Reg);
278         unsigned NewVReg = MRI->createVirtualRegister(RC);
279         bool isKill = true;
280         for (unsigned j = 0, ee = RMI->getNumOperands(); j != ee; ++j) {
281           MachineOperand &RRMO = RMI->getOperand(j);
282           if (RRMO.isReg() && RRMO.getReg() == Reg) {
283             RRMO.setReg(NewVReg);
284             RRMO.setIsUndef();
285             if (isKill) {
286               // Only the first operand of NewVReg is marked kill.
287               RRMO.setIsKill();
288               isKill = false;
289             }
290           }
291         }
292       }
293       RUses.clear();
294       ModInsts.clear();
295     }
296     ImpDefRegs.clear();
297     ImpDefMIs.clear();
298   }
299
300   return Changed;
301 }
302