1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===// 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 pass moves instructions into successor blocks when possible, so that 11 // they aren't executed on paths where their results aren't needed. 12 // 13 // This pass is not intended to be a replacement or a complete alternative 14 // for an LLVM-IR-level sinking pass. It is only designed to sink simple 15 // constructs that are not exposed before lowering and instruction selection. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/Passes.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/MachineDominators.h" 25 #include "llvm/CodeGen/MachineLoopInfo.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include "llvm/Target/TargetInstrInfo.h" 31 #include "llvm/Target/TargetMachine.h" 32 #include "llvm/Target/TargetRegisterInfo.h" 33 #include "llvm/Target/TargetSubtargetInfo.h" 34 using namespace llvm; 35 36 #define DEBUG_TYPE "machine-sink" 37 38 static cl::opt<bool> 39 SplitEdges("machine-sink-split", 40 cl::desc("Split critical edges during machine sinking"), 41 cl::init(true), cl::Hidden); 42 43 STATISTIC(NumSunk, "Number of machine instructions sunk"); 44 STATISTIC(NumSplit, "Number of critical edges split"); 45 STATISTIC(NumCoalesces, "Number of copies coalesced"); 46 47 namespace { 48 class MachineSinking : public MachineFunctionPass { 49 const TargetInstrInfo *TII; 50 const TargetRegisterInfo *TRI; 51 MachineRegisterInfo *MRI; // Machine register information 52 MachineDominatorTree *DT; // Machine dominator tree 53 MachineLoopInfo *LI; 54 AliasAnalysis *AA; 55 56 // Remember which edges have been considered for breaking. 57 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8> 58 CEBCandidates; 59 // Remember which edges we are about to split. 60 // This is different from CEBCandidates since those edges 61 // will be split. 62 SetVector<std::pair<MachineBasicBlock*,MachineBasicBlock*> > ToSplit; 63 64 public: 65 static char ID; // Pass identification 66 MachineSinking() : MachineFunctionPass(ID) { 67 initializeMachineSinkingPass(*PassRegistry::getPassRegistry()); 68 } 69 70 bool runOnMachineFunction(MachineFunction &MF) override; 71 72 void getAnalysisUsage(AnalysisUsage &AU) const override { 73 AU.setPreservesCFG(); 74 MachineFunctionPass::getAnalysisUsage(AU); 75 AU.addRequired<AliasAnalysis>(); 76 AU.addRequired<MachineDominatorTree>(); 77 AU.addRequired<MachineLoopInfo>(); 78 AU.addPreserved<MachineDominatorTree>(); 79 AU.addPreserved<MachineLoopInfo>(); 80 } 81 82 void releaseMemory() override { 83 CEBCandidates.clear(); 84 } 85 86 private: 87 bool ProcessBlock(MachineBasicBlock &MBB); 88 bool isWorthBreakingCriticalEdge(MachineInstr *MI, 89 MachineBasicBlock *From, 90 MachineBasicBlock *To); 91 /// \brief Postpone the splitting of the given critical 92 /// edge (\p From, \p To). 93 /// 94 /// We do not split the edges on the fly. Indeed, this invalidates 95 /// the dominance information and thus triggers a lot of updates 96 /// of that information underneath. 97 /// Instead, we postpone all the splits after each iteration of 98 /// the main loop. That way, the information is at least valid 99 /// for the lifetime of an iteration. 100 /// 101 /// \return True if the edge is marked as toSplit, false otherwise. 102 /// False can be retruned if, for instance, this is not profitable. 103 bool PostponeSplitCriticalEdge(MachineInstr *MI, 104 MachineBasicBlock *From, 105 MachineBasicBlock *To, 106 bool BreakPHIEdge); 107 bool SinkInstruction(MachineInstr *MI, bool &SawStore); 108 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB, 109 MachineBasicBlock *DefMBB, 110 bool &BreakPHIEdge, bool &LocalUse) const; 111 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB, 112 bool &BreakPHIEdge); 113 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI, 114 MachineBasicBlock *MBB, 115 MachineBasicBlock *SuccToSinkTo); 116 117 bool PerformTrivialForwardCoalescing(MachineInstr *MI, 118 MachineBasicBlock *MBB); 119 }; 120 } // end anonymous namespace 121 122 char MachineSinking::ID = 0; 123 char &llvm::MachineSinkingID = MachineSinking::ID; 124 INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink", 125 "Machine code sinking", false, false) 126 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 127 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 128 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 129 INITIALIZE_PASS_END(MachineSinking, "machine-sink", 130 "Machine code sinking", false, false) 131 132 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI, 133 MachineBasicBlock *MBB) { 134 if (!MI->isCopy()) 135 return false; 136 137 unsigned SrcReg = MI->getOperand(1).getReg(); 138 unsigned DstReg = MI->getOperand(0).getReg(); 139 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || 140 !TargetRegisterInfo::isVirtualRegister(DstReg) || 141 !MRI->hasOneNonDBGUse(SrcReg)) 142 return false; 143 144 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg); 145 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg); 146 if (SRC != DRC) 147 return false; 148 149 MachineInstr *DefMI = MRI->getVRegDef(SrcReg); 150 if (DefMI->isCopyLike()) 151 return false; 152 DEBUG(dbgs() << "Coalescing: " << *DefMI); 153 DEBUG(dbgs() << "*** to: " << *MI); 154 MRI->replaceRegWith(DstReg, SrcReg); 155 MI->eraseFromParent(); 156 ++NumCoalesces; 157 return true; 158 } 159 160 /// AllUsesDominatedByBlock - Return true if all uses of the specified register 161 /// occur in blocks dominated by the specified block. If any use is in the 162 /// definition block, then return false since it is never legal to move def 163 /// after uses. 164 bool 165 MachineSinking::AllUsesDominatedByBlock(unsigned Reg, 166 MachineBasicBlock *MBB, 167 MachineBasicBlock *DefMBB, 168 bool &BreakPHIEdge, 169 bool &LocalUse) const { 170 assert(TargetRegisterInfo::isVirtualRegister(Reg) && 171 "Only makes sense for vregs"); 172 173 // Ignore debug uses because debug info doesn't affect the code. 174 if (MRI->use_nodbg_empty(Reg)) 175 return true; 176 177 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken 178 // into and they are all PHI nodes. In this case, machine-sink must break 179 // the critical edge first. e.g. 180 // 181 // BB#1: derived from LLVM BB %bb4.preheader 182 // Predecessors according to CFG: BB#0 183 // ... 184 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead> 185 // ... 186 // JE_4 <BB#37>, %EFLAGS<imp-use> 187 // Successors according to CFG: BB#37 BB#2 188 // 189 // BB#2: derived from LLVM BB %bb.nph 190 // Predecessors according to CFG: BB#0 BB#1 191 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1> 192 BreakPHIEdge = true; 193 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 194 MachineInstr *UseInst = MO.getParent(); 195 unsigned OpNo = &MO - &UseInst->getOperand(0); 196 MachineBasicBlock *UseBlock = UseInst->getParent(); 197 if (!(UseBlock == MBB && UseInst->isPHI() && 198 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) { 199 BreakPHIEdge = false; 200 break; 201 } 202 } 203 if (BreakPHIEdge) 204 return true; 205 206 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 207 // Determine the block of the use. 208 MachineInstr *UseInst = MO.getParent(); 209 unsigned OpNo = &MO - &UseInst->getOperand(0); 210 MachineBasicBlock *UseBlock = UseInst->getParent(); 211 if (UseInst->isPHI()) { 212 // PHI nodes use the operand in the predecessor block, not the block with 213 // the PHI. 214 UseBlock = UseInst->getOperand(OpNo+1).getMBB(); 215 } else if (UseBlock == DefMBB) { 216 LocalUse = true; 217 return false; 218 } 219 220 // Check that it dominates. 221 if (!DT->dominates(MBB, UseBlock)) 222 return false; 223 } 224 225 return true; 226 } 227 228 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) { 229 if (skipOptnoneFunction(*MF.getFunction())) 230 return false; 231 232 DEBUG(dbgs() << "******** Machine Sinking ********\n"); 233 234 const TargetMachine &TM = MF.getTarget(); 235 TII = TM.getSubtargetImpl()->getInstrInfo(); 236 TRI = TM.getSubtargetImpl()->getRegisterInfo(); 237 MRI = &MF.getRegInfo(); 238 DT = &getAnalysis<MachineDominatorTree>(); 239 LI = &getAnalysis<MachineLoopInfo>(); 240 AA = &getAnalysis<AliasAnalysis>(); 241 242 bool EverMadeChange = false; 243 244 while (1) { 245 bool MadeChange = false; 246 247 // Process all basic blocks. 248 CEBCandidates.clear(); 249 ToSplit.clear(); 250 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); 251 I != E; ++I) 252 MadeChange |= ProcessBlock(*I); 253 254 // If we have anything we marked as toSplit, split it now. 255 for (auto &Pair : ToSplit) { 256 auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, this); 257 if (NewSucc != nullptr) { 258 DEBUG(dbgs() << " *** Splitting critical edge:" 259 " BB#" << Pair.first->getNumber() 260 << " -- BB#" << NewSucc->getNumber() 261 << " -- BB#" << Pair.second->getNumber() << '\n'); 262 MadeChange = true; 263 ++NumSplit; 264 } else 265 DEBUG(dbgs() << " *** Not legal to break critical edge\n"); 266 } 267 // If this iteration over the code changed anything, keep iterating. 268 if (!MadeChange) break; 269 EverMadeChange = true; 270 } 271 return EverMadeChange; 272 } 273 274 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) { 275 // Can't sink anything out of a block that has less than two successors. 276 if (MBB.succ_size() <= 1 || MBB.empty()) return false; 277 278 // Don't bother sinking code out of unreachable blocks. In addition to being 279 // unprofitable, it can also lead to infinite looping, because in an 280 // unreachable loop there may be nowhere to stop. 281 if (!DT->isReachableFromEntry(&MBB)) return false; 282 283 bool MadeChange = false; 284 285 // Walk the basic block bottom-up. Remember if we saw a store. 286 MachineBasicBlock::iterator I = MBB.end(); 287 --I; 288 bool ProcessedBegin, SawStore = false; 289 do { 290 MachineInstr *MI = I; // The instruction to sink. 291 292 // Predecrement I (if it's not begin) so that it isn't invalidated by 293 // sinking. 294 ProcessedBegin = I == MBB.begin(); 295 if (!ProcessedBegin) 296 --I; 297 298 if (MI->isDebugValue()) 299 continue; 300 301 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB); 302 if (Joined) { 303 MadeChange = true; 304 continue; 305 } 306 307 if (SinkInstruction(MI, SawStore)) 308 ++NumSunk, MadeChange = true; 309 310 // If we just processed the first instruction in the block, we're done. 311 } while (!ProcessedBegin); 312 313 return MadeChange; 314 } 315 316 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI, 317 MachineBasicBlock *From, 318 MachineBasicBlock *To) { 319 // FIXME: Need much better heuristics. 320 321 // If the pass has already considered breaking this edge (during this pass 322 // through the function), then let's go ahead and break it. This means 323 // sinking multiple "cheap" instructions into the same block. 324 if (!CEBCandidates.insert(std::make_pair(From, To))) 325 return true; 326 327 if (!MI->isCopy() && !TII->isAsCheapAsAMove(MI)) 328 return true; 329 330 // MI is cheap, we probably don't want to break the critical edge for it. 331 // However, if this would allow some definitions of its source operands 332 // to be sunk then it's probably worth it. 333 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 334 const MachineOperand &MO = MI->getOperand(i); 335 if (!MO.isReg() || !MO.isUse()) 336 continue; 337 unsigned Reg = MO.getReg(); 338 if (Reg == 0) 339 continue; 340 341 // We don't move live definitions of physical registers, 342 // so sinking their uses won't enable any opportunities. 343 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 344 continue; 345 346 // If this instruction is the only user of a virtual register, 347 // check if breaking the edge will enable sinking 348 // both this instruction and the defining instruction. 349 if (MRI->hasOneNonDBGUse(Reg)) { 350 // If the definition resides in same MBB, 351 // claim it's likely we can sink these together. 352 // If definition resides elsewhere, we aren't 353 // blocking it from being sunk so don't break the edge. 354 MachineInstr *DefMI = MRI->getVRegDef(Reg); 355 if (DefMI->getParent() == MI->getParent()) 356 return true; 357 } 358 } 359 360 return false; 361 } 362 363 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr *MI, 364 MachineBasicBlock *FromBB, 365 MachineBasicBlock *ToBB, 366 bool BreakPHIEdge) { 367 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB)) 368 return false; 369 370 // Avoid breaking back edge. From == To means backedge for single BB loop. 371 if (!SplitEdges || FromBB == ToBB) 372 return false; 373 374 // Check for backedges of more "complex" loops. 375 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) && 376 LI->isLoopHeader(ToBB)) 377 return false; 378 379 // It's not always legal to break critical edges and sink the computation 380 // to the edge. 381 // 382 // BB#1: 383 // v1024 384 // Beq BB#3 385 // <fallthrough> 386 // BB#2: 387 // ... no uses of v1024 388 // <fallthrough> 389 // BB#3: 390 // ... 391 // = v1024 392 // 393 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted: 394 // 395 // BB#1: 396 // ... 397 // Bne BB#2 398 // BB#4: 399 // v1024 = 400 // B BB#3 401 // BB#2: 402 // ... no uses of v1024 403 // <fallthrough> 404 // BB#3: 405 // ... 406 // = v1024 407 // 408 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3 409 // flow. We need to ensure the new basic block where the computation is 410 // sunk to dominates all the uses. 411 // It's only legal to break critical edge and sink the computation to the 412 // new block if all the predecessors of "To", except for "From", are 413 // not dominated by "From". Given SSA property, this means these 414 // predecessors are dominated by "To". 415 // 416 // There is no need to do this check if all the uses are PHI nodes. PHI 417 // sources are only defined on the specific predecessor edges. 418 if (!BreakPHIEdge) { 419 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(), 420 E = ToBB->pred_end(); PI != E; ++PI) { 421 if (*PI == FromBB) 422 continue; 423 if (!DT->dominates(ToBB, *PI)) 424 return false; 425 } 426 } 427 428 ToSplit.insert(std::make_pair(FromBB, ToBB)); 429 430 return true; 431 } 432 433 static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) { 434 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence(); 435 } 436 437 /// collectDebgValues - Scan instructions following MI and collect any 438 /// matching DBG_VALUEs. 439 static void collectDebugValues(MachineInstr *MI, 440 SmallVectorImpl<MachineInstr *> &DbgValues) { 441 DbgValues.clear(); 442 if (!MI->getOperand(0).isReg()) 443 return; 444 445 MachineBasicBlock::iterator DI = MI; ++DI; 446 for (MachineBasicBlock::iterator DE = MI->getParent()->end(); 447 DI != DE; ++DI) { 448 if (!DI->isDebugValue()) 449 return; 450 if (DI->getOperand(0).isReg() && 451 DI->getOperand(0).getReg() == MI->getOperand(0).getReg()) 452 DbgValues.push_back(DI); 453 } 454 } 455 456 /// isPostDominatedBy - Return true if A is post dominated by B. 457 static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) { 458 459 // FIXME - Use real post dominator. 460 if (A->succ_size() != 2) 461 return false; 462 MachineBasicBlock::succ_iterator I = A->succ_begin(); 463 if (B == *I) 464 ++I; 465 MachineBasicBlock *OtherSuccBlock = *I; 466 if (OtherSuccBlock->succ_size() != 1 || 467 *(OtherSuccBlock->succ_begin()) != B) 468 return false; 469 470 return true; 471 } 472 473 /// isProfitableToSinkTo - Return true if it is profitable to sink MI. 474 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI, 475 MachineBasicBlock *MBB, 476 MachineBasicBlock *SuccToSinkTo) { 477 assert (MI && "Invalid MachineInstr!"); 478 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB"); 479 480 if (MBB == SuccToSinkTo) 481 return false; 482 483 // It is profitable if SuccToSinkTo does not post dominate current block. 484 if (!isPostDominatedBy(MBB, SuccToSinkTo)) 485 return true; 486 487 // Check if only use in post dominated block is PHI instruction. 488 bool NonPHIUse = false; 489 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) { 490 MachineBasicBlock *UseBlock = UseInst.getParent(); 491 if (UseBlock == SuccToSinkTo && !UseInst.isPHI()) 492 NonPHIUse = true; 493 } 494 if (!NonPHIUse) 495 return true; 496 497 // If SuccToSinkTo post dominates then also it may be profitable if MI 498 // can further profitably sinked into another block in next round. 499 bool BreakPHIEdge = false; 500 // FIXME - If finding successor is compile time expensive then catch results. 501 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge)) 502 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2); 503 504 // If SuccToSinkTo is final destination and it is a post dominator of current 505 // block then it is not profitable to sink MI into SuccToSinkTo block. 506 return false; 507 } 508 509 /// FindSuccToSinkTo - Find a successor to sink this instruction to. 510 MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI, 511 MachineBasicBlock *MBB, 512 bool &BreakPHIEdge) { 513 514 assert (MI && "Invalid MachineInstr!"); 515 assert (MBB && "Invalid MachineBasicBlock!"); 516 517 // Loop over all the operands of the specified instruction. If there is 518 // anything we can't handle, bail out. 519 520 // SuccToSinkTo - This is the successor to sink this instruction to, once we 521 // decide. 522 MachineBasicBlock *SuccToSinkTo = nullptr; 523 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 524 const MachineOperand &MO = MI->getOperand(i); 525 if (!MO.isReg()) continue; // Ignore non-register operands. 526 527 unsigned Reg = MO.getReg(); 528 if (Reg == 0) continue; 529 530 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 531 if (MO.isUse()) { 532 // If the physreg has no defs anywhere, it's just an ambient register 533 // and we can freely move its uses. Alternatively, if it's allocatable, 534 // it could get allocated to something with a def during allocation. 535 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent())) 536 return nullptr; 537 } else if (!MO.isDead()) { 538 // A def that isn't dead. We can't move it. 539 return nullptr; 540 } 541 } else { 542 // Virtual register uses are always safe to sink. 543 if (MO.isUse()) continue; 544 545 // If it's not safe to move defs of the register class, then abort. 546 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg))) 547 return nullptr; 548 549 // FIXME: This picks a successor to sink into based on having one 550 // successor that dominates all the uses. However, there are cases where 551 // sinking can happen but where the sink point isn't a successor. For 552 // example: 553 // 554 // x = computation 555 // if () {} else {} 556 // use x 557 // 558 // the instruction could be sunk over the whole diamond for the 559 // if/then/else (or loop, etc), allowing it to be sunk into other blocks 560 // after that. 561 562 // Virtual register defs can only be sunk if all their uses are in blocks 563 // dominated by one of the successors. 564 if (SuccToSinkTo) { 565 // If a previous operand picked a block to sink to, then this operand 566 // must be sinkable to the same block. 567 bool LocalUse = false; 568 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, 569 BreakPHIEdge, LocalUse)) 570 return nullptr; 571 572 continue; 573 } 574 575 // Otherwise, we should look at all the successors and decide which one 576 // we should sink to. 577 // We give successors with smaller loop depth higher priority. 578 SmallVector<MachineBasicBlock*, 4> Succs(MBB->succ_begin(), MBB->succ_end()); 579 // Sort Successors according to their loop depth. 580 std::stable_sort( 581 Succs.begin(), Succs.end(), 582 [this](const MachineBasicBlock *LHS, const MachineBasicBlock *RHS) { 583 return LI->getLoopDepth(LHS) < LI->getLoopDepth(RHS); 584 }); 585 for (SmallVectorImpl<MachineBasicBlock *>::iterator SI = Succs.begin(), 586 E = Succs.end(); SI != E; ++SI) { 587 MachineBasicBlock *SuccBlock = *SI; 588 bool LocalUse = false; 589 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, 590 BreakPHIEdge, LocalUse)) { 591 SuccToSinkTo = SuccBlock; 592 break; 593 } 594 if (LocalUse) 595 // Def is used locally, it's never safe to move this def. 596 return nullptr; 597 } 598 599 // If we couldn't find a block to sink to, ignore this instruction. 600 if (!SuccToSinkTo) 601 return nullptr; 602 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo)) 603 return nullptr; 604 } 605 } 606 607 // It is not possible to sink an instruction into its own block. This can 608 // happen with loops. 609 if (MBB == SuccToSinkTo) 610 return nullptr; 611 612 // It's not safe to sink instructions to EH landing pad. Control flow into 613 // landing pad is implicitly defined. 614 if (SuccToSinkTo && SuccToSinkTo->isLandingPad()) 615 return nullptr; 616 617 return SuccToSinkTo; 618 } 619 620 /// SinkInstruction - Determine whether it is safe to sink the specified machine 621 /// instruction out of its current block into a successor. 622 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) { 623 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to 624 // be close to the source to make it easier to coalesce. 625 if (AvoidsSinking(MI, MRI)) 626 return false; 627 628 // Check if it's safe to move the instruction. 629 if (!MI->isSafeToMove(TII, AA, SawStore)) 630 return false; 631 632 // FIXME: This should include support for sinking instructions within the 633 // block they are currently in to shorten the live ranges. We often get 634 // instructions sunk into the top of a large block, but it would be better to 635 // also sink them down before their first use in the block. This xform has to 636 // be careful not to *increase* register pressure though, e.g. sinking 637 // "x = y + z" down if it kills y and z would increase the live ranges of y 638 // and z and only shrink the live range of x. 639 640 bool BreakPHIEdge = false; 641 MachineBasicBlock *ParentBlock = MI->getParent(); 642 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge); 643 644 // If there are no outputs, it must have side-effects. 645 if (!SuccToSinkTo) 646 return false; 647 648 649 // If the instruction to move defines a dead physical register which is live 650 // when leaving the basic block, don't move it because it could turn into a 651 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>) 652 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { 653 const MachineOperand &MO = MI->getOperand(I); 654 if (!MO.isReg()) continue; 655 unsigned Reg = MO.getReg(); 656 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue; 657 if (SuccToSinkTo->isLiveIn(Reg)) 658 return false; 659 } 660 661 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo); 662 663 // If the block has multiple predecessors, this is a critical edge. 664 // Decide if we can sink along it or need to break the edge. 665 if (SuccToSinkTo->pred_size() > 1) { 666 // We cannot sink a load across a critical edge - there may be stores in 667 // other code paths. 668 bool TryBreak = false; 669 bool store = true; 670 if (!MI->isSafeToMove(TII, AA, store)) { 671 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n"); 672 TryBreak = true; 673 } 674 675 // We don't want to sink across a critical edge if we don't dominate the 676 // successor. We could be introducing calculations to new code paths. 677 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) { 678 DEBUG(dbgs() << " *** NOTE: Critical edge found\n"); 679 TryBreak = true; 680 } 681 682 // Don't sink instructions into a loop. 683 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) { 684 DEBUG(dbgs() << " *** NOTE: Loop header found\n"); 685 TryBreak = true; 686 } 687 688 // Otherwise we are OK with sinking along a critical edge. 689 if (!TryBreak) 690 DEBUG(dbgs() << "Sinking along critical edge.\n"); 691 else { 692 // Mark this edge as to be split. 693 // If the edge can actually be split, the next iteration of the main loop 694 // will sink MI in the newly created block. 695 bool Status = 696 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge); 697 if (!Status) 698 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to " 699 "break critical edge\n"); 700 // The instruction will not be sunk this time. 701 return false; 702 } 703 } 704 705 if (BreakPHIEdge) { 706 // BreakPHIEdge is true if all the uses are in the successor MBB being 707 // sunken into and they are all PHI nodes. In this case, machine-sink must 708 // break the critical edge first. 709 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock, 710 SuccToSinkTo, BreakPHIEdge); 711 if (!Status) 712 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to " 713 "break critical edge\n"); 714 // The instruction will not be sunk this time. 715 return false; 716 } 717 718 // Determine where to insert into. Skip phi nodes. 719 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin(); 720 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI()) 721 ++InsertPos; 722 723 // collect matching debug values. 724 SmallVector<MachineInstr *, 2> DbgValuesToSink; 725 collectDebugValues(MI, DbgValuesToSink); 726 727 // Move the instruction. 728 SuccToSinkTo->splice(InsertPos, ParentBlock, MI, 729 ++MachineBasicBlock::iterator(MI)); 730 731 // Move debug values. 732 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(), 733 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) { 734 MachineInstr *DbgMI = *DBI; 735 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI, 736 ++MachineBasicBlock::iterator(DbgMI)); 737 } 738 739 // Conservatively, clear any kill flags, since it's possible that they are no 740 // longer correct. 741 MI->clearKillInfo(); 742 743 return true; 744 } 745