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