1 //===- HexagonPacketizer.cpp - VLIW packetizer ----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements a simple VLIW packetizer using DFA. The packetizer works on 11 // machine basic blocks. For each instruction I in BB, the packetizer consults 12 // the DFA to see if machine resources are available to execute I. If so, the 13 // packetizer checks if I depends on any instruction J in the current packet. 14 // If no dependency is found, I is added to current packet and machine resource 15 // is marked as taken. If any dependency is found, a target API call is made to 16 // prune the dependence. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "HexagonVLIWPacketizer.h" 21 #include "Hexagon.h" 22 #include "HexagonInstrInfo.h" 23 #include "HexagonRegisterInfo.h" 24 #include "HexagonSubtarget.h" 25 #include "llvm/ADT/BitVector.h" 26 #include "llvm/ADT/DenseSet.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/Analysis/AliasAnalysis.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 31 #include "llvm/CodeGen/MachineDominators.h" 32 #include "llvm/CodeGen/MachineFrameInfo.h" 33 #include "llvm/CodeGen/MachineFunction.h" 34 #include "llvm/CodeGen/MachineFunctionPass.h" 35 #include "llvm/CodeGen/MachineInstr.h" 36 #include "llvm/CodeGen/MachineInstrBundle.h" 37 #include "llvm/CodeGen/MachineLoopInfo.h" 38 #include "llvm/CodeGen/MachineOperand.h" 39 #include "llvm/CodeGen/ScheduleDAG.h" 40 #include "llvm/CodeGen/TargetRegisterInfo.h" 41 #include "llvm/CodeGen/TargetSubtargetInfo.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/MC/MCInstrDesc.h" 44 #include "llvm/Pass.h" 45 #include "llvm/Support/CommandLine.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/ErrorHandling.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include <cassert> 50 #include <cstdint> 51 #include <iterator> 52 53 using namespace llvm; 54 55 #define DEBUG_TYPE "packets" 56 57 static cl::opt<bool> DisablePacketizer("disable-packetizer", cl::Hidden, 58 cl::ZeroOrMore, cl::init(false), 59 cl::desc("Disable Hexagon packetizer pass")); 60 61 cl::opt<bool> Slot1Store("slot1-store-slot0-load", cl::Hidden, 62 cl::ZeroOrMore, cl::init(true), 63 cl::desc("Allow slot1 store and slot0 load")); 64 65 static cl::opt<bool> PacketizeVolatiles("hexagon-packetize-volatiles", 66 cl::ZeroOrMore, cl::Hidden, cl::init(true), 67 cl::desc("Allow non-solo packetization of volatile memory references")); 68 69 static cl::opt<bool> EnableGenAllInsnClass("enable-gen-insn", cl::init(false), 70 cl::Hidden, cl::ZeroOrMore, cl::desc("Generate all instruction with TC")); 71 72 static cl::opt<bool> DisableVecDblNVStores("disable-vecdbl-nv-stores", 73 cl::init(false), cl::Hidden, cl::ZeroOrMore, 74 cl::desc("Disable vector double new-value-stores")); 75 76 extern cl::opt<bool> ScheduleInlineAsm; 77 78 namespace llvm { 79 80 FunctionPass *createHexagonPacketizer(); 81 void initializeHexagonPacketizerPass(PassRegistry&); 82 83 } // end namespace llvm 84 85 namespace { 86 87 class HexagonPacketizer : public MachineFunctionPass { 88 public: 89 static char ID; 90 91 HexagonPacketizer() : MachineFunctionPass(ID) {} 92 93 void getAnalysisUsage(AnalysisUsage &AU) const override { 94 AU.setPreservesCFG(); 95 AU.addRequired<AAResultsWrapperPass>(); 96 AU.addRequired<MachineBranchProbabilityInfo>(); 97 AU.addRequired<MachineDominatorTree>(); 98 AU.addRequired<MachineLoopInfo>(); 99 AU.addPreserved<MachineDominatorTree>(); 100 AU.addPreserved<MachineLoopInfo>(); 101 MachineFunctionPass::getAnalysisUsage(AU); 102 } 103 104 StringRef getPassName() const override { return "Hexagon Packetizer"; } 105 bool runOnMachineFunction(MachineFunction &Fn) override; 106 107 MachineFunctionProperties getRequiredProperties() const override { 108 return MachineFunctionProperties().set( 109 MachineFunctionProperties::Property::NoVRegs); 110 } 111 112 private: 113 const HexagonInstrInfo *HII; 114 const HexagonRegisterInfo *HRI; 115 }; 116 117 } // end anonymous namespace 118 119 char HexagonPacketizer::ID = 0; 120 121 INITIALIZE_PASS_BEGIN(HexagonPacketizer, "hexagon-packetizer", 122 "Hexagon Packetizer", false, false) 123 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 124 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 125 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 126 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 127 INITIALIZE_PASS_END(HexagonPacketizer, "hexagon-packetizer", 128 "Hexagon Packetizer", false, false) 129 130 HexagonPacketizerList::HexagonPacketizerList(MachineFunction &MF, 131 MachineLoopInfo &MLI, AliasAnalysis *AA, 132 const MachineBranchProbabilityInfo *MBPI) 133 : VLIWPacketizerList(MF, MLI, AA), MBPI(MBPI), MLI(&MLI) { 134 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo(); 135 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 136 137 addMutation(llvm::make_unique<HexagonSubtarget::UsrOverflowMutation>()); 138 addMutation(llvm::make_unique<HexagonSubtarget::HVXMemLatencyMutation>()); 139 addMutation(llvm::make_unique<HexagonSubtarget::BankConflictMutation>()); 140 } 141 142 // Check if FirstI modifies a register that SecondI reads. 143 static bool hasWriteToReadDep(const MachineInstr &FirstI, 144 const MachineInstr &SecondI, 145 const TargetRegisterInfo *TRI) { 146 for (auto &MO : FirstI.operands()) { 147 if (!MO.isReg() || !MO.isDef()) 148 continue; 149 unsigned R = MO.getReg(); 150 if (SecondI.readsRegister(R, TRI)) 151 return true; 152 } 153 return false; 154 } 155 156 157 static MachineBasicBlock::iterator moveInstrOut(MachineInstr &MI, 158 MachineBasicBlock::iterator BundleIt, bool Before) { 159 MachineBasicBlock::instr_iterator InsertPt; 160 if (Before) 161 InsertPt = BundleIt.getInstrIterator(); 162 else 163 InsertPt = std::next(BundleIt).getInstrIterator(); 164 165 MachineBasicBlock &B = *MI.getParent(); 166 // The instruction should at least be bundled with the preceding instruction 167 // (there will always be one, i.e. BUNDLE, if nothing else). 168 assert(MI.isBundledWithPred()); 169 if (MI.isBundledWithSucc()) { 170 MI.clearFlag(MachineInstr::BundledSucc); 171 MI.clearFlag(MachineInstr::BundledPred); 172 } else { 173 // If it's not bundled with the successor (i.e. it is the last one 174 // in the bundle), then we can simply unbundle it from the predecessor, 175 // which will take care of updating the predecessor's flag. 176 MI.unbundleFromPred(); 177 } 178 B.splice(InsertPt, &B, MI.getIterator()); 179 180 // Get the size of the bundle without asserting. 181 MachineBasicBlock::const_instr_iterator I = BundleIt.getInstrIterator(); 182 MachineBasicBlock::const_instr_iterator E = B.instr_end(); 183 unsigned Size = 0; 184 for (++I; I != E && I->isBundledWithPred(); ++I) 185 ++Size; 186 187 // If there are still two or more instructions, then there is nothing 188 // else to be done. 189 if (Size > 1) 190 return BundleIt; 191 192 // Otherwise, extract the single instruction out and delete the bundle. 193 MachineBasicBlock::iterator NextIt = std::next(BundleIt); 194 MachineInstr &SingleI = *BundleIt->getNextNode(); 195 SingleI.unbundleFromPred(); 196 assert(!SingleI.isBundledWithSucc()); 197 BundleIt->eraseFromParent(); 198 return NextIt; 199 } 200 201 bool HexagonPacketizer::runOnMachineFunction(MachineFunction &MF) { 202 if (DisablePacketizer || skipFunction(MF.getFunction())) 203 return false; 204 205 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo(); 206 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 207 auto &MLI = getAnalysis<MachineLoopInfo>(); 208 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 209 auto *MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 210 211 if (EnableGenAllInsnClass) 212 HII->genAllInsnTimingClasses(MF); 213 214 // Instantiate the packetizer. 215 HexagonPacketizerList Packetizer(MF, MLI, AA, MBPI); 216 217 // DFA state table should not be empty. 218 assert(Packetizer.getResourceTracker() && "Empty DFA table!"); 219 220 // Loop over all basic blocks and remove KILL pseudo-instructions 221 // These instructions confuse the dependence analysis. Consider: 222 // D0 = ... (Insn 0) 223 // R0 = KILL R0, D0 (Insn 1) 224 // R0 = ... (Insn 2) 225 // Here, Insn 1 will result in the dependence graph not emitting an output 226 // dependence between Insn 0 and Insn 2. This can lead to incorrect 227 // packetization 228 for (auto &MB : MF) { 229 auto End = MB.end(); 230 auto MI = MB.begin(); 231 while (MI != End) { 232 auto NextI = std::next(MI); 233 if (MI->isKill()) { 234 MB.erase(MI); 235 End = MB.end(); 236 } 237 MI = NextI; 238 } 239 } 240 241 // Loop over all of the basic blocks. 242 for (auto &MB : MF) { 243 auto Begin = MB.begin(), End = MB.end(); 244 while (Begin != End) { 245 // Find the first non-boundary starting from the end of the last 246 // scheduling region. 247 MachineBasicBlock::iterator RB = Begin; 248 while (RB != End && HII->isSchedulingBoundary(*RB, &MB, MF)) 249 ++RB; 250 // Find the first boundary starting from the beginning of the new 251 // region. 252 MachineBasicBlock::iterator RE = RB; 253 while (RE != End && !HII->isSchedulingBoundary(*RE, &MB, MF)) 254 ++RE; 255 // Add the scheduling boundary if it's not block end. 256 if (RE != End) 257 ++RE; 258 // If RB == End, then RE == End. 259 if (RB != End) 260 Packetizer.PacketizeMIs(&MB, RB, RE); 261 262 Begin = RE; 263 } 264 } 265 266 Packetizer.unpacketizeSoloInstrs(MF); 267 return true; 268 } 269 270 // Reserve resources for a constant extender. Trigger an assertion if the 271 // reservation fails. 272 void HexagonPacketizerList::reserveResourcesForConstExt() { 273 if (!tryAllocateResourcesForConstExt(true)) 274 llvm_unreachable("Resources not available"); 275 } 276 277 bool HexagonPacketizerList::canReserveResourcesForConstExt() { 278 return tryAllocateResourcesForConstExt(false); 279 } 280 281 // Allocate resources (i.e. 4 bytes) for constant extender. If succeeded, 282 // return true, otherwise, return false. 283 bool HexagonPacketizerList::tryAllocateResourcesForConstExt(bool Reserve) { 284 auto *ExtMI = MF.CreateMachineInstr(HII->get(Hexagon::A4_ext), DebugLoc()); 285 bool Avail = ResourceTracker->canReserveResources(*ExtMI); 286 if (Reserve && Avail) 287 ResourceTracker->reserveResources(*ExtMI); 288 MF.DeleteMachineInstr(ExtMI); 289 return Avail; 290 } 291 292 bool HexagonPacketizerList::isCallDependent(const MachineInstr &MI, 293 SDep::Kind DepType, unsigned DepReg) { 294 // Check for LR dependence. 295 if (DepReg == HRI->getRARegister()) 296 return true; 297 298 if (HII->isDeallocRet(MI)) 299 if (DepReg == HRI->getFrameRegister() || DepReg == HRI->getStackRegister()) 300 return true; 301 302 // Call-like instructions can be packetized with preceding instructions 303 // that define registers implicitly used or modified by the call. Explicit 304 // uses are still prohibited, as in the case of indirect calls: 305 // r0 = ... 306 // J2_jumpr r0 307 if (DepType == SDep::Data) { 308 for (const MachineOperand MO : MI.operands()) 309 if (MO.isReg() && MO.getReg() == DepReg && !MO.isImplicit()) 310 return true; 311 } 312 313 return false; 314 } 315 316 static bool isRegDependence(const SDep::Kind DepType) { 317 return DepType == SDep::Data || DepType == SDep::Anti || 318 DepType == SDep::Output; 319 } 320 321 static bool isDirectJump(const MachineInstr &MI) { 322 return MI.getOpcode() == Hexagon::J2_jump; 323 } 324 325 static bool isSchedBarrier(const MachineInstr &MI) { 326 switch (MI.getOpcode()) { 327 case Hexagon::Y2_barrier: 328 return true; 329 } 330 return false; 331 } 332 333 static bool isControlFlow(const MachineInstr &MI) { 334 return MI.getDesc().isTerminator() || MI.getDesc().isCall(); 335 } 336 337 /// Returns true if the instruction modifies a callee-saved register. 338 static bool doesModifyCalleeSavedReg(const MachineInstr &MI, 339 const TargetRegisterInfo *TRI) { 340 const MachineFunction &MF = *MI.getParent()->getParent(); 341 for (auto *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR) 342 if (MI.modifiesRegister(*CSR, TRI)) 343 return true; 344 return false; 345 } 346 347 // Returns true if an instruction can be promoted to .new predicate or 348 // new-value store. 349 bool HexagonPacketizerList::isNewifiable(const MachineInstr &MI, 350 const TargetRegisterClass *NewRC) { 351 // Vector stores can be predicated, and can be new-value stores, but 352 // they cannot be predicated on a .new predicate value. 353 if (NewRC == &Hexagon::PredRegsRegClass) { 354 if (HII->isHVXVec(MI) && MI.mayStore()) 355 return false; 356 return HII->isPredicated(MI) && HII->getDotNewPredOp(MI, nullptr) > 0; 357 } 358 // If the class is not PredRegs, it could only apply to new-value stores. 359 return HII->mayBeNewStore(MI); 360 } 361 362 // Promote an instructiont to its .cur form. 363 // At this time, we have already made a call to canPromoteToDotCur and made 364 // sure that it can *indeed* be promoted. 365 bool HexagonPacketizerList::promoteToDotCur(MachineInstr &MI, 366 SDep::Kind DepType, MachineBasicBlock::iterator &MII, 367 const TargetRegisterClass* RC) { 368 assert(DepType == SDep::Data); 369 int CurOpcode = HII->getDotCurOp(MI); 370 MI.setDesc(HII->get(CurOpcode)); 371 return true; 372 } 373 374 void HexagonPacketizerList::cleanUpDotCur() { 375 MachineInstr *MI = nullptr; 376 for (auto BI : CurrentPacketMIs) { 377 DEBUG(dbgs() << "Cleanup packet has "; BI->dump();); 378 if (HII->isDotCurInst(*BI)) { 379 MI = BI; 380 continue; 381 } 382 if (MI) { 383 for (auto &MO : BI->operands()) 384 if (MO.isReg() && MO.getReg() == MI->getOperand(0).getReg()) 385 return; 386 } 387 } 388 if (!MI) 389 return; 390 // We did not find a use of the CUR, so de-cur it. 391 MI->setDesc(HII->get(HII->getNonDotCurOp(*MI))); 392 DEBUG(dbgs() << "Demoted CUR "; MI->dump();); 393 } 394 395 // Check to see if an instruction can be dot cur. 396 bool HexagonPacketizerList::canPromoteToDotCur(const MachineInstr &MI, 397 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII, 398 const TargetRegisterClass *RC) { 399 if (!HII->isHVXVec(MI)) 400 return false; 401 if (!HII->isHVXVec(*MII)) 402 return false; 403 404 // Already a dot new instruction. 405 if (HII->isDotCurInst(MI) && !HII->mayBeCurLoad(MI)) 406 return false; 407 408 if (!HII->mayBeCurLoad(MI)) 409 return false; 410 411 // The "cur value" cannot come from inline asm. 412 if (PacketSU->getInstr()->isInlineAsm()) 413 return false; 414 415 // Make sure candidate instruction uses cur. 416 DEBUG(dbgs() << "Can we DOT Cur Vector MI\n"; 417 MI.dump(); 418 dbgs() << "in packet\n";); 419 MachineInstr &MJ = *MII; 420 DEBUG({ 421 dbgs() << "Checking CUR against "; 422 MJ.dump(); 423 }); 424 unsigned DestReg = MI.getOperand(0).getReg(); 425 bool FoundMatch = false; 426 for (auto &MO : MJ.operands()) 427 if (MO.isReg() && MO.getReg() == DestReg) 428 FoundMatch = true; 429 if (!FoundMatch) 430 return false; 431 432 // Check for existing uses of a vector register within the packet which 433 // would be affected by converting a vector load into .cur formt. 434 for (auto BI : CurrentPacketMIs) { 435 DEBUG(dbgs() << "packet has "; BI->dump();); 436 if (BI->readsRegister(DepReg, MF.getSubtarget().getRegisterInfo())) 437 return false; 438 } 439 440 DEBUG(dbgs() << "Can Dot CUR MI\n"; MI.dump();); 441 // We can convert the opcode into a .cur. 442 return true; 443 } 444 445 // Promote an instruction to its .new form. At this time, we have already 446 // made a call to canPromoteToDotNew and made sure that it can *indeed* be 447 // promoted. 448 bool HexagonPacketizerList::promoteToDotNew(MachineInstr &MI, 449 SDep::Kind DepType, MachineBasicBlock::iterator &MII, 450 const TargetRegisterClass* RC) { 451 assert(DepType == SDep::Data); 452 int NewOpcode; 453 if (RC == &Hexagon::PredRegsRegClass) 454 NewOpcode = HII->getDotNewPredOp(MI, MBPI); 455 else 456 NewOpcode = HII->getDotNewOp(MI); 457 MI.setDesc(HII->get(NewOpcode)); 458 return true; 459 } 460 461 bool HexagonPacketizerList::demoteToDotOld(MachineInstr &MI) { 462 int NewOpcode = HII->getDotOldOp(MI); 463 MI.setDesc(HII->get(NewOpcode)); 464 return true; 465 } 466 467 bool HexagonPacketizerList::useCallersSP(MachineInstr &MI) { 468 unsigned Opc = MI.getOpcode(); 469 switch (Opc) { 470 case Hexagon::S2_storerd_io: 471 case Hexagon::S2_storeri_io: 472 case Hexagon::S2_storerh_io: 473 case Hexagon::S2_storerb_io: 474 break; 475 default: 476 llvm_unreachable("Unexpected instruction"); 477 } 478 unsigned FrameSize = MF.getFrameInfo().getStackSize(); 479 MachineOperand &Off = MI.getOperand(1); 480 int64_t NewOff = Off.getImm() - (FrameSize + HEXAGON_LRFP_SIZE); 481 if (HII->isValidOffset(Opc, NewOff, HRI)) { 482 Off.setImm(NewOff); 483 return true; 484 } 485 return false; 486 } 487 488 void HexagonPacketizerList::useCalleesSP(MachineInstr &MI) { 489 unsigned Opc = MI.getOpcode(); 490 switch (Opc) { 491 case Hexagon::S2_storerd_io: 492 case Hexagon::S2_storeri_io: 493 case Hexagon::S2_storerh_io: 494 case Hexagon::S2_storerb_io: 495 break; 496 default: 497 llvm_unreachable("Unexpected instruction"); 498 } 499 unsigned FrameSize = MF.getFrameInfo().getStackSize(); 500 MachineOperand &Off = MI.getOperand(1); 501 Off.setImm(Off.getImm() + FrameSize + HEXAGON_LRFP_SIZE); 502 } 503 504 /// Return true if we can update the offset in MI so that MI and MJ 505 /// can be packetized together. 506 bool HexagonPacketizerList::updateOffset(SUnit *SUI, SUnit *SUJ) { 507 assert(SUI->getInstr() && SUJ->getInstr()); 508 MachineInstr &MI = *SUI->getInstr(); 509 MachineInstr &MJ = *SUJ->getInstr(); 510 511 unsigned BPI, OPI; 512 if (!HII->getBaseAndOffsetPosition(MI, BPI, OPI)) 513 return false; 514 unsigned BPJ, OPJ; 515 if (!HII->getBaseAndOffsetPosition(MJ, BPJ, OPJ)) 516 return false; 517 unsigned Reg = MI.getOperand(BPI).getReg(); 518 if (Reg != MJ.getOperand(BPJ).getReg()) 519 return false; 520 // Make sure that the dependences do not restrict adding MI to the packet. 521 // That is, ignore anti dependences, and make sure the only data dependence 522 // involves the specific register. 523 for (const auto &PI : SUI->Preds) 524 if (PI.getKind() != SDep::Anti && 525 (PI.getKind() != SDep::Data || PI.getReg() != Reg)) 526 return false; 527 int Incr; 528 if (!HII->getIncrementValue(MJ, Incr)) 529 return false; 530 531 int64_t Offset = MI.getOperand(OPI).getImm(); 532 MI.getOperand(OPI).setImm(Offset + Incr); 533 ChangedOffset = Offset; 534 return true; 535 } 536 537 /// Undo the changed offset. This is needed if the instruction cannot be 538 /// added to the current packet due to a different instruction. 539 void HexagonPacketizerList::undoChangedOffset(MachineInstr &MI) { 540 unsigned BP, OP; 541 if (!HII->getBaseAndOffsetPosition(MI, BP, OP)) 542 llvm_unreachable("Unable to find base and offset operands."); 543 MI.getOperand(OP).setImm(ChangedOffset); 544 } 545 546 enum PredicateKind { 547 PK_False, 548 PK_True, 549 PK_Unknown 550 }; 551 552 /// Returns true if an instruction is predicated on p0 and false if it's 553 /// predicated on !p0. 554 static PredicateKind getPredicateSense(const MachineInstr &MI, 555 const HexagonInstrInfo *HII) { 556 if (!HII->isPredicated(MI)) 557 return PK_Unknown; 558 if (HII->isPredicatedTrue(MI)) 559 return PK_True; 560 return PK_False; 561 } 562 563 static const MachineOperand &getPostIncrementOperand(const MachineInstr &MI, 564 const HexagonInstrInfo *HII) { 565 assert(HII->isPostIncrement(MI) && "Not a post increment operation."); 566 #ifndef NDEBUG 567 // Post Increment means duplicates. Use dense map to find duplicates in the 568 // list. Caution: Densemap initializes with the minimum of 64 buckets, 569 // whereas there are at most 5 operands in the post increment. 570 DenseSet<unsigned> DefRegsSet; 571 for (auto &MO : MI.operands()) 572 if (MO.isReg() && MO.isDef()) 573 DefRegsSet.insert(MO.getReg()); 574 575 for (auto &MO : MI.operands()) 576 if (MO.isReg() && MO.isUse() && DefRegsSet.count(MO.getReg())) 577 return MO; 578 #else 579 if (MI.mayLoad()) { 580 const MachineOperand &Op1 = MI.getOperand(1); 581 // The 2nd operand is always the post increment operand in load. 582 assert(Op1.isReg() && "Post increment operand has be to a register."); 583 return Op1; 584 } 585 if (MI.getDesc().mayStore()) { 586 const MachineOperand &Op0 = MI.getOperand(0); 587 // The 1st operand is always the post increment operand in store. 588 assert(Op0.isReg() && "Post increment operand has be to a register."); 589 return Op0; 590 } 591 #endif 592 // we should never come here. 593 llvm_unreachable("mayLoad or mayStore not set for Post Increment operation"); 594 } 595 596 // Get the value being stored. 597 static const MachineOperand& getStoreValueOperand(const MachineInstr &MI) { 598 // value being stored is always the last operand. 599 return MI.getOperand(MI.getNumOperands()-1); 600 } 601 602 static bool isLoadAbsSet(const MachineInstr &MI) { 603 unsigned Opc = MI.getOpcode(); 604 switch (Opc) { 605 case Hexagon::L4_loadrd_ap: 606 case Hexagon::L4_loadrb_ap: 607 case Hexagon::L4_loadrh_ap: 608 case Hexagon::L4_loadrub_ap: 609 case Hexagon::L4_loadruh_ap: 610 case Hexagon::L4_loadri_ap: 611 return true; 612 } 613 return false; 614 } 615 616 static const MachineOperand &getAbsSetOperand(const MachineInstr &MI) { 617 assert(isLoadAbsSet(MI)); 618 return MI.getOperand(1); 619 } 620 621 // Can be new value store? 622 // Following restrictions are to be respected in convert a store into 623 // a new value store. 624 // 1. If an instruction uses auto-increment, its address register cannot 625 // be a new-value register. Arch Spec 5.4.2.1 626 // 2. If an instruction uses absolute-set addressing mode, its address 627 // register cannot be a new-value register. Arch Spec 5.4.2.1. 628 // 3. If an instruction produces a 64-bit result, its registers cannot be used 629 // as new-value registers. Arch Spec 5.4.2.2. 630 // 4. If the instruction that sets the new-value register is conditional, then 631 // the instruction that uses the new-value register must also be conditional, 632 // and both must always have their predicates evaluate identically. 633 // Arch Spec 5.4.2.3. 634 // 5. There is an implied restriction that a packet cannot have another store, 635 // if there is a new value store in the packet. Corollary: if there is 636 // already a store in a packet, there can not be a new value store. 637 // Arch Spec: 3.4.4.2 638 bool HexagonPacketizerList::canPromoteToNewValueStore(const MachineInstr &MI, 639 const MachineInstr &PacketMI, unsigned DepReg) { 640 // Make sure we are looking at the store, that can be promoted. 641 if (!HII->mayBeNewStore(MI)) 642 return false; 643 644 // Make sure there is dependency and can be new value'd. 645 const MachineOperand &Val = getStoreValueOperand(MI); 646 if (Val.isReg() && Val.getReg() != DepReg) 647 return false; 648 649 const MCInstrDesc& MCID = PacketMI.getDesc(); 650 651 // First operand is always the result. 652 const TargetRegisterClass *PacketRC = HII->getRegClass(MCID, 0, HRI, MF); 653 // Double regs can not feed into new value store: PRM section: 5.4.2.2. 654 if (PacketRC == &Hexagon::DoubleRegsRegClass) 655 return false; 656 657 // New-value stores are of class NV (slot 0), dual stores require class ST 658 // in slot 0 (PRM 5.5). 659 for (auto I : CurrentPacketMIs) { 660 SUnit *PacketSU = MIToSUnit.find(I)->second; 661 if (PacketSU->getInstr()->mayStore()) 662 return false; 663 } 664 665 // Make sure it's NOT the post increment register that we are going to 666 // new value. 667 if (HII->isPostIncrement(MI) && 668 getPostIncrementOperand(MI, HII).getReg() == DepReg) { 669 return false; 670 } 671 672 if (HII->isPostIncrement(PacketMI) && PacketMI.mayLoad() && 673 getPostIncrementOperand(PacketMI, HII).getReg() == DepReg) { 674 // If source is post_inc, or absolute-set addressing, it can not feed 675 // into new value store 676 // r3 = memw(r2++#4) 677 // memw(r30 + #-1404) = r2.new -> can not be new value store 678 // arch spec section: 5.4.2.1. 679 return false; 680 } 681 682 if (isLoadAbsSet(PacketMI) && getAbsSetOperand(PacketMI).getReg() == DepReg) 683 return false; 684 685 // If the source that feeds the store is predicated, new value store must 686 // also be predicated. 687 if (HII->isPredicated(PacketMI)) { 688 if (!HII->isPredicated(MI)) 689 return false; 690 691 // Check to make sure that they both will have their predicates 692 // evaluate identically. 693 unsigned predRegNumSrc = 0; 694 unsigned predRegNumDst = 0; 695 const TargetRegisterClass* predRegClass = nullptr; 696 697 // Get predicate register used in the source instruction. 698 for (auto &MO : PacketMI.operands()) { 699 if (!MO.isReg()) 700 continue; 701 predRegNumSrc = MO.getReg(); 702 predRegClass = HRI->getMinimalPhysRegClass(predRegNumSrc); 703 if (predRegClass == &Hexagon::PredRegsRegClass) 704 break; 705 } 706 assert((predRegClass == &Hexagon::PredRegsRegClass) && 707 "predicate register not found in a predicated PacketMI instruction"); 708 709 // Get predicate register used in new-value store instruction. 710 for (auto &MO : MI.operands()) { 711 if (!MO.isReg()) 712 continue; 713 predRegNumDst = MO.getReg(); 714 predRegClass = HRI->getMinimalPhysRegClass(predRegNumDst); 715 if (predRegClass == &Hexagon::PredRegsRegClass) 716 break; 717 } 718 assert((predRegClass == &Hexagon::PredRegsRegClass) && 719 "predicate register not found in a predicated MI instruction"); 720 721 // New-value register producer and user (store) need to satisfy these 722 // constraints: 723 // 1) Both instructions should be predicated on the same register. 724 // 2) If producer of the new-value register is .new predicated then store 725 // should also be .new predicated and if producer is not .new predicated 726 // then store should not be .new predicated. 727 // 3) Both new-value register producer and user should have same predicate 728 // sense, i.e, either both should be negated or both should be non-negated. 729 if (predRegNumDst != predRegNumSrc || 730 HII->isDotNewInst(PacketMI) != HII->isDotNewInst(MI) || 731 getPredicateSense(MI, HII) != getPredicateSense(PacketMI, HII)) 732 return false; 733 } 734 735 // Make sure that other than the new-value register no other store instruction 736 // register has been modified in the same packet. Predicate registers can be 737 // modified by they should not be modified between the producer and the store 738 // instruction as it will make them both conditional on different values. 739 // We already know this to be true for all the instructions before and 740 // including PacketMI. Howerver, we need to perform the check for the 741 // remaining instructions in the packet. 742 743 unsigned StartCheck = 0; 744 745 for (auto I : CurrentPacketMIs) { 746 SUnit *TempSU = MIToSUnit.find(I)->second; 747 MachineInstr &TempMI = *TempSU->getInstr(); 748 749 // Following condition is true for all the instructions until PacketMI is 750 // reached (StartCheck is set to 0 before the for loop). 751 // StartCheck flag is 1 for all the instructions after PacketMI. 752 if (&TempMI != &PacketMI && !StartCheck) // Start processing only after 753 continue; // encountering PacketMI. 754 755 StartCheck = 1; 756 if (&TempMI == &PacketMI) // We don't want to check PacketMI for dependence. 757 continue; 758 759 for (auto &MO : MI.operands()) 760 if (MO.isReg() && TempSU->getInstr()->modifiesRegister(MO.getReg(), HRI)) 761 return false; 762 } 763 764 // Make sure that for non-POST_INC stores: 765 // 1. The only use of reg is DepReg and no other registers. 766 // This handles V4 base+index registers. 767 // The following store can not be dot new. 768 // Eg. r0 = add(r0, #3) 769 // memw(r1+r0<<#2) = r0 770 if (!HII->isPostIncrement(MI)) { 771 for (unsigned opNum = 0; opNum < MI.getNumOperands()-1; opNum++) { 772 const MachineOperand &MO = MI.getOperand(opNum); 773 if (MO.isReg() && MO.getReg() == DepReg) 774 return false; 775 } 776 } 777 778 // If data definition is because of implicit definition of the register, 779 // do not newify the store. Eg. 780 // %r9 = ZXTH %r12, implicit %d6, implicit-def %r12 781 // S2_storerh_io %r8, 2, killed %r12; mem:ST2[%scevgep343] 782 for (auto &MO : PacketMI.operands()) { 783 if (MO.isRegMask() && MO.clobbersPhysReg(DepReg)) 784 return false; 785 if (!MO.isReg() || !MO.isDef() || !MO.isImplicit()) 786 continue; 787 unsigned R = MO.getReg(); 788 if (R == DepReg || HRI->isSuperRegister(DepReg, R)) 789 return false; 790 } 791 792 // Handle imp-use of super reg case. There is a target independent side 793 // change that should prevent this situation but I am handling it for 794 // just-in-case. For example, we cannot newify R2 in the following case: 795 // %r3 = A2_tfrsi 0; 796 // S2_storeri_io killed %r0, 0, killed %r2, implicit killed %d1; 797 for (auto &MO : MI.operands()) { 798 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == DepReg) 799 return false; 800 } 801 802 // Can be dot new store. 803 return true; 804 } 805 806 // Can this MI to promoted to either new value store or new value jump. 807 bool HexagonPacketizerList::canPromoteToNewValue(const MachineInstr &MI, 808 const SUnit *PacketSU, unsigned DepReg, 809 MachineBasicBlock::iterator &MII) { 810 if (!HII->mayBeNewStore(MI)) 811 return false; 812 813 // Check to see the store can be new value'ed. 814 MachineInstr &PacketMI = *PacketSU->getInstr(); 815 if (canPromoteToNewValueStore(MI, PacketMI, DepReg)) 816 return true; 817 818 // Check to see the compare/jump can be new value'ed. 819 // This is done as a pass on its own. Don't need to check it here. 820 return false; 821 } 822 823 static bool isImplicitDependency(const MachineInstr &I, bool CheckDef, 824 unsigned DepReg) { 825 for (auto &MO : I.operands()) { 826 if (CheckDef && MO.isRegMask() && MO.clobbersPhysReg(DepReg)) 827 return true; 828 if (!MO.isReg() || MO.getReg() != DepReg || !MO.isImplicit()) 829 continue; 830 if (CheckDef == MO.isDef()) 831 return true; 832 } 833 return false; 834 } 835 836 // Check to see if an instruction can be dot new 837 // There are three kinds. 838 // 1. dot new on predicate - V2/V3/V4 839 // 2. dot new on stores NV/ST - V4 840 // 3. dot new on jump NV/J - V4 -- This is generated in a pass. 841 bool HexagonPacketizerList::canPromoteToDotNew(const MachineInstr &MI, 842 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII, 843 const TargetRegisterClass* RC) { 844 // Already a dot new instruction. 845 if (HII->isDotNewInst(MI) && !HII->mayBeNewStore(MI)) 846 return false; 847 848 if (!isNewifiable(MI, RC)) 849 return false; 850 851 const MachineInstr &PI = *PacketSU->getInstr(); 852 853 // The "new value" cannot come from inline asm. 854 if (PI.isInlineAsm()) 855 return false; 856 857 // IMPLICIT_DEFs won't materialize as real instructions, so .new makes no 858 // sense. 859 if (PI.isImplicitDef()) 860 return false; 861 862 // If dependency is trough an implicitly defined register, we should not 863 // newify the use. 864 if (isImplicitDependency(PI, true, DepReg) || 865 isImplicitDependency(MI, false, DepReg)) 866 return false; 867 868 const MCInstrDesc& MCID = PI.getDesc(); 869 const TargetRegisterClass *VecRC = HII->getRegClass(MCID, 0, HRI, MF); 870 if (DisableVecDblNVStores && VecRC == &Hexagon::HvxWRRegClass) 871 return false; 872 873 // predicate .new 874 if (RC == &Hexagon::PredRegsRegClass) 875 return HII->predCanBeUsedAsDotNew(PI, DepReg); 876 877 if (RC != &Hexagon::PredRegsRegClass && !HII->mayBeNewStore(MI)) 878 return false; 879 880 // Create a dot new machine instruction to see if resources can be 881 // allocated. If not, bail out now. 882 int NewOpcode = HII->getDotNewOp(MI); 883 const MCInstrDesc &D = HII->get(NewOpcode); 884 MachineInstr *NewMI = MF.CreateMachineInstr(D, DebugLoc()); 885 bool ResourcesAvailable = ResourceTracker->canReserveResources(*NewMI); 886 MF.DeleteMachineInstr(NewMI); 887 if (!ResourcesAvailable) 888 return false; 889 890 // New Value Store only. New Value Jump generated as a separate pass. 891 if (!canPromoteToNewValue(MI, PacketSU, DepReg, MII)) 892 return false; 893 894 return true; 895 } 896 897 // Go through the packet instructions and search for an anti dependency between 898 // them and DepReg from MI. Consider this case: 899 // Trying to add 900 // a) %r1 = TFRI_cdNotPt %p3, 2 901 // to this packet: 902 // { 903 // b) %p0 = C2_or killed %p3, killed %p0 904 // c) %p3 = C2_tfrrp %r23 905 // d) %r1 = C2_cmovenewit %p3, 4 906 // } 907 // The P3 from a) and d) will be complements after 908 // a)'s P3 is converted to .new form 909 // Anti-dep between c) and b) is irrelevant for this case 910 bool HexagonPacketizerList::restrictingDepExistInPacket(MachineInstr &MI, 911 unsigned DepReg) { 912 SUnit *PacketSUDep = MIToSUnit.find(&MI)->second; 913 914 for (auto I : CurrentPacketMIs) { 915 // We only care for dependencies to predicated instructions 916 if (!HII->isPredicated(*I)) 917 continue; 918 919 // Scheduling Unit for current insn in the packet 920 SUnit *PacketSU = MIToSUnit.find(I)->second; 921 922 // Look at dependencies between current members of the packet and 923 // predicate defining instruction MI. Make sure that dependency is 924 // on the exact register we care about. 925 if (PacketSU->isSucc(PacketSUDep)) { 926 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) { 927 auto &Dep = PacketSU->Succs[i]; 928 if (Dep.getSUnit() == PacketSUDep && Dep.getKind() == SDep::Anti && 929 Dep.getReg() == DepReg) 930 return true; 931 } 932 } 933 } 934 935 return false; 936 } 937 938 /// Gets the predicate register of a predicated instruction. 939 static unsigned getPredicatedRegister(MachineInstr &MI, 940 const HexagonInstrInfo *QII) { 941 /// We use the following rule: The first predicate register that is a use is 942 /// the predicate register of a predicated instruction. 943 assert(QII->isPredicated(MI) && "Must be predicated instruction"); 944 945 for (auto &Op : MI.operands()) { 946 if (Op.isReg() && Op.getReg() && Op.isUse() && 947 Hexagon::PredRegsRegClass.contains(Op.getReg())) 948 return Op.getReg(); 949 } 950 951 llvm_unreachable("Unknown instruction operand layout"); 952 return 0; 953 } 954 955 // Given two predicated instructions, this function detects whether 956 // the predicates are complements. 957 bool HexagonPacketizerList::arePredicatesComplements(MachineInstr &MI1, 958 MachineInstr &MI2) { 959 // If we don't know the predicate sense of the instructions bail out early, we 960 // need it later. 961 if (getPredicateSense(MI1, HII) == PK_Unknown || 962 getPredicateSense(MI2, HII) == PK_Unknown) 963 return false; 964 965 // Scheduling unit for candidate. 966 SUnit *SU = MIToSUnit[&MI1]; 967 968 // One corner case deals with the following scenario: 969 // Trying to add 970 // a) %r24 = A2_tfrt %p0, %r25 971 // to this packet: 972 // { 973 // b) %r25 = A2_tfrf %p0, %r24 974 // c) %p0 = C2_cmpeqi %r26, 1 975 // } 976 // 977 // On general check a) and b) are complements, but presence of c) will 978 // convert a) to .new form, and then it is not a complement. 979 // We attempt to detect it by analyzing existing dependencies in the packet. 980 981 // Analyze relationships between all existing members of the packet. 982 // Look for Anti dependecy on the same predicate reg as used in the 983 // candidate. 984 for (auto I : CurrentPacketMIs) { 985 // Scheduling Unit for current insn in the packet. 986 SUnit *PacketSU = MIToSUnit.find(I)->second; 987 988 // If this instruction in the packet is succeeded by the candidate... 989 if (PacketSU->isSucc(SU)) { 990 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) { 991 auto Dep = PacketSU->Succs[i]; 992 // The corner case exist when there is true data dependency between 993 // candidate and one of current packet members, this dep is on 994 // predicate reg, and there already exist anti dep on the same pred in 995 // the packet. 996 if (Dep.getSUnit() == SU && Dep.getKind() == SDep::Data && 997 Hexagon::PredRegsRegClass.contains(Dep.getReg())) { 998 // Here I know that I is predicate setting instruction with true 999 // data dep to candidate on the register we care about - c) in the 1000 // above example. Now I need to see if there is an anti dependency 1001 // from c) to any other instruction in the same packet on the pred 1002 // reg of interest. 1003 if (restrictingDepExistInPacket(*I, Dep.getReg())) 1004 return false; 1005 } 1006 } 1007 } 1008 } 1009 1010 // If the above case does not apply, check regular complement condition. 1011 // Check that the predicate register is the same and that the predicate 1012 // sense is different We also need to differentiate .old vs. .new: !p0 1013 // is not complementary to p0.new. 1014 unsigned PReg1 = getPredicatedRegister(MI1, HII); 1015 unsigned PReg2 = getPredicatedRegister(MI2, HII); 1016 return PReg1 == PReg2 && 1017 Hexagon::PredRegsRegClass.contains(PReg1) && 1018 Hexagon::PredRegsRegClass.contains(PReg2) && 1019 getPredicateSense(MI1, HII) != getPredicateSense(MI2, HII) && 1020 HII->isDotNewInst(MI1) == HII->isDotNewInst(MI2); 1021 } 1022 1023 // Initialize packetizer flags. 1024 void HexagonPacketizerList::initPacketizerState() { 1025 Dependence = false; 1026 PromotedToDotNew = false; 1027 GlueToNewValueJump = false; 1028 GlueAllocframeStore = false; 1029 FoundSequentialDependence = false; 1030 ChangedOffset = INT64_MAX; 1031 } 1032 1033 // Ignore bundling of pseudo instructions. 1034 bool HexagonPacketizerList::ignorePseudoInstruction(const MachineInstr &MI, 1035 const MachineBasicBlock *) { 1036 if (MI.isDebugValue()) 1037 return true; 1038 1039 if (MI.isCFIInstruction()) 1040 return false; 1041 1042 // We must print out inline assembly. 1043 if (MI.isInlineAsm()) 1044 return false; 1045 1046 if (MI.isImplicitDef()) 1047 return false; 1048 1049 // We check if MI has any functional units mapped to it. If it doesn't, 1050 // we ignore the instruction. 1051 const MCInstrDesc& TID = MI.getDesc(); 1052 auto *IS = ResourceTracker->getInstrItins()->beginStage(TID.getSchedClass()); 1053 unsigned FuncUnits = IS->getUnits(); 1054 return !FuncUnits; 1055 } 1056 1057 bool HexagonPacketizerList::isSoloInstruction(const MachineInstr &MI) { 1058 // Ensure any bundles created by gather packetize remain seperate. 1059 if (MI.isBundle()) 1060 return true; 1061 1062 if (MI.isEHLabel() || MI.isCFIInstruction()) 1063 return true; 1064 1065 // Consider inline asm to not be a solo instruction by default. 1066 // Inline asm will be put in a packet temporarily, but then it will be 1067 // removed, and placed outside of the packet (before or after, depending 1068 // on dependencies). This is to reduce the impact of inline asm as a 1069 // "packet splitting" instruction. 1070 if (MI.isInlineAsm() && !ScheduleInlineAsm) 1071 return true; 1072 1073 // From Hexagon V4 Programmer's Reference Manual 3.4.4 Grouping constraints: 1074 // trap, pause, barrier, icinva, isync, and syncht are solo instructions. 1075 // They must not be grouped with other instructions in a packet. 1076 if (isSchedBarrier(MI)) 1077 return true; 1078 1079 if (HII->isSolo(MI)) 1080 return true; 1081 1082 if (MI.getOpcode() == Hexagon::A2_nop) 1083 return true; 1084 1085 return false; 1086 } 1087 1088 // Quick check if instructions MI and MJ cannot coexist in the same packet. 1089 // Limit the tests to be "one-way", e.g. "if MI->isBranch and MJ->isInlineAsm", 1090 // but not the symmetric case: "if MJ->isBranch and MI->isInlineAsm". 1091 // For full test call this function twice: 1092 // cannotCoexistAsymm(MI, MJ) || cannotCoexistAsymm(MJ, MI) 1093 // Doing the test only one way saves the amount of code in this function, 1094 // since every test would need to be repeated with the MI and MJ reversed. 1095 static bool cannotCoexistAsymm(const MachineInstr &MI, const MachineInstr &MJ, 1096 const HexagonInstrInfo &HII) { 1097 const MachineFunction *MF = MI.getParent()->getParent(); 1098 if (MF->getSubtarget<HexagonSubtarget>().hasV60TOpsOnly() && 1099 HII.isHVXMemWithAIndirect(MI, MJ)) 1100 return true; 1101 1102 // An inline asm cannot be together with a branch, because we may not be 1103 // able to remove the asm out after packetizing (i.e. if the asm must be 1104 // moved past the bundle). Similarly, two asms cannot be together to avoid 1105 // complications when determining their relative order outside of a bundle. 1106 if (MI.isInlineAsm()) 1107 return MJ.isInlineAsm() || MJ.isBranch() || MJ.isBarrier() || 1108 MJ.isCall() || MJ.isTerminator(); 1109 1110 switch (MI.getOpcode()) { 1111 case Hexagon::S2_storew_locked: 1112 case Hexagon::S4_stored_locked: 1113 case Hexagon::L2_loadw_locked: 1114 case Hexagon::L4_loadd_locked: 1115 case Hexagon::Y4_l2fetch: 1116 case Hexagon::Y5_l2fetch: { 1117 // These instructions can only be grouped with ALU32 or non-floating-point 1118 // XTYPE instructions. Since there is no convenient way of identifying fp 1119 // XTYPE instructions, only allow grouping with ALU32 for now. 1120 unsigned TJ = HII.getType(MJ); 1121 if (TJ != HexagonII::TypeALU32_2op && 1122 TJ != HexagonII::TypeALU32_3op && 1123 TJ != HexagonII::TypeALU32_ADDI) 1124 return true; 1125 break; 1126 } 1127 default: 1128 break; 1129 } 1130 1131 // "False" really means that the quick check failed to determine if 1132 // I and J cannot coexist. 1133 return false; 1134 } 1135 1136 // Full, symmetric check. 1137 bool HexagonPacketizerList::cannotCoexist(const MachineInstr &MI, 1138 const MachineInstr &MJ) { 1139 return cannotCoexistAsymm(MI, MJ, *HII) || cannotCoexistAsymm(MJ, MI, *HII); 1140 } 1141 1142 void HexagonPacketizerList::unpacketizeSoloInstrs(MachineFunction &MF) { 1143 for (auto &B : MF) { 1144 MachineBasicBlock::iterator BundleIt; 1145 MachineBasicBlock::instr_iterator NextI; 1146 for (auto I = B.instr_begin(), E = B.instr_end(); I != E; I = NextI) { 1147 NextI = std::next(I); 1148 MachineInstr &MI = *I; 1149 if (MI.isBundle()) 1150 BundleIt = I; 1151 if (!MI.isInsideBundle()) 1152 continue; 1153 1154 // Decide on where to insert the instruction that we are pulling out. 1155 // Debug instructions always go before the bundle, but the placement of 1156 // INLINE_ASM depends on potential dependencies. By default, try to 1157 // put it before the bundle, but if the asm writes to a register that 1158 // other instructions in the bundle read, then we need to place it 1159 // after the bundle (to preserve the bundle semantics). 1160 bool InsertBeforeBundle; 1161 if (MI.isInlineAsm()) 1162 InsertBeforeBundle = !hasWriteToReadDep(MI, *BundleIt, HRI); 1163 else if (MI.isDebugValue()) 1164 InsertBeforeBundle = true; 1165 else 1166 continue; 1167 1168 BundleIt = moveInstrOut(MI, BundleIt, InsertBeforeBundle); 1169 } 1170 } 1171 } 1172 1173 // Check if a given instruction is of class "system". 1174 static bool isSystemInstr(const MachineInstr &MI) { 1175 unsigned Opc = MI.getOpcode(); 1176 switch (Opc) { 1177 case Hexagon::Y2_barrier: 1178 case Hexagon::Y2_dcfetchbo: 1179 case Hexagon::Y4_l2fetch: 1180 case Hexagon::Y5_l2fetch: 1181 return true; 1182 } 1183 return false; 1184 } 1185 1186 bool HexagonPacketizerList::hasDeadDependence(const MachineInstr &I, 1187 const MachineInstr &J) { 1188 // The dependence graph may not include edges between dead definitions, 1189 // so without extra checks, we could end up packetizing two instruction 1190 // defining the same (dead) register. 1191 if (I.isCall() || J.isCall()) 1192 return false; 1193 if (HII->isPredicated(I) || HII->isPredicated(J)) 1194 return false; 1195 1196 BitVector DeadDefs(Hexagon::NUM_TARGET_REGS); 1197 for (auto &MO : I.operands()) { 1198 if (!MO.isReg() || !MO.isDef() || !MO.isDead()) 1199 continue; 1200 DeadDefs[MO.getReg()] = true; 1201 } 1202 1203 for (auto &MO : J.operands()) { 1204 if (!MO.isReg() || !MO.isDef() || !MO.isDead()) 1205 continue; 1206 unsigned R = MO.getReg(); 1207 if (R != Hexagon::USR_OVF && DeadDefs[R]) 1208 return true; 1209 } 1210 return false; 1211 } 1212 1213 bool HexagonPacketizerList::hasControlDependence(const MachineInstr &I, 1214 const MachineInstr &J) { 1215 // A save callee-save register function call can only be in a packet 1216 // with instructions that don't write to the callee-save registers. 1217 if ((HII->isSaveCalleeSavedRegsCall(I) && 1218 doesModifyCalleeSavedReg(J, HRI)) || 1219 (HII->isSaveCalleeSavedRegsCall(J) && 1220 doesModifyCalleeSavedReg(I, HRI))) 1221 return true; 1222 1223 // Two control flow instructions cannot go in the same packet. 1224 if (isControlFlow(I) && isControlFlow(J)) 1225 return true; 1226 1227 // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot 1228 // contain a speculative indirect jump, 1229 // a new-value compare jump or a dealloc_return. 1230 auto isBadForLoopN = [this] (const MachineInstr &MI) -> bool { 1231 if (MI.isCall() || HII->isDeallocRet(MI) || HII->isNewValueJump(MI)) 1232 return true; 1233 if (HII->isPredicated(MI) && HII->isPredicatedNew(MI) && HII->isJumpR(MI)) 1234 return true; 1235 return false; 1236 }; 1237 1238 if (HII->isLoopN(I) && isBadForLoopN(J)) 1239 return true; 1240 if (HII->isLoopN(J) && isBadForLoopN(I)) 1241 return true; 1242 1243 // dealloc_return cannot appear in the same packet as a conditional or 1244 // unconditional jump. 1245 return HII->isDeallocRet(I) && 1246 (J.isBranch() || J.isCall() || J.isBarrier()); 1247 } 1248 1249 bool HexagonPacketizerList::hasRegMaskDependence(const MachineInstr &I, 1250 const MachineInstr &J) { 1251 // Adding I to a packet that has J. 1252 1253 // Regmasks are not reflected in the scheduling dependency graph, so 1254 // we need to check them manually. This code assumes that regmasks only 1255 // occur on calls, and the problematic case is when we add an instruction 1256 // defining a register R to a packet that has a call that clobbers R via 1257 // a regmask. Those cannot be packetized together, because the call will 1258 // be executed last. That's also a reson why it is ok to add a call 1259 // clobbering R to a packet that defines R. 1260 1261 // Look for regmasks in J. 1262 for (const MachineOperand &OpJ : J.operands()) { 1263 if (!OpJ.isRegMask()) 1264 continue; 1265 assert((J.isCall() || HII->isTailCall(J)) && "Regmask on a non-call"); 1266 for (const MachineOperand &OpI : I.operands()) { 1267 if (OpI.isReg()) { 1268 if (OpJ.clobbersPhysReg(OpI.getReg())) 1269 return true; 1270 } else if (OpI.isRegMask()) { 1271 // Both are regmasks. Assume that they intersect. 1272 return true; 1273 } 1274 } 1275 } 1276 return false; 1277 } 1278 1279 bool HexagonPacketizerList::hasV4SpecificDependence(const MachineInstr &I, 1280 const MachineInstr &J) { 1281 bool SysI = isSystemInstr(I), SysJ = isSystemInstr(J); 1282 bool StoreI = I.mayStore(), StoreJ = J.mayStore(); 1283 if ((SysI && StoreJ) || (SysJ && StoreI)) 1284 return true; 1285 1286 if (StoreI && StoreJ) { 1287 if (HII->isNewValueInst(J) || HII->isMemOp(J) || HII->isMemOp(I)) 1288 return true; 1289 } else { 1290 // A memop cannot be in the same packet with another memop or a store. 1291 // Two stores can be together, but here I and J cannot both be stores. 1292 bool MopStI = HII->isMemOp(I) || StoreI; 1293 bool MopStJ = HII->isMemOp(J) || StoreJ; 1294 if (MopStI && MopStJ) 1295 return true; 1296 } 1297 1298 return (StoreJ && HII->isDeallocRet(I)) || (StoreI && HII->isDeallocRet(J)); 1299 } 1300 1301 // SUI is the current instruction that is out side of the current packet. 1302 // SUJ is the current instruction inside the current packet against which that 1303 // SUI will be packetized. 1304 bool HexagonPacketizerList::isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) { 1305 assert(SUI->getInstr() && SUJ->getInstr()); 1306 MachineInstr &I = *SUI->getInstr(); 1307 MachineInstr &J = *SUJ->getInstr(); 1308 1309 // Clear IgnoreDepMIs when Packet starts. 1310 if (CurrentPacketMIs.size() == 1) 1311 IgnoreDepMIs.clear(); 1312 1313 MachineBasicBlock::iterator II = I.getIterator(); 1314 1315 // Solo instructions cannot go in the packet. 1316 assert(!isSoloInstruction(I) && "Unexpected solo instr!"); 1317 1318 if (cannotCoexist(I, J)) 1319 return false; 1320 1321 Dependence = hasDeadDependence(I, J) || hasControlDependence(I, J); 1322 if (Dependence) 1323 return false; 1324 1325 // Regmasks are not accounted for in the scheduling graph, so we need 1326 // to explicitly check for dependencies caused by them. They should only 1327 // appear on calls, so it's not too pessimistic to reject all regmask 1328 // dependencies. 1329 Dependence = hasRegMaskDependence(I, J); 1330 if (Dependence) 1331 return false; 1332 1333 // V4 allows dual stores. It does not allow second store, if the first 1334 // store is not in SLOT0. New value store, new value jump, dealloc_return 1335 // and memop always take SLOT0. Arch spec 3.4.4.2. 1336 Dependence = hasV4SpecificDependence(I, J); 1337 if (Dependence) 1338 return false; 1339 1340 // If an instruction feeds new value jump, glue it. 1341 MachineBasicBlock::iterator NextMII = I.getIterator(); 1342 ++NextMII; 1343 if (NextMII != I.getParent()->end() && HII->isNewValueJump(*NextMII)) { 1344 MachineInstr &NextMI = *NextMII; 1345 1346 bool secondRegMatch = false; 1347 const MachineOperand &NOp0 = NextMI.getOperand(0); 1348 const MachineOperand &NOp1 = NextMI.getOperand(1); 1349 1350 if (NOp1.isReg() && I.getOperand(0).getReg() == NOp1.getReg()) 1351 secondRegMatch = true; 1352 1353 for (MachineInstr *PI : CurrentPacketMIs) { 1354 // NVJ can not be part of the dual jump - Arch Spec: section 7.8. 1355 if (PI->isCall()) { 1356 Dependence = true; 1357 break; 1358 } 1359 // Validate: 1360 // 1. Packet does not have a store in it. 1361 // 2. If the first operand of the nvj is newified, and the second 1362 // operand is also a reg, it (second reg) is not defined in 1363 // the same packet. 1364 // 3. If the second operand of the nvj is newified, (which means 1365 // first operand is also a reg), first reg is not defined in 1366 // the same packet. 1367 if (PI->getOpcode() == Hexagon::S2_allocframe || PI->mayStore() || 1368 HII->isLoopN(*PI)) { 1369 Dependence = true; 1370 break; 1371 } 1372 // Check #2/#3. 1373 const MachineOperand &OpR = secondRegMatch ? NOp0 : NOp1; 1374 if (OpR.isReg() && PI->modifiesRegister(OpR.getReg(), HRI)) { 1375 Dependence = true; 1376 break; 1377 } 1378 } 1379 1380 GlueToNewValueJump = true; 1381 if (Dependence) 1382 return false; 1383 } 1384 1385 // There no dependency between a prolog instruction and its successor. 1386 if (!SUJ->isSucc(SUI)) 1387 return true; 1388 1389 for (unsigned i = 0; i < SUJ->Succs.size(); ++i) { 1390 if (FoundSequentialDependence) 1391 break; 1392 1393 if (SUJ->Succs[i].getSUnit() != SUI) 1394 continue; 1395 1396 SDep::Kind DepType = SUJ->Succs[i].getKind(); 1397 // For direct calls: 1398 // Ignore register dependences for call instructions for packetization 1399 // purposes except for those due to r31 and predicate registers. 1400 // 1401 // For indirect calls: 1402 // Same as direct calls + check for true dependences to the register 1403 // used in the indirect call. 1404 // 1405 // We completely ignore Order dependences for call instructions. 1406 // 1407 // For returns: 1408 // Ignore register dependences for return instructions like jumpr, 1409 // dealloc return unless we have dependencies on the explicit uses 1410 // of the registers used by jumpr (like r31) or dealloc return 1411 // (like r29 or r30). 1412 unsigned DepReg = 0; 1413 const TargetRegisterClass *RC = nullptr; 1414 if (DepType == SDep::Data) { 1415 DepReg = SUJ->Succs[i].getReg(); 1416 RC = HRI->getMinimalPhysRegClass(DepReg); 1417 } 1418 1419 if (I.isCall() || HII->isJumpR(I) || I.isReturn() || HII->isTailCall(I)) { 1420 if (!isRegDependence(DepType)) 1421 continue; 1422 if (!isCallDependent(I, DepType, SUJ->Succs[i].getReg())) 1423 continue; 1424 } 1425 1426 if (DepType == SDep::Data) { 1427 if (canPromoteToDotCur(J, SUJ, DepReg, II, RC)) 1428 if (promoteToDotCur(J, DepType, II, RC)) 1429 continue; 1430 } 1431 1432 // Data dpendence ok if we have load.cur. 1433 if (DepType == SDep::Data && HII->isDotCurInst(J)) { 1434 if (HII->isHVXVec(I)) 1435 continue; 1436 } 1437 1438 // For instructions that can be promoted to dot-new, try to promote. 1439 if (DepType == SDep::Data) { 1440 if (canPromoteToDotNew(I, SUJ, DepReg, II, RC)) { 1441 if (promoteToDotNew(I, DepType, II, RC)) { 1442 PromotedToDotNew = true; 1443 if (cannotCoexist(I, J)) 1444 FoundSequentialDependence = true; 1445 continue; 1446 } 1447 } 1448 if (HII->isNewValueJump(I)) 1449 continue; 1450 } 1451 1452 // For predicated instructions, if the predicates are complements then 1453 // there can be no dependence. 1454 if (HII->isPredicated(I) && HII->isPredicated(J) && 1455 arePredicatesComplements(I, J)) { 1456 // Not always safe to do this translation. 1457 // DAG Builder attempts to reduce dependence edges using transitive 1458 // nature of dependencies. Here is an example: 1459 // 1460 // r0 = tfr_pt ... (1) 1461 // r0 = tfr_pf ... (2) 1462 // r0 = tfr_pt ... (3) 1463 // 1464 // There will be an output dependence between (1)->(2) and (2)->(3). 1465 // However, there is no dependence edge between (1)->(3). This results 1466 // in all 3 instructions going in the same packet. We ignore dependce 1467 // only once to avoid this situation. 1468 auto Itr = find(IgnoreDepMIs, &J); 1469 if (Itr != IgnoreDepMIs.end()) { 1470 Dependence = true; 1471 return false; 1472 } 1473 IgnoreDepMIs.push_back(&I); 1474 continue; 1475 } 1476 1477 // Ignore Order dependences between unconditional direct branches 1478 // and non-control-flow instructions. 1479 if (isDirectJump(I) && !J.isBranch() && !J.isCall() && 1480 DepType == SDep::Order) 1481 continue; 1482 1483 // Ignore all dependences for jumps except for true and output 1484 // dependences. 1485 if (I.isConditionalBranch() && DepType != SDep::Data && 1486 DepType != SDep::Output) 1487 continue; 1488 1489 if (DepType == SDep::Output) { 1490 FoundSequentialDependence = true; 1491 break; 1492 } 1493 1494 // For Order dependences: 1495 // 1. On V4 or later, volatile loads/stores can be packetized together, 1496 // unless other rules prevent is. 1497 // 2. Store followed by a load is not allowed. 1498 // 3. Store followed by a store is only valid on V4 or later. 1499 // 4. Load followed by any memory operation is allowed. 1500 if (DepType == SDep::Order) { 1501 if (!PacketizeVolatiles) { 1502 bool OrdRefs = I.hasOrderedMemoryRef() || J.hasOrderedMemoryRef(); 1503 if (OrdRefs) { 1504 FoundSequentialDependence = true; 1505 break; 1506 } 1507 } 1508 // J is first, I is second. 1509 bool LoadJ = J.mayLoad(), StoreJ = J.mayStore(); 1510 bool LoadI = I.mayLoad(), StoreI = I.mayStore(); 1511 bool NVStoreJ = HII->isNewValueStore(J); 1512 bool NVStoreI = HII->isNewValueStore(I); 1513 bool IsVecJ = HII->isHVXVec(J); 1514 bool IsVecI = HII->isHVXVec(I); 1515 1516 if (Slot1Store && MF.getSubtarget<HexagonSubtarget>().hasV65TOps() && 1517 ((LoadJ && StoreI && !NVStoreI) || 1518 (StoreJ && LoadI && !NVStoreJ)) && 1519 (J.getOpcode() != Hexagon::S2_allocframe && 1520 I.getOpcode() != Hexagon::S2_allocframe) && 1521 (J.getOpcode() != Hexagon::L2_deallocframe && 1522 I.getOpcode() != Hexagon::L2_deallocframe) && 1523 (!HII->isMemOp(J) && !HII->isMemOp(I)) && (!IsVecJ && !IsVecI)) 1524 setmemShufDisabled(true); 1525 else 1526 if (StoreJ && LoadI && alias(J, I)) { 1527 FoundSequentialDependence = true; 1528 break; 1529 } 1530 1531 if (!StoreJ) 1532 if (!LoadJ || (!LoadI && !StoreI)) { 1533 // If J is neither load nor store, assume a dependency. 1534 // If J is a load, but I is neither, also assume a dependency. 1535 FoundSequentialDependence = true; 1536 break; 1537 } 1538 // Store followed by store: not OK on V2. 1539 // Store followed by load: not OK on all. 1540 // Load followed by store: OK on all. 1541 // Load followed by load: OK on all. 1542 continue; 1543 } 1544 1545 // For V4, special case ALLOCFRAME. Even though there is dependency 1546 // between ALLOCFRAME and subsequent store, allow it to be packetized 1547 // in a same packet. This implies that the store is using the caller's 1548 // SP. Hence, offset needs to be updated accordingly. 1549 if (DepType == SDep::Data && J.getOpcode() == Hexagon::S2_allocframe) { 1550 unsigned Opc = I.getOpcode(); 1551 switch (Opc) { 1552 case Hexagon::S2_storerd_io: 1553 case Hexagon::S2_storeri_io: 1554 case Hexagon::S2_storerh_io: 1555 case Hexagon::S2_storerb_io: 1556 if (I.getOperand(0).getReg() == HRI->getStackRegister()) { 1557 // Since this store is to be glued with allocframe in the same 1558 // packet, it will use SP of the previous stack frame, i.e. 1559 // caller's SP. Therefore, we need to recalculate offset 1560 // according to this change. 1561 GlueAllocframeStore = useCallersSP(I); 1562 if (GlueAllocframeStore) 1563 continue; 1564 } 1565 default: 1566 break; 1567 } 1568 } 1569 1570 // There are certain anti-dependencies that cannot be ignored. 1571 // Specifically: 1572 // J2_call ... implicit-def %r0 ; SUJ 1573 // R0 = ... ; SUI 1574 // Those cannot be packetized together, since the call will observe 1575 // the effect of the assignment to R0. 1576 if ((DepType == SDep::Anti || DepType == SDep::Output) && J.isCall()) { 1577 // Check if I defines any volatile register. We should also check 1578 // registers that the call may read, but these happen to be a 1579 // subset of the volatile register set. 1580 for (const MachineOperand &Op : I.operands()) { 1581 if (Op.isReg() && Op.isDef()) { 1582 unsigned R = Op.getReg(); 1583 if (!J.readsRegister(R, HRI) && !J.modifiesRegister(R, HRI)) 1584 continue; 1585 } else if (!Op.isRegMask()) { 1586 // If I has a regmask assume dependency. 1587 continue; 1588 } 1589 FoundSequentialDependence = true; 1590 break; 1591 } 1592 } 1593 1594 // Skip over remaining anti-dependences. Two instructions that are 1595 // anti-dependent can share a packet, since in most such cases all 1596 // operands are read before any modifications take place. 1597 // The exceptions are branch and call instructions, since they are 1598 // executed after all other instructions have completed (at least 1599 // conceptually). 1600 if (DepType != SDep::Anti) { 1601 FoundSequentialDependence = true; 1602 break; 1603 } 1604 } 1605 1606 if (FoundSequentialDependence) { 1607 Dependence = true; 1608 return false; 1609 } 1610 1611 return true; 1612 } 1613 1614 bool HexagonPacketizerList::isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) { 1615 assert(SUI->getInstr() && SUJ->getInstr()); 1616 MachineInstr &I = *SUI->getInstr(); 1617 MachineInstr &J = *SUJ->getInstr(); 1618 1619 bool Coexist = !cannotCoexist(I, J); 1620 1621 if (Coexist && !Dependence) 1622 return true; 1623 1624 // Check if the instruction was promoted to a dot-new. If so, demote it 1625 // back into a dot-old. 1626 if (PromotedToDotNew) 1627 demoteToDotOld(I); 1628 1629 cleanUpDotCur(); 1630 // Check if the instruction (must be a store) was glued with an allocframe 1631 // instruction. If so, restore its offset to its original value, i.e. use 1632 // current SP instead of caller's SP. 1633 if (GlueAllocframeStore) { 1634 useCalleesSP(I); 1635 GlueAllocframeStore = false; 1636 } 1637 1638 if (ChangedOffset != INT64_MAX) 1639 undoChangedOffset(I); 1640 1641 if (GlueToNewValueJump) { 1642 // Putting I and J together would prevent the new-value jump from being 1643 // packetized with the producer. In that case I and J must be separated. 1644 GlueToNewValueJump = false; 1645 return false; 1646 } 1647 1648 if (ChangedOffset == INT64_MAX && updateOffset(SUI, SUJ)) { 1649 FoundSequentialDependence = false; 1650 Dependence = false; 1651 return true; 1652 } 1653 1654 return false; 1655 } 1656 1657 1658 bool HexagonPacketizerList::foundLSInPacket() { 1659 bool FoundLoad = false; 1660 bool FoundStore = false; 1661 1662 for (auto MJ : CurrentPacketMIs) { 1663 unsigned Opc = MJ->getOpcode(); 1664 if (Opc == Hexagon::S2_allocframe || Opc == Hexagon::L2_deallocframe) 1665 continue; 1666 if (HII->isMemOp(*MJ)) 1667 continue; 1668 if (MJ->mayLoad()) 1669 FoundLoad = true; 1670 if (MJ->mayStore() && !HII->isNewValueStore(*MJ)) 1671 FoundStore = true; 1672 } 1673 return FoundLoad && FoundStore; 1674 } 1675 1676 1677 MachineBasicBlock::iterator 1678 HexagonPacketizerList::addToPacket(MachineInstr &MI) { 1679 MachineBasicBlock::iterator MII = MI.getIterator(); 1680 MachineBasicBlock *MBB = MI.getParent(); 1681 1682 if (CurrentPacketMIs.empty()) 1683 PacketStalls = false; 1684 PacketStalls |= producesStall(MI); 1685 1686 if (MI.isImplicitDef()) 1687 return MII; 1688 assert(ResourceTracker->canReserveResources(MI)); 1689 1690 bool ExtMI = HII->isExtended(MI) || HII->isConstExtended(MI); 1691 bool Good = true; 1692 1693 if (GlueToNewValueJump) { 1694 MachineInstr &NvjMI = *++MII; 1695 // We need to put both instructions in the same packet: MI and NvjMI. 1696 // Either of them can require a constant extender. Try to add both to 1697 // the current packet, and if that fails, end the packet and start a 1698 // new one. 1699 ResourceTracker->reserveResources(MI); 1700 if (ExtMI) 1701 Good = tryAllocateResourcesForConstExt(true); 1702 1703 bool ExtNvjMI = HII->isExtended(NvjMI) || HII->isConstExtended(NvjMI); 1704 if (Good) { 1705 if (ResourceTracker->canReserveResources(NvjMI)) 1706 ResourceTracker->reserveResources(NvjMI); 1707 else 1708 Good = false; 1709 } 1710 if (Good && ExtNvjMI) 1711 Good = tryAllocateResourcesForConstExt(true); 1712 1713 if (!Good) { 1714 endPacket(MBB, MI); 1715 assert(ResourceTracker->canReserveResources(MI)); 1716 ResourceTracker->reserveResources(MI); 1717 if (ExtMI) { 1718 assert(canReserveResourcesForConstExt()); 1719 tryAllocateResourcesForConstExt(true); 1720 } 1721 assert(ResourceTracker->canReserveResources(NvjMI)); 1722 ResourceTracker->reserveResources(NvjMI); 1723 if (ExtNvjMI) { 1724 assert(canReserveResourcesForConstExt()); 1725 reserveResourcesForConstExt(); 1726 } 1727 } 1728 CurrentPacketMIs.push_back(&MI); 1729 CurrentPacketMIs.push_back(&NvjMI); 1730 return MII; 1731 } 1732 1733 ResourceTracker->reserveResources(MI); 1734 if (ExtMI && !tryAllocateResourcesForConstExt(true)) { 1735 endPacket(MBB, MI); 1736 if (PromotedToDotNew) 1737 demoteToDotOld(MI); 1738 if (GlueAllocframeStore) { 1739 useCalleesSP(MI); 1740 GlueAllocframeStore = false; 1741 } 1742 ResourceTracker->reserveResources(MI); 1743 reserveResourcesForConstExt(); 1744 } 1745 1746 CurrentPacketMIs.push_back(&MI); 1747 return MII; 1748 } 1749 1750 void HexagonPacketizerList::endPacket(MachineBasicBlock *MBB, 1751 MachineBasicBlock::iterator MI) { 1752 // Replace VLIWPacketizerList::endPacket(MBB, MI). 1753 1754 bool memShufDisabled = getmemShufDisabled(); 1755 if (memShufDisabled && !foundLSInPacket()) { 1756 setmemShufDisabled(false); 1757 DEBUG(dbgs() << " Not added to NoShufPacket\n"); 1758 } 1759 memShufDisabled = getmemShufDisabled(); 1760 1761 if (CurrentPacketMIs.size() > 1) { 1762 MachineBasicBlock::instr_iterator FirstMI(CurrentPacketMIs.front()); 1763 MachineBasicBlock::instr_iterator LastMI(MI.getInstrIterator()); 1764 finalizeBundle(*MBB, FirstMI, LastMI); 1765 1766 auto BundleMII = std::prev(FirstMI); 1767 if (memShufDisabled) 1768 HII->setBundleNoShuf(BundleMII); 1769 1770 setmemShufDisabled(false); 1771 } 1772 OldPacketMIs = CurrentPacketMIs; 1773 CurrentPacketMIs.clear(); 1774 1775 ResourceTracker->clearResources(); 1776 DEBUG(dbgs() << "End packet\n"); 1777 } 1778 1779 bool HexagonPacketizerList::shouldAddToPacket(const MachineInstr &MI) { 1780 return !producesStall(MI); 1781 } 1782 1783 // V60 forward scheduling. 1784 bool HexagonPacketizerList::producesStall(const MachineInstr &I) { 1785 // If the packet already stalls, then ignore the stall from a subsequent 1786 // instruction in the same packet. 1787 if (PacketStalls) 1788 return false; 1789 1790 // Check whether the previous packet is in a different loop. If this is the 1791 // case, there is little point in trying to avoid a stall because that would 1792 // favor the rare case (loop entry) over the common case (loop iteration). 1793 // 1794 // TODO: We should really be able to check all the incoming edges if this is 1795 // the first packet in a basic block, so we can avoid stalls from the loop 1796 // backedge. 1797 if (!OldPacketMIs.empty()) { 1798 auto *OldBB = OldPacketMIs.front()->getParent(); 1799 auto *ThisBB = I.getParent(); 1800 if (MLI->getLoopFor(OldBB) != MLI->getLoopFor(ThisBB)) 1801 return false; 1802 } 1803 1804 SUnit *SUI = MIToSUnit[const_cast<MachineInstr *>(&I)]; 1805 1806 // Check if the latency is 0 between this instruction and any instruction 1807 // in the current packet. If so, we disregard any potential stalls due to 1808 // the instructions in the previous packet. Most of the instruction pairs 1809 // that can go together in the same packet have 0 latency between them. 1810 // Only exceptions are newValueJumps as they're generated much later and 1811 // the latencies can't be changed at that point. Another is .cur 1812 // instructions if its consumer has a 0 latency successor (such as .new). 1813 // In this case, the latency between .cur and the consumer stays non-zero 1814 // even though we can have both .cur and .new in the same packet. Changing 1815 // the latency to 0 is not an option as it causes software pipeliner to 1816 // not pipeline in some cases. 1817 1818 // For Example: 1819 // { 1820 // I1: v6.cur = vmem(r0++#1) 1821 // I2: v7 = valign(v6,v4,r2) 1822 // I3: vmem(r5++#1) = v7.new 1823 // } 1824 // Here I2 and I3 has 0 cycle latency, but I1 and I2 has 2. 1825 1826 for (auto J : CurrentPacketMIs) { 1827 SUnit *SUJ = MIToSUnit[J]; 1828 for (auto &Pred : SUI->Preds) 1829 if (Pred.getSUnit() == SUJ && 1830 (Pred.getLatency() == 0 || HII->isNewValueJump(I) || 1831 HII->isToBeScheduledASAP(*J, I))) 1832 return false; 1833 } 1834 1835 // Check if the latency is greater than one between this instruction and any 1836 // instruction in the previous packet. 1837 for (auto J : OldPacketMIs) { 1838 SUnit *SUJ = MIToSUnit[J]; 1839 for (auto &Pred : SUI->Preds) 1840 if (Pred.getSUnit() == SUJ && Pred.getLatency() > 1) 1841 return true; 1842 } 1843 1844 // Check if the latency is greater than one between this instruction and any 1845 // instruction in the previous packet. 1846 for (auto J : OldPacketMIs) { 1847 SUnit *SUJ = MIToSUnit[J]; 1848 for (auto &Pred : SUI->Preds) 1849 if (Pred.getSUnit() == SUJ && Pred.getLatency() > 1) 1850 return true; 1851 } 1852 1853 return false; 1854 } 1855 1856 //===----------------------------------------------------------------------===// 1857 // Public Constructor Functions 1858 //===----------------------------------------------------------------------===// 1859 1860 FunctionPass *llvm::createHexagonPacketizer() { 1861 return new HexagonPacketizer(); 1862 } 1863