1 //===-- ARMLowOverheadLoops.cpp - CodeGen Low-overhead Loops ---*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// Finalize v8.1-m low-overhead loops by converting the associated pseudo 10 /// instructions into machine operations. 11 /// The expectation is that the loop contains three pseudo instructions: 12 /// - t2*LoopStart - placed in the preheader or pre-preheader. The do-loop 13 /// form should be in the preheader, whereas the while form should be in the 14 /// preheaders only predecessor. 15 /// - t2LoopDec - placed within in the loop body. 16 /// - t2LoopEnd - the loop latch terminator. 17 /// 18 /// In addition to this, we also look for the presence of the VCTP instruction, 19 /// which determines whether we can generated the tail-predicated low-overhead 20 /// loop form. 21 /// 22 /// Assumptions and Dependencies: 23 /// Low-overhead loops are constructed and executed using a setup instruction: 24 /// DLS, WLS, DLSTP or WLSTP and an instruction that loops back: LE or LETP. 25 /// WLS(TP) and LE(TP) are branching instructions with a (large) limited range 26 /// but fixed polarity: WLS can only branch forwards and LE can only branch 27 /// backwards. These restrictions mean that this pass is dependent upon block 28 /// layout and block sizes, which is why it's the last pass to run. The same is 29 /// true for ConstantIslands, but this pass does not increase the size of the 30 /// basic blocks, nor does it change the CFG. Instructions are mainly removed 31 /// during the transform and pseudo instructions are replaced by real ones. In 32 /// some cases, when we have to revert to a 'normal' loop, we have to introduce 33 /// multiple instructions for a single pseudo (see RevertWhile and 34 /// RevertLoopEnd). To handle this situation, t2WhileLoopStart and t2LoopEnd 35 /// are defined to be as large as this maximum sequence of replacement 36 /// instructions. 37 /// 38 /// A note on VPR.P0 (the lane mask): 39 /// VPT, VCMP, VPNOT and VCTP won't overwrite VPR.P0 when they update it in a 40 /// "VPT Active" context (which includes low-overhead loops and vpt blocks). 41 /// They will simply "and" the result of their calculation with the current 42 /// value of VPR.P0. You can think of it like this: 43 /// \verbatim 44 /// if VPT active: ; Between a DLSTP/LETP, or for predicated instrs 45 /// VPR.P0 &= Value 46 /// else 47 /// VPR.P0 = Value 48 /// \endverbatim 49 /// When we're inside the low-overhead loop (between DLSTP and LETP), we always 50 /// fall in the "VPT active" case, so we can consider that all VPR writes by 51 /// one of those instruction is actually a "and". 52 //===----------------------------------------------------------------------===// 53 54 #include "ARM.h" 55 #include "ARMBaseInstrInfo.h" 56 #include "ARMBaseRegisterInfo.h" 57 #include "ARMBasicBlockInfo.h" 58 #include "ARMSubtarget.h" 59 #include "Thumb2InstrInfo.h" 60 #include "llvm/ADT/SetOperations.h" 61 #include "llvm/ADT/SmallSet.h" 62 #include "llvm/CodeGen/LivePhysRegs.h" 63 #include "llvm/CodeGen/MachineFunctionPass.h" 64 #include "llvm/CodeGen/MachineLoopInfo.h" 65 #include "llvm/CodeGen/MachineLoopUtils.h" 66 #include "llvm/CodeGen/MachineRegisterInfo.h" 67 #include "llvm/CodeGen/Passes.h" 68 #include "llvm/CodeGen/ReachingDefAnalysis.h" 69 #include "llvm/MC/MCInstrDesc.h" 70 71 using namespace llvm; 72 73 #define DEBUG_TYPE "arm-low-overhead-loops" 74 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass" 75 76 static cl::opt<bool> 77 DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden, 78 cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"), 79 cl::init(false)); 80 81 static bool isVectorPredicated(MachineInstr *MI) { 82 int PIdx = llvm::findFirstVPTPredOperandIdx(*MI); 83 return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR; 84 } 85 86 static bool isVectorPredicate(MachineInstr *MI) { 87 return MI->findRegisterDefOperandIdx(ARM::VPR) != -1; 88 } 89 90 static bool hasVPRUse(MachineInstr *MI) { 91 return MI->findRegisterUseOperandIdx(ARM::VPR) != -1; 92 } 93 94 static bool isDomainMVE(MachineInstr *MI) { 95 uint64_t Domain = MI->getDesc().TSFlags & ARMII::DomainMask; 96 return Domain == ARMII::DomainMVE; 97 } 98 99 static bool shouldInspect(MachineInstr &MI) { 100 return isDomainMVE(&MI) || isVectorPredicate(&MI) || 101 hasVPRUse(&MI); 102 } 103 104 static bool isDo(MachineInstr *MI) { 105 return MI->getOpcode() != ARM::t2WhileLoopStart; 106 } 107 108 namespace { 109 110 using InstSet = SmallPtrSetImpl<MachineInstr *>; 111 112 class PostOrderLoopTraversal { 113 MachineLoop &ML; 114 MachineLoopInfo &MLI; 115 SmallPtrSet<MachineBasicBlock*, 4> Visited; 116 SmallVector<MachineBasicBlock*, 4> Order; 117 118 public: 119 PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI) 120 : ML(ML), MLI(MLI) { } 121 122 const SmallVectorImpl<MachineBasicBlock*> &getOrder() const { 123 return Order; 124 } 125 126 // Visit all the blocks within the loop, as well as exit blocks and any 127 // blocks properly dominating the header. 128 void ProcessLoop() { 129 std::function<void(MachineBasicBlock*)> Search = [this, &Search] 130 (MachineBasicBlock *MBB) -> void { 131 if (Visited.count(MBB)) 132 return; 133 134 Visited.insert(MBB); 135 for (auto *Succ : MBB->successors()) { 136 if (!ML.contains(Succ)) 137 continue; 138 Search(Succ); 139 } 140 Order.push_back(MBB); 141 }; 142 143 // Insert exit blocks. 144 SmallVector<MachineBasicBlock*, 2> ExitBlocks; 145 ML.getExitBlocks(ExitBlocks); 146 for (auto *MBB : ExitBlocks) 147 Order.push_back(MBB); 148 149 // Then add the loop body. 150 Search(ML.getHeader()); 151 152 // Then try the preheader and its predecessors. 153 std::function<void(MachineBasicBlock*)> GetPredecessor = 154 [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void { 155 Order.push_back(MBB); 156 if (MBB->pred_size() == 1) 157 GetPredecessor(*MBB->pred_begin()); 158 }; 159 160 if (auto *Preheader = ML.getLoopPreheader()) 161 GetPredecessor(Preheader); 162 else if (auto *Preheader = MLI.findLoopPreheader(&ML, true)) 163 GetPredecessor(Preheader); 164 } 165 }; 166 167 struct PredicatedMI { 168 MachineInstr *MI = nullptr; 169 SetVector<MachineInstr*> Predicates; 170 171 public: 172 PredicatedMI(MachineInstr *I, SetVector<MachineInstr *> &Preds) : MI(I) { 173 assert(I && "Instruction must not be null!"); 174 Predicates.insert(Preds.begin(), Preds.end()); 175 } 176 }; 177 178 // Represent the current state of the VPR and hold all instances which 179 // represent a VPT block, which is a list of instructions that begins with a 180 // VPT/VPST and has a maximum of four proceeding instructions. All 181 // instructions within the block are predicated upon the vpr and we allow 182 // instructions to define the vpr within in the block too. 183 class VPTState { 184 friend struct LowOverheadLoop; 185 186 SmallVector<MachineInstr *, 4> Insts; 187 188 static SmallVector<VPTState, 4> Blocks; 189 static SetVector<MachineInstr *> CurrentPredicates; 190 static std::map<MachineInstr *, 191 std::unique_ptr<PredicatedMI>> PredicatedInsts; 192 193 static void CreateVPTBlock(MachineInstr *MI) { 194 assert((CurrentPredicates.size() || MI->getParent()->isLiveIn(ARM::VPR)) 195 && "Can't begin VPT without predicate"); 196 Blocks.emplace_back(MI); 197 // The execution of MI is predicated upon the current set of instructions 198 // that are AND'ed together to form the VPR predicate value. In the case 199 // that MI is a VPT, CurrentPredicates will also just be MI. 200 PredicatedInsts.emplace( 201 MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates)); 202 } 203 204 static void reset() { 205 Blocks.clear(); 206 PredicatedInsts.clear(); 207 CurrentPredicates.clear(); 208 } 209 210 static void addInst(MachineInstr *MI) { 211 Blocks.back().insert(MI); 212 PredicatedInsts.emplace( 213 MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates)); 214 } 215 216 static void addPredicate(MachineInstr *MI) { 217 LLVM_DEBUG(dbgs() << "ARM Loops: Adding VPT Predicate: " << *MI); 218 CurrentPredicates.insert(MI); 219 } 220 221 static void resetPredicate(MachineInstr *MI) { 222 LLVM_DEBUG(dbgs() << "ARM Loops: Resetting VPT Predicate: " << *MI); 223 CurrentPredicates.clear(); 224 CurrentPredicates.insert(MI); 225 } 226 227 public: 228 // Have we found an instruction within the block which defines the vpr? If 229 // so, not all the instructions in the block will have the same predicate. 230 static bool hasUniformPredicate(VPTState &Block) { 231 return getDivergent(Block) == nullptr; 232 } 233 234 // If it exists, return the first internal instruction which modifies the 235 // VPR. 236 static MachineInstr *getDivergent(VPTState &Block) { 237 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 238 for (unsigned i = 1; i < Insts.size(); ++i) { 239 MachineInstr *Next = Insts[i]; 240 if (isVectorPredicate(Next)) 241 return Next; // Found an instruction altering the vpr. 242 } 243 return nullptr; 244 } 245 246 // Return whether the given instruction is predicated upon a VCTP. 247 static bool isPredicatedOnVCTP(MachineInstr *MI, bool Exclusive = false) { 248 SetVector<MachineInstr *> &Predicates = PredicatedInsts[MI]->Predicates; 249 if (Exclusive && Predicates.size() != 1) 250 return false; 251 for (auto *PredMI : Predicates) 252 if (isVCTP(PredMI)) 253 return true; 254 return false; 255 } 256 257 // Is the VPST, controlling the block entry, predicated upon a VCTP. 258 static bool isEntryPredicatedOnVCTP(VPTState &Block, 259 bool Exclusive = false) { 260 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 261 return isPredicatedOnVCTP(Insts.front(), Exclusive); 262 } 263 264 // If this block begins with a VPT, we can check whether it's using 265 // at least one predicated input(s), as well as possible loop invariant 266 // which would result in it being implicitly predicated. 267 static bool hasImplicitlyValidVPT(VPTState &Block, 268 ReachingDefAnalysis &RDA) { 269 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 270 MachineInstr *VPT = Insts.front(); 271 assert(isVPTOpcode(VPT->getOpcode()) && 272 "Expected VPT block to begin with VPT/VPST"); 273 274 if (VPT->getOpcode() == ARM::MVE_VPST) 275 return false; 276 277 auto IsOperandPredicated = [&](MachineInstr *MI, unsigned Idx) { 278 MachineInstr *Op = RDA.getMIOperand(MI, MI->getOperand(Idx)); 279 return Op && PredicatedInsts.count(Op) && isPredicatedOnVCTP(Op); 280 }; 281 282 auto IsOperandInvariant = [&](MachineInstr *MI, unsigned Idx) { 283 MachineOperand &MO = MI->getOperand(Idx); 284 if (!MO.isReg() || !MO.getReg()) 285 return true; 286 287 SmallPtrSet<MachineInstr *, 2> Defs; 288 RDA.getGlobalReachingDefs(MI, MO.getReg(), Defs); 289 if (Defs.empty()) 290 return true; 291 292 for (auto *Def : Defs) 293 if (Def->getParent() == VPT->getParent()) 294 return false; 295 return true; 296 }; 297 298 // Check that at least one of the operands is directly predicated on a 299 // vctp and allow an invariant value too. 300 return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) && 301 (IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) && 302 (IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2)); 303 } 304 305 static bool isValid(ReachingDefAnalysis &RDA) { 306 // All predication within the loop should be based on vctp. If the block 307 // isn't predicated on entry, check whether the vctp is within the block 308 // and that all other instructions are then predicated on it. 309 for (auto &Block : Blocks) { 310 if (isEntryPredicatedOnVCTP(Block, false) || 311 hasImplicitlyValidVPT(Block, RDA)) 312 continue; 313 314 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 315 for (auto *MI : Insts) { 316 // Check that any internal VCTPs are 'Then' predicated. 317 if (isVCTP(MI) && getVPTInstrPredicate(*MI) != ARMVCC::Then) 318 return false; 319 // Skip other instructions that build up the predicate. 320 if (MI->getOpcode() == ARM::MVE_VPST || isVectorPredicate(MI)) 321 continue; 322 // Check that any other instructions are predicated upon a vctp. 323 // TODO: We could infer when VPTs are implicitly predicated on the 324 // vctp (when the operands are predicated). 325 if (!isPredicatedOnVCTP(MI)) { 326 LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *MI); 327 return false; 328 } 329 } 330 } 331 return true; 332 } 333 334 VPTState(MachineInstr *MI) { Insts.push_back(MI); } 335 336 void insert(MachineInstr *MI) { 337 Insts.push_back(MI); 338 // VPT/VPST + 4 predicated instructions. 339 assert(Insts.size() <= 5 && "Too many instructions in VPT block!"); 340 } 341 342 bool containsVCTP() const { 343 for (auto *MI : Insts) 344 if (isVCTP(MI)) 345 return true; 346 return false; 347 } 348 349 unsigned size() const { return Insts.size(); } 350 SmallVectorImpl<MachineInstr *> &getInsts() { return Insts; } 351 }; 352 353 struct LowOverheadLoop { 354 355 MachineLoop &ML; 356 MachineBasicBlock *Preheader = nullptr; 357 MachineLoopInfo &MLI; 358 ReachingDefAnalysis &RDA; 359 const TargetRegisterInfo &TRI; 360 const ARMBaseInstrInfo &TII; 361 MachineFunction *MF = nullptr; 362 MachineBasicBlock::iterator StartInsertPt; 363 MachineBasicBlock *StartInsertBB = nullptr; 364 MachineInstr *Start = nullptr; 365 MachineInstr *Dec = nullptr; 366 MachineInstr *End = nullptr; 367 MachineOperand TPNumElements; 368 SmallVector<MachineInstr*, 4> VCTPs; 369 SmallPtrSet<MachineInstr*, 4> ToRemove; 370 SmallPtrSet<MachineInstr*, 4> BlockMasksToRecompute; 371 bool Revert = false; 372 bool CannotTailPredicate = false; 373 374 LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI, 375 ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI, 376 const ARMBaseInstrInfo &TII) 377 : ML(ML), MLI(MLI), RDA(RDA), TRI(TRI), TII(TII), 378 TPNumElements(MachineOperand::CreateImm(0)) { 379 MF = ML.getHeader()->getParent(); 380 if (auto *MBB = ML.getLoopPreheader()) 381 Preheader = MBB; 382 else if (auto *MBB = MLI.findLoopPreheader(&ML, true)) 383 Preheader = MBB; 384 VPTState::reset(); 385 } 386 387 // If this is an MVE instruction, check that we know how to use tail 388 // predication with it. Record VPT blocks and return whether the 389 // instruction is valid for tail predication. 390 bool ValidateMVEInst(MachineInstr *MI); 391 392 void AnalyseMVEInst(MachineInstr *MI) { 393 CannotTailPredicate = !ValidateMVEInst(MI); 394 } 395 396 bool IsTailPredicationLegal() const { 397 // For now, let's keep things really simple and only support a single 398 // block for tail predication. 399 return !Revert && FoundAllComponents() && !VCTPs.empty() && 400 !CannotTailPredicate && ML.getNumBlocks() == 1; 401 } 402 403 // Given that MI is a VCTP, check that is equivalent to any other VCTPs 404 // found. 405 bool AddVCTP(MachineInstr *MI); 406 407 // Check that the predication in the loop will be equivalent once we 408 // perform the conversion. Also ensure that we can provide the number 409 // of elements to the loop start instruction. 410 bool ValidateTailPredicate(); 411 412 // Check that any values available outside of the loop will be the same 413 // after tail predication conversion. 414 bool ValidateLiveOuts(); 415 416 // Is it safe to define LR with DLS/WLS? 417 // LR can be defined if it is the operand to start, because it's the same 418 // value, or if it's going to be equivalent to the operand to Start. 419 MachineInstr *isSafeToDefineLR(); 420 421 // Check the branch targets are within range and we satisfy our 422 // restrictions. 423 void Validate(ARMBasicBlockUtils *BBUtils); 424 425 bool FoundAllComponents() const { 426 return Start && Dec && End; 427 } 428 429 SmallVectorImpl<VPTState> &getVPTBlocks() { 430 return VPTState::Blocks; 431 } 432 433 // Return the operand for the loop start instruction. This will be the loop 434 // iteration count, or the number of elements if we're tail predicating. 435 MachineOperand &getLoopStartOperand() { 436 if (IsTailPredicationLegal()) 437 return TPNumElements; 438 return isDo(Start) ? Start->getOperand(1) : Start->getOperand(0); 439 } 440 441 unsigned getStartOpcode() const { 442 bool IsDo = isDo(Start); 443 if (!IsTailPredicationLegal()) 444 return IsDo ? ARM::t2DLS : ARM::t2WLS; 445 446 return VCTPOpcodeToLSTP(VCTPs.back()->getOpcode(), IsDo); 447 } 448 449 void dump() const { 450 if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start; 451 if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec; 452 if (End) dbgs() << "ARM Loops: Found Loop End: " << *End; 453 if (!VCTPs.empty()) { 454 dbgs() << "ARM Loops: Found VCTP(s):\n"; 455 for (auto *MI : VCTPs) 456 dbgs() << " - " << *MI; 457 } 458 if (!FoundAllComponents()) 459 dbgs() << "ARM Loops: Not a low-overhead loop.\n"; 460 else if (!(Start && Dec && End)) 461 dbgs() << "ARM Loops: Failed to find all loop components.\n"; 462 } 463 }; 464 465 class ARMLowOverheadLoops : public MachineFunctionPass { 466 MachineFunction *MF = nullptr; 467 MachineLoopInfo *MLI = nullptr; 468 ReachingDefAnalysis *RDA = nullptr; 469 const ARMBaseInstrInfo *TII = nullptr; 470 MachineRegisterInfo *MRI = nullptr; 471 const TargetRegisterInfo *TRI = nullptr; 472 std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr; 473 474 public: 475 static char ID; 476 477 ARMLowOverheadLoops() : MachineFunctionPass(ID) { } 478 479 void getAnalysisUsage(AnalysisUsage &AU) const override { 480 AU.setPreservesCFG(); 481 AU.addRequired<MachineLoopInfo>(); 482 AU.addRequired<ReachingDefAnalysis>(); 483 MachineFunctionPass::getAnalysisUsage(AU); 484 } 485 486 bool runOnMachineFunction(MachineFunction &MF) override; 487 488 MachineFunctionProperties getRequiredProperties() const override { 489 return MachineFunctionProperties().set( 490 MachineFunctionProperties::Property::NoVRegs).set( 491 MachineFunctionProperties::Property::TracksLiveness); 492 } 493 494 StringRef getPassName() const override { 495 return ARM_LOW_OVERHEAD_LOOPS_NAME; 496 } 497 498 private: 499 bool ProcessLoop(MachineLoop *ML); 500 501 bool RevertNonLoops(); 502 503 void RevertWhile(MachineInstr *MI) const; 504 void RevertDo(MachineInstr *MI) const; 505 506 bool RevertLoopDec(MachineInstr *MI) const; 507 508 void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const; 509 510 void ConvertVPTBlocks(LowOverheadLoop &LoLoop); 511 512 MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop); 513 514 void Expand(LowOverheadLoop &LoLoop); 515 516 void IterationCountDCE(LowOverheadLoop &LoLoop); 517 }; 518 } 519 520 char ARMLowOverheadLoops::ID = 0; 521 522 SmallVector<VPTState, 4> VPTState::Blocks; 523 SetVector<MachineInstr *> VPTState::CurrentPredicates; 524 std::map<MachineInstr *, 525 std::unique_ptr<PredicatedMI>> VPTState::PredicatedInsts; 526 527 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME, 528 false, false) 529 530 static bool TryRemove(MachineInstr *MI, ReachingDefAnalysis &RDA, 531 InstSet &ToRemove, InstSet &Ignore) { 532 533 // Check that we can remove all of Killed without having to modify any IT 534 // blocks. 535 auto WontCorruptITs = [](InstSet &Killed, ReachingDefAnalysis &RDA) { 536 // Collect the dead code and the MBBs in which they reside. 537 SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks; 538 for (auto *Dead : Killed) 539 BasicBlocks.insert(Dead->getParent()); 540 541 // Collect IT blocks in all affected basic blocks. 542 std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks; 543 for (auto *MBB : BasicBlocks) { 544 for (auto &IT : *MBB) { 545 if (IT.getOpcode() != ARM::t2IT) 546 continue; 547 RDA.getReachingLocalUses(&IT, MCRegister::from(ARM::ITSTATE), 548 ITBlocks[&IT]); 549 } 550 } 551 552 // If we're removing all of the instructions within an IT block, then 553 // also remove the IT instruction. 554 SmallPtrSet<MachineInstr *, 2> ModifiedITs; 555 SmallPtrSet<MachineInstr *, 2> RemoveITs; 556 for (auto *Dead : Killed) { 557 if (MachineOperand *MO = Dead->findRegisterUseOperand(ARM::ITSTATE)) { 558 MachineInstr *IT = RDA.getMIOperand(Dead, *MO); 559 RemoveITs.insert(IT); 560 auto &CurrentBlock = ITBlocks[IT]; 561 CurrentBlock.erase(Dead); 562 if (CurrentBlock.empty()) 563 ModifiedITs.erase(IT); 564 else 565 ModifiedITs.insert(IT); 566 } 567 } 568 if (!ModifiedITs.empty()) 569 return false; 570 Killed.insert(RemoveITs.begin(), RemoveITs.end()); 571 return true; 572 }; 573 574 SmallPtrSet<MachineInstr *, 2> Uses; 575 if (!RDA.isSafeToRemove(MI, Uses, Ignore)) 576 return false; 577 578 if (WontCorruptITs(Uses, RDA)) { 579 ToRemove.insert(Uses.begin(), Uses.end()); 580 LLVM_DEBUG(dbgs() << "ARM Loops: Able to remove: " << *MI 581 << " - can also remove:\n"; 582 for (auto *Use : Uses) 583 dbgs() << " - " << *Use); 584 585 SmallPtrSet<MachineInstr*, 4> Killed; 586 RDA.collectKilledOperands(MI, Killed); 587 if (WontCorruptITs(Killed, RDA)) { 588 ToRemove.insert(Killed.begin(), Killed.end()); 589 LLVM_DEBUG(for (auto *Dead : Killed) 590 dbgs() << " - " << *Dead); 591 } 592 return true; 593 } 594 return false; 595 } 596 597 bool LowOverheadLoop::ValidateTailPredicate() { 598 if (!IsTailPredicationLegal()) { 599 LLVM_DEBUG(if (VCTPs.empty()) 600 dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n"; 601 dbgs() << "ARM Loops: Tail-predication is not valid.\n"); 602 return false; 603 } 604 605 assert(!VCTPs.empty() && "VCTP instruction expected but is not set"); 606 assert(ML.getBlocks().size() == 1 && 607 "Shouldn't be processing a loop with more than one block"); 608 609 if (DisableTailPredication) { 610 LLVM_DEBUG(dbgs() << "ARM Loops: tail-predication is disabled\n"); 611 return false; 612 } 613 614 if (!VPTState::isValid(RDA)) { 615 LLVM_DEBUG(dbgs() << "ARM Loops: Invalid VPT state.\n"); 616 return false; 617 } 618 619 if (!ValidateLiveOuts()) { 620 LLVM_DEBUG(dbgs() << "ARM Loops: Invalid live outs.\n"); 621 return false; 622 } 623 624 // Check that creating a [W|D]LSTP, which will define LR with an element 625 // count instead of iteration count, won't affect any other instructions 626 // than the LoopStart and LoopDec. 627 // TODO: We should try to insert the [W|D]LSTP after any of the other uses. 628 Register StartReg = isDo(Start) ? Start->getOperand(1).getReg() 629 : Start->getOperand(0).getReg(); 630 if (StartInsertPt == Start && StartReg == ARM::LR) { 631 if (auto *IterCount = RDA.getMIOperand(Start, isDo(Start) ? 1 : 0)) { 632 SmallPtrSet<MachineInstr *, 2> Uses; 633 RDA.getGlobalUses(IterCount, MCRegister::from(ARM::LR), Uses); 634 for (auto *Use : Uses) { 635 if (Use != Start && Use != Dec) { 636 LLVM_DEBUG(dbgs() << " ARM Loops: Found LR use: " << *Use); 637 return false; 638 } 639 } 640 } 641 } 642 643 // For tail predication, we need to provide the number of elements, instead 644 // of the iteration count, to the loop start instruction. The number of 645 // elements is provided to the vctp instruction, so we need to check that 646 // we can use this register at InsertPt. 647 MachineInstr *VCTP = VCTPs.back(); 648 if (Start->getOpcode() == ARM::t2DoLoopStartTP) { 649 TPNumElements = Start->getOperand(2); 650 StartInsertPt = Start; 651 StartInsertBB = Start->getParent(); 652 } else { 653 TPNumElements = VCTP->getOperand(1); 654 MCRegister NumElements = TPNumElements.getReg().asMCReg(); 655 656 // If the register is defined within loop, then we can't perform TP. 657 // TODO: Check whether this is just a mov of a register that would be 658 // available. 659 if (RDA.hasLocalDefBefore(VCTP, NumElements)) { 660 LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n"); 661 return false; 662 } 663 664 // The element count register maybe defined after InsertPt, in which case we 665 // need to try to move either InsertPt or the def so that the [w|d]lstp can 666 // use the value. 667 668 if (StartInsertPt != StartInsertBB->end() && 669 !RDA.isReachingDefLiveOut(&*StartInsertPt, NumElements)) { 670 if (auto *ElemDef = 671 RDA.getLocalLiveOutMIDef(StartInsertBB, NumElements)) { 672 if (RDA.isSafeToMoveForwards(ElemDef, &*StartInsertPt)) { 673 ElemDef->removeFromParent(); 674 StartInsertBB->insert(StartInsertPt, ElemDef); 675 LLVM_DEBUG(dbgs() 676 << "ARM Loops: Moved element count def: " << *ElemDef); 677 } else if (RDA.isSafeToMoveBackwards(&*StartInsertPt, ElemDef)) { 678 StartInsertPt->removeFromParent(); 679 StartInsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef), 680 &*StartInsertPt); 681 LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef); 682 } else { 683 // If we fail to move an instruction and the element count is provided 684 // by a mov, use the mov operand if it will have the same value at the 685 // insertion point 686 MachineOperand Operand = ElemDef->getOperand(1); 687 if (isMovRegOpcode(ElemDef->getOpcode()) && 688 RDA.getUniqueReachingMIDef(ElemDef, Operand.getReg().asMCReg()) == 689 RDA.getUniqueReachingMIDef(&*StartInsertPt, 690 Operand.getReg().asMCReg())) { 691 TPNumElements = Operand; 692 NumElements = TPNumElements.getReg(); 693 } else { 694 LLVM_DEBUG(dbgs() 695 << "ARM Loops: Unable to move element count to loop " 696 << "start instruction.\n"); 697 return false; 698 } 699 } 700 } 701 } 702 703 // Especially in the case of while loops, InsertBB may not be the 704 // preheader, so we need to check that the register isn't redefined 705 // before entering the loop. 706 auto CannotProvideElements = [this](MachineBasicBlock *MBB, 707 MCRegister NumElements) { 708 if (MBB->empty()) 709 return false; 710 // NumElements is redefined in this block. 711 if (RDA.hasLocalDefBefore(&MBB->back(), NumElements)) 712 return true; 713 714 // Don't continue searching up through multiple predecessors. 715 if (MBB->pred_size() > 1) 716 return true; 717 718 return false; 719 }; 720 721 // Search backwards for a def, until we get to InsertBB. 722 MachineBasicBlock *MBB = Preheader; 723 while (MBB && MBB != StartInsertBB) { 724 if (CannotProvideElements(MBB, NumElements)) { 725 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n"); 726 return false; 727 } 728 MBB = *MBB->pred_begin(); 729 } 730 } 731 732 // Could inserting the [W|D]LSTP cause some unintended affects? In a perfect 733 // world the [w|d]lstp instruction would be last instruction in the preheader 734 // and so it would only affect instructions within the loop body. But due to 735 // scheduling, and/or the logic in this pass (above), the insertion point can 736 // be moved earlier. So if the Loop Start isn't the last instruction in the 737 // preheader, and if the initial element count is smaller than the vector 738 // width, the Loop Start instruction will immediately generate one or more 739 // false lane mask which can, incorrectly, affect the proceeding MVE 740 // instructions in the preheader. 741 auto CannotInsertWDLSTPBetween = [](MachineBasicBlock::iterator I, 742 MachineBasicBlock::iterator E) { 743 for (; I != E; ++I) { 744 if (shouldInspect(*I)) { 745 LLVM_DEBUG(dbgs() << "ARM Loops: Instruction blocks [W|D]LSTP" 746 << " insertion: " << *I); 747 return true; 748 } 749 } 750 return false; 751 }; 752 753 if (CannotInsertWDLSTPBetween(StartInsertPt, StartInsertBB->end())) 754 return false; 755 756 // Check that the value change of the element count is what we expect and 757 // that the predication will be equivalent. For this we need: 758 // NumElements = NumElements - VectorWidth. The sub will be a sub immediate 759 // and we can also allow register copies within the chain too. 760 auto IsValidSub = [](MachineInstr *MI, int ExpectedVecWidth) { 761 return -getAddSubImmediate(*MI) == ExpectedVecWidth; 762 }; 763 764 MachineBasicBlock *MBB = VCTP->getParent(); 765 // Remove modifications to the element count since they have no purpose in a 766 // tail predicated loop. Explicitly refer to the vctp operand no matter which 767 // register NumElements has been assigned to, since that is what the 768 // modifications will be using 769 if (auto *Def = RDA.getUniqueReachingMIDef( 770 &MBB->back(), VCTP->getOperand(1).getReg().asMCReg())) { 771 SmallPtrSet<MachineInstr*, 2> ElementChain; 772 SmallPtrSet<MachineInstr*, 2> Ignore; 773 unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode()); 774 775 Ignore.insert(VCTPs.begin(), VCTPs.end()); 776 777 if (TryRemove(Def, RDA, ElementChain, Ignore)) { 778 bool FoundSub = false; 779 780 for (auto *MI : ElementChain) { 781 if (isMovRegOpcode(MI->getOpcode())) 782 continue; 783 784 if (isSubImmOpcode(MI->getOpcode())) { 785 if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth)) { 786 LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element" 787 " count: " << *MI); 788 return false; 789 } 790 FoundSub = true; 791 } else { 792 LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element" 793 " count: " << *MI); 794 return false; 795 } 796 } 797 ToRemove.insert(ElementChain.begin(), ElementChain.end()); 798 } 799 } 800 return true; 801 } 802 803 static bool isRegInClass(const MachineOperand &MO, 804 const TargetRegisterClass *Class) { 805 return MO.isReg() && MO.getReg() && Class->contains(MO.getReg()); 806 } 807 808 // MVE 'narrowing' operate on half a lane, reading from half and writing 809 // to half, which are referred to has the top and bottom half. The other 810 // half retains its previous value. 811 static bool retainsPreviousHalfElement(const MachineInstr &MI) { 812 const MCInstrDesc &MCID = MI.getDesc(); 813 uint64_t Flags = MCID.TSFlags; 814 return (Flags & ARMII::RetainsPreviousHalfElement) != 0; 815 } 816 817 // Some MVE instructions read from the top/bottom halves of their operand(s) 818 // and generate a vector result with result elements that are double the 819 // width of the input. 820 static bool producesDoubleWidthResult(const MachineInstr &MI) { 821 const MCInstrDesc &MCID = MI.getDesc(); 822 uint64_t Flags = MCID.TSFlags; 823 return (Flags & ARMII::DoubleWidthResult) != 0; 824 } 825 826 static bool isHorizontalReduction(const MachineInstr &MI) { 827 const MCInstrDesc &MCID = MI.getDesc(); 828 uint64_t Flags = MCID.TSFlags; 829 return (Flags & ARMII::HorizontalReduction) != 0; 830 } 831 832 // Can this instruction generate a non-zero result when given only zeroed 833 // operands? This allows us to know that, given operands with false bytes 834 // zeroed by masked loads, that the result will also contain zeros in those 835 // bytes. 836 static bool canGenerateNonZeros(const MachineInstr &MI) { 837 838 // Check for instructions which can write into a larger element size, 839 // possibly writing into a previous zero'd lane. 840 if (producesDoubleWidthResult(MI)) 841 return true; 842 843 switch (MI.getOpcode()) { 844 default: 845 break; 846 // FIXME: VNEG FP and -0? I think we'll need to handle this once we allow 847 // fp16 -> fp32 vector conversions. 848 // Instructions that perform a NOT will generate 1s from 0s. 849 case ARM::MVE_VMVN: 850 case ARM::MVE_VORN: 851 // Count leading zeros will do just that! 852 case ARM::MVE_VCLZs8: 853 case ARM::MVE_VCLZs16: 854 case ARM::MVE_VCLZs32: 855 return true; 856 } 857 return false; 858 } 859 860 // Look at its register uses to see if it only can only receive zeros 861 // into its false lanes which would then produce zeros. Also check that 862 // the output register is also defined by an FalseLanesZero instruction 863 // so that if tail-predication happens, the lanes that aren't updated will 864 // still be zeros. 865 static bool producesFalseLanesZero(MachineInstr &MI, 866 const TargetRegisterClass *QPRs, 867 const ReachingDefAnalysis &RDA, 868 InstSet &FalseLanesZero) { 869 if (canGenerateNonZeros(MI)) 870 return false; 871 872 bool isPredicated = isVectorPredicated(&MI); 873 // Predicated loads will write zeros to the falsely predicated bytes of the 874 // destination register. 875 if (MI.mayLoad()) 876 return isPredicated; 877 878 auto IsZeroInit = [](MachineInstr *Def) { 879 return !isVectorPredicated(Def) && 880 Def->getOpcode() == ARM::MVE_VMOVimmi32 && 881 Def->getOperand(1).getImm() == 0; 882 }; 883 884 bool AllowScalars = isHorizontalReduction(MI); 885 for (auto &MO : MI.operands()) { 886 if (!MO.isReg() || !MO.getReg()) 887 continue; 888 if (!isRegInClass(MO, QPRs) && AllowScalars) 889 continue; 890 891 // Check that this instruction will produce zeros in its false lanes: 892 // - If it only consumes false lanes zero or constant 0 (vmov #0) 893 // - If it's predicated, it only matters that it's def register already has 894 // false lane zeros, so we can ignore the uses. 895 SmallPtrSet<MachineInstr *, 2> Defs; 896 RDA.getGlobalReachingDefs(&MI, MO.getReg(), Defs); 897 for (auto *Def : Defs) { 898 if (Def == &MI || FalseLanesZero.count(Def) || IsZeroInit(Def)) 899 continue; 900 if (MO.isUse() && isPredicated) 901 continue; 902 return false; 903 } 904 } 905 LLVM_DEBUG(dbgs() << "ARM Loops: Always False Zeros: " << MI); 906 return true; 907 } 908 909 bool LowOverheadLoop::ValidateLiveOuts() { 910 // We want to find out if the tail-predicated version of this loop will 911 // produce the same values as the loop in its original form. For this to 912 // be true, the newly inserted implicit predication must not change the 913 // the (observable) results. 914 // We're doing this because many instructions in the loop will not be 915 // predicated and so the conversion from VPT predication to tail-predication 916 // can result in different values being produced; due to the tail-predication 917 // preventing many instructions from updating their falsely predicated 918 // lanes. This analysis assumes that all the instructions perform lane-wise 919 // operations and don't perform any exchanges. 920 // A masked load, whether through VPT or tail predication, will write zeros 921 // to any of the falsely predicated bytes. So, from the loads, we know that 922 // the false lanes are zeroed and here we're trying to track that those false 923 // lanes remain zero, or where they change, the differences are masked away 924 // by their user(s). 925 // All MVE stores have to be predicated, so we know that any predicate load 926 // operands, or stored results are equivalent already. Other explicitly 927 // predicated instructions will perform the same operation in the original 928 // loop and the tail-predicated form too. Because of this, we can insert 929 // loads, stores and other predicated instructions into our Predicated 930 // set and build from there. 931 const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID); 932 SetVector<MachineInstr *> FalseLanesUnknown; 933 SmallPtrSet<MachineInstr *, 4> FalseLanesZero; 934 SmallPtrSet<MachineInstr *, 4> Predicated; 935 MachineBasicBlock *Header = ML.getHeader(); 936 937 for (auto &MI : *Header) { 938 if (!shouldInspect(MI)) 939 continue; 940 941 if (isVCTP(&MI) || isVPTOpcode(MI.getOpcode())) 942 continue; 943 944 bool isPredicated = isVectorPredicated(&MI); 945 bool retainsOrReduces = 946 retainsPreviousHalfElement(MI) || isHorizontalReduction(MI); 947 948 if (isPredicated) 949 Predicated.insert(&MI); 950 if (producesFalseLanesZero(MI, QPRs, RDA, FalseLanesZero)) 951 FalseLanesZero.insert(&MI); 952 else if (MI.getNumDefs() == 0) 953 continue; 954 else if (!isPredicated && retainsOrReduces) 955 return false; 956 else if (!isPredicated) 957 FalseLanesUnknown.insert(&MI); 958 } 959 960 auto HasPredicatedUsers = [this](MachineInstr *MI, const MachineOperand &MO, 961 SmallPtrSetImpl<MachineInstr *> &Predicated) { 962 SmallPtrSet<MachineInstr *, 2> Uses; 963 RDA.getGlobalUses(MI, MO.getReg().asMCReg(), Uses); 964 for (auto *Use : Uses) { 965 if (Use != MI && !Predicated.count(Use)) 966 return false; 967 } 968 return true; 969 }; 970 971 // Visit the unknowns in reverse so that we can start at the values being 972 // stored and then we can work towards the leaves, hopefully adding more 973 // instructions to Predicated. Successfully terminating the loop means that 974 // all the unknown values have to found to be masked by predicated user(s). 975 // For any unpredicated values, we store them in NonPredicated so that we 976 // can later check whether these form a reduction. 977 SmallPtrSet<MachineInstr*, 2> NonPredicated; 978 for (auto *MI : reverse(FalseLanesUnknown)) { 979 for (auto &MO : MI->operands()) { 980 if (!isRegInClass(MO, QPRs) || !MO.isDef()) 981 continue; 982 if (!HasPredicatedUsers(MI, MO, Predicated)) { 983 LLVM_DEBUG(dbgs() << "ARM Loops: Found an unknown def of : " 984 << TRI.getRegAsmName(MO.getReg()) << " at " << *MI); 985 NonPredicated.insert(MI); 986 break; 987 } 988 } 989 // Any unknown false lanes have been masked away by the user(s). 990 if (!NonPredicated.contains(MI)) 991 Predicated.insert(MI); 992 } 993 994 SmallPtrSet<MachineInstr *, 2> LiveOutMIs; 995 SmallVector<MachineBasicBlock *, 2> ExitBlocks; 996 ML.getExitBlocks(ExitBlocks); 997 assert(ML.getNumBlocks() == 1 && "Expected single block loop!"); 998 assert(ExitBlocks.size() == 1 && "Expected a single exit block"); 999 MachineBasicBlock *ExitBB = ExitBlocks.front(); 1000 for (const MachineBasicBlock::RegisterMaskPair &RegMask : ExitBB->liveins()) { 1001 // TODO: Instead of blocking predication, we could move the vctp to the exit 1002 // block and calculate it's operand there in or the preheader. 1003 if (RegMask.PhysReg == ARM::VPR) 1004 return false; 1005 // Check Q-regs that are live in the exit blocks. We don't collect scalars 1006 // because they won't be affected by lane predication. 1007 if (QPRs->contains(RegMask.PhysReg)) 1008 if (auto *MI = RDA.getLocalLiveOutMIDef(Header, RegMask.PhysReg)) 1009 LiveOutMIs.insert(MI); 1010 } 1011 1012 // We've already validated that any VPT predication within the loop will be 1013 // equivalent when we perform the predication transformation; so we know that 1014 // any VPT predicated instruction is predicated upon VCTP. Any live-out 1015 // instruction needs to be predicated, so check this here. The instructions 1016 // in NonPredicated have been found to be a reduction that we can ensure its 1017 // legality. 1018 for (auto *MI : LiveOutMIs) { 1019 if (NonPredicated.count(MI) && FalseLanesUnknown.contains(MI)) { 1020 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to handle live out: " << *MI); 1021 return false; 1022 } 1023 } 1024 1025 return true; 1026 } 1027 1028 void LowOverheadLoop::Validate(ARMBasicBlockUtils *BBUtils) { 1029 if (Revert) 1030 return; 1031 1032 // Check branch target ranges: WLS[TP] can only branch forwards and LE[TP] 1033 // can only jump back. 1034 auto ValidateRanges = [](MachineInstr *Start, MachineInstr *End, 1035 ARMBasicBlockUtils *BBUtils, MachineLoop &ML) { 1036 assert(End->getOperand(1).isMBB() && 1037 "Expected LoopEnd to target basic block!"); 1038 1039 // TODO Maybe there's cases where the target doesn't have to be the header, 1040 // but for now be safe and revert. 1041 if (End->getOperand(1).getMBB() != ML.getHeader()) { 1042 LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targeting header.\n"); 1043 return false; 1044 } 1045 1046 // The WLS and LE instructions have 12-bits for the label offset. WLS 1047 // requires a positive offset, while LE uses negative. 1048 if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) || 1049 !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) { 1050 LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n"); 1051 return false; 1052 } 1053 1054 if (Start->getOpcode() == ARM::t2WhileLoopStart && 1055 (BBUtils->getOffsetOf(Start) > 1056 BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) || 1057 !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) { 1058 LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n"); 1059 return false; 1060 } 1061 return true; 1062 }; 1063 1064 // Find a suitable position to insert the loop start instruction. It needs to 1065 // be able to safely define LR. 1066 auto FindStartInsertionPoint = [](MachineInstr *Start, MachineInstr *Dec, 1067 MachineBasicBlock::iterator &InsertPt, 1068 MachineBasicBlock *&InsertBB, 1069 ReachingDefAnalysis &RDA, 1070 InstSet &ToRemove) { 1071 // For a t2DoLoopStart it is always valid to use the start insertion point. 1072 // For WLS we can define LR if LR already contains the same value. 1073 if (isDo(Start) || Start->getOperand(0).getReg() == ARM::LR) { 1074 InsertPt = MachineBasicBlock::iterator(Start); 1075 InsertBB = Start->getParent(); 1076 return true; 1077 } 1078 1079 // We've found no suitable LR def and Start doesn't use LR directly. Can we 1080 // just define LR anyway? 1081 if (!RDA.isSafeToDefRegAt(Start, MCRegister::from(ARM::LR))) 1082 return false; 1083 1084 InsertPt = MachineBasicBlock::iterator(Start); 1085 InsertBB = Start->getParent(); 1086 return true; 1087 }; 1088 1089 if (!FindStartInsertionPoint(Start, Dec, StartInsertPt, StartInsertBB, RDA, 1090 ToRemove)) { 1091 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n"); 1092 Revert = true; 1093 return; 1094 } 1095 LLVM_DEBUG(if (StartInsertPt == StartInsertBB->end()) 1096 dbgs() << "ARM Loops: Will insert LoopStart at end of block\n"; 1097 else 1098 dbgs() << "ARM Loops: Will insert LoopStart at " 1099 << *StartInsertPt 1100 ); 1101 1102 Revert = !ValidateRanges(Start, End, BBUtils, ML); 1103 CannotTailPredicate = !ValidateTailPredicate(); 1104 } 1105 1106 bool LowOverheadLoop::AddVCTP(MachineInstr *MI) { 1107 LLVM_DEBUG(dbgs() << "ARM Loops: Adding VCTP: " << *MI); 1108 if (VCTPs.empty()) { 1109 VCTPs.push_back(MI); 1110 return true; 1111 } 1112 1113 // If we find another VCTP, check whether it uses the same value as the main VCTP. 1114 // If it does, store it in the VCTPs set, else refuse it. 1115 MachineInstr *Prev = VCTPs.back(); 1116 if (!Prev->getOperand(1).isIdenticalTo(MI->getOperand(1)) || 1117 !RDA.hasSameReachingDef(Prev, MI, MI->getOperand(1).getReg().asMCReg())) { 1118 LLVM_DEBUG(dbgs() << "ARM Loops: Found VCTP with a different reaching " 1119 "definition from the main VCTP"); 1120 return false; 1121 } 1122 VCTPs.push_back(MI); 1123 return true; 1124 } 1125 1126 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) { 1127 if (CannotTailPredicate) 1128 return false; 1129 1130 if (!shouldInspect(*MI)) 1131 return true; 1132 1133 if (MI->getOpcode() == ARM::MVE_VPSEL || 1134 MI->getOpcode() == ARM::MVE_VPNOT) { 1135 // TODO: Allow VPSEL and VPNOT, we currently cannot because: 1136 // 1) It will use the VPR as a predicate operand, but doesn't have to be 1137 // instead a VPT block, which means we can assert while building up 1138 // the VPT block because we don't find another VPT or VPST to being a new 1139 // one. 1140 // 2) VPSEL still requires a VPR operand even after tail predicating, 1141 // which means we can't remove it unless there is another 1142 // instruction, such as vcmp, that can provide the VPR def. 1143 return false; 1144 } 1145 1146 // Record all VCTPs and check that they're equivalent to one another. 1147 if (isVCTP(MI) && !AddVCTP(MI)) 1148 return false; 1149 1150 // Inspect uses first so that any instructions that alter the VPR don't 1151 // alter the predicate upon themselves. 1152 const MCInstrDesc &MCID = MI->getDesc(); 1153 bool IsUse = false; 1154 unsigned LastOpIdx = MI->getNumOperands() - 1; 1155 for (auto &Op : enumerate(reverse(MCID.operands()))) { 1156 const MachineOperand &MO = MI->getOperand(LastOpIdx - Op.index()); 1157 if (!MO.isReg() || !MO.isUse() || MO.getReg() != ARM::VPR) 1158 continue; 1159 1160 if (ARM::isVpred(Op.value().OperandType)) { 1161 VPTState::addInst(MI); 1162 IsUse = true; 1163 } else if (MI->getOpcode() != ARM::MVE_VPST) { 1164 LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI); 1165 return false; 1166 } 1167 } 1168 1169 // If we find an instruction that has been marked as not valid for tail 1170 // predication, only allow the instruction if it's contained within a valid 1171 // VPT block. 1172 bool RequiresExplicitPredication = 1173 (MCID.TSFlags & ARMII::ValidForTailPredication) == 0; 1174 if (isDomainMVE(MI) && RequiresExplicitPredication) { 1175 LLVM_DEBUG(if (!IsUse) 1176 dbgs() << "ARM Loops: Can't tail predicate: " << *MI); 1177 return IsUse; 1178 } 1179 1180 // If the instruction is already explicitly predicated, then the conversion 1181 // will be fine, but ensure that all store operations are predicated. 1182 if (MI->mayStore()) 1183 return IsUse; 1184 1185 // If this instruction defines the VPR, update the predicate for the 1186 // proceeding instructions. 1187 if (isVectorPredicate(MI)) { 1188 // Clear the existing predicate when we're not in VPT Active state, 1189 // otherwise we add to it. 1190 if (!isVectorPredicated(MI)) 1191 VPTState::resetPredicate(MI); 1192 else 1193 VPTState::addPredicate(MI); 1194 } 1195 1196 // Finally once the predicate has been modified, we can start a new VPT 1197 // block if necessary. 1198 if (isVPTOpcode(MI->getOpcode())) 1199 VPTState::CreateVPTBlock(MI); 1200 1201 return true; 1202 } 1203 1204 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) { 1205 const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget()); 1206 if (!ST.hasLOB()) 1207 return false; 1208 1209 MF = &mf; 1210 LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n"); 1211 1212 MLI = &getAnalysis<MachineLoopInfo>(); 1213 RDA = &getAnalysis<ReachingDefAnalysis>(); 1214 MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness); 1215 MRI = &MF->getRegInfo(); 1216 TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo()); 1217 TRI = ST.getRegisterInfo(); 1218 BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF)); 1219 BBUtils->computeAllBlockSizes(); 1220 BBUtils->adjustBBOffsetsAfter(&MF->front()); 1221 1222 bool Changed = false; 1223 for (auto ML : *MLI) { 1224 if (ML->isOutermost()) 1225 Changed |= ProcessLoop(ML); 1226 } 1227 Changed |= RevertNonLoops(); 1228 return Changed; 1229 } 1230 1231 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) { 1232 1233 bool Changed = false; 1234 1235 // Process inner loops first. 1236 for (auto I = ML->begin(), E = ML->end(); I != E; ++I) 1237 Changed |= ProcessLoop(*I); 1238 1239 LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n"; 1240 if (auto *Preheader = ML->getLoopPreheader()) 1241 dbgs() << " - " << Preheader->getName() << "\n"; 1242 else if (auto *Preheader = MLI->findLoopPreheader(ML)) 1243 dbgs() << " - " << Preheader->getName() << "\n"; 1244 else if (auto *Preheader = MLI->findLoopPreheader(ML, true)) 1245 dbgs() << " - " << Preheader->getName() << "\n"; 1246 for (auto *MBB : ML->getBlocks()) 1247 dbgs() << " - " << MBB->getName() << "\n"; 1248 ); 1249 1250 // Search the given block for a loop start instruction. If one isn't found, 1251 // and there's only one predecessor block, search that one too. 1252 std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart = 1253 [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* { 1254 for (auto &MI : *MBB) { 1255 if (isLoopStart(MI)) 1256 return &MI; 1257 } 1258 if (MBB->pred_size() == 1) 1259 return SearchForStart(*MBB->pred_begin()); 1260 return nullptr; 1261 }; 1262 1263 LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI, *TII); 1264 // Search the preheader for the start intrinsic. 1265 // FIXME: I don't see why we shouldn't be supporting multiple predecessors 1266 // with potentially multiple set.loop.iterations, so we need to enable this. 1267 if (LoLoop.Preheader) 1268 LoLoop.Start = SearchForStart(LoLoop.Preheader); 1269 else 1270 return false; 1271 1272 // Find the low-overhead loop components and decide whether or not to fall 1273 // back to a normal loop. Also look for a vctp instructions and decide 1274 // whether we can convert that predicate using tail predication. 1275 for (auto *MBB : reverse(ML->getBlocks())) { 1276 for (auto &MI : *MBB) { 1277 if (MI.isDebugValue()) 1278 continue; 1279 else if (MI.getOpcode() == ARM::t2LoopDec) 1280 LoLoop.Dec = &MI; 1281 else if (MI.getOpcode() == ARM::t2LoopEnd) 1282 LoLoop.End = &MI; 1283 else if (isLoopStart(MI)) 1284 LoLoop.Start = &MI; 1285 else if (MI.getDesc().isCall()) { 1286 // TODO: Though the call will require LE to execute again, does this 1287 // mean we should revert? Always executing LE hopefully should be 1288 // faster than performing a sub,cmp,br or even subs,br. 1289 LoLoop.Revert = true; 1290 LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n"); 1291 } else { 1292 // Record VPR defs and build up their corresponding vpt blocks. 1293 // Check we know how to tail predicate any mve instructions. 1294 LoLoop.AnalyseMVEInst(&MI); 1295 } 1296 } 1297 } 1298 1299 LLVM_DEBUG(LoLoop.dump()); 1300 if (!LoLoop.FoundAllComponents()) { 1301 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n"); 1302 return false; 1303 } 1304 1305 // Check that the only instruction using LoopDec is LoopEnd. 1306 // TODO: Check for copy chains that really have no effect. 1307 SmallPtrSet<MachineInstr*, 2> Uses; 1308 RDA->getReachingLocalUses(LoLoop.Dec, MCRegister::from(ARM::LR), Uses); 1309 if (Uses.size() > 1 || !Uses.count(LoLoop.End)) { 1310 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n"); 1311 LoLoop.Revert = true; 1312 } 1313 LoLoop.Validate(BBUtils.get()); 1314 Expand(LoLoop); 1315 return true; 1316 } 1317 1318 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a 1319 // beq that branches to the exit branch. 1320 // TODO: We could also try to generate a cbz if the value in LR is also in 1321 // another low register. 1322 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const { 1323 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI); 1324 MachineBasicBlock *MBB = MI->getParent(); 1325 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), 1326 TII->get(ARM::t2CMPri)); 1327 MIB.add(MI->getOperand(0)); 1328 MIB.addImm(0); 1329 MIB.addImm(ARMCC::AL); 1330 MIB.addReg(ARM::NoRegister); 1331 1332 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB(); 1333 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ? 1334 ARM::tBcc : ARM::t2Bcc; 1335 1336 MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc)); 1337 MIB.add(MI->getOperand(1)); // branch target 1338 MIB.addImm(ARMCC::EQ); // condition code 1339 MIB.addReg(ARM::CPSR); 1340 MI->eraseFromParent(); 1341 } 1342 1343 void ARMLowOverheadLoops::RevertDo(MachineInstr *MI) const { 1344 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to mov: " << *MI); 1345 MachineBasicBlock *MBB = MI->getParent(); 1346 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::tMOVr)) 1347 .add(MI->getOperand(0)) 1348 .add(MI->getOperand(1)) 1349 .add(predOps(ARMCC::AL)); 1350 MI->eraseFromParent(); 1351 } 1352 1353 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const { 1354 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI); 1355 MachineBasicBlock *MBB = MI->getParent(); 1356 SmallPtrSet<MachineInstr*, 1> Ignore; 1357 for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) { 1358 if (I->getOpcode() == ARM::t2LoopEnd) { 1359 Ignore.insert(&*I); 1360 break; 1361 } 1362 } 1363 1364 // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS. 1365 bool SetFlags = 1366 RDA->isSafeToDefRegAt(MI, MCRegister::from(ARM::CPSR), Ignore); 1367 1368 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), 1369 TII->get(ARM::t2SUBri)); 1370 MIB.addDef(ARM::LR); 1371 MIB.add(MI->getOperand(1)); 1372 MIB.add(MI->getOperand(2)); 1373 MIB.addImm(ARMCC::AL); 1374 MIB.addReg(0); 1375 1376 if (SetFlags) { 1377 MIB.addReg(ARM::CPSR); 1378 MIB->getOperand(5).setIsDef(true); 1379 } else 1380 MIB.addReg(0); 1381 1382 MI->eraseFromParent(); 1383 return SetFlags; 1384 } 1385 1386 // Generate a subs, or sub and cmp, and a branch instead of an LE. 1387 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const { 1388 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI); 1389 1390 MachineBasicBlock *MBB = MI->getParent(); 1391 // Create cmp 1392 if (!SkipCmp) { 1393 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), 1394 TII->get(ARM::t2CMPri)); 1395 MIB.addReg(ARM::LR); 1396 MIB.addImm(0); 1397 MIB.addImm(ARMCC::AL); 1398 MIB.addReg(ARM::NoRegister); 1399 } 1400 1401 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB(); 1402 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ? 1403 ARM::tBcc : ARM::t2Bcc; 1404 1405 // Create bne 1406 MachineInstrBuilder MIB = 1407 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc)); 1408 MIB.add(MI->getOperand(1)); // branch target 1409 MIB.addImm(ARMCC::NE); // condition code 1410 MIB.addReg(ARM::CPSR); 1411 MI->eraseFromParent(); 1412 } 1413 1414 // Perform dead code elimation on the loop iteration count setup expression. 1415 // If we are tail-predicating, the number of elements to be processed is the 1416 // operand of the VCTP instruction in the vector body, see getCount(), which is 1417 // register $r3 in this example: 1418 // 1419 // $lr = big-itercount-expression 1420 // .. 1421 // $lr = t2DoLoopStart renamable $lr 1422 // vector.body: 1423 // .. 1424 // $vpr = MVE_VCTP32 renamable $r3 1425 // renamable $lr = t2LoopDec killed renamable $lr, 1 1426 // t2LoopEnd renamable $lr, %vector.body 1427 // tB %end 1428 // 1429 // What we would like achieve here is to replace the do-loop start pseudo 1430 // instruction t2DoLoopStart with: 1431 // 1432 // $lr = MVE_DLSTP_32 killed renamable $r3 1433 // 1434 // Thus, $r3 which defines the number of elements, is written to $lr, 1435 // and then we want to delete the whole chain that used to define $lr, 1436 // see the comment below how this chain could look like. 1437 // 1438 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) { 1439 if (!LoLoop.IsTailPredicationLegal()) 1440 return; 1441 1442 LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n"); 1443 1444 MachineInstr *Def = 1445 RDA->getMIOperand(LoLoop.Start, isDo(LoLoop.Start) ? 1 : 0); 1446 if (!Def) { 1447 LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n"); 1448 return; 1449 } 1450 1451 // Collect and remove the users of iteration count. 1452 SmallPtrSet<MachineInstr*, 4> Killed = { LoLoop.Start, LoLoop.Dec, 1453 LoLoop.End }; 1454 if (!TryRemove(Def, *RDA, LoLoop.ToRemove, Killed)) 1455 LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n"); 1456 } 1457 1458 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) { 1459 LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n"); 1460 // When using tail-predication, try to delete the dead code that was used to 1461 // calculate the number of loop iterations. 1462 IterationCountDCE(LoLoop); 1463 1464 MachineBasicBlock::iterator InsertPt = LoLoop.StartInsertPt; 1465 MachineInstr *Start = LoLoop.Start; 1466 MachineBasicBlock *MBB = LoLoop.StartInsertBB; 1467 unsigned Opc = LoLoop.getStartOpcode(); 1468 MachineOperand &Count = LoLoop.getLoopStartOperand(); 1469 1470 MachineInstrBuilder MIB = 1471 BuildMI(*MBB, InsertPt, Start->getDebugLoc(), TII->get(Opc)); 1472 1473 MIB.addDef(ARM::LR); 1474 MIB.add(Count); 1475 if (!isDo(Start)) 1476 MIB.add(Start->getOperand(1)); 1477 1478 LoLoop.ToRemove.insert(Start); 1479 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB); 1480 return &*MIB; 1481 } 1482 1483 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) { 1484 auto RemovePredicate = [](MachineInstr *MI) { 1485 LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI); 1486 if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) { 1487 assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then && 1488 "Expected Then predicate!"); 1489 MI->getOperand(PIdx).setImm(ARMVCC::None); 1490 MI->getOperand(PIdx+1).setReg(0); 1491 } else 1492 llvm_unreachable("trying to unpredicate a non-predicated instruction"); 1493 }; 1494 1495 for (auto &Block : LoLoop.getVPTBlocks()) { 1496 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 1497 1498 if (VPTState::isEntryPredicatedOnVCTP(Block, /*exclusive*/true)) { 1499 if (VPTState::hasUniformPredicate(Block)) { 1500 // A vpt block starting with VPST, is only predicated upon vctp and has no 1501 // internal vpr defs: 1502 // - Remove vpst. 1503 // - Unpredicate the remaining instructions. 1504 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Insts.front()); 1505 LoLoop.ToRemove.insert(Insts.front()); 1506 for (unsigned i = 1; i < Insts.size(); ++i) 1507 RemovePredicate(Insts[i]); 1508 } else { 1509 // The VPT block has a non-uniform predicate but it uses a vpst and its 1510 // entry is guarded only by a vctp, which means we: 1511 // - Need to remove the original vpst. 1512 // - Then need to unpredicate any following instructions, until 1513 // we come across the divergent vpr def. 1514 // - Insert a new vpst to predicate the instruction(s) that following 1515 // the divergent vpr def. 1516 // TODO: We could be producing more VPT blocks than necessary and could 1517 // fold the newly created one into a proceeding one. 1518 MachineInstr *Divergent = VPTState::getDivergent(Block); 1519 MachineInstr *VPST = Insts.front(); 1520 auto DivergentNext = ++MachineBasicBlock::iterator(Divergent); 1521 bool DivergentNextIsPredicated = 1522 getVPTInstrPredicate(*DivergentNext) != ARMVCC::None; 1523 1524 for (auto I = ++MachineBasicBlock::iterator(VPST), E = DivergentNext; 1525 I != E; ++I) 1526 RemovePredicate(&*I); 1527 1528 // Check if the instruction defining vpr is a vcmp so it can be combined 1529 // with the VPST This should be the divergent instruction 1530 MachineInstr *VCMP = 1531 VCMPOpcodeToVPT(Divergent->getOpcode()) != 0 ? Divergent : nullptr; 1532 1533 auto ReplaceVCMPWithVPT = [&]() { 1534 // Replace the VCMP with a VPT 1535 MachineInstrBuilder MIB = BuildMI( 1536 *Divergent->getParent(), Divergent, Divergent->getDebugLoc(), 1537 TII->get(VCMPOpcodeToVPT(VCMP->getOpcode()))); 1538 MIB.addImm(ARMVCC::Then); 1539 // Register one 1540 MIB.add(VCMP->getOperand(1)); 1541 // Register two 1542 MIB.add(VCMP->getOperand(2)); 1543 // The comparison code, e.g. ge, eq, lt 1544 MIB.add(VCMP->getOperand(3)); 1545 LLVM_DEBUG(dbgs() 1546 << "ARM Loops: Combining with VCMP to VPT: " << *MIB); 1547 LoLoop.BlockMasksToRecompute.insert(MIB.getInstr()); 1548 LoLoop.ToRemove.insert(VCMP); 1549 }; 1550 1551 if (DivergentNextIsPredicated) { 1552 // Insert a VPST at the divergent only if the next instruction 1553 // would actually use it. A VCMP following a VPST can be 1554 // merged into a VPT so do that instead if the VCMP exists. 1555 if (!VCMP) { 1556 // Create a VPST (with a null mask for now, we'll recompute it 1557 // later) 1558 MachineInstrBuilder MIB = 1559 BuildMI(*Divergent->getParent(), Divergent, 1560 Divergent->getDebugLoc(), TII->get(ARM::MVE_VPST)); 1561 MIB.addImm(0); 1562 LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB); 1563 LoLoop.BlockMasksToRecompute.insert(MIB.getInstr()); 1564 } else { 1565 // No RDA checks are necessary here since the VPST would have been 1566 // directly before the VCMP 1567 ReplaceVCMPWithVPT(); 1568 } 1569 } 1570 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST); 1571 LoLoop.ToRemove.insert(VPST); 1572 } 1573 } else if (Block.containsVCTP()) { 1574 // The vctp will be removed, so the block mask of the vp(s)t will need 1575 // to be recomputed. 1576 LoLoop.BlockMasksToRecompute.insert(Insts.front()); 1577 } 1578 } 1579 1580 LoLoop.ToRemove.insert(LoLoop.VCTPs.begin(), LoLoop.VCTPs.end()); 1581 } 1582 1583 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) { 1584 1585 // Combine the LoopDec and LoopEnd instructions into LE(TP). 1586 auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) { 1587 MachineInstr *End = LoLoop.End; 1588 MachineBasicBlock *MBB = End->getParent(); 1589 unsigned Opc = LoLoop.IsTailPredicationLegal() ? 1590 ARM::MVE_LETP : ARM::t2LEUpdate; 1591 MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(), 1592 TII->get(Opc)); 1593 MIB.addDef(ARM::LR); 1594 MIB.add(End->getOperand(0)); 1595 MIB.add(End->getOperand(1)); 1596 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB); 1597 LoLoop.ToRemove.insert(LoLoop.Dec); 1598 LoLoop.ToRemove.insert(End); 1599 return &*MIB; 1600 }; 1601 1602 // TODO: We should be able to automatically remove these branches before we 1603 // get here - probably by teaching analyzeBranch about the pseudo 1604 // instructions. 1605 // If there is an unconditional branch, after I, that just branches to the 1606 // next block, remove it. 1607 auto RemoveDeadBranch = [](MachineInstr *I) { 1608 MachineBasicBlock *BB = I->getParent(); 1609 MachineInstr *Terminator = &BB->instr_back(); 1610 if (Terminator->isUnconditionalBranch() && I != Terminator) { 1611 MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB(); 1612 if (BB->isLayoutSuccessor(Succ)) { 1613 LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator); 1614 Terminator->eraseFromParent(); 1615 } 1616 } 1617 }; 1618 1619 if (LoLoop.Revert) { 1620 if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart) 1621 RevertWhile(LoLoop.Start); 1622 else 1623 RevertDo(LoLoop.Start); 1624 bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec); 1625 RevertLoopEnd(LoLoop.End, FlagsAlreadySet); 1626 } else { 1627 LoLoop.Start = ExpandLoopStart(LoLoop); 1628 RemoveDeadBranch(LoLoop.Start); 1629 LoLoop.End = ExpandLoopEnd(LoLoop); 1630 RemoveDeadBranch(LoLoop.End); 1631 if (LoLoop.IsTailPredicationLegal()) 1632 ConvertVPTBlocks(LoLoop); 1633 for (auto *I : LoLoop.ToRemove) { 1634 LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I); 1635 I->eraseFromParent(); 1636 } 1637 for (auto *I : LoLoop.BlockMasksToRecompute) { 1638 LLVM_DEBUG(dbgs() << "ARM Loops: Recomputing VPT/VPST Block Mask: " << *I); 1639 recomputeVPTBlockMask(*I); 1640 LLVM_DEBUG(dbgs() << " ... done: " << *I); 1641 } 1642 } 1643 1644 PostOrderLoopTraversal DFS(LoLoop.ML, *MLI); 1645 DFS.ProcessLoop(); 1646 const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder(); 1647 for (auto *MBB : PostOrder) { 1648 recomputeLiveIns(*MBB); 1649 // FIXME: For some reason, the live-in print order is non-deterministic for 1650 // our tests and I can't out why... So just sort them. 1651 MBB->sortUniqueLiveIns(); 1652 } 1653 1654 for (auto *MBB : reverse(PostOrder)) 1655 recomputeLivenessFlags(*MBB); 1656 1657 // We've moved, removed and inserted new instructions, so update RDA. 1658 RDA->reset(); 1659 } 1660 1661 bool ARMLowOverheadLoops::RevertNonLoops() { 1662 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n"); 1663 bool Changed = false; 1664 1665 for (auto &MBB : *MF) { 1666 SmallVector<MachineInstr*, 4> Starts; 1667 SmallVector<MachineInstr*, 4> Decs; 1668 SmallVector<MachineInstr*, 4> Ends; 1669 1670 for (auto &I : MBB) { 1671 if (isLoopStart(I)) 1672 Starts.push_back(&I); 1673 else if (I.getOpcode() == ARM::t2LoopDec) 1674 Decs.push_back(&I); 1675 else if (I.getOpcode() == ARM::t2LoopEnd) 1676 Ends.push_back(&I); 1677 } 1678 1679 if (Starts.empty() && Decs.empty() && Ends.empty()) 1680 continue; 1681 1682 Changed = true; 1683 1684 for (auto *Start : Starts) { 1685 if (Start->getOpcode() == ARM::t2WhileLoopStart) 1686 RevertWhile(Start); 1687 else 1688 RevertDo(Start); 1689 } 1690 for (auto *Dec : Decs) 1691 RevertLoopDec(Dec); 1692 1693 for (auto *End : Ends) 1694 RevertLoopEnd(End); 1695 } 1696 return Changed; 1697 } 1698 1699 FunctionPass *llvm::createARMLowOverheadLoopsPass() { 1700 return new ARMLowOverheadLoops(); 1701 } 1702