1 //===- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ----===// 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 looks for safe point where the prologue and epilogue can be 11 // inserted. 12 // The safe point for the prologue (resp. epilogue) is called Save 13 // (resp. Restore). 14 // A point is safe for prologue (resp. epilogue) if and only if 15 // it 1) dominates (resp. post-dominates) all the frame related operations and 16 // between 2) two executions of the Save (resp. Restore) point there is an 17 // execution of the Restore (resp. Save) point. 18 // 19 // For instance, the following points are safe: 20 // for (int i = 0; i < 10; ++i) { 21 // Save 22 // ... 23 // Restore 24 // } 25 // Indeed, the execution looks like Save -> Restore -> Save -> Restore ... 26 // And the following points are not: 27 // for (int i = 0; i < 10; ++i) { 28 // Save 29 // ... 30 // } 31 // for (int i = 0; i < 10; ++i) { 32 // ... 33 // Restore 34 // } 35 // Indeed, the execution looks like Save -> Save -> ... -> Restore -> Restore. 36 // 37 // This pass also ensures that the safe points are 3) cheaper than the regular 38 // entry and exits blocks. 39 // 40 // Property #1 is ensured via the use of MachineDominatorTree and 41 // MachinePostDominatorTree. 42 // Property #2 is ensured via property #1 and MachineLoopInfo, i.e., both 43 // points must be in the same loop. 44 // Property #3 is ensured via the MachineBlockFrequencyInfo. 45 // 46 // If this pass found points matching all these properties, then 47 // MachineFrameInfo is updated with this information. 48 // 49 //===----------------------------------------------------------------------===// 50 51 #include "llvm/ADT/BitVector.h" 52 #include "llvm/ADT/PostOrderIterator.h" 53 #include "llvm/ADT/SetVector.h" 54 #include "llvm/ADT/SmallVector.h" 55 #include "llvm/ADT/Statistic.h" 56 #include "llvm/Analysis/CFG.h" 57 #include "llvm/CodeGen/MachineBasicBlock.h" 58 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 59 #include "llvm/CodeGen/MachineDominators.h" 60 #include "llvm/CodeGen/MachineFrameInfo.h" 61 #include "llvm/CodeGen/MachineFunction.h" 62 #include "llvm/CodeGen/MachineFunctionPass.h" 63 #include "llvm/CodeGen/MachineInstr.h" 64 #include "llvm/CodeGen/MachineLoopInfo.h" 65 #include "llvm/CodeGen/MachineOperand.h" 66 #include "llvm/CodeGen/MachinePostDominators.h" 67 #include "llvm/CodeGen/RegisterClassInfo.h" 68 #include "llvm/CodeGen/RegisterScavenging.h" 69 #include "llvm/CodeGen/TargetFrameLowering.h" 70 #include "llvm/CodeGen/TargetInstrInfo.h" 71 #include "llvm/CodeGen/TargetRegisterInfo.h" 72 #include "llvm/CodeGen/TargetSubtargetInfo.h" 73 #include "llvm/IR/Attributes.h" 74 #include "llvm/IR/Function.h" 75 #include "llvm/MC/MCAsmInfo.h" 76 #include "llvm/Pass.h" 77 #include "llvm/Support/CommandLine.h" 78 #include "llvm/Support/Debug.h" 79 #include "llvm/Support/ErrorHandling.h" 80 #include "llvm/Support/raw_ostream.h" 81 #include "llvm/Target/TargetMachine.h" 82 #include <cassert> 83 #include <cstdint> 84 #include <memory> 85 86 using namespace llvm; 87 88 #define DEBUG_TYPE "shrink-wrap" 89 90 STATISTIC(NumFunc, "Number of functions"); 91 STATISTIC(NumCandidates, "Number of shrink-wrapping candidates"); 92 STATISTIC(NumCandidatesDropped, 93 "Number of shrink-wrapping candidates dropped because of frequency"); 94 95 static cl::opt<cl::boolOrDefault> 96 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden, 97 cl::desc("enable the shrink-wrapping pass")); 98 99 namespace { 100 101 /// \brief Class to determine where the safe point to insert the 102 /// prologue and epilogue are. 103 /// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the 104 /// shrink-wrapping term for prologue/epilogue placement, this pass 105 /// does not rely on expensive data-flow analysis. Instead we use the 106 /// dominance properties and loop information to decide which point 107 /// are safe for such insertion. 108 class ShrinkWrap : public MachineFunctionPass { 109 /// Hold callee-saved information. 110 RegisterClassInfo RCI; 111 MachineDominatorTree *MDT; 112 MachinePostDominatorTree *MPDT; 113 114 /// Current safe point found for the prologue. 115 /// The prologue will be inserted before the first instruction 116 /// in this basic block. 117 MachineBasicBlock *Save; 118 119 /// Current safe point found for the epilogue. 120 /// The epilogue will be inserted before the first terminator instruction 121 /// in this basic block. 122 MachineBasicBlock *Restore; 123 124 /// Hold the information of the basic block frequency. 125 /// Use to check the profitability of the new points. 126 MachineBlockFrequencyInfo *MBFI; 127 128 /// Hold the loop information. Used to determine if Save and Restore 129 /// are in the same loop. 130 MachineLoopInfo *MLI; 131 132 /// Frequency of the Entry block. 133 uint64_t EntryFreq; 134 135 /// Current opcode for frame setup. 136 unsigned FrameSetupOpcode; 137 138 /// Current opcode for frame destroy. 139 unsigned FrameDestroyOpcode; 140 141 /// Entry block. 142 const MachineBasicBlock *Entry; 143 144 using SetOfRegs = SmallSetVector<unsigned, 16>; 145 146 /// Registers that need to be saved for the current function. 147 mutable SetOfRegs CurrentCSRs; 148 149 /// Current MachineFunction. 150 MachineFunction *MachineFunc; 151 152 /// \brief Check if \p MI uses or defines a callee-saved register or 153 /// a frame index. If this is the case, this means \p MI must happen 154 /// after Save and before Restore. 155 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS) const; 156 157 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const { 158 if (CurrentCSRs.empty()) { 159 BitVector SavedRegs; 160 const TargetFrameLowering *TFI = 161 MachineFunc->getSubtarget().getFrameLowering(); 162 163 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS); 164 165 for (int Reg = SavedRegs.find_first(); Reg != -1; 166 Reg = SavedRegs.find_next(Reg)) 167 CurrentCSRs.insert((unsigned)Reg); 168 } 169 return CurrentCSRs; 170 } 171 172 /// \brief Update the Save and Restore points such that \p MBB is in 173 /// the region that is dominated by Save and post-dominated by Restore 174 /// and Save and Restore still match the safe point definition. 175 /// Such point may not exist and Save and/or Restore may be null after 176 /// this call. 177 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS); 178 179 /// \brief Initialize the pass for \p MF. 180 void init(MachineFunction &MF) { 181 RCI.runOnMachineFunction(MF); 182 MDT = &getAnalysis<MachineDominatorTree>(); 183 MPDT = &getAnalysis<MachinePostDominatorTree>(); 184 Save = nullptr; 185 Restore = nullptr; 186 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 187 MLI = &getAnalysis<MachineLoopInfo>(); 188 EntryFreq = MBFI->getEntryFreq(); 189 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 190 FrameSetupOpcode = TII.getCallFrameSetupOpcode(); 191 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode(); 192 Entry = &MF.front(); 193 CurrentCSRs.clear(); 194 MachineFunc = &MF; 195 196 ++NumFunc; 197 } 198 199 /// Check whether or not Save and Restore points are still interesting for 200 /// shrink-wrapping. 201 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; } 202 203 /// \brief Check if shrink wrapping is enabled for this target and function. 204 static bool isShrinkWrapEnabled(const MachineFunction &MF); 205 206 public: 207 static char ID; 208 209 ShrinkWrap() : MachineFunctionPass(ID) { 210 initializeShrinkWrapPass(*PassRegistry::getPassRegistry()); 211 } 212 213 void getAnalysisUsage(AnalysisUsage &AU) const override { 214 AU.setPreservesAll(); 215 AU.addRequired<MachineBlockFrequencyInfo>(); 216 AU.addRequired<MachineDominatorTree>(); 217 AU.addRequired<MachinePostDominatorTree>(); 218 AU.addRequired<MachineLoopInfo>(); 219 MachineFunctionPass::getAnalysisUsage(AU); 220 } 221 222 MachineFunctionProperties getRequiredProperties() const override { 223 return MachineFunctionProperties().set( 224 MachineFunctionProperties::Property::NoVRegs); 225 } 226 227 StringRef getPassName() const override { return "Shrink Wrapping analysis"; } 228 229 /// \brief Perform the shrink-wrapping analysis and update 230 /// the MachineFrameInfo attached to \p MF with the results. 231 bool runOnMachineFunction(MachineFunction &MF) override; 232 }; 233 234 } // end anonymous namespace 235 236 char ShrinkWrap::ID = 0; 237 238 char &llvm::ShrinkWrapID = ShrinkWrap::ID; 239 240 INITIALIZE_PASS_BEGIN(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false) 241 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 242 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 243 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 244 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 245 INITIALIZE_PASS_END(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false) 246 247 bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI, 248 RegScavenger *RS) const { 249 if (MI.getOpcode() == FrameSetupOpcode || 250 MI.getOpcode() == FrameDestroyOpcode) { 251 DEBUG(dbgs() << "Frame instruction: " << MI << '\n'); 252 return true; 253 } 254 for (const MachineOperand &MO : MI.operands()) { 255 bool UseOrDefCSR = false; 256 if (MO.isReg()) { 257 // Ignore instructions like DBG_VALUE which don't read/def the register. 258 if (!MO.isDef() && !MO.readsReg()) 259 continue; 260 unsigned PhysReg = MO.getReg(); 261 if (!PhysReg) 262 continue; 263 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && 264 "Unallocated register?!"); 265 UseOrDefCSR = RCI.getLastCalleeSavedAlias(PhysReg); 266 } else if (MO.isRegMask()) { 267 // Check if this regmask clobbers any of the CSRs. 268 for (unsigned Reg : getCurrentCSRs(RS)) { 269 if (MO.clobbersPhysReg(Reg)) { 270 UseOrDefCSR = true; 271 break; 272 } 273 } 274 } 275 // Skip FrameIndex operands in DBG_VALUE instructions. 276 if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) { 277 DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI(" 278 << MO.isFI() << "): " << MI << '\n'); 279 return true; 280 } 281 } 282 return false; 283 } 284 285 /// \brief Helper function to find the immediate (post) dominator. 286 template <typename ListOfBBs, typename DominanceAnalysis> 287 static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs, 288 DominanceAnalysis &Dom) { 289 MachineBasicBlock *IDom = &Block; 290 for (MachineBasicBlock *BB : BBs) { 291 IDom = Dom.findNearestCommonDominator(IDom, BB); 292 if (!IDom) 293 break; 294 } 295 if (IDom == &Block) 296 return nullptr; 297 return IDom; 298 } 299 300 void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB, 301 RegScavenger *RS) { 302 // Get rid of the easy cases first. 303 if (!Save) 304 Save = &MBB; 305 else 306 Save = MDT->findNearestCommonDominator(Save, &MBB); 307 308 if (!Save) { 309 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n"); 310 return; 311 } 312 313 if (!Restore) 314 Restore = &MBB; 315 else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it 316 // means the block never returns. If that's the 317 // case, we don't want to call 318 // `findNearestCommonDominator`, which will 319 // return `Restore`. 320 Restore = MPDT->findNearestCommonDominator(Restore, &MBB); 321 else 322 Restore = nullptr; // Abort, we can't find a restore point in this case. 323 324 // Make sure we would be able to insert the restore code before the 325 // terminator. 326 if (Restore == &MBB) { 327 for (const MachineInstr &Terminator : MBB.terminators()) { 328 if (!useOrDefCSROrFI(Terminator, RS)) 329 continue; 330 // One of the terminator needs to happen before the restore point. 331 if (MBB.succ_empty()) { 332 Restore = nullptr; // Abort, we can't find a restore point in this case. 333 break; 334 } 335 // Look for a restore point that post-dominates all the successors. 336 // The immediate post-dominator is what we are looking for. 337 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT); 338 break; 339 } 340 } 341 342 if (!Restore) { 343 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n"); 344 return; 345 } 346 347 // Make sure Save and Restore are suitable for shrink-wrapping: 348 // 1. all path from Save needs to lead to Restore before exiting. 349 // 2. all path to Restore needs to go through Save from Entry. 350 // We achieve that by making sure that: 351 // A. Save dominates Restore. 352 // B. Restore post-dominates Save. 353 // C. Save and Restore are in the same loop. 354 bool SaveDominatesRestore = false; 355 bool RestorePostDominatesSave = false; 356 while (Save && Restore && 357 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) || 358 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) || 359 // Post-dominance is not enough in loops to ensure that all uses/defs 360 // are after the prologue and before the epilogue at runtime. 361 // E.g., 362 // while(1) { 363 // Save 364 // Restore 365 // if (...) 366 // break; 367 // use/def CSRs 368 // } 369 // All the uses/defs of CSRs are dominated by Save and post-dominated 370 // by Restore. However, the CSRs uses are still reachable after 371 // Restore and before Save are executed. 372 // 373 // For now, just push the restore/save points outside of loops. 374 // FIXME: Refine the criteria to still find interesting cases 375 // for loops. 376 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) { 377 // Fix (A). 378 if (!SaveDominatesRestore) { 379 Save = MDT->findNearestCommonDominator(Save, Restore); 380 continue; 381 } 382 // Fix (B). 383 if (!RestorePostDominatesSave) 384 Restore = MPDT->findNearestCommonDominator(Restore, Save); 385 386 // Fix (C). 387 if (Save && Restore && 388 (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) { 389 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) { 390 // Push Save outside of this loop if immediate dominator is different 391 // from save block. If immediate dominator is not different, bail out. 392 Save = FindIDom<>(*Save, Save->predecessors(), *MDT); 393 if (!Save) 394 break; 395 } else { 396 // If the loop does not exit, there is no point in looking 397 // for a post-dominator outside the loop. 398 SmallVector<MachineBasicBlock*, 4> ExitBlocks; 399 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks); 400 // Push Restore outside of this loop. 401 // Look for the immediate post-dominator of the loop exits. 402 MachineBasicBlock *IPdom = Restore; 403 for (MachineBasicBlock *LoopExitBB: ExitBlocks) { 404 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT); 405 if (!IPdom) 406 break; 407 } 408 // If the immediate post-dominator is not in a less nested loop, 409 // then we are stuck in a program with an infinite loop. 410 // In that case, we will not find a safe point, hence, bail out. 411 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore)) 412 Restore = IPdom; 413 else { 414 Restore = nullptr; 415 break; 416 } 417 } 418 } 419 } 420 } 421 422 bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) { 423 if (skipFunction(MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF)) 424 return false; 425 426 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n'); 427 428 init(MF); 429 430 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin()); 431 if (containsIrreducibleCFG<MachineBasicBlock *>(RPOT, *MLI)) { 432 // If MF is irreducible, a block may be in a loop without 433 // MachineLoopInfo reporting it. I.e., we may use the 434 // post-dominance property in loops, which lead to incorrect 435 // results. Moreover, we may miss that the prologue and 436 // epilogue are not in the same loop, leading to unbalanced 437 // construction/deconstruction of the stack frame. 438 DEBUG(dbgs() << "Irreducible CFGs are not supported yet\n"); 439 return false; 440 } 441 442 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 443 std::unique_ptr<RegScavenger> RS( 444 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr); 445 446 for (MachineBasicBlock &MBB : MF) { 447 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName() 448 << '\n'); 449 450 if (MBB.isEHFuncletEntry()) { 451 DEBUG(dbgs() << "EH Funclets are not supported yet.\n"); 452 return false; 453 } 454 455 if (MBB.isEHPad()) { 456 // Push the prologue and epilogue outside of 457 // the region that may throw by making sure 458 // that all the landing pads are at least at the 459 // boundary of the save and restore points. 460 // The problem with exceptions is that the throw 461 // is not properly modeled and in particular, a 462 // basic block can jump out from the middle. 463 updateSaveRestorePoints(MBB, RS.get()); 464 if (!ArePointsInteresting()) { 465 DEBUG(dbgs() << "EHPad prevents shrink-wrapping\n"); 466 return false; 467 } 468 continue; 469 } 470 471 for (const MachineInstr &MI : MBB) { 472 if (!useOrDefCSROrFI(MI, RS.get())) 473 continue; 474 // Save (resp. restore) point must dominate (resp. post dominate) 475 // MI. Look for the proper basic block for those. 476 updateSaveRestorePoints(MBB, RS.get()); 477 // If we are at a point where we cannot improve the placement of 478 // save/restore instructions, just give up. 479 if (!ArePointsInteresting()) { 480 DEBUG(dbgs() << "No Shrink wrap candidate found\n"); 481 return false; 482 } 483 // No need to look for other instructions, this basic block 484 // will already be part of the handled region. 485 break; 486 } 487 } 488 if (!ArePointsInteresting()) { 489 // If the points are not interesting at this point, then they must be null 490 // because it means we did not encounter any frame/CSR related code. 491 // Otherwise, we would have returned from the previous loop. 492 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!"); 493 DEBUG(dbgs() << "Nothing to shrink-wrap\n"); 494 return false; 495 } 496 497 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq 498 << '\n'); 499 500 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 501 do { 502 DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: " 503 << Save->getNumber() << ' ' << Save->getName() << ' ' 504 << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: " 505 << Restore->getNumber() << ' ' << Restore->getName() << ' ' 506 << MBFI->getBlockFreq(Restore).getFrequency() << '\n'); 507 508 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false; 509 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) && 510 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) && 511 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) && 512 TFI->canUseAsEpilogue(*Restore))) 513 break; 514 DEBUG(dbgs() << "New points are too expensive or invalid for the target\n"); 515 MachineBasicBlock *NewBB; 516 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) { 517 Save = FindIDom<>(*Save, Save->predecessors(), *MDT); 518 if (!Save) 519 break; 520 NewBB = Save; 521 } else { 522 // Restore is expensive. 523 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT); 524 if (!Restore) 525 break; 526 NewBB = Restore; 527 } 528 updateSaveRestorePoints(*NewBB, RS.get()); 529 } while (Save && Restore); 530 531 if (!ArePointsInteresting()) { 532 ++NumCandidatesDropped; 533 return false; 534 } 535 536 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber() 537 << ' ' << Save->getName() << "\nRestore: " 538 << Restore->getNumber() << ' ' << Restore->getName() << '\n'); 539 540 MachineFrameInfo &MFI = MF.getFrameInfo(); 541 MFI.setSavePoint(Save); 542 MFI.setRestorePoint(Restore); 543 ++NumCandidates; 544 return false; 545 } 546 547 bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) { 548 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 549 550 switch (EnableShrinkWrapOpt) { 551 case cl::BOU_UNSET: 552 return TFI->enableShrinkWrapping(MF) && 553 // Windows with CFI has some limitations that make it impossible 554 // to use shrink-wrapping. 555 !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() && 556 // Sanitizers look at the value of the stack at the location 557 // of the crash. Since a crash can happen anywhere, the 558 // frame must be lowered before anything else happen for the 559 // sanitizers to be able to get a correct stack frame. 560 !(MF.getFunction().hasFnAttribute(Attribute::SanitizeAddress) || 561 MF.getFunction().hasFnAttribute(Attribute::SanitizeThread) || 562 MF.getFunction().hasFnAttribute(Attribute::SanitizeMemory) || 563 MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress)); 564 // If EnableShrinkWrap is set, it takes precedence on whatever the 565 // target sets. The rational is that we assume we want to test 566 // something related to shrink-wrapping. 567 case cl::BOU_TRUE: 568 return true; 569 case cl::BOU_FALSE: 570 return false; 571 } 572 llvm_unreachable("Invalid shrink-wrapping state"); 573 } 574