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