[C++11] Add 'override' keywords and remove 'virtual'. Additionally add 'final' and...
[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 #include "llvm/Support/Debug.h"
18 #include "AMDGPU.h"
19 #include "R600InstrInfo.h"
20 #include "llvm/CodeGen/DFAPacketizer.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/ScheduleDAG.h"
26 #include "llvm/Support/raw_ostream.h"
27
28 using namespace llvm;
29
30 #define DEBUG_TYPE "packets"
31
32 namespace {
33
34 class R600Packetizer : public MachineFunctionPass {
35
36 public:
37   static char ID;
38   R600Packetizer(const TargetMachine &TM) : MachineFunctionPass(ID) {}
39
40   void getAnalysisUsage(AnalysisUsage &AU) const override {
41     AU.setPreservesCFG();
42     AU.addRequired<MachineDominatorTree>();
43     AU.addPreserved<MachineDominatorTree>();
44     AU.addRequired<MachineLoopInfo>();
45     AU.addPreserved<MachineLoopInfo>();
46     MachineFunctionPass::getAnalysisUsage(AU);
47   }
48
49   const char *getPassName() const override {
50     return "R600 Packetizer";
51   }
52
53   bool runOnMachineFunction(MachineFunction &Fn) override;
54 };
55 char R600Packetizer::ID = 0;
56
57 class R600PacketizerList : public VLIWPacketizerList {
58
59 private:
60   const R600InstrInfo *TII;
61   const R600RegisterInfo &TRI;
62   bool VLIW5;
63   bool ConsideredInstUsesAlreadyWrittenVectorElement;
64
65   unsigned getSlot(const MachineInstr *MI) const {
66     return TRI.getHWRegChan(MI->getOperand(0).getReg());
67   }
68
69   /// \returns register to PV chan mapping for bundle/single instructions that
70   /// immediately precedes I.
71   DenseMap<unsigned, unsigned> getPreviousVector(MachineBasicBlock::iterator I)
72       const {
73     DenseMap<unsigned, unsigned> Result;
74     I--;
75     if (!TII->isALUInstr(I->getOpcode()) && !I->isBundle())
76       return Result;
77     MachineBasicBlock::instr_iterator BI = I.getInstrIterator();
78     if (I->isBundle())
79       BI++;
80     int LastDstChan = -1;
81     do {
82       bool isTrans = false;
83       int BISlot = getSlot(BI);
84       if (LastDstChan >= BISlot)
85         isTrans = true;
86       LastDstChan = BISlot;
87       if (TII->isPredicated(BI))
88         continue;
89       int OperandIdx = TII->getOperandIdx(BI->getOpcode(), AMDGPU::OpName::write);
90       if (OperandIdx > -1 && BI->getOperand(OperandIdx).getImm() == 0)
91         continue;
92       int DstIdx = TII->getOperandIdx(BI->getOpcode(), AMDGPU::OpName::dst);
93       if (DstIdx == -1) {
94         continue;
95       }
96       unsigned Dst = BI->getOperand(DstIdx).getReg();
97       if (isTrans || TII->isTransOnly(BI)) {
98         Result[Dst] = AMDGPU::PS;
99         continue;
100       }
101       if (BI->getOpcode() == AMDGPU::DOT4_r600 ||
102           BI->getOpcode() == AMDGPU::DOT4_eg) {
103         Result[Dst] = AMDGPU::PV_X;
104         continue;
105       }
106       if (Dst == AMDGPU::OQAP) {
107         continue;
108       }
109       unsigned PVReg = 0;
110       switch (TRI.getHWRegChan(Dst)) {
111       case 0:
112         PVReg = AMDGPU::PV_X;
113         break;
114       case 1:
115         PVReg = AMDGPU::PV_Y;
116         break;
117       case 2:
118         PVReg = AMDGPU::PV_Z;
119         break;
120       case 3:
121         PVReg = AMDGPU::PV_W;
122         break;
123       default:
124         llvm_unreachable("Invalid Chan");
125       }
126       Result[Dst] = PVReg;
127     } while ((++BI)->isBundledWithPred());
128     return Result;
129   }
130
131   void substitutePV(MachineInstr *MI, const DenseMap<unsigned, unsigned> &PVs)
132       const {
133     unsigned Ops[] = {
134       AMDGPU::OpName::src0,
135       AMDGPU::OpName::src1,
136       AMDGPU::OpName::src2
137     };
138     for (unsigned i = 0; i < 3; i++) {
139       int OperandIdx = TII->getOperandIdx(MI->getOpcode(), Ops[i]);
140       if (OperandIdx < 0)
141         continue;
142       unsigned Src = MI->getOperand(OperandIdx).getReg();
143       const DenseMap<unsigned, unsigned>::const_iterator It = PVs.find(Src);
144       if (It != PVs.end())
145         MI->getOperand(OperandIdx).setReg(It->second);
146     }
147   }
148 public:
149   // Ctor.
150   R600PacketizerList(MachineFunction &MF, MachineLoopInfo &MLI,
151                         MachineDominatorTree &MDT)
152   : VLIWPacketizerList(MF, MLI, MDT, true),
153     TII (static_cast<const R600InstrInfo *>(MF.getTarget().getInstrInfo())),
154     TRI(TII->getRegisterInfo()) {
155     VLIW5 = !MF.getTarget().getSubtarget<AMDGPUSubtarget>().hasCaymanISA();
156   }
157
158   // initPacketizerState - initialize some internal flags.
159   void initPacketizerState() override {
160     ConsideredInstUsesAlreadyWrittenVectorElement = false;
161   }
162
163   // ignorePseudoInstruction - Ignore bundling of pseudo instructions.
164   bool ignorePseudoInstruction(MachineInstr *MI,
165                                MachineBasicBlock *MBB) override {
166     return false;
167   }
168
169   // isSoloInstruction - return true if instruction MI can not be packetized
170   // with any other instruction, which means that MI itself is a packet.
171   bool isSoloInstruction(MachineInstr *MI) override {
172     if (TII->isVector(*MI))
173       return true;
174     if (!TII->isALUInstr(MI->getOpcode()))
175       return true;
176     if (MI->getOpcode() == AMDGPU::GROUP_BARRIER)
177       return true;
178     // XXX: This can be removed once the packetizer properly handles all the
179     // LDS instruction group restrictions.
180     if (TII->isLDSInstr(MI->getOpcode()))
181       return true;
182     return false;
183   }
184
185   // isLegalToPacketizeTogether - Is it legal to packetize SUI and SUJ
186   // together.
187   bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) override {
188     MachineInstr *MII = SUI->getInstr(), *MIJ = SUJ->getInstr();
189     if (getSlot(MII) == getSlot(MIJ))
190       ConsideredInstUsesAlreadyWrittenVectorElement = true;
191     // Does MII and MIJ share the same pred_sel ?
192     int OpI = TII->getOperandIdx(MII->getOpcode(), AMDGPU::OpName::pred_sel),
193         OpJ = TII->getOperandIdx(MIJ->getOpcode(), AMDGPU::OpName::pred_sel);
194     unsigned PredI = (OpI > -1)?MII->getOperand(OpI).getReg():0,
195         PredJ = (OpJ > -1)?MIJ->getOperand(OpJ).getReg():0;
196     if (PredI != PredJ)
197       return false;
198     if (SUJ->isSucc(SUI)) {
199       for (unsigned i = 0, e = SUJ->Succs.size(); i < e; ++i) {
200         const SDep &Dep = SUJ->Succs[i];
201         if (Dep.getSUnit() != SUI)
202           continue;
203         if (Dep.getKind() == SDep::Anti)
204           continue;
205         if (Dep.getKind() == SDep::Output)
206           if (MII->getOperand(0).getReg() != MIJ->getOperand(0).getReg())
207             continue;
208         return false;
209       }
210     }
211
212     bool ARDef = TII->definesAddressRegister(MII) ||
213                  TII->definesAddressRegister(MIJ);
214     bool ARUse = TII->usesAddressRegister(MII) ||
215                  TII->usesAddressRegister(MIJ);
216     if (ARDef && ARUse)
217       return false;
218
219     return true;
220   }
221
222   // isLegalToPruneDependencies - Is it legal to prune dependece between SUI
223   // and SUJ.
224   bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) override {
225     return false;
226   }
227
228   void setIsLastBit(MachineInstr *MI, unsigned Bit) const {
229     unsigned LastOp = TII->getOperandIdx(MI->getOpcode(), AMDGPU::OpName::last);
230     MI->getOperand(LastOp).setImm(Bit);
231   }
232
233   bool isBundlableWithCurrentPMI(MachineInstr *MI,
234                                  const DenseMap<unsigned, unsigned> &PV,
235                                  std::vector<R600InstrInfo::BankSwizzle> &BS,
236                                  bool &isTransSlot) {
237     isTransSlot = TII->isTransOnly(MI);
238     assert (!isTransSlot || VLIW5);
239
240     // Is the dst reg sequence legal ?
241     if (!isTransSlot && !CurrentPacketMIs.empty()) {
242       if (getSlot(MI) <= getSlot(CurrentPacketMIs.back())) {
243         if (ConsideredInstUsesAlreadyWrittenVectorElement  &&
244             !TII->isVectorOnly(MI) && VLIW5) {
245           isTransSlot = true;
246           DEBUG(dbgs() << "Considering as Trans Inst :"; MI->dump(););
247         }
248         else
249           return false;
250       }
251     }
252
253     // Are the Constants limitations met ?
254     CurrentPacketMIs.push_back(MI);
255     if (!TII->fitsConstReadLimitations(CurrentPacketMIs)) {
256       DEBUG(
257         dbgs() << "Couldn't pack :\n";
258         MI->dump();
259         dbgs() << "with the following packets :\n";
260         for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
261           CurrentPacketMIs[i]->dump();
262           dbgs() << "\n";
263         }
264         dbgs() << "because of Consts read limitations\n";
265       );
266       CurrentPacketMIs.pop_back();
267       return false;
268     }
269
270     // Is there a BankSwizzle set that meet Read Port limitations ?
271     if (!TII->fitsReadPortLimitations(CurrentPacketMIs,
272             PV, BS, isTransSlot)) {
273       DEBUG(
274         dbgs() << "Couldn't pack :\n";
275         MI->dump();
276         dbgs() << "with the following packets :\n";
277         for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
278           CurrentPacketMIs[i]->dump();
279           dbgs() << "\n";
280         }
281         dbgs() << "because of Read port limitations\n";
282       );
283       CurrentPacketMIs.pop_back();
284       return false;
285     }
286
287     // We cannot read LDS source registrs from the Trans slot.
288     if (isTransSlot && TII->readsLDSSrcReg(MI))
289       return false;
290
291     CurrentPacketMIs.pop_back();
292     return true;
293   }
294
295   MachineBasicBlock::iterator addToPacket(MachineInstr *MI) override {
296     MachineBasicBlock::iterator FirstInBundle =
297         CurrentPacketMIs.empty() ? MI : CurrentPacketMIs.front();
298     const DenseMap<unsigned, unsigned> &PV =
299         getPreviousVector(FirstInBundle);
300     std::vector<R600InstrInfo::BankSwizzle> BS;
301     bool isTransSlot;
302
303     if (isBundlableWithCurrentPMI(MI, PV, BS, isTransSlot)) {
304       for (unsigned i = 0, e = CurrentPacketMIs.size(); i < e; i++) {
305         MachineInstr *MI = CurrentPacketMIs[i];
306         unsigned Op = TII->getOperandIdx(MI->getOpcode(),
307             AMDGPU::OpName::bank_swizzle);
308         MI->getOperand(Op).setImm(BS[i]);
309       }
310       unsigned Op = TII->getOperandIdx(MI->getOpcode(),
311           AMDGPU::OpName::bank_swizzle);
312       MI->getOperand(Op).setImm(BS.back());
313       if (!CurrentPacketMIs.empty())
314         setIsLastBit(CurrentPacketMIs.back(), 0);
315       substitutePV(MI, PV);
316       MachineBasicBlock::iterator It = VLIWPacketizerList::addToPacket(MI);
317       if (isTransSlot) {
318         endPacket(std::next(It)->getParent(), std::next(It));
319       }
320       return It;
321     }
322     endPacket(MI->getParent(), MI);
323     if (TII->isTransOnly(MI))
324       return MI;
325     return VLIWPacketizerList::addToPacket(MI);
326   }
327 };
328
329 bool R600Packetizer::runOnMachineFunction(MachineFunction &Fn) {
330   const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
331   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
332   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
333
334   // Instantiate the packetizer.
335   R600PacketizerList Packetizer(Fn, MLI, MDT);
336
337   // DFA state table should not be empty.
338   assert(Packetizer.getResourceTracker() && "Empty DFA table!");
339
340   //
341   // Loop over all basic blocks and remove KILL pseudo-instructions
342   // These instructions confuse the dependence analysis. Consider:
343   // D0 = ...   (Insn 0)
344   // R0 = KILL R0, D0 (Insn 1)
345   // R0 = ... (Insn 2)
346   // Here, Insn 1 will result in the dependence graph not emitting an output
347   // dependence between Insn 0 and Insn 2. This can lead to incorrect
348   // packetization
349   //
350   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
351        MBB != MBBe; ++MBB) {
352     MachineBasicBlock::iterator End = MBB->end();
353     MachineBasicBlock::iterator MI = MBB->begin();
354     while (MI != End) {
355       if (MI->isKill() || MI->getOpcode() == AMDGPU::IMPLICIT_DEF ||
356           (MI->getOpcode() == AMDGPU::CF_ALU && !MI->getOperand(8).getImm())) {
357         MachineBasicBlock::iterator DeleteMI = MI;
358         ++MI;
359         MBB->erase(DeleteMI);
360         End = MBB->end();
361         continue;
362       }
363       ++MI;
364     }
365   }
366
367   // Loop over all of the basic blocks.
368   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
369        MBB != MBBe; ++MBB) {
370     // Find scheduling regions and schedule / packetize each region.
371     unsigned RemainingCount = MBB->size();
372     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
373         RegionEnd != MBB->begin();) {
374       // The next region starts above the previous region. Look backward in the
375       // instruction stream until we find the nearest boundary.
376       MachineBasicBlock::iterator I = RegionEnd;
377       for(;I != MBB->begin(); --I, --RemainingCount) {
378         if (TII->isSchedulingBoundary(std::prev(I), MBB, Fn))
379           break;
380       }
381       I = MBB->begin();
382
383       // Skip empty scheduling regions.
384       if (I == RegionEnd) {
385         RegionEnd = std::prev(RegionEnd);
386         --RemainingCount;
387         continue;
388       }
389       // Skip regions with one instruction.
390       if (I == std::prev(RegionEnd)) {
391         RegionEnd = std::prev(RegionEnd);
392         continue;
393       }
394
395       Packetizer.PacketizeMIs(MBB, I, RegionEnd);
396       RegionEnd = I;
397     }
398   }
399
400   return true;
401
402 }
403
404 } // end anonymous namespace
405
406 llvm::FunctionPass *llvm::createR600Packetizer(TargetMachine &tm) {
407   return new R600Packetizer(tm);
408 }