R600/SI: Re-initialize the m0 register after using it for indirect addressing
[oota-llvm.git] / lib / Target / R600 / SILowerControlFlow.cpp
1 //===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
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 /// \brief This pass lowers the pseudo control flow instructions to real
12 /// machine instructions.
13 ///
14 /// All control flow is handled using predicated instructions and
15 /// a predicate stack.  Each Scalar ALU controls the operations of 64 Vector
16 /// ALUs.  The Scalar ALU can update the predicate for any of the Vector ALUs
17 /// by writting to the 64-bit EXEC register (each bit corresponds to a
18 /// single vector ALU).  Typically, for predicates, a vector ALU will write
19 /// to its bit of the VCC register (like EXEC VCC is 64-bits, one for each
20 /// Vector ALU) and then the ScalarALU will AND the VCC register with the
21 /// EXEC to update the predicates.
22 ///
23 /// For example:
24 /// %VCC = V_CMP_GT_F32 %VGPR1, %VGPR2
25 /// %SGPR0 = SI_IF %VCC
26 ///   %VGPR0 = V_ADD_F32 %VGPR0, %VGPR0
27 /// %SGPR0 = SI_ELSE %SGPR0
28 ///   %VGPR0 = V_SUB_F32 %VGPR0, %VGPR0
29 /// SI_END_CF %SGPR0
30 ///
31 /// becomes:
32 ///
33 /// %SGPR0 = S_AND_SAVEEXEC_B64 %VCC  // Save and update the exec mask
34 /// %SGPR0 = S_XOR_B64 %SGPR0, %EXEC  // Clear live bits from saved exec mask
35 /// S_CBRANCH_EXECZ label0            // This instruction is an optional
36 ///                                   // optimization which allows us to
37 ///                                   // branch if all the bits of
38 ///                                   // EXEC are zero.
39 /// %VGPR0 = V_ADD_F32 %VGPR0, %VGPR0 // Do the IF block of the branch
40 ///
41 /// label0:
42 /// %SGPR0 = S_OR_SAVEEXEC_B64 %EXEC   // Restore the exec mask for the Then block
43 /// %EXEC = S_XOR_B64 %SGPR0, %EXEC    // Clear live bits from saved exec mask
44 /// S_BRANCH_EXECZ label1              // Use our branch optimization
45 ///                                    // instruction again.
46 /// %VGPR0 = V_SUB_F32 %VGPR0, %VGPR   // Do the THEN block
47 /// label1:
48 /// %EXEC = S_OR_B64 %EXEC, %SGPR0     // Re-enable saved exec mask bits
49 //===----------------------------------------------------------------------===//
50
51 #include "AMDGPU.h"
52 #include "SIInstrInfo.h"
53 #include "SIMachineFunctionInfo.h"
54 #include "llvm/CodeGen/MachineFunction.h"
55 #include "llvm/CodeGen/MachineFunctionPass.h"
56 #include "llvm/CodeGen/MachineInstrBuilder.h"
57 #include "llvm/CodeGen/MachineRegisterInfo.h"
58 #include "llvm/IR/Constants.h"
59
60 using namespace llvm;
61
62 namespace {
63
64 class SILowerControlFlowPass : public MachineFunctionPass {
65
66 private:
67   static const unsigned SkipThreshold = 12;
68
69   static char ID;
70   const SIRegisterInfo *TRI;
71   const SIInstrInfo *TII;
72
73   bool shouldSkip(MachineBasicBlock *From, MachineBasicBlock *To);
74
75   void Skip(MachineInstr &From, MachineOperand &To);
76   void SkipIfDead(MachineInstr &MI);
77
78   void If(MachineInstr &MI);
79   void Else(MachineInstr &MI);
80   void Break(MachineInstr &MI);
81   void IfBreak(MachineInstr &MI);
82   void ElseBreak(MachineInstr &MI);
83   void Loop(MachineInstr &MI);
84   void EndCf(MachineInstr &MI);
85
86   void Kill(MachineInstr &MI);
87   void Branch(MachineInstr &MI);
88
89   void InitM0ForLDS(MachineBasicBlock::iterator MI);
90   void LoadM0(MachineInstr &MI, MachineInstr *MovRel);
91   void IndirectSrc(MachineInstr &MI);
92   void IndirectDst(MachineInstr &MI);
93
94 public:
95   SILowerControlFlowPass(TargetMachine &tm) :
96     MachineFunctionPass(ID), TRI(nullptr), TII(nullptr) { }
97
98   bool runOnMachineFunction(MachineFunction &MF) override;
99
100   const char *getPassName() const override {
101     return "SI Lower control flow instructions";
102   }
103
104 };
105
106 } // End anonymous namespace
107
108 char SILowerControlFlowPass::ID = 0;
109
110 FunctionPass *llvm::createSILowerControlFlowPass(TargetMachine &tm) {
111   return new SILowerControlFlowPass(tm);
112 }
113
114 bool SILowerControlFlowPass::shouldSkip(MachineBasicBlock *From,
115                                         MachineBasicBlock *To) {
116
117   unsigned NumInstr = 0;
118
119   for (MachineBasicBlock *MBB = From; MBB != To && !MBB->succ_empty();
120        MBB = *MBB->succ_begin()) {
121
122     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
123          NumInstr < SkipThreshold && I != E; ++I) {
124
125       if (I->isBundle() || !I->isBundled())
126         if (++NumInstr >= SkipThreshold)
127           return true;
128     }
129   }
130
131   return false;
132 }
133
134 void SILowerControlFlowPass::Skip(MachineInstr &From, MachineOperand &To) {
135
136   if (!shouldSkip(*From.getParent()->succ_begin(), To.getMBB()))
137     return;
138
139   DebugLoc DL = From.getDebugLoc();
140   BuildMI(*From.getParent(), &From, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
141           .addOperand(To)
142           .addReg(AMDGPU::EXEC);
143 }
144
145 void SILowerControlFlowPass::SkipIfDead(MachineInstr &MI) {
146
147   MachineBasicBlock &MBB = *MI.getParent();
148   DebugLoc DL = MI.getDebugLoc();
149
150   if (MBB.getParent()->getInfo<SIMachineFunctionInfo>()->ShaderType !=
151       ShaderType::PIXEL ||
152       !shouldSkip(&MBB, &MBB.getParent()->back()))
153     return;
154
155   MachineBasicBlock::iterator Insert = &MI;
156   ++Insert;
157
158   // If the exec mask is non-zero, skip the next two instructions
159   BuildMI(MBB, Insert, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
160           .addImm(3)
161           .addReg(AMDGPU::EXEC);
162
163   // Exec mask is zero: Export to NULL target...
164   BuildMI(MBB, Insert, DL, TII->get(AMDGPU::EXP))
165           .addImm(0)
166           .addImm(0x09) // V_008DFC_SQ_EXP_NULL
167           .addImm(0)
168           .addImm(1)
169           .addImm(1)
170           .addReg(AMDGPU::VGPR0)
171           .addReg(AMDGPU::VGPR0)
172           .addReg(AMDGPU::VGPR0)
173           .addReg(AMDGPU::VGPR0);
174
175   // ... and terminate wavefront
176   BuildMI(MBB, Insert, DL, TII->get(AMDGPU::S_ENDPGM));
177 }
178
179 void SILowerControlFlowPass::If(MachineInstr &MI) {
180   MachineBasicBlock &MBB = *MI.getParent();
181   DebugLoc DL = MI.getDebugLoc();
182   unsigned Reg = MI.getOperand(0).getReg();
183   unsigned Vcc = MI.getOperand(1).getReg();
184
185   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), Reg)
186           .addReg(Vcc);
187
188   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_XOR_B64), Reg)
189           .addReg(AMDGPU::EXEC)
190           .addReg(Reg);
191
192   Skip(MI, MI.getOperand(2));
193
194   MI.eraseFromParent();
195 }
196
197 void SILowerControlFlowPass::Else(MachineInstr &MI) {
198   MachineBasicBlock &MBB = *MI.getParent();
199   DebugLoc DL = MI.getDebugLoc();
200   unsigned Dst = MI.getOperand(0).getReg();
201   unsigned Src = MI.getOperand(1).getReg();
202
203   BuildMI(MBB, MBB.getFirstNonPHI(), DL,
204           TII->get(AMDGPU::S_OR_SAVEEXEC_B64), Dst)
205           .addReg(Src); // Saved EXEC
206
207   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
208           .addReg(AMDGPU::EXEC)
209           .addReg(Dst);
210
211   Skip(MI, MI.getOperand(2));
212
213   MI.eraseFromParent();
214 }
215
216 void SILowerControlFlowPass::Break(MachineInstr &MI) {
217   MachineBasicBlock &MBB = *MI.getParent();
218   DebugLoc DL = MI.getDebugLoc();
219
220   unsigned Dst = MI.getOperand(0).getReg();
221   unsigned Src = MI.getOperand(1).getReg();
222  
223   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst)
224           .addReg(AMDGPU::EXEC)
225           .addReg(Src);
226
227   MI.eraseFromParent();
228 }
229
230 void SILowerControlFlowPass::IfBreak(MachineInstr &MI) {
231   MachineBasicBlock &MBB = *MI.getParent();
232   DebugLoc DL = MI.getDebugLoc();
233
234   unsigned Dst = MI.getOperand(0).getReg();
235   unsigned Vcc = MI.getOperand(1).getReg();
236   unsigned Src = MI.getOperand(2).getReg();
237  
238   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst)
239           .addReg(Vcc)
240           .addReg(Src);
241
242   MI.eraseFromParent();
243 }
244
245 void SILowerControlFlowPass::ElseBreak(MachineInstr &MI) {
246   MachineBasicBlock &MBB = *MI.getParent();
247   DebugLoc DL = MI.getDebugLoc();
248
249   unsigned Dst = MI.getOperand(0).getReg();
250   unsigned Saved = MI.getOperand(1).getReg();
251   unsigned Src = MI.getOperand(2).getReg();
252  
253   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst)
254           .addReg(Saved)
255           .addReg(Src);
256
257   MI.eraseFromParent();
258 }
259
260 void SILowerControlFlowPass::Loop(MachineInstr &MI) {
261   MachineBasicBlock &MBB = *MI.getParent();
262   DebugLoc DL = MI.getDebugLoc();
263   unsigned Src = MI.getOperand(0).getReg();
264
265   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_ANDN2_B64), AMDGPU::EXEC)
266           .addReg(AMDGPU::EXEC)
267           .addReg(Src);
268
269   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
270           .addOperand(MI.getOperand(1))
271           .addReg(AMDGPU::EXEC);
272
273   MI.eraseFromParent();
274 }
275
276 void SILowerControlFlowPass::EndCf(MachineInstr &MI) {
277   MachineBasicBlock &MBB = *MI.getParent();
278   DebugLoc DL = MI.getDebugLoc();
279   unsigned Reg = MI.getOperand(0).getReg();
280
281   BuildMI(MBB, MBB.getFirstNonPHI(), DL,
282           TII->get(AMDGPU::S_OR_B64), AMDGPU::EXEC)
283           .addReg(AMDGPU::EXEC)
284           .addReg(Reg);
285
286   MI.eraseFromParent();
287 }
288
289 void SILowerControlFlowPass::Branch(MachineInstr &MI) {
290   if (MI.getOperand(0).getMBB() == MI.getParent()->getNextNode())
291     MI.eraseFromParent();
292
293   // If these aren't equal, this is probably an infinite loop.
294 }
295
296 void SILowerControlFlowPass::Kill(MachineInstr &MI) {
297   MachineBasicBlock &MBB = *MI.getParent();
298   DebugLoc DL = MI.getDebugLoc();
299   const MachineOperand &Op = MI.getOperand(0);
300
301   // Kill is only allowed in pixel / geometry shaders
302   assert(MBB.getParent()->getInfo<SIMachineFunctionInfo>()->ShaderType ==
303          ShaderType::PIXEL ||
304          MBB.getParent()->getInfo<SIMachineFunctionInfo>()->ShaderType ==
305          ShaderType::GEOMETRY);
306
307   // Clear this thread from the exec mask if the operand is negative
308   if ((Op.isImm() || Op.isFPImm())) {
309     // Constant operand: Set exec mask to 0 or do nothing
310     if (Op.isImm() ? (Op.getImm() & 0x80000000) :
311         Op.getFPImm()->isNegative()) {
312       BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
313               .addImm(0);
314     }
315   } else {
316     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::V_CMPX_LE_F32_e32), AMDGPU::VCC)
317            .addImm(0)
318            .addOperand(Op);
319   }
320
321   MI.eraseFromParent();
322 }
323
324 /// The m0 register stores the maximum allowable address for LDS reads and
325 /// writes.  Its value must be at least the size in bytes of LDS allocated by
326 /// the shader.  For simplicity, we set it to the maximum possible value.
327 void SILowerControlFlowPass::InitM0ForLDS(MachineBasicBlock::iterator MI) {
328     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),  TII->get(AMDGPU::S_MOV_B32),
329             AMDGPU::M0).addImm(0xffffffff);
330 }
331
332 void SILowerControlFlowPass::LoadM0(MachineInstr &MI, MachineInstr *MovRel) {
333
334   MachineBasicBlock &MBB = *MI.getParent();
335   DebugLoc DL = MI.getDebugLoc();
336   MachineBasicBlock::iterator I = MI;
337
338   unsigned Save = MI.getOperand(1).getReg();
339   unsigned Idx = MI.getOperand(3).getReg();
340
341   if (AMDGPU::SReg_32RegClass.contains(Idx)) {
342     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
343             .addReg(Idx);
344     MBB.insert(I, MovRel);
345   } else {
346
347     assert(AMDGPU::SReg_64RegClass.contains(Save));
348     assert(AMDGPU::VReg_32RegClass.contains(Idx));
349
350     // Save the EXEC mask
351     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_MOV_B64), Save)
352             .addReg(AMDGPU::EXEC);
353
354     // Read the next variant into VCC (lower 32 bits) <- also loop target
355     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
356             AMDGPU::VCC_LO)
357             .addReg(Idx);
358
359     // Move index from VCC into M0
360     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
361             .addReg(AMDGPU::VCC_LO);
362
363     // Compare the just read M0 value to all possible Idx values
364     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e32), AMDGPU::VCC)
365             .addReg(AMDGPU::M0)
366             .addReg(Idx);
367
368     // Update EXEC, save the original EXEC value to VCC
369     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), AMDGPU::VCC)
370             .addReg(AMDGPU::VCC);
371
372     // Do the actual move
373     MBB.insert(I, MovRel);
374
375     // Update EXEC, switch all done bits to 0 and all todo bits to 1
376     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
377             .addReg(AMDGPU::EXEC)
378             .addReg(AMDGPU::VCC);
379
380     // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover
381     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
382             .addImm(-7)
383             .addReg(AMDGPU::EXEC);
384
385     // Restore EXEC
386     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
387             .addReg(Save);
388
389   }
390   // FIXME: Are there any values other than the LDS address clamp that need to
391   // be stored in the m0 register and may be live for more than a few
392   // instructions?  If so, we should save the m0 register at the beginning
393   // of this function and restore it here.
394   // FIXME: Add support for LDS direct loads.
395   InitM0ForLDS(&MI);
396   MI.eraseFromParent();
397 }
398
399 void SILowerControlFlowPass::IndirectSrc(MachineInstr &MI) {
400
401   MachineBasicBlock &MBB = *MI.getParent();
402   DebugLoc DL = MI.getDebugLoc();
403
404   unsigned Dst = MI.getOperand(0).getReg();
405   unsigned Vec = MI.getOperand(2).getReg();
406   unsigned Off = MI.getOperand(4).getImm();
407   unsigned SubReg = TRI->getSubReg(Vec, AMDGPU::sub0);
408   if (!SubReg)
409     SubReg = Vec;
410
411   MachineInstr *MovRel =
412     BuildMI(*MBB.getParent(), DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
413             .addReg(SubReg + Off)
414             .addReg(AMDGPU::M0, RegState::Implicit)
415             .addReg(Vec, RegState::Implicit);
416
417   LoadM0(MI, MovRel);
418 }
419
420 void SILowerControlFlowPass::IndirectDst(MachineInstr &MI) {
421
422   MachineBasicBlock &MBB = *MI.getParent();
423   DebugLoc DL = MI.getDebugLoc();
424
425   unsigned Dst = MI.getOperand(0).getReg();
426   unsigned Off = MI.getOperand(4).getImm();
427   unsigned Val = MI.getOperand(5).getReg();
428   unsigned SubReg = TRI->getSubReg(Dst, AMDGPU::sub0);
429   if (!SubReg)
430     SubReg = Dst;
431
432   MachineInstr *MovRel = 
433     BuildMI(*MBB.getParent(), DL, TII->get(AMDGPU::V_MOVRELD_B32_e32))
434             .addReg(SubReg + Off, RegState::Define)
435             .addReg(Val)
436             .addReg(AMDGPU::M0, RegState::Implicit)
437             .addReg(Dst, RegState::Implicit);
438
439   LoadM0(MI, MovRel);
440 }
441
442 bool SILowerControlFlowPass::runOnMachineFunction(MachineFunction &MF) {
443   TII = static_cast<const SIInstrInfo*>(MF.getTarget().getInstrInfo());
444   TRI = static_cast<const SIRegisterInfo*>(MF.getTarget().getRegisterInfo());
445   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
446
447   bool HaveKill = false;
448   bool NeedM0 = false;
449   bool NeedWQM = false;
450   unsigned Depth = 0;
451
452   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
453        BI != BE; ++BI) {
454
455     MachineBasicBlock &MBB = *BI;
456     MachineBasicBlock::iterator I, Next;
457     for (I = MBB.begin(); I != MBB.end(); I = Next) {
458       Next = std::next(I);
459
460       MachineInstr &MI = *I;
461       if (TII->isDS(MI.getOpcode())) {
462         NeedM0 = true;
463         NeedWQM = true;
464       }
465
466       switch (MI.getOpcode()) {
467         default: break;
468         case AMDGPU::SI_IF:
469           ++Depth;
470           If(MI);
471           break;
472
473         case AMDGPU::SI_ELSE:
474           Else(MI);
475           break;
476
477         case AMDGPU::SI_BREAK:
478           Break(MI);
479           break;
480
481         case AMDGPU::SI_IF_BREAK:
482           IfBreak(MI);
483           break;
484
485         case AMDGPU::SI_ELSE_BREAK:
486           ElseBreak(MI);
487           break;
488
489         case AMDGPU::SI_LOOP:
490           ++Depth;
491           Loop(MI);
492           break;
493
494         case AMDGPU::SI_END_CF:
495           if (--Depth == 0 && HaveKill) {
496             SkipIfDead(MI);
497             HaveKill = false;
498           }
499           EndCf(MI);
500           break;
501
502         case AMDGPU::SI_KILL:
503           if (Depth == 0)
504             SkipIfDead(MI);
505           else
506             HaveKill = true;
507           Kill(MI);
508           break;
509
510         case AMDGPU::S_BRANCH:
511           Branch(MI);
512           break;
513
514         case AMDGPU::SI_INDIRECT_SRC:
515           IndirectSrc(MI);
516           break;
517
518         case AMDGPU::SI_INDIRECT_DST_V1:
519         case AMDGPU::SI_INDIRECT_DST_V2:
520         case AMDGPU::SI_INDIRECT_DST_V4:
521         case AMDGPU::SI_INDIRECT_DST_V8:
522         case AMDGPU::SI_INDIRECT_DST_V16:
523           IndirectDst(MI);
524           break;
525
526         case AMDGPU::V_INTERP_P1_F32:
527         case AMDGPU::V_INTERP_P2_F32:
528         case AMDGPU::V_INTERP_MOV_F32:
529           NeedWQM = true;
530           break;
531
532       }
533     }
534   }
535
536   if (NeedM0) {
537     MachineBasicBlock &MBB = MF.front();
538     // Initialize M0 to a value that won't cause LDS access to be discarded
539     // due to offset clamping
540     InitM0ForLDS(MBB.getFirstNonPHI());
541   }
542
543   if (NeedWQM && MFI->ShaderType == ShaderType::PIXEL) {
544     MachineBasicBlock &MBB = MF.front();
545     BuildMI(MBB, MBB.getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::S_WQM_B64),
546             AMDGPU::EXEC).addReg(AMDGPU::EXEC);
547   }
548
549   return true;
550 }