Move passes from namespace llvm into anonymous namespaces. Sort includes while there.
[oota-llvm.git] / lib / Target / R600 / R600Packetizer.cpp
1 //===----- R600Packetizer.cpp - VLIW packetizer ---------------------------===//
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 /// \file
11 /// This pass implements instructions packetization for R600. It unsets isLast
12 /// bit of instructions inside a bundle and substitutes src register with
13 /// PreviousVector when applicable.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "packets"
18 #include "llvm/Support/Debug.h"
19 #include "AMDGPU.h"
20 #include "R600InstrInfo.h"
21 #include "llvm/CodeGen/DFAPacketizer.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/ScheduleDAG.h"
27 #include "llvm/Support/raw_ostream.h"
28
29 using namespace llvm;
30
31 namespace {
32
33 class R600Packetizer : public MachineFunctionPass {
34
35 public:
36   static char ID;
37   R600Packetizer(const TargetMachine &TM) : MachineFunctionPass(ID) {}
38
39   void getAnalysisUsage(AnalysisUsage &AU) const {
40     AU.setPreservesCFG();
41     AU.addRequired<MachineDominatorTree>();
42     AU.addPreserved<MachineDominatorTree>();
43     AU.addRequired<MachineLoopInfo>();
44     AU.addPreserved<MachineLoopInfo>();
45     MachineFunctionPass::getAnalysisUsage(AU);
46   }
47
48   const char *getPassName() const {
49     return "R600 Packetizer";
50   }
51
52   bool runOnMachineFunction(MachineFunction &Fn);
53 };
54 char R600Packetizer::ID = 0;
55
56 class R600PacketizerList : public VLIWPacketizerList {
57
58 private:
59   const R600InstrInfo *TII;
60   const R600RegisterInfo &TRI;
61
62   unsigned getSlot(const MachineInstr *MI) const {
63     return TRI.getHWRegChan(MI->getOperand(0).getReg());
64   }
65
66   /// \returns register to PV chan mapping for bundle/single instructions that
67   /// immediatly precedes I.
68   DenseMap<unsigned, unsigned> getPreviousVector(MachineBasicBlock::iterator I)
69       const {
70     DenseMap<unsigned, unsigned> Result;
71     I--;
72     if (!TII->isALUInstr(I->getOpcode()) && !I->isBundle())
73       return Result;
74     MachineBasicBlock::instr_iterator BI = I.getInstrIterator();
75     if (I->isBundle())
76       BI++;
77     do {
78       if (TII->isPredicated(BI))
79         continue;
80       if (TII->isTransOnly(BI))
81         continue;
82       int OperandIdx = TII->getOperandIdx(BI->getOpcode(), R600Operands::WRITE);
83       if (OperandIdx < 0)
84         continue;
85       if (BI->getOperand(OperandIdx).getImm() == 0)
86         continue;
87       unsigned Dst = BI->getOperand(0).getReg();
88       if (BI->getOpcode() == AMDGPU::DOT4_r600 ||
89           BI->getOpcode() == AMDGPU::DOT4_eg) {
90         Result[Dst] = AMDGPU::PV_X;
91         continue;
92       }
93       unsigned PVReg = 0;
94       switch (TRI.getHWRegChan(Dst)) {
95       case 0:
96         PVReg = AMDGPU::PV_X;
97         break;
98       case 1:
99         PVReg = AMDGPU::PV_Y;
100         break;
101       case 2:
102         PVReg = AMDGPU::PV_Z;
103         break;
104       case 3:
105         PVReg = AMDGPU::PV_W;
106         break;
107       default:
108         llvm_unreachable("Invalid Chan");
109       }
110       Result[Dst] = PVReg;
111     } while ((++BI)->isBundledWithPred());
112     return Result;
113   }
114
115   void substitutePV(MachineInstr *MI, const DenseMap<unsigned, unsigned> &PVs)
116       const {
117     R600Operands::Ops Ops[] = {
118       R600Operands::SRC0,
119       R600Operands::SRC1,
120       R600Operands::SRC2
121     };
122     for (unsigned i = 0; i < 3; i++) {
123       int OperandIdx = TII->getOperandIdx(MI->getOpcode(), Ops[i]);
124       if (OperandIdx < 0)
125         continue;
126       unsigned Src = MI->getOperand(OperandIdx).getReg();
127       const DenseMap<unsigned, unsigned>::const_iterator It = PVs.find(Src);
128       if (It != PVs.end())
129         MI->getOperand(OperandIdx).setReg(It->second);
130     }
131   }
132 public:
133   // Ctor.
134   R600PacketizerList(MachineFunction &MF, MachineLoopInfo &MLI,
135                         MachineDominatorTree &MDT)
136   : VLIWPacketizerList(MF, MLI, MDT, true),
137     TII (static_cast<const R600InstrInfo *>(MF.getTarget().getInstrInfo())),
138     TRI(TII->getRegisterInfo()) { }
139
140   // initPacketizerState - initialize some internal flags.
141   void initPacketizerState() { }
142
143   // ignorePseudoInstruction - Ignore bundling of pseudo instructions.
144   bool ignorePseudoInstruction(MachineInstr *MI, MachineBasicBlock *MBB) {
145     return false;
146   }
147
148   // isSoloInstruction - return true if instruction MI can not be packetized
149   // with any other instruction, which means that MI itself is a packet.
150   bool isSoloInstruction(MachineInstr *MI) {
151     if (TII->isVector(*MI))
152       return true;
153     if (!TII->isALUInstr(MI->getOpcode()))
154       return true;
155     if (TII->get(MI->getOpcode()).TSFlags & R600_InstFlag::TRANS_ONLY)
156       return true;
157     if (TII->isTransOnly(MI))
158       return true;
159     return false;
160   }
161
162   // isLegalToPacketizeTogether - Is it legal to packetize SUI and SUJ
163   // together.
164   bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {
165     MachineInstr *MII = SUI->getInstr(), *MIJ = SUJ->getInstr();
166     if (getSlot(MII) <= getSlot(MIJ))
167       return false;
168     // Does MII and MIJ share the same pred_sel ?
169     int OpI = TII->getOperandIdx(MII->getOpcode(), R600Operands::PRED_SEL),
170         OpJ = TII->getOperandIdx(MIJ->getOpcode(), R600Operands::PRED_SEL);
171     unsigned PredI = (OpI > -1)?MII->getOperand(OpI).getReg():0,
172         PredJ = (OpJ > -1)?MIJ->getOperand(OpJ).getReg():0;
173     if (PredI != PredJ)
174       return false;
175     if (SUJ->isSucc(SUI)) {
176       for (unsigned i = 0, e = SUJ->Succs.size(); i < e; ++i) {
177         const SDep &Dep = SUJ->Succs[i];
178         if (Dep.getSUnit() != SUI)
179           continue;
180         if (Dep.getKind() == SDep::Anti)
181           continue;
182         if (Dep.getKind() == SDep::Output)
183           if (MII->getOperand(0).getReg() != MIJ->getOperand(0).getReg())
184             continue;
185         return false;
186       }
187     }
188     return true;
189   }
190
191   // isLegalToPruneDependencies - Is it legal to prune dependece between SUI
192   // and SUJ.
193   bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) {return false;}
194
195   void setIsLastBit(MachineInstr *MI, unsigned Bit) const {
196     unsigned LastOp = TII->getOperandIdx(MI->getOpcode(), R600Operands::LAST);
197     MI->getOperand(LastOp).setImm(Bit);
198   }
199
200   MachineBasicBlock::iterator addToPacket(MachineInstr *MI) {
201     CurrentPacketMIs.push_back(MI);
202     bool FitsConstLimits = TII->canBundle(CurrentPacketMIs);
203     DEBUG(
204       if (!FitsConstLimits) {
205         dbgs() << "Couldn't pack :\n";
206         MI->dump();
207         dbgs() << "with the following packets :\n";
208         for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
209           CurrentPacketMIs[i]->dump();
210           dbgs() << "\n";
211         }
212         dbgs() << "because of Consts read limitations\n";
213       });
214     const DenseMap<unsigned, unsigned> &PV =
215         getPreviousVector(CurrentPacketMIs.front());
216     std::vector<R600InstrInfo::BankSwizzle> BS;
217     bool FitsReadPortLimits =
218         TII->fitsReadPortLimitations(CurrentPacketMIs, PV, BS);
219     DEBUG(
220       if (!FitsReadPortLimits) {
221         dbgs() << "Couldn't pack :\n";
222         MI->dump();
223         dbgs() << "with the following packets :\n";
224         for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
225           CurrentPacketMIs[i]->dump();
226           dbgs() << "\n";
227         }
228         dbgs() << "because of Read port limitations\n";
229       });
230     bool isBundlable = FitsConstLimits && FitsReadPortLimits;
231     if (isBundlable) {
232       for (unsigned i = 0, e = CurrentPacketMIs.size(); i < e; i++) {
233         MachineInstr *MI = CurrentPacketMIs[i];
234             unsigned Op = TII->getOperandIdx(MI->getOpcode(),
235                 R600Operands::BANK_SWIZZLE);
236             MI->getOperand(Op).setImm(BS[i]);
237       }
238     }
239     CurrentPacketMIs.pop_back();
240     if (!isBundlable) {
241       endPacket(MI->getParent(), MI);
242       substitutePV(MI, getPreviousVector(MI));
243       return VLIWPacketizerList::addToPacket(MI);
244     }
245     if (!CurrentPacketMIs.empty())
246       setIsLastBit(CurrentPacketMIs.back(), 0);
247     substitutePV(MI, PV);
248     return VLIWPacketizerList::addToPacket(MI);
249   }
250 };
251
252 bool R600Packetizer::runOnMachineFunction(MachineFunction &Fn) {
253   const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
254   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
255   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
256
257   // Instantiate the packetizer.
258   R600PacketizerList Packetizer(Fn, MLI, MDT);
259
260   // DFA state table should not be empty.
261   assert(Packetizer.getResourceTracker() && "Empty DFA table!");
262
263   //
264   // Loop over all basic blocks and remove KILL pseudo-instructions
265   // These instructions confuse the dependence analysis. Consider:
266   // D0 = ...   (Insn 0)
267   // R0 = KILL R0, D0 (Insn 1)
268   // R0 = ... (Insn 2)
269   // Here, Insn 1 will result in the dependence graph not emitting an output
270   // dependence between Insn 0 and Insn 2. This can lead to incorrect
271   // packetization
272   //
273   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
274        MBB != MBBe; ++MBB) {
275     MachineBasicBlock::iterator End = MBB->end();
276     MachineBasicBlock::iterator MI = MBB->begin();
277     while (MI != End) {
278       if (MI->isKill()) {
279         MachineBasicBlock::iterator DeleteMI = MI;
280         ++MI;
281         MBB->erase(DeleteMI);
282         End = MBB->end();
283         continue;
284       }
285       ++MI;
286     }
287   }
288
289   // Loop over all of the basic blocks.
290   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
291        MBB != MBBe; ++MBB) {
292     // Find scheduling regions and schedule / packetize each region.
293     unsigned RemainingCount = MBB->size();
294     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
295         RegionEnd != MBB->begin();) {
296       // The next region starts above the previous region. Look backward in the
297       // instruction stream until we find the nearest boundary.
298       MachineBasicBlock::iterator I = RegionEnd;
299       for(;I != MBB->begin(); --I, --RemainingCount) {
300         if (TII->isSchedulingBoundary(llvm::prior(I), MBB, Fn))
301           break;
302       }
303       I = MBB->begin();
304
305       // Skip empty scheduling regions.
306       if (I == RegionEnd) {
307         RegionEnd = llvm::prior(RegionEnd);
308         --RemainingCount;
309         continue;
310       }
311       // Skip regions with one instruction.
312       if (I == llvm::prior(RegionEnd)) {
313         RegionEnd = llvm::prior(RegionEnd);
314         continue;
315       }
316
317       Packetizer.PacketizeMIs(MBB, I, RegionEnd);
318       RegionEnd = I;
319     }
320   }
321
322   return true;
323
324 }
325
326 } // end anonymous namespace
327
328 llvm::FunctionPass *llvm::createR600Packetizer(TargetMachine &tm) {
329   return new R600Packetizer(tm);
330 }