1 //===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===// 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 pass performs loop invariant code motion on machine instructions. We 10 // attempt to remove as much code from the body of a loop as possible. 11 // 12 // This pass is not intended to be a replacement or a complete alternative 13 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple 14 // constructs that are not exposed before lowering and instruction selection. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineBasicBlock.h" 26 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 27 #include "llvm/CodeGen/MachineDominators.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineFunctionPass.h" 31 #include "llvm/CodeGen/MachineInstr.h" 32 #include "llvm/CodeGen/MachineLoopInfo.h" 33 #include "llvm/CodeGen/MachineMemOperand.h" 34 #include "llvm/CodeGen/MachineOperand.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/PseudoSourceValue.h" 37 #include "llvm/CodeGen/TargetInstrInfo.h" 38 #include "llvm/CodeGen/TargetLowering.h" 39 #include "llvm/CodeGen/TargetRegisterInfo.h" 40 #include "llvm/CodeGen/TargetSchedule.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/MC/MCRegister.h" 46 #include "llvm/MC/MCRegisterInfo.h" 47 #include "llvm/Pass.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Support/Debug.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include <algorithm> 53 #include <cassert> 54 #include <limits> 55 #include <vector> 56 57 using namespace llvm; 58 59 #define DEBUG_TYPE "machinelicm" 60 61 static cl::opt<bool> 62 AvoidSpeculation("avoid-speculation", 63 cl::desc("MachineLICM should avoid speculation"), 64 cl::init(true), cl::Hidden); 65 66 static cl::opt<bool> 67 HoistCheapInsts("hoist-cheap-insts", 68 cl::desc("MachineLICM should hoist even cheap instructions"), 69 cl::init(false), cl::Hidden); 70 71 static cl::opt<bool> 72 SinkInstsToAvoidSpills("sink-insts-to-avoid-spills", 73 cl::desc("MachineLICM should sink instructions into " 74 "loops to avoid register spills"), 75 cl::init(false), cl::Hidden); 76 static cl::opt<bool> 77 HoistConstStores("hoist-const-stores", 78 cl::desc("Hoist invariant stores"), 79 cl::init(true), cl::Hidden); 80 // The default threshold of 100 (i.e. if target block is 100 times hotter) 81 // is based on empirical data on a single target and is subject to tuning. 82 static cl::opt<unsigned> 83 BlockFrequencyRatioThreshold("block-freq-ratio-threshold", 84 cl::desc("Do not hoist instructions if target" 85 "block is N times hotter than the source."), 86 cl::init(100), cl::Hidden); 87 88 enum class UseBFI { None, PGO, All }; 89 90 static cl::opt<UseBFI> 91 DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks", 92 cl::desc("Disable hoisting instructions to" 93 " hotter blocks"), 94 cl::init(UseBFI::PGO), cl::Hidden, 95 cl::values(clEnumValN(UseBFI::None, "none", 96 "disable the feature"), 97 clEnumValN(UseBFI::PGO, "pgo", 98 "enable the feature when using profile data"), 99 clEnumValN(UseBFI::All, "all", 100 "enable the feature with/wo profile data"))); 101 102 STATISTIC(NumHoisted, 103 "Number of machine instructions hoisted out of loops"); 104 STATISTIC(NumLowRP, 105 "Number of instructions hoisted in low reg pressure situation"); 106 STATISTIC(NumHighLatency, 107 "Number of high latency instructions hoisted"); 108 STATISTIC(NumCSEed, 109 "Number of hoisted machine instructions CSEed"); 110 STATISTIC(NumPostRAHoisted, 111 "Number of machine instructions hoisted out of loops post regalloc"); 112 STATISTIC(NumStoreConst, 113 "Number of stores of const phys reg hoisted out of loops"); 114 STATISTIC(NumNotHoistedDueToHotness, 115 "Number of instructions not hoisted due to block frequency"); 116 117 namespace { 118 119 class MachineLICMBase : public MachineFunctionPass { 120 const TargetInstrInfo *TII; 121 const TargetLoweringBase *TLI; 122 const TargetRegisterInfo *TRI; 123 const MachineFrameInfo *MFI; 124 MachineRegisterInfo *MRI; 125 TargetSchedModel SchedModel; 126 bool PreRegAlloc; 127 bool HasProfileData; 128 129 // Various analyses that we use... 130 AliasAnalysis *AA; // Alias analysis info. 131 MachineBlockFrequencyInfo *MBFI; // Machine block frequncy info 132 MachineLoopInfo *MLI; // Current MachineLoopInfo 133 MachineDominatorTree *DT; // Machine dominator tree for the cur loop 134 135 // State that is updated as we process loops 136 bool Changed; // True if a loop is changed. 137 bool FirstInLoop; // True if it's the first LICM in the loop. 138 MachineLoop *CurLoop; // The current loop we are working on. 139 MachineBasicBlock *CurPreheader; // The preheader for CurLoop. 140 141 // Exit blocks for CurLoop. 142 SmallVector<MachineBasicBlock *, 8> ExitBlocks; 143 144 bool isExitBlock(const MachineBasicBlock *MBB) const { 145 return is_contained(ExitBlocks, MBB); 146 } 147 148 // Track 'estimated' register pressure. 149 SmallSet<Register, 32> RegSeen; 150 SmallVector<unsigned, 8> RegPressure; 151 152 // Register pressure "limit" per register pressure set. If the pressure 153 // is higher than the limit, then it's considered high. 154 SmallVector<unsigned, 8> RegLimit; 155 156 // Register pressure on path leading from loop preheader to current BB. 157 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace; 158 159 // For each opcode, keep a list of potential CSE instructions. 160 DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap; 161 162 enum { 163 SpeculateFalse = 0, 164 SpeculateTrue = 1, 165 SpeculateUnknown = 2 166 }; 167 168 // If a MBB does not dominate loop exiting blocks then it may not safe 169 // to hoist loads from this block. 170 // Tri-state: 0 - false, 1 - true, 2 - unknown 171 unsigned SpeculationState; 172 173 public: 174 MachineLICMBase(char &PassID, bool PreRegAlloc) 175 : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {} 176 177 bool runOnMachineFunction(MachineFunction &MF) override; 178 179 void getAnalysisUsage(AnalysisUsage &AU) const override { 180 AU.addRequired<MachineLoopInfo>(); 181 if (DisableHoistingToHotterBlocks != UseBFI::None) 182 AU.addRequired<MachineBlockFrequencyInfo>(); 183 AU.addRequired<MachineDominatorTree>(); 184 AU.addRequired<AAResultsWrapperPass>(); 185 AU.addPreserved<MachineLoopInfo>(); 186 MachineFunctionPass::getAnalysisUsage(AU); 187 } 188 189 void releaseMemory() override { 190 RegSeen.clear(); 191 RegPressure.clear(); 192 RegLimit.clear(); 193 BackTrace.clear(); 194 CSEMap.clear(); 195 } 196 197 private: 198 /// Keep track of information about hoisting candidates. 199 struct CandidateInfo { 200 MachineInstr *MI; 201 unsigned Def; 202 int FI; 203 204 CandidateInfo(MachineInstr *mi, unsigned def, int fi) 205 : MI(mi), Def(def), FI(fi) {} 206 }; 207 208 void HoistRegionPostRA(); 209 210 void HoistPostRA(MachineInstr *MI, unsigned Def); 211 212 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs, 213 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs, 214 SmallVectorImpl<CandidateInfo> &Candidates); 215 216 void AddToLiveIns(MCRegister Reg); 217 218 bool IsLICMCandidate(MachineInstr &I); 219 220 bool IsLoopInvariantInst(MachineInstr &I); 221 222 bool HasLoopPHIUse(const MachineInstr *MI) const; 223 224 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx, 225 Register Reg) const; 226 227 bool IsCheapInstruction(MachineInstr &MI) const; 228 229 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost, 230 bool Cheap); 231 232 void UpdateBackTraceRegPressure(const MachineInstr *MI); 233 234 bool IsProfitableToHoist(MachineInstr &MI); 235 236 bool IsGuaranteedToExecute(MachineBasicBlock *BB); 237 238 void EnterScope(MachineBasicBlock *MBB); 239 240 void ExitScope(MachineBasicBlock *MBB); 241 242 void ExitScopeIfDone( 243 MachineDomTreeNode *Node, 244 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren, 245 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap); 246 247 void HoistOutOfLoop(MachineDomTreeNode *HeaderN); 248 249 void SinkIntoLoop(); 250 251 void InitRegPressure(MachineBasicBlock *BB); 252 253 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI, 254 bool ConsiderSeen, 255 bool ConsiderUnseenAsDef); 256 257 void UpdateRegPressure(const MachineInstr *MI, 258 bool ConsiderUnseenAsDef = false); 259 260 MachineInstr *ExtractHoistableLoad(MachineInstr *MI); 261 262 const MachineInstr * 263 LookForDuplicate(const MachineInstr *MI, 264 std::vector<const MachineInstr *> &PrevMIs); 265 266 bool EliminateCSE( 267 MachineInstr *MI, 268 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI); 269 270 bool MayCSE(MachineInstr *MI); 271 272 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader); 273 274 void InitCSEMap(MachineBasicBlock *BB); 275 276 bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock, 277 MachineBasicBlock *TgtBlock); 278 MachineBasicBlock *getCurPreheader(); 279 }; 280 281 class MachineLICM : public MachineLICMBase { 282 public: 283 static char ID; 284 MachineLICM() : MachineLICMBase(ID, false) { 285 initializeMachineLICMPass(*PassRegistry::getPassRegistry()); 286 } 287 }; 288 289 class EarlyMachineLICM : public MachineLICMBase { 290 public: 291 static char ID; 292 EarlyMachineLICM() : MachineLICMBase(ID, true) { 293 initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry()); 294 } 295 }; 296 297 } // end anonymous namespace 298 299 char MachineLICM::ID; 300 char EarlyMachineLICM::ID; 301 302 char &llvm::MachineLICMID = MachineLICM::ID; 303 char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID; 304 305 INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE, 306 "Machine Loop Invariant Code Motion", false, false) 307 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 308 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 309 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 310 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 311 INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE, 312 "Machine Loop Invariant Code Motion", false, false) 313 314 INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm", 315 "Early Machine Loop Invariant Code Motion", false, false) 316 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 317 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 318 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 319 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 320 INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm", 321 "Early Machine Loop Invariant Code Motion", false, false) 322 323 /// Test if the given loop is the outer-most loop that has a unique predecessor. 324 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) { 325 // Check whether this loop even has a unique predecessor. 326 if (!CurLoop->getLoopPredecessor()) 327 return false; 328 // Ok, now check to see if any of its outer loops do. 329 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop()) 330 if (L->getLoopPredecessor()) 331 return false; 332 // None of them did, so this is the outermost with a unique predecessor. 333 return true; 334 } 335 336 bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) { 337 if (skipFunction(MF.getFunction())) 338 return false; 339 340 Changed = FirstInLoop = false; 341 const TargetSubtargetInfo &ST = MF.getSubtarget(); 342 TII = ST.getInstrInfo(); 343 TLI = ST.getTargetLowering(); 344 TRI = ST.getRegisterInfo(); 345 MFI = &MF.getFrameInfo(); 346 MRI = &MF.getRegInfo(); 347 SchedModel.init(&ST); 348 349 PreRegAlloc = MRI->isSSA(); 350 HasProfileData = MF.getFunction().hasProfileData(); 351 352 if (PreRegAlloc) 353 LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: "); 354 else 355 LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: "); 356 LLVM_DEBUG(dbgs() << MF.getName() << " ********\n"); 357 358 if (PreRegAlloc) { 359 // Estimate register pressure during pre-regalloc pass. 360 unsigned NumRPS = TRI->getNumRegPressureSets(); 361 RegPressure.resize(NumRPS); 362 std::fill(RegPressure.begin(), RegPressure.end(), 0); 363 RegLimit.resize(NumRPS); 364 for (unsigned i = 0, e = NumRPS; i != e; ++i) 365 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i); 366 } 367 368 // Get our Loop information... 369 if (DisableHoistingToHotterBlocks != UseBFI::None) 370 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 371 MLI = &getAnalysis<MachineLoopInfo>(); 372 DT = &getAnalysis<MachineDominatorTree>(); 373 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 374 375 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end()); 376 while (!Worklist.empty()) { 377 CurLoop = Worklist.pop_back_val(); 378 CurPreheader = nullptr; 379 ExitBlocks.clear(); 380 381 // If this is done before regalloc, only visit outer-most preheader-sporting 382 // loops. 383 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) { 384 Worklist.append(CurLoop->begin(), CurLoop->end()); 385 continue; 386 } 387 388 CurLoop->getExitBlocks(ExitBlocks); 389 390 if (!PreRegAlloc) 391 HoistRegionPostRA(); 392 else { 393 // CSEMap is initialized for loop header when the first instruction is 394 // being hoisted. 395 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader()); 396 FirstInLoop = true; 397 HoistOutOfLoop(N); 398 CSEMap.clear(); 399 400 if (SinkInstsToAvoidSpills) 401 SinkIntoLoop(); 402 } 403 } 404 405 return Changed; 406 } 407 408 /// Return true if instruction stores to the specified frame. 409 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) { 410 // Check mayStore before memory operands so that e.g. DBG_VALUEs will return 411 // true since they have no memory operands. 412 if (!MI->mayStore()) 413 return false; 414 // If we lost memory operands, conservatively assume that the instruction 415 // writes to all slots. 416 if (MI->memoperands_empty()) 417 return true; 418 for (const MachineMemOperand *MemOp : MI->memoperands()) { 419 if (!MemOp->isStore() || !MemOp->getPseudoValue()) 420 continue; 421 if (const FixedStackPseudoSourceValue *Value = 422 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) { 423 if (Value->getFrameIndex() == FI) 424 return true; 425 } 426 } 427 return false; 428 } 429 430 /// Examine the instruction for potentai LICM candidate. Also 431 /// gather register def and frame object update information. 432 void MachineLICMBase::ProcessMI(MachineInstr *MI, 433 BitVector &PhysRegDefs, 434 BitVector &PhysRegClobbers, 435 SmallSet<int, 32> &StoredFIs, 436 SmallVectorImpl<CandidateInfo> &Candidates) { 437 bool RuledOut = false; 438 bool HasNonInvariantUse = false; 439 unsigned Def = 0; 440 for (const MachineOperand &MO : MI->operands()) { 441 if (MO.isFI()) { 442 // Remember if the instruction stores to the frame index. 443 int FI = MO.getIndex(); 444 if (!StoredFIs.count(FI) && 445 MFI->isSpillSlotObjectIndex(FI) && 446 InstructionStoresToFI(MI, FI)) 447 StoredFIs.insert(FI); 448 HasNonInvariantUse = true; 449 continue; 450 } 451 452 // We can't hoist an instruction defining a physreg that is clobbered in 453 // the loop. 454 if (MO.isRegMask()) { 455 PhysRegClobbers.setBitsNotInMask(MO.getRegMask()); 456 continue; 457 } 458 459 if (!MO.isReg()) 460 continue; 461 Register Reg = MO.getReg(); 462 if (!Reg) 463 continue; 464 assert(Register::isPhysicalRegister(Reg) && 465 "Not expecting virtual register!"); 466 467 if (!MO.isDef()) { 468 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg))) 469 // If it's using a non-loop-invariant register, then it's obviously not 470 // safe to hoist. 471 HasNonInvariantUse = true; 472 continue; 473 } 474 475 if (MO.isImplicit()) { 476 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 477 PhysRegClobbers.set(*AI); 478 if (!MO.isDead()) 479 // Non-dead implicit def? This cannot be hoisted. 480 RuledOut = true; 481 // No need to check if a dead implicit def is also defined by 482 // another instruction. 483 continue; 484 } 485 486 // FIXME: For now, avoid instructions with multiple defs, unless 487 // it's a dead implicit def. 488 if (Def) 489 RuledOut = true; 490 else 491 Def = Reg; 492 493 // If we have already seen another instruction that defines the same 494 // register, then this is not safe. Two defs is indicated by setting a 495 // PhysRegClobbers bit. 496 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) { 497 if (PhysRegDefs.test(*AS)) 498 PhysRegClobbers.set(*AS); 499 } 500 // Need a second loop because MCRegAliasIterator can visit the same 501 // register twice. 502 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) 503 PhysRegDefs.set(*AS); 504 505 if (PhysRegClobbers.test(Reg)) 506 // MI defined register is seen defined by another instruction in 507 // the loop, it cannot be a LICM candidate. 508 RuledOut = true; 509 } 510 511 // Only consider reloads for now and remats which do not have register 512 // operands. FIXME: Consider unfold load folding instructions. 513 if (Def && !RuledOut) { 514 int FI = std::numeric_limits<int>::min(); 515 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) || 516 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI))) 517 Candidates.push_back(CandidateInfo(MI, Def, FI)); 518 } 519 } 520 521 /// Walk the specified region of the CFG and hoist loop invariants out to the 522 /// preheader. 523 void MachineLICMBase::HoistRegionPostRA() { 524 MachineBasicBlock *Preheader = getCurPreheader(); 525 if (!Preheader) 526 return; 527 528 unsigned NumRegs = TRI->getNumRegs(); 529 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop. 530 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once. 531 532 SmallVector<CandidateInfo, 32> Candidates; 533 SmallSet<int, 32> StoredFIs; 534 535 // Walk the entire region, count number of defs for each register, and 536 // collect potential LICM candidates. 537 for (MachineBasicBlock *BB : CurLoop->getBlocks()) { 538 // If the header of the loop containing this basic block is a landing pad, 539 // then don't try to hoist instructions out of this loop. 540 const MachineLoop *ML = MLI->getLoopFor(BB); 541 if (ML && ML->getHeader()->isEHPad()) continue; 542 543 // Conservatively treat live-in's as an external def. 544 // FIXME: That means a reload that're reused in successor block(s) will not 545 // be LICM'ed. 546 for (const auto &LI : BB->liveins()) { 547 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) 548 PhysRegDefs.set(*AI); 549 } 550 551 SpeculationState = SpeculateUnknown; 552 for (MachineInstr &MI : *BB) 553 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates); 554 } 555 556 // Gather the registers read / clobbered by the terminator. 557 BitVector TermRegs(NumRegs); 558 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator(); 559 if (TI != Preheader->end()) { 560 for (const MachineOperand &MO : TI->operands()) { 561 if (!MO.isReg()) 562 continue; 563 Register Reg = MO.getReg(); 564 if (!Reg) 565 continue; 566 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 567 TermRegs.set(*AI); 568 } 569 } 570 571 // Now evaluate whether the potential candidates qualify. 572 // 1. Check if the candidate defined register is defined by another 573 // instruction in the loop. 574 // 2. If the candidate is a load from stack slot (always true for now), 575 // check if the slot is stored anywhere in the loop. 576 // 3. Make sure candidate def should not clobber 577 // registers read by the terminator. Similarly its def should not be 578 // clobbered by the terminator. 579 for (CandidateInfo &Candidate : Candidates) { 580 if (Candidate.FI != std::numeric_limits<int>::min() && 581 StoredFIs.count(Candidate.FI)) 582 continue; 583 584 unsigned Def = Candidate.Def; 585 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) { 586 bool Safe = true; 587 MachineInstr *MI = Candidate.MI; 588 for (const MachineOperand &MO : MI->operands()) { 589 if (!MO.isReg() || MO.isDef() || !MO.getReg()) 590 continue; 591 Register Reg = MO.getReg(); 592 if (PhysRegDefs.test(Reg) || 593 PhysRegClobbers.test(Reg)) { 594 // If it's using a non-loop-invariant register, then it's obviously 595 // not safe to hoist. 596 Safe = false; 597 break; 598 } 599 } 600 if (Safe) 601 HoistPostRA(MI, Candidate.Def); 602 } 603 } 604 } 605 606 /// Add register 'Reg' to the livein sets of BBs in the current loop, and make 607 /// sure it is not killed by any instructions in the loop. 608 void MachineLICMBase::AddToLiveIns(MCRegister Reg) { 609 for (MachineBasicBlock *BB : CurLoop->getBlocks()) { 610 if (!BB->isLiveIn(Reg)) 611 BB->addLiveIn(Reg); 612 for (MachineInstr &MI : *BB) { 613 for (MachineOperand &MO : MI.operands()) { 614 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue; 615 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg())) 616 MO.setIsKill(false); 617 } 618 } 619 } 620 } 621 622 /// When an instruction is found to only use loop invariant operands that is 623 /// safe to hoist, this instruction is called to do the dirty work. 624 void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) { 625 MachineBasicBlock *Preheader = getCurPreheader(); 626 627 // Now move the instructions to the predecessor, inserting it before any 628 // terminator instructions. 629 LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader) 630 << " from " << printMBBReference(*MI->getParent()) << ": " 631 << *MI); 632 633 // Splice the instruction to the preheader. 634 MachineBasicBlock *MBB = MI->getParent(); 635 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI); 636 637 // Since we are moving the instruction out of its basic block, we do not 638 // retain its debug location. Doing so would degrade the debugging 639 // experience and adversely affect the accuracy of profiling information. 640 assert(!MI->isDebugInstr() && "Should not hoist debug inst"); 641 MI->setDebugLoc(DebugLoc()); 642 643 // Add register to livein list to all the BBs in the current loop since a 644 // loop invariant must be kept live throughout the whole loop. This is 645 // important to ensure later passes do not scavenge the def register. 646 AddToLiveIns(Def); 647 648 ++NumPostRAHoisted; 649 Changed = true; 650 } 651 652 /// Check if this mbb is guaranteed to execute. If not then a load from this mbb 653 /// may not be safe to hoist. 654 bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) { 655 if (SpeculationState != SpeculateUnknown) 656 return SpeculationState == SpeculateFalse; 657 658 if (BB != CurLoop->getHeader()) { 659 // Check loop exiting blocks. 660 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks; 661 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks); 662 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks) 663 if (!DT->dominates(BB, CurrentLoopExitingBlock)) { 664 SpeculationState = SpeculateTrue; 665 return false; 666 } 667 } 668 669 SpeculationState = SpeculateFalse; 670 return true; 671 } 672 673 void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) { 674 LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n'); 675 676 // Remember livein register pressure. 677 BackTrace.push_back(RegPressure); 678 } 679 680 void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) { 681 LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n'); 682 BackTrace.pop_back(); 683 } 684 685 /// Destroy scope for the MBB that corresponds to the given dominator tree node 686 /// if its a leaf or all of its children are done. Walk up the dominator tree to 687 /// destroy ancestors which are now done. 688 void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node, 689 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren, 690 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) { 691 if (OpenChildren[Node]) 692 return; 693 694 // Pop scope. 695 ExitScope(Node->getBlock()); 696 697 // Now traverse upwards to pop ancestors whose offsprings are all done. 698 while (MachineDomTreeNode *Parent = ParentMap[Node]) { 699 unsigned Left = --OpenChildren[Parent]; 700 if (Left != 0) 701 break; 702 ExitScope(Parent->getBlock()); 703 Node = Parent; 704 } 705 } 706 707 /// Walk the specified loop in the CFG (defined by all blocks dominated by the 708 /// specified header block, and that are in the current loop) in depth first 709 /// order w.r.t the DominatorTree. This allows us to visit definitions before 710 /// uses, allowing us to hoist a loop body in one pass without iteration. 711 void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) { 712 MachineBasicBlock *Preheader = getCurPreheader(); 713 if (!Preheader) 714 return; 715 716 SmallVector<MachineDomTreeNode*, 32> Scopes; 717 SmallVector<MachineDomTreeNode*, 8> WorkList; 718 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap; 719 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren; 720 721 // Perform a DFS walk to determine the order of visit. 722 WorkList.push_back(HeaderN); 723 while (!WorkList.empty()) { 724 MachineDomTreeNode *Node = WorkList.pop_back_val(); 725 assert(Node && "Null dominator tree node?"); 726 MachineBasicBlock *BB = Node->getBlock(); 727 728 // If the header of the loop containing this basic block is a landing pad, 729 // then don't try to hoist instructions out of this loop. 730 const MachineLoop *ML = MLI->getLoopFor(BB); 731 if (ML && ML->getHeader()->isEHPad()) 732 continue; 733 734 // If this subregion is not in the top level loop at all, exit. 735 if (!CurLoop->contains(BB)) 736 continue; 737 738 Scopes.push_back(Node); 739 unsigned NumChildren = Node->getNumChildren(); 740 741 // Don't hoist things out of a large switch statement. This often causes 742 // code to be hoisted that wasn't going to be executed, and increases 743 // register pressure in a situation where it's likely to matter. 744 if (BB->succ_size() >= 25) 745 NumChildren = 0; 746 747 OpenChildren[Node] = NumChildren; 748 if (NumChildren) { 749 // Add children in reverse order as then the next popped worklist node is 750 // the first child of this node. This means we ultimately traverse the 751 // DOM tree in exactly the same order as if we'd recursed. 752 for (MachineDomTreeNode *Child : reverse(Node->children())) { 753 ParentMap[Child] = Node; 754 WorkList.push_back(Child); 755 } 756 } 757 } 758 759 if (Scopes.size() == 0) 760 return; 761 762 // Compute registers which are livein into the loop headers. 763 RegSeen.clear(); 764 BackTrace.clear(); 765 InitRegPressure(Preheader); 766 767 // Now perform LICM. 768 for (MachineDomTreeNode *Node : Scopes) { 769 MachineBasicBlock *MBB = Node->getBlock(); 770 771 EnterScope(MBB); 772 773 // Process the block 774 SpeculationState = SpeculateUnknown; 775 for (MachineBasicBlock::iterator 776 MII = MBB->begin(), E = MBB->end(); MII != E; ) { 777 MachineBasicBlock::iterator NextMII = MII; ++NextMII; 778 MachineInstr *MI = &*MII; 779 if (!Hoist(MI, Preheader)) 780 UpdateRegPressure(MI); 781 // If we have hoisted an instruction that may store, it can only be a 782 // constant store. 783 MII = NextMII; 784 } 785 786 // If it's a leaf node, it's done. Traverse upwards to pop ancestors. 787 ExitScopeIfDone(Node, OpenChildren, ParentMap); 788 } 789 } 790 791 /// Sink instructions into loops if profitable. This especially tries to prevent 792 /// register spills caused by register pressure if there is little to no 793 /// overhead moving instructions into loops. 794 void MachineLICMBase::SinkIntoLoop() { 795 MachineBasicBlock *Preheader = getCurPreheader(); 796 if (!Preheader) 797 return; 798 799 SmallVector<MachineInstr *, 8> Candidates; 800 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin(); 801 I != Preheader->instr_end(); ++I) { 802 // We need to ensure that we can safely move this instruction into the loop. 803 // As such, it must not have side-effects, e.g. such as a call has. 804 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I)) 805 Candidates.push_back(&*I); 806 } 807 808 for (MachineInstr *I : Candidates) { 809 const MachineOperand &MO = I->getOperand(0); 810 if (!MO.isDef() || !MO.isReg() || !MO.getReg()) 811 continue; 812 if (!MRI->hasOneDef(MO.getReg())) 813 continue; 814 bool CanSink = true; 815 MachineBasicBlock *B = nullptr; 816 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) { 817 // FIXME: Come up with a proper cost model that estimates whether sinking 818 // the instruction (and thus possibly executing it on every loop 819 // iteration) is more expensive than a register. 820 // For now assumes that copies are cheap and thus almost always worth it. 821 if (!MI.isCopy()) { 822 CanSink = false; 823 break; 824 } 825 if (!B) { 826 B = MI.getParent(); 827 continue; 828 } 829 B = DT->findNearestCommonDominator(B, MI.getParent()); 830 if (!B) { 831 CanSink = false; 832 break; 833 } 834 } 835 if (!CanSink || !B || B == Preheader) 836 continue; 837 838 LLVM_DEBUG(dbgs() << "Sinking to " << printMBBReference(*B) << " from " 839 << printMBBReference(*I->getParent()) << ": " << *I); 840 B->splice(B->getFirstNonPHI(), Preheader, I); 841 842 // The instruction is is moved from its basic block, so do not retain the 843 // debug information. 844 assert(!I->isDebugInstr() && "Should not sink debug inst"); 845 I->setDebugLoc(DebugLoc()); 846 } 847 } 848 849 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) { 850 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg()); 851 } 852 853 /// Find all virtual register references that are liveout of the preheader to 854 /// initialize the starting "register pressure". Note this does not count live 855 /// through (livein but not used) registers. 856 void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) { 857 std::fill(RegPressure.begin(), RegPressure.end(), 0); 858 859 // If the preheader has only a single predecessor and it ends with a 860 // fallthrough or an unconditional branch, then scan its predecessor for live 861 // defs as well. This happens whenever the preheader is created by splitting 862 // the critical edge from the loop predecessor to the loop header. 863 if (BB->pred_size() == 1) { 864 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 865 SmallVector<MachineOperand, 4> Cond; 866 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty()) 867 InitRegPressure(*BB->pred_begin()); 868 } 869 870 for (const MachineInstr &MI : *BB) 871 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true); 872 } 873 874 /// Update estimate of register pressure after the specified instruction. 875 void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI, 876 bool ConsiderUnseenAsDef) { 877 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef); 878 for (const auto &RPIdAndCost : Cost) { 879 unsigned Class = RPIdAndCost.first; 880 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second) 881 RegPressure[Class] = 0; 882 else 883 RegPressure[Class] += RPIdAndCost.second; 884 } 885 } 886 887 /// Calculate the additional register pressure that the registers used in MI 888 /// cause. 889 /// 890 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to 891 /// figure out which usages are live-ins. 892 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths. 893 DenseMap<unsigned, int> 894 MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen, 895 bool ConsiderUnseenAsDef) { 896 DenseMap<unsigned, int> Cost; 897 if (MI->isImplicitDef()) 898 return Cost; 899 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) { 900 const MachineOperand &MO = MI->getOperand(i); 901 if (!MO.isReg() || MO.isImplicit()) 902 continue; 903 Register Reg = MO.getReg(); 904 if (!Register::isVirtualRegister(Reg)) 905 continue; 906 907 // FIXME: It seems bad to use RegSeen only for some of these calculations. 908 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false; 909 const TargetRegisterClass *RC = MRI->getRegClass(Reg); 910 911 RegClassWeight W = TRI->getRegClassWeight(RC); 912 int RCCost = 0; 913 if (MO.isDef()) 914 RCCost = W.RegWeight; 915 else { 916 bool isKill = isOperandKill(MO, MRI); 917 if (isNew && !isKill && ConsiderUnseenAsDef) 918 // Haven't seen this, it must be a livein. 919 RCCost = W.RegWeight; 920 else if (!isNew && isKill) 921 RCCost = -W.RegWeight; 922 } 923 if (RCCost == 0) 924 continue; 925 const int *PS = TRI->getRegClassPressureSets(RC); 926 for (; *PS != -1; ++PS) { 927 if (Cost.find(*PS) == Cost.end()) 928 Cost[*PS] = RCCost; 929 else 930 Cost[*PS] += RCCost; 931 } 932 } 933 return Cost; 934 } 935 936 /// Return true if this machine instruction loads from global offset table or 937 /// constant pool. 938 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) { 939 assert(MI.mayLoad() && "Expected MI that loads!"); 940 941 // If we lost memory operands, conservatively assume that the instruction 942 // reads from everything.. 943 if (MI.memoperands_empty()) 944 return true; 945 946 for (MachineMemOperand *MemOp : MI.memoperands()) 947 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue()) 948 if (PSV->isGOT() || PSV->isConstantPool()) 949 return true; 950 951 return false; 952 } 953 954 // This function iterates through all the operands of the input store MI and 955 // checks that each register operand statisfies isCallerPreservedPhysReg. 956 // This means, the value being stored and the address where it is being stored 957 // is constant throughout the body of the function (not including prologue and 958 // epilogue). When called with an MI that isn't a store, it returns false. 959 // A future improvement can be to check if the store registers are constant 960 // throughout the loop rather than throughout the funtion. 961 static bool isInvariantStore(const MachineInstr &MI, 962 const TargetRegisterInfo *TRI, 963 const MachineRegisterInfo *MRI) { 964 965 bool FoundCallerPresReg = false; 966 if (!MI.mayStore() || MI.hasUnmodeledSideEffects() || 967 (MI.getNumOperands() == 0)) 968 return false; 969 970 // Check that all register operands are caller-preserved physical registers. 971 for (const MachineOperand &MO : MI.operands()) { 972 if (MO.isReg()) { 973 Register Reg = MO.getReg(); 974 // If operand is a virtual register, check if it comes from a copy of a 975 // physical register. 976 if (Register::isVirtualRegister(Reg)) 977 Reg = TRI->lookThruCopyLike(MO.getReg(), MRI); 978 if (Register::isVirtualRegister(Reg)) 979 return false; 980 if (!TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *MI.getMF())) 981 return false; 982 else 983 FoundCallerPresReg = true; 984 } else if (!MO.isImm()) { 985 return false; 986 } 987 } 988 return FoundCallerPresReg; 989 } 990 991 // Return true if the input MI is a copy instruction that feeds an invariant 992 // store instruction. This means that the src of the copy has to satisfy 993 // isCallerPreservedPhysReg and atleast one of it's users should satisfy 994 // isInvariantStore. 995 static bool isCopyFeedingInvariantStore(const MachineInstr &MI, 996 const MachineRegisterInfo *MRI, 997 const TargetRegisterInfo *TRI) { 998 999 // FIXME: If targets would like to look through instructions that aren't 1000 // pure copies, this can be updated to a query. 1001 if (!MI.isCopy()) 1002 return false; 1003 1004 const MachineFunction *MF = MI.getMF(); 1005 // Check that we are copying a constant physical register. 1006 Register CopySrcReg = MI.getOperand(1).getReg(); 1007 if (Register::isVirtualRegister(CopySrcReg)) 1008 return false; 1009 1010 if (!TRI->isCallerPreservedPhysReg(CopySrcReg.asMCReg(), *MF)) 1011 return false; 1012 1013 Register CopyDstReg = MI.getOperand(0).getReg(); 1014 // Check if any of the uses of the copy are invariant stores. 1015 assert(Register::isVirtualRegister(CopyDstReg) && 1016 "copy dst is not a virtual reg"); 1017 1018 for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) { 1019 if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI)) 1020 return true; 1021 } 1022 return false; 1023 } 1024 1025 /// Returns true if the instruction may be a suitable candidate for LICM. 1026 /// e.g. If the instruction is a call, then it's obviously not safe to hoist it. 1027 bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) { 1028 // Check if it's safe to move the instruction. 1029 bool DontMoveAcrossStore = true; 1030 if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) && 1031 !(HoistConstStores && isInvariantStore(I, TRI, MRI))) { 1032 return false; 1033 } 1034 1035 // If it is load then check if it is guaranteed to execute by making sure that 1036 // it dominates all exiting blocks. If it doesn't, then there is a path out of 1037 // the loop which does not execute this load, so we can't hoist it. Loads 1038 // from constant memory are not safe to speculate all the time, for example 1039 // indexed load from a jump table. 1040 // Stores and side effects are already checked by isSafeToMove. 1041 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) && 1042 !IsGuaranteedToExecute(I.getParent())) 1043 return false; 1044 1045 // Convergent attribute has been used on operations that involve inter-thread 1046 // communication which results are implicitly affected by the enclosing 1047 // control flows. It is not safe to hoist or sink such operations across 1048 // control flow. 1049 if (I.isConvergent()) 1050 return false; 1051 1052 return true; 1053 } 1054 1055 /// Returns true if the instruction is loop invariant. 1056 /// I.e., all virtual register operands are defined outside of the loop, 1057 /// physical registers aren't accessed explicitly, and there are no side 1058 /// effects that aren't captured by the operands or other flags. 1059 bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) { 1060 if (!IsLICMCandidate(I)) 1061 return false; 1062 1063 // The instruction is loop invariant if all of its operands are. 1064 for (const MachineOperand &MO : I.operands()) { 1065 if (!MO.isReg()) 1066 continue; 1067 1068 Register Reg = MO.getReg(); 1069 if (Reg == 0) continue; 1070 1071 // Don't hoist an instruction that uses or defines a physical register. 1072 if (Register::isPhysicalRegister(Reg)) { 1073 if (MO.isUse()) { 1074 // If the physreg has no defs anywhere, it's just an ambient register 1075 // and we can freely move its uses. Alternatively, if it's allocatable, 1076 // it could get allocated to something with a def during allocation. 1077 // However, if the physreg is known to always be caller saved/restored 1078 // then this use is safe to hoist. 1079 if (!MRI->isConstantPhysReg(Reg) && 1080 !(TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *I.getMF()))) 1081 return false; 1082 // Otherwise it's safe to move. 1083 continue; 1084 } else if (!MO.isDead()) { 1085 // A def that isn't dead. We can't move it. 1086 return false; 1087 } else if (CurLoop->getHeader()->isLiveIn(Reg)) { 1088 // If the reg is live into the loop, we can't hoist an instruction 1089 // which would clobber it. 1090 return false; 1091 } 1092 } 1093 1094 if (!MO.isUse()) 1095 continue; 1096 1097 assert(MRI->getVRegDef(Reg) && 1098 "Machine instr not mapped for this vreg?!"); 1099 1100 // If the loop contains the definition of an operand, then the instruction 1101 // isn't loop invariant. 1102 if (CurLoop->contains(MRI->getVRegDef(Reg))) 1103 return false; 1104 } 1105 1106 // If we got this far, the instruction is loop invariant! 1107 return true; 1108 } 1109 1110 /// Return true if the specified instruction is used by a phi node and hoisting 1111 /// it could cause a copy to be inserted. 1112 bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const { 1113 SmallVector<const MachineInstr*, 8> Work(1, MI); 1114 do { 1115 MI = Work.pop_back_val(); 1116 for (const MachineOperand &MO : MI->operands()) { 1117 if (!MO.isReg() || !MO.isDef()) 1118 continue; 1119 Register Reg = MO.getReg(); 1120 if (!Register::isVirtualRegister(Reg)) 1121 continue; 1122 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) { 1123 // A PHI may cause a copy to be inserted. 1124 if (UseMI.isPHI()) { 1125 // A PHI inside the loop causes a copy because the live range of Reg is 1126 // extended across the PHI. 1127 if (CurLoop->contains(&UseMI)) 1128 return true; 1129 // A PHI in an exit block can cause a copy to be inserted if the PHI 1130 // has multiple predecessors in the loop with different values. 1131 // For now, approximate by rejecting all exit blocks. 1132 if (isExitBlock(UseMI.getParent())) 1133 return true; 1134 continue; 1135 } 1136 // Look past copies as well. 1137 if (UseMI.isCopy() && CurLoop->contains(&UseMI)) 1138 Work.push_back(&UseMI); 1139 } 1140 } 1141 } while (!Work.empty()); 1142 return false; 1143 } 1144 1145 /// Compute operand latency between a def of 'Reg' and an use in the current 1146 /// loop, return true if the target considered it high. 1147 bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx, 1148 Register Reg) const { 1149 if (MRI->use_nodbg_empty(Reg)) 1150 return false; 1151 1152 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) { 1153 if (UseMI.isCopyLike()) 1154 continue; 1155 if (!CurLoop->contains(UseMI.getParent())) 1156 continue; 1157 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) { 1158 const MachineOperand &MO = UseMI.getOperand(i); 1159 if (!MO.isReg() || !MO.isUse()) 1160 continue; 1161 Register MOReg = MO.getReg(); 1162 if (MOReg != Reg) 1163 continue; 1164 1165 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i)) 1166 return true; 1167 } 1168 1169 // Only look at the first in loop use. 1170 break; 1171 } 1172 1173 return false; 1174 } 1175 1176 /// Return true if the instruction is marked "cheap" or the operand latency 1177 /// between its def and a use is one or less. 1178 bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const { 1179 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike()) 1180 return true; 1181 1182 bool isCheap = false; 1183 unsigned NumDefs = MI.getDesc().getNumDefs(); 1184 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) { 1185 MachineOperand &DefMO = MI.getOperand(i); 1186 if (!DefMO.isReg() || !DefMO.isDef()) 1187 continue; 1188 --NumDefs; 1189 Register Reg = DefMO.getReg(); 1190 if (Register::isPhysicalRegister(Reg)) 1191 continue; 1192 1193 if (!TII->hasLowDefLatency(SchedModel, MI, i)) 1194 return false; 1195 isCheap = true; 1196 } 1197 1198 return isCheap; 1199 } 1200 1201 /// Visit BBs from header to current BB, check if hoisting an instruction of the 1202 /// given cost matrix can cause high register pressure. 1203 bool 1204 MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost, 1205 bool CheapInstr) { 1206 for (const auto &RPIdAndCost : Cost) { 1207 if (RPIdAndCost.second <= 0) 1208 continue; 1209 1210 unsigned Class = RPIdAndCost.first; 1211 int Limit = RegLimit[Class]; 1212 1213 // Don't hoist cheap instructions if they would increase register pressure, 1214 // even if we're under the limit. 1215 if (CheapInstr && !HoistCheapInsts) 1216 return true; 1217 1218 for (const auto &RP : BackTrace) 1219 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit) 1220 return true; 1221 } 1222 1223 return false; 1224 } 1225 1226 /// Traverse the back trace from header to the current block and update their 1227 /// register pressures to reflect the effect of hoisting MI from the current 1228 /// block to the preheader. 1229 void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) { 1230 // First compute the 'cost' of the instruction, i.e. its contribution 1231 // to register pressure. 1232 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false, 1233 /*ConsiderUnseenAsDef=*/false); 1234 1235 // Update register pressure of blocks from loop header to current block. 1236 for (auto &RP : BackTrace) 1237 for (const auto &RPIdAndCost : Cost) 1238 RP[RPIdAndCost.first] += RPIdAndCost.second; 1239 } 1240 1241 /// Return true if it is potentially profitable to hoist the given loop 1242 /// invariant. 1243 bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) { 1244 if (MI.isImplicitDef()) 1245 return true; 1246 1247 // Besides removing computation from the loop, hoisting an instruction has 1248 // these effects: 1249 // 1250 // - The value defined by the instruction becomes live across the entire 1251 // loop. This increases register pressure in the loop. 1252 // 1253 // - If the value is used by a PHI in the loop, a copy will be required for 1254 // lowering the PHI after extending the live range. 1255 // 1256 // - When hoisting the last use of a value in the loop, that value no longer 1257 // needs to be live in the loop. This lowers register pressure in the loop. 1258 1259 if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI)) 1260 return true; 1261 1262 bool CheapInstr = IsCheapInstruction(MI); 1263 bool CreatesCopy = HasLoopPHIUse(&MI); 1264 1265 // Don't hoist a cheap instruction if it would create a copy in the loop. 1266 if (CheapInstr && CreatesCopy) { 1267 LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI); 1268 return false; 1269 } 1270 1271 // Rematerializable instructions should always be hoisted since the register 1272 // allocator can just pull them down again when needed. 1273 if (TII->isTriviallyReMaterializable(MI, AA)) 1274 return true; 1275 1276 // FIXME: If there are long latency loop-invariant instructions inside the 1277 // loop at this point, why didn't the optimizer's LICM hoist them? 1278 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) { 1279 const MachineOperand &MO = MI.getOperand(i); 1280 if (!MO.isReg() || MO.isImplicit()) 1281 continue; 1282 Register Reg = MO.getReg(); 1283 if (!Register::isVirtualRegister(Reg)) 1284 continue; 1285 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) { 1286 LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI); 1287 ++NumHighLatency; 1288 return true; 1289 } 1290 } 1291 1292 // Estimate register pressure to determine whether to LICM the instruction. 1293 // In low register pressure situation, we can be more aggressive about 1294 // hoisting. Also, favors hoisting long latency instructions even in 1295 // moderately high pressure situation. 1296 // Cheap instructions will only be hoisted if they don't increase register 1297 // pressure at all. 1298 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false, 1299 /*ConsiderUnseenAsDef=*/false); 1300 1301 // Visit BBs from header to current BB, if hoisting this doesn't cause 1302 // high register pressure, then it's safe to proceed. 1303 if (!CanCauseHighRegPressure(Cost, CheapInstr)) { 1304 LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI); 1305 ++NumLowRP; 1306 return true; 1307 } 1308 1309 // Don't risk increasing register pressure if it would create copies. 1310 if (CreatesCopy) { 1311 LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI); 1312 return false; 1313 } 1314 1315 // Do not "speculate" in high register pressure situation. If an 1316 // instruction is not guaranteed to be executed in the loop, it's best to be 1317 // conservative. 1318 if (AvoidSpeculation && 1319 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) { 1320 LLVM_DEBUG(dbgs() << "Won't speculate: " << MI); 1321 return false; 1322 } 1323 1324 // High register pressure situation, only hoist if the instruction is going 1325 // to be remat'ed. 1326 if (!TII->isTriviallyReMaterializable(MI, AA) && 1327 !MI.isDereferenceableInvariantLoad(AA)) { 1328 LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI); 1329 return false; 1330 } 1331 1332 return true; 1333 } 1334 1335 /// Unfold a load from the given machineinstr if the load itself could be 1336 /// hoisted. Return the unfolded and hoistable load, or null if the load 1337 /// couldn't be unfolded or if it wouldn't be hoistable. 1338 MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) { 1339 // Don't unfold simple loads. 1340 if (MI->canFoldAsLoad()) 1341 return nullptr; 1342 1343 // If not, we may be able to unfold a load and hoist that. 1344 // First test whether the instruction is loading from an amenable 1345 // memory location. 1346 if (!MI->isDereferenceableInvariantLoad(AA)) 1347 return nullptr; 1348 1349 // Next determine the register class for a temporary register. 1350 unsigned LoadRegIndex; 1351 unsigned NewOpc = 1352 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(), 1353 /*UnfoldLoad=*/true, 1354 /*UnfoldStore=*/false, 1355 &LoadRegIndex); 1356 if (NewOpc == 0) return nullptr; 1357 const MCInstrDesc &MID = TII->get(NewOpc); 1358 MachineFunction &MF = *MI->getMF(); 1359 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF); 1360 // Ok, we're unfolding. Create a temporary register and do the unfold. 1361 Register Reg = MRI->createVirtualRegister(RC); 1362 1363 SmallVector<MachineInstr *, 2> NewMIs; 1364 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg, 1365 /*UnfoldLoad=*/true, 1366 /*UnfoldStore=*/false, NewMIs); 1367 (void)Success; 1368 assert(Success && 1369 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold " 1370 "succeeded!"); 1371 assert(NewMIs.size() == 2 && 1372 "Unfolded a load into multiple instructions!"); 1373 MachineBasicBlock *MBB = MI->getParent(); 1374 MachineBasicBlock::iterator Pos = MI; 1375 MBB->insert(Pos, NewMIs[0]); 1376 MBB->insert(Pos, NewMIs[1]); 1377 // If unfolding produced a load that wasn't loop-invariant or profitable to 1378 // hoist, discard the new instructions and bail. 1379 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) { 1380 NewMIs[0]->eraseFromParent(); 1381 NewMIs[1]->eraseFromParent(); 1382 return nullptr; 1383 } 1384 1385 // Update register pressure for the unfolded instruction. 1386 UpdateRegPressure(NewMIs[1]); 1387 1388 // Otherwise we successfully unfolded a load that we can hoist. 1389 1390 // Update the call site info. 1391 if (MI->shouldUpdateCallSiteInfo()) 1392 MF.eraseCallSiteInfo(MI); 1393 1394 MI->eraseFromParent(); 1395 return NewMIs[0]; 1396 } 1397 1398 /// Initialize the CSE map with instructions that are in the current loop 1399 /// preheader that may become duplicates of instructions that are hoisted 1400 /// out of the loop. 1401 void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) { 1402 for (MachineInstr &MI : *BB) 1403 CSEMap[MI.getOpcode()].push_back(&MI); 1404 } 1405 1406 /// Find an instruction amount PrevMIs that is a duplicate of MI. 1407 /// Return this instruction if it's found. 1408 const MachineInstr* 1409 MachineLICMBase::LookForDuplicate(const MachineInstr *MI, 1410 std::vector<const MachineInstr*> &PrevMIs) { 1411 for (const MachineInstr *PrevMI : PrevMIs) 1412 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr))) 1413 return PrevMI; 1414 1415 return nullptr; 1416 } 1417 1418 /// Given a LICM'ed instruction, look for an instruction on the preheader that 1419 /// computes the same value. If it's found, do a RAU on with the definition of 1420 /// the existing instruction rather than hoisting the instruction to the 1421 /// preheader. 1422 bool MachineLICMBase::EliminateCSE(MachineInstr *MI, 1423 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) { 1424 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate 1425 // the undef property onto uses. 1426 if (CI == CSEMap.end() || MI->isImplicitDef()) 1427 return false; 1428 1429 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) { 1430 LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup); 1431 1432 // Replace virtual registers defined by MI by their counterparts defined 1433 // by Dup. 1434 SmallVector<unsigned, 2> Defs; 1435 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1436 const MachineOperand &MO = MI->getOperand(i); 1437 1438 // Physical registers may not differ here. 1439 assert((!MO.isReg() || MO.getReg() == 0 || 1440 !Register::isPhysicalRegister(MO.getReg()) || 1441 MO.getReg() == Dup->getOperand(i).getReg()) && 1442 "Instructions with different phys regs are not identical!"); 1443 1444 if (MO.isReg() && MO.isDef() && 1445 !Register::isPhysicalRegister(MO.getReg())) 1446 Defs.push_back(i); 1447 } 1448 1449 SmallVector<const TargetRegisterClass*, 2> OrigRCs; 1450 for (unsigned i = 0, e = Defs.size(); i != e; ++i) { 1451 unsigned Idx = Defs[i]; 1452 Register Reg = MI->getOperand(Idx).getReg(); 1453 Register DupReg = Dup->getOperand(Idx).getReg(); 1454 OrigRCs.push_back(MRI->getRegClass(DupReg)); 1455 1456 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) { 1457 // Restore old RCs if more than one defs. 1458 for (unsigned j = 0; j != i; ++j) 1459 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]); 1460 return false; 1461 } 1462 } 1463 1464 for (unsigned Idx : Defs) { 1465 Register Reg = MI->getOperand(Idx).getReg(); 1466 Register DupReg = Dup->getOperand(Idx).getReg(); 1467 MRI->replaceRegWith(Reg, DupReg); 1468 MRI->clearKillFlags(DupReg); 1469 } 1470 1471 MI->eraseFromParent(); 1472 ++NumCSEed; 1473 return true; 1474 } 1475 return false; 1476 } 1477 1478 /// Return true if the given instruction will be CSE'd if it's hoisted out of 1479 /// the loop. 1480 bool MachineLICMBase::MayCSE(MachineInstr *MI) { 1481 unsigned Opcode = MI->getOpcode(); 1482 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator 1483 CI = CSEMap.find(Opcode); 1484 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate 1485 // the undef property onto uses. 1486 if (CI == CSEMap.end() || MI->isImplicitDef()) 1487 return false; 1488 1489 return LookForDuplicate(MI, CI->second) != nullptr; 1490 } 1491 1492 /// When an instruction is found to use only loop invariant operands 1493 /// that are safe to hoist, this instruction is called to do the dirty work. 1494 /// It returns true if the instruction is hoisted. 1495 bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) { 1496 MachineBasicBlock *SrcBlock = MI->getParent(); 1497 1498 // Disable the instruction hoisting due to block hotness 1499 if ((DisableHoistingToHotterBlocks == UseBFI::All || 1500 (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) && 1501 isTgtHotterThanSrc(SrcBlock, Preheader)) { 1502 ++NumNotHoistedDueToHotness; 1503 return false; 1504 } 1505 // First check whether we should hoist this instruction. 1506 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) { 1507 // If not, try unfolding a hoistable load. 1508 MI = ExtractHoistableLoad(MI); 1509 if (!MI) return false; 1510 } 1511 1512 // If we have hoisted an instruction that may store, it can only be a constant 1513 // store. 1514 if (MI->mayStore()) 1515 NumStoreConst++; 1516 1517 // Now move the instructions to the predecessor, inserting it before any 1518 // terminator instructions. 1519 LLVM_DEBUG({ 1520 dbgs() << "Hoisting " << *MI; 1521 if (MI->getParent()->getBasicBlock()) 1522 dbgs() << " from " << printMBBReference(*MI->getParent()); 1523 if (Preheader->getBasicBlock()) 1524 dbgs() << " to " << printMBBReference(*Preheader); 1525 dbgs() << "\n"; 1526 }); 1527 1528 // If this is the first instruction being hoisted to the preheader, 1529 // initialize the CSE map with potential common expressions. 1530 if (FirstInLoop) { 1531 InitCSEMap(Preheader); 1532 FirstInLoop = false; 1533 } 1534 1535 // Look for opportunity to CSE the hoisted instruction. 1536 unsigned Opcode = MI->getOpcode(); 1537 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator 1538 CI = CSEMap.find(Opcode); 1539 if (!EliminateCSE(MI, CI)) { 1540 // Otherwise, splice the instruction to the preheader. 1541 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI); 1542 1543 // Since we are moving the instruction out of its basic block, we do not 1544 // retain its debug location. Doing so would degrade the debugging 1545 // experience and adversely affect the accuracy of profiling information. 1546 assert(!MI->isDebugInstr() && "Should not hoist debug inst"); 1547 MI->setDebugLoc(DebugLoc()); 1548 1549 // Update register pressure for BBs from header to this block. 1550 UpdateBackTraceRegPressure(MI); 1551 1552 // Clear the kill flags of any register this instruction defines, 1553 // since they may need to be live throughout the entire loop 1554 // rather than just live for part of it. 1555 for (MachineOperand &MO : MI->operands()) 1556 if (MO.isReg() && MO.isDef() && !MO.isDead()) 1557 MRI->clearKillFlags(MO.getReg()); 1558 1559 // Add to the CSE map. 1560 if (CI != CSEMap.end()) 1561 CI->second.push_back(MI); 1562 else 1563 CSEMap[Opcode].push_back(MI); 1564 } 1565 1566 ++NumHoisted; 1567 Changed = true; 1568 1569 return true; 1570 } 1571 1572 /// Get the preheader for the current loop, splitting a critical edge if needed. 1573 MachineBasicBlock *MachineLICMBase::getCurPreheader() { 1574 // Determine the block to which to hoist instructions. If we can't find a 1575 // suitable loop predecessor, we can't do any hoisting. 1576 1577 // If we've tried to get a preheader and failed, don't try again. 1578 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1)) 1579 return nullptr; 1580 1581 if (!CurPreheader) { 1582 CurPreheader = CurLoop->getLoopPreheader(); 1583 if (!CurPreheader) { 1584 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor(); 1585 if (!Pred) { 1586 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1); 1587 return nullptr; 1588 } 1589 1590 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this); 1591 if (!CurPreheader) { 1592 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1); 1593 return nullptr; 1594 } 1595 } 1596 } 1597 return CurPreheader; 1598 } 1599 1600 /// Is the target basic block at least "BlockFrequencyRatioThreshold" 1601 /// times hotter than the source basic block. 1602 bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock, 1603 MachineBasicBlock *TgtBlock) { 1604 // Parse source and target basic block frequency from MBFI 1605 uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency(); 1606 uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency(); 1607 1608 // Disable the hoisting if source block frequency is zero 1609 if (!SrcBF) 1610 return true; 1611 1612 double Ratio = (double)DstBF / SrcBF; 1613 1614 // Compare the block frequency ratio with the threshold 1615 return Ratio > BlockFrequencyRatioThreshold; 1616 } 1617