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 "AMDGPUSubtarget.h" 53 #include "SIInstrInfo.h" 54 #include "llvm/ADT/SmallVector.h" 55 #include "llvm/ADT/StringRef.h" 56 #include "llvm/CodeGen/LiveIntervals.h" 57 #include "llvm/CodeGen/MachineBasicBlock.h" 58 #include "llvm/CodeGen/MachineFunction.h" 59 #include "llvm/CodeGen/MachineFunctionPass.h" 60 #include "llvm/CodeGen/MachineInstr.h" 61 #include "llvm/CodeGen/MachineInstrBuilder.h" 62 #include "llvm/CodeGen/MachineOperand.h" 63 #include "llvm/CodeGen/MachineRegisterInfo.h" 64 #include "llvm/CodeGen/Passes.h" 65 #include "llvm/CodeGen/SlotIndexes.h" 66 #include "llvm/CodeGen/TargetRegisterInfo.h" 67 #include "llvm/MC/MCRegisterInfo.h" 68 #include "llvm/Pass.h" 69 #include <cassert> 70 #include <iterator> 71 72 using namespace llvm; 73 74 #define DEBUG_TYPE "si-lower-control-flow" 75 76 namespace { 77 78 class SILowerControlFlow : public MachineFunctionPass { 79 private: 80 const SIRegisterInfo *TRI = nullptr; 81 const SIInstrInfo *TII = nullptr; 82 LiveIntervals *LIS = nullptr; 83 MachineRegisterInfo *MRI = nullptr; 84 85 void emitIf(MachineInstr &MI); 86 void emitElse(MachineInstr &MI); 87 void emitBreak(MachineInstr &MI); 88 void emitIfBreak(MachineInstr &MI); 89 void emitElseBreak(MachineInstr &MI); 90 void emitLoop(MachineInstr &MI); 91 void emitEndCf(MachineInstr &MI); 92 93 void findMaskOperands(MachineInstr &MI, unsigned OpNo, 94 SmallVectorImpl<MachineOperand> &Src) const; 95 96 void combineMasks(MachineInstr &MI); 97 98 public: 99 static char ID; 100 101 SILowerControlFlow() : MachineFunctionPass(ID) {} 102 103 bool runOnMachineFunction(MachineFunction &MF) override; 104 105 StringRef getPassName() const override { 106 return "SI Lower control flow pseudo instructions"; 107 } 108 109 void getAnalysisUsage(AnalysisUsage &AU) const override { 110 // Should preserve the same set that TwoAddressInstructions does. 111 AU.addPreserved<SlotIndexes>(); 112 AU.addPreserved<LiveIntervals>(); 113 AU.addPreservedID(LiveVariablesID); 114 AU.addPreservedID(MachineLoopInfoID); 115 AU.addPreservedID(MachineDominatorsID); 116 AU.setPreservesCFG(); 117 MachineFunctionPass::getAnalysisUsage(AU); 118 } 119 }; 120 121 } // end anonymous namespace 122 123 char SILowerControlFlow::ID = 0; 124 125 INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE, 126 "SI lower control flow", false, false) 127 128 static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) { 129 MachineOperand &ImpDefSCC = MI.getOperand(3); 130 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef()); 131 132 ImpDefSCC.setIsDead(IsDead); 133 } 134 135 char &llvm::SILowerControlFlowID = SILowerControlFlow::ID; 136 137 static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI, 138 const SIInstrInfo *TII) { 139 unsigned SaveExecReg = MI.getOperand(0).getReg(); 140 auto U = MRI->use_instr_nodbg_begin(SaveExecReg); 141 142 if (U == MRI->use_instr_nodbg_end() || 143 std::next(U) != MRI->use_instr_nodbg_end() || 144 U->getOpcode() != AMDGPU::SI_END_CF) 145 return false; 146 147 // Check for SI_KILL_*_TERMINATOR on path from if to endif. 148 // if there is any such terminator simplififcations are not safe. 149 auto SMBB = MI.getParent(); 150 auto EMBB = U->getParent(); 151 DenseSet<const MachineBasicBlock*> Visited; 152 SmallVector<MachineBasicBlock*, 4> Worklist(SMBB->succ_begin(), 153 SMBB->succ_end()); 154 155 while (!Worklist.empty()) { 156 MachineBasicBlock *MBB = Worklist.pop_back_val(); 157 158 if (MBB == EMBB || !Visited.insert(MBB).second) 159 continue; 160 for(auto &Term : MBB->terminators()) 161 if (TII->isKillTerminator(Term.getOpcode())) 162 return false; 163 164 Worklist.append(MBB->succ_begin(), MBB->succ_end()); 165 } 166 167 return true; 168 } 169 170 void SILowerControlFlow::emitIf(MachineInstr &MI) { 171 MachineBasicBlock &MBB = *MI.getParent(); 172 const DebugLoc &DL = MI.getDebugLoc(); 173 MachineBasicBlock::iterator I(&MI); 174 175 MachineOperand &SaveExec = MI.getOperand(0); 176 MachineOperand &Cond = MI.getOperand(1); 177 assert(SaveExec.getSubReg() == AMDGPU::NoSubRegister && 178 Cond.getSubReg() == AMDGPU::NoSubRegister); 179 180 unsigned SaveExecReg = SaveExec.getReg(); 181 182 MachineOperand &ImpDefSCC = MI.getOperand(4); 183 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef()); 184 185 // If there is only one use of save exec register and that use is SI_END_CF, 186 // we can optimize SI_IF by returning the full saved exec mask instead of 187 // just cleared bits. 188 bool SimpleIf = isSimpleIf(MI, MRI, TII); 189 190 // Add an implicit def of exec to discourage scheduling VALU after this which 191 // will interfere with trying to form s_and_saveexec_b64 later. 192 unsigned CopyReg = SimpleIf ? SaveExecReg 193 : MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); 194 MachineInstr *CopyExec = 195 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg) 196 .addReg(AMDGPU::EXEC) 197 .addReg(AMDGPU::EXEC, RegState::ImplicitDefine); 198 199 unsigned Tmp = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); 200 201 MachineInstr *And = 202 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_AND_B64), Tmp) 203 .addReg(CopyReg) 204 //.addReg(AMDGPU::EXEC) 205 .addReg(Cond.getReg()); 206 setImpSCCDefDead(*And, true); 207 208 MachineInstr *Xor = nullptr; 209 if (!SimpleIf) { 210 Xor = 211 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_XOR_B64), SaveExecReg) 212 .addReg(Tmp) 213 .addReg(CopyReg); 214 setImpSCCDefDead(*Xor, ImpDefSCC.isDead()); 215 } 216 217 // Use a copy that is a terminator to get correct spill code placement it with 218 // fast regalloc. 219 MachineInstr *SetExec = 220 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64_term), AMDGPU::EXEC) 221 .addReg(Tmp, RegState::Kill); 222 223 // Insert a pseudo terminator to help keep the verifier happy. This will also 224 // be used later when inserting skips. 225 MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::SI_MASK_BRANCH)) 226 .add(MI.getOperand(2)); 227 228 if (!LIS) { 229 MI.eraseFromParent(); 230 return; 231 } 232 233 LIS->InsertMachineInstrInMaps(*CopyExec); 234 235 // Replace with and so we don't need to fix the live interval for condition 236 // register. 237 LIS->ReplaceMachineInstrInMaps(MI, *And); 238 239 if (!SimpleIf) 240 LIS->InsertMachineInstrInMaps(*Xor); 241 LIS->InsertMachineInstrInMaps(*SetExec); 242 LIS->InsertMachineInstrInMaps(*NewBr); 243 244 LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::EXEC, TRI)); 245 MI.eraseFromParent(); 246 247 // FIXME: Is there a better way of adjusting the liveness? It shouldn't be 248 // hard to add another def here but I'm not sure how to correctly update the 249 // valno. 250 LIS->removeInterval(SaveExecReg); 251 LIS->createAndComputeVirtRegInterval(SaveExecReg); 252 LIS->createAndComputeVirtRegInterval(Tmp); 253 if (!SimpleIf) 254 LIS->createAndComputeVirtRegInterval(CopyReg); 255 } 256 257 void SILowerControlFlow::emitElse(MachineInstr &MI) { 258 MachineBasicBlock &MBB = *MI.getParent(); 259 const DebugLoc &DL = MI.getDebugLoc(); 260 261 unsigned DstReg = MI.getOperand(0).getReg(); 262 assert(MI.getOperand(0).getSubReg() == AMDGPU::NoSubRegister); 263 264 bool ExecModified = MI.getOperand(3).getImm() != 0; 265 MachineBasicBlock::iterator Start = MBB.begin(); 266 267 // We are running before TwoAddressInstructions, and si_else's operands are 268 // tied. In order to correctly tie the registers, split this into a copy of 269 // the src like it does. 270 unsigned CopyReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); 271 MachineInstr *CopyExec = 272 BuildMI(MBB, Start, DL, TII->get(AMDGPU::COPY), CopyReg) 273 .add(MI.getOperand(1)); // Saved EXEC 274 275 // This must be inserted before phis and any spill code inserted before the 276 // else. 277 unsigned SaveReg = ExecModified ? 278 MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass) : DstReg; 279 MachineInstr *OrSaveExec = 280 BuildMI(MBB, Start, DL, TII->get(AMDGPU::S_OR_SAVEEXEC_B64), SaveReg) 281 .addReg(CopyReg); 282 283 MachineBasicBlock *DestBB = MI.getOperand(2).getMBB(); 284 285 MachineBasicBlock::iterator ElsePt(MI); 286 287 if (ExecModified) { 288 MachineInstr *And = 289 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_AND_B64), DstReg) 290 .addReg(AMDGPU::EXEC) 291 .addReg(SaveReg); 292 293 if (LIS) 294 LIS->InsertMachineInstrInMaps(*And); 295 } 296 297 MachineInstr *Xor = 298 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_XOR_B64_term), AMDGPU::EXEC) 299 .addReg(AMDGPU::EXEC) 300 .addReg(DstReg); 301 302 MachineInstr *Branch = 303 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::SI_MASK_BRANCH)) 304 .addMBB(DestBB); 305 306 if (!LIS) { 307 MI.eraseFromParent(); 308 return; 309 } 310 311 LIS->RemoveMachineInstrFromMaps(MI); 312 MI.eraseFromParent(); 313 314 LIS->InsertMachineInstrInMaps(*CopyExec); 315 LIS->InsertMachineInstrInMaps(*OrSaveExec); 316 317 LIS->InsertMachineInstrInMaps(*Xor); 318 LIS->InsertMachineInstrInMaps(*Branch); 319 320 // src reg is tied to dst reg. 321 LIS->removeInterval(DstReg); 322 LIS->createAndComputeVirtRegInterval(DstReg); 323 LIS->createAndComputeVirtRegInterval(CopyReg); 324 if (ExecModified) 325 LIS->createAndComputeVirtRegInterval(SaveReg); 326 327 // Let this be recomputed. 328 LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::EXEC, TRI)); 329 } 330 331 void SILowerControlFlow::emitBreak(MachineInstr &MI) { 332 MachineBasicBlock &MBB = *MI.getParent(); 333 const DebugLoc &DL = MI.getDebugLoc(); 334 unsigned Dst = MI.getOperand(0).getReg(); 335 336 MachineInstr *Or = BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst) 337 .addReg(AMDGPU::EXEC) 338 .add(MI.getOperand(1)); 339 340 if (LIS) 341 LIS->ReplaceMachineInstrInMaps(MI, *Or); 342 MI.eraseFromParent(); 343 } 344 345 void SILowerControlFlow::emitIfBreak(MachineInstr &MI) { 346 MI.setDesc(TII->get(AMDGPU::S_OR_B64)); 347 } 348 349 void SILowerControlFlow::emitElseBreak(MachineInstr &MI) { 350 MI.setDesc(TII->get(AMDGPU::S_OR_B64)); 351 } 352 353 void SILowerControlFlow::emitLoop(MachineInstr &MI) { 354 MachineBasicBlock &MBB = *MI.getParent(); 355 const DebugLoc &DL = MI.getDebugLoc(); 356 357 MachineInstr *AndN2 = 358 BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_ANDN2_B64_term), AMDGPU::EXEC) 359 .addReg(AMDGPU::EXEC) 360 .add(MI.getOperand(0)); 361 362 MachineInstr *Branch = 363 BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 364 .add(MI.getOperand(1)); 365 366 if (LIS) { 367 LIS->ReplaceMachineInstrInMaps(MI, *AndN2); 368 LIS->InsertMachineInstrInMaps(*Branch); 369 } 370 371 MI.eraseFromParent(); 372 } 373 374 void SILowerControlFlow::emitEndCf(MachineInstr &MI) { 375 MachineBasicBlock &MBB = *MI.getParent(); 376 const DebugLoc &DL = MI.getDebugLoc(); 377 378 MachineBasicBlock::iterator InsPt = MBB.begin(); 379 MachineInstr *NewMI = 380 BuildMI(MBB, InsPt, DL, TII->get(AMDGPU::S_OR_B64), AMDGPU::EXEC) 381 .addReg(AMDGPU::EXEC) 382 .add(MI.getOperand(0)); 383 384 if (LIS) 385 LIS->ReplaceMachineInstrInMaps(MI, *NewMI); 386 387 MI.eraseFromParent(); 388 389 if (LIS) 390 LIS->handleMove(*NewMI); 391 } 392 393 // Returns replace operands for a logical operation, either single result 394 // for exec or two operands if source was another equivalent operation. 395 void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo, 396 SmallVectorImpl<MachineOperand> &Src) const { 397 MachineOperand &Op = MI.getOperand(OpNo); 398 if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg())) { 399 Src.push_back(Op); 400 return; 401 } 402 403 MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg()); 404 if (!Def || Def->getParent() != MI.getParent() || 405 !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode()))) 406 return; 407 408 // Make sure we do not modify exec between def and use. 409 // A copy with implcitly defined exec inserted earlier is an exclusion, it 410 // does not really modify exec. 411 for (auto I = Def->getIterator(); I != MI.getIterator(); ++I) 412 if (I->modifiesRegister(AMDGPU::EXEC, TRI) && 413 !(I->isCopy() && I->getOperand(0).getReg() != AMDGPU::EXEC)) 414 return; 415 416 for (const auto &SrcOp : Def->explicit_operands()) 417 if (SrcOp.isUse() && (!SrcOp.isReg() || 418 TargetRegisterInfo::isVirtualRegister(SrcOp.getReg()) || 419 SrcOp.getReg() == AMDGPU::EXEC)) 420 Src.push_back(SrcOp); 421 } 422 423 // Search and combine pairs of equivalent instructions, like 424 // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y 425 // S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y 426 // One of the operands is exec mask. 427 void SILowerControlFlow::combineMasks(MachineInstr &MI) { 428 assert(MI.getNumExplicitOperands() == 3); 429 SmallVector<MachineOperand, 4> Ops; 430 unsigned OpToReplace = 1; 431 findMaskOperands(MI, 1, Ops); 432 if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy 433 findMaskOperands(MI, 2, Ops); 434 if (Ops.size() != 3) return; 435 436 unsigned UniqueOpndIdx; 437 if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2; 438 else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1; 439 else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1; 440 else return; 441 442 unsigned Reg = MI.getOperand(OpToReplace).getReg(); 443 MI.RemoveOperand(OpToReplace); 444 MI.addOperand(Ops[UniqueOpndIdx]); 445 if (MRI->use_empty(Reg)) 446 MRI->getUniqueVRegDef(Reg)->eraseFromParent(); 447 } 448 449 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) { 450 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 451 TII = ST.getInstrInfo(); 452 TRI = &TII->getRegisterInfo(); 453 454 // This doesn't actually need LiveIntervals, but we can preserve them. 455 LIS = getAnalysisIfAvailable<LiveIntervals>(); 456 MRI = &MF.getRegInfo(); 457 458 MachineFunction::iterator NextBB; 459 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); 460 BI != BE; BI = NextBB) { 461 NextBB = std::next(BI); 462 MachineBasicBlock &MBB = *BI; 463 464 MachineBasicBlock::iterator I, Next, Last; 465 466 for (I = MBB.begin(), Last = MBB.end(); I != MBB.end(); I = Next) { 467 Next = std::next(I); 468 MachineInstr &MI = *I; 469 470 switch (MI.getOpcode()) { 471 case AMDGPU::SI_IF: 472 emitIf(MI); 473 break; 474 475 case AMDGPU::SI_ELSE: 476 emitElse(MI); 477 break; 478 479 case AMDGPU::SI_BREAK: 480 emitBreak(MI); 481 break; 482 483 case AMDGPU::SI_IF_BREAK: 484 emitIfBreak(MI); 485 break; 486 487 case AMDGPU::SI_ELSE_BREAK: 488 emitElseBreak(MI); 489 break; 490 491 case AMDGPU::SI_LOOP: 492 emitLoop(MI); 493 break; 494 495 case AMDGPU::SI_END_CF: 496 emitEndCf(MI); 497 break; 498 499 case AMDGPU::S_AND_B64: 500 case AMDGPU::S_OR_B64: 501 // Cleanup bit manipulations on exec mask 502 combineMasks(MI); 503 Last = I; 504 continue; 505 506 default: 507 Last = I; 508 continue; 509 } 510 511 // Replay newly inserted code to combine masks 512 Next = (Last == MBB.end()) ? MBB.begin() : Last; 513 } 514 } 515 516 return true; 517 } 518