1//===- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ----===//
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 looks for safe point where the prologue and epilogue can be
10// inserted.
11// The safe point for the prologue (resp. epilogue) is called Save
12// (resp. Restore).
13// A point is safe for prologue (resp. epilogue) if and only if
14// it 1) dominates (resp. post-dominates) all the frame related operations and
15// between 2) two executions of the Save (resp. Restore) point there is an
16// execution of the Restore (resp. Save) point.
17//
18// For instance, the following points are safe:
19// for (int i = 0; i < 10; ++i) {
20// Save
21// ...
22// Restore
23// }
24// Indeed, the execution looks like Save -> Restore -> Save -> Restore ...
25// And the following points are not:
26// for (int i = 0; i < 10; ++i) {
27// Save
28// ...
29// }
30// for (int i = 0; i < 10; ++i) {
31// ...
32// Restore
33// }
34// Indeed, the execution looks like Save -> Save -> ... -> Restore -> Restore.
35//
36// This pass also ensures that the safe points are 3) cheaper than the regular
37// entry and exits blocks.
38//
39// Property #1 is ensured via the use of MachineDominatorTree and
40// MachinePostDominatorTree.
41// Property #2 is ensured via property #1 and MachineLoopInfo, i.e., both
42// points must be in the same loop.
43// Property #3 is ensured via the MachineBlockFrequencyInfo.
44//
45// If this pass found points matching all these properties, then
46// MachineFrameInfo is updated with this information.
47//
48//===----------------------------------------------------------------------===//
49
50#include "llvm/CodeGen/ShrinkWrap.h"
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/Analysis/ValueTracking.h"
58#include "llvm/CodeGen/MachineBasicBlock.h"
59#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
60#include "llvm/CodeGen/MachineDominators.h"
61#include "llvm/CodeGen/MachineFrameInfo.h"
62#include "llvm/CodeGen/MachineFunction.h"
63#include "llvm/CodeGen/MachineFunctionPass.h"
64#include "llvm/CodeGen/MachineInstr.h"
65#include "llvm/CodeGen/MachineLoopInfo.h"
66#include "llvm/CodeGen/MachineOperand.h"
67#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
68#include "llvm/CodeGen/MachinePostDominators.h"
69#include "llvm/CodeGen/RegisterClassInfo.h"
70#include "llvm/CodeGen/RegisterScavenging.h"
71#include "llvm/CodeGen/TargetFrameLowering.h"
72#include "llvm/CodeGen/TargetInstrInfo.h"
73#include "llvm/CodeGen/TargetLowering.h"
74#include "llvm/CodeGen/TargetRegisterInfo.h"
75#include "llvm/CodeGen/TargetSubtargetInfo.h"
76#include "llvm/IR/Attributes.h"
77#include "llvm/IR/Function.h"
78#include "llvm/InitializePasses.h"
79#include "llvm/MC/MCAsmInfo.h"
80#include "llvm/Pass.h"
81#include "llvm/Support/CommandLine.h"
82#include "llvm/Support/Debug.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/raw_ostream.h"
85#include "llvm/Target/TargetMachine.h"
86#include <cassert>
87#include <memory>
88
89using namespace llvm;
90
91#define DEBUG_TYPE "shrink-wrap"
92
93STATISTIC(NumFunc, "Number of functions");
94STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
95STATISTIC(NumCandidatesDropped,
96 "Number of shrink-wrapping candidates dropped because of frequency");
97
98static cl::opt<cl::boolOrDefault>
99EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
100 cl::desc("enable the shrink-wrapping pass"));
101static cl::opt<bool> EnablePostShrinkWrapOpt(
102 "enable-shrink-wrap-region-split", cl::init(Val: true), cl::Hidden,
103 cl::desc("enable splitting of the restore block if possible"));
104
105namespace {
106
107/// Class to determine where the safe point to insert the
108/// prologue and epilogue are.
109/// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
110/// shrink-wrapping term for prologue/epilogue placement, this pass
111/// does not rely on expensive data-flow analysis. Instead we use the
112/// dominance properties and loop information to decide which point
113/// are safe for such insertion.
114class ShrinkWrapImpl {
115 /// Hold callee-saved information.
116 RegisterClassInfo RCI;
117 MachineDominatorTree *MDT = nullptr;
118 MachinePostDominatorTree *MPDT = nullptr;
119
120 /// Current safe point found for the prologue.
121 /// The prologue will be inserted before the first instruction
122 /// in this basic block.
123 MachineBasicBlock *Save = nullptr;
124
125 /// Current safe point found for the epilogue.
126 /// The epilogue will be inserted before the first terminator instruction
127 /// in this basic block.
128 MachineBasicBlock *Restore = nullptr;
129
130 /// Hold the information of the basic block frequency.
131 /// Use to check the profitability of the new points.
132 MachineBlockFrequencyInfo *MBFI = nullptr;
133
134 /// Hold the loop information. Used to determine if Save and Restore
135 /// are in the same loop.
136 MachineLoopInfo *MLI = nullptr;
137
138 // Emit remarks.
139 MachineOptimizationRemarkEmitter *ORE = nullptr;
140
141 /// Frequency of the Entry block.
142 BlockFrequency EntryFreq;
143
144 /// Current opcode for frame setup.
145 unsigned FrameSetupOpcode = ~0u;
146
147 /// Current opcode for frame destroy.
148 unsigned FrameDestroyOpcode = ~0u;
149
150 /// Stack pointer register, used by llvm.{savestack,restorestack}
151 Register SP;
152
153 /// Entry block.
154 const MachineBasicBlock *Entry = nullptr;
155
156 using SetOfRegs = SmallSetVector<unsigned, 16>;
157
158 /// Registers that need to be saved for the current function.
159 mutable SetOfRegs CurrentCSRs;
160
161 /// Current MachineFunction.
162 MachineFunction *MachineFunc = nullptr;
163
164 /// Is `true` for the block numbers where we assume possible stack accesses
165 /// or computation of stack-relative addresses on any CFG path including the
166 /// block itself. Is `false` for basic blocks where we can guarantee the
167 /// opposite. False positives won't lead to incorrect analysis results,
168 /// therefore this approach is fair.
169 BitVector StackAddressUsedBlockInfo;
170
171 /// Check if \p MI uses or defines a callee-saved register or
172 /// a frame index. If this is the case, this means \p MI must happen
173 /// after Save and before Restore.
174 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS,
175 bool StackAddressUsed) const;
176
177 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
178 if (CurrentCSRs.empty()) {
179 BitVector SavedRegs;
180 const TargetFrameLowering *TFI =
181 MachineFunc->getSubtarget().getFrameLowering();
182
183 TFI->determineCalleeSaves(MF&: *MachineFunc, SavedRegs, RS);
184
185 for (int Reg = SavedRegs.find_first(); Reg != -1;
186 Reg = SavedRegs.find_next(Prev: Reg))
187 CurrentCSRs.insert(X: (unsigned)Reg);
188 }
189 return CurrentCSRs;
190 }
191
192 /// Update the Save and Restore points such that \p MBB is in
193 /// the region that is dominated by Save and post-dominated by Restore
194 /// and Save and Restore still match the safe point definition.
195 /// Such point may not exist and Save and/or Restore may be null after
196 /// this call.
197 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
198
199 // Try to find safe point based on dominance and block frequency without
200 // any change in IR.
201 bool performShrinkWrapping(
202 const ReversePostOrderTraversal<MachineBasicBlock *> &RPOT,
203 RegScavenger *RS);
204
205 /// This function tries to split the restore point if doing so can shrink the
206 /// save point further. \return True if restore point is split.
207 bool postShrinkWrapping(bool HasCandidate, MachineFunction &MF,
208 RegScavenger *RS);
209
210 /// This function analyzes if the restore point can split to create a new
211 /// restore point. This function collects
212 /// 1. Any preds of current restore that are reachable by callee save/FI
213 /// blocks
214 /// - indicated by DirtyPreds
215 /// 2. Any preds of current restore that are not DirtyPreds - indicated by
216 /// CleanPreds
217 /// Both sets should be non-empty for considering restore point split.
218 bool checkIfRestoreSplittable(
219 const MachineBasicBlock *CurRestore,
220 const DenseSet<const MachineBasicBlock *> &ReachableByDirty,
221 SmallVectorImpl<MachineBasicBlock *> &DirtyPreds,
222 SmallVectorImpl<MachineBasicBlock *> &CleanPreds,
223 const TargetInstrInfo *TII, RegScavenger *RS);
224
225 /// Initialize the pass for \p MF.
226 void init(MachineFunction &MF) {
227 RCI.runOnMachineFunction(MF);
228 Save = nullptr;
229 Restore = nullptr;
230 EntryFreq = MBFI->getEntryFreq();
231 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
232 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
233 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
234 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
235 SP = Subtarget.getTargetLowering()->getStackPointerRegisterToSaveRestore();
236 Entry = &MF.front();
237 CurrentCSRs.clear();
238 MachineFunc = &MF;
239
240 ++NumFunc;
241 }
242
243 /// Check whether or not Save and Restore points are still interesting for
244 /// shrink-wrapping.
245 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
246
247public:
248 ShrinkWrapImpl(MachineDominatorTree *MDT, MachinePostDominatorTree *MPDT,
249 MachineBlockFrequencyInfo *MBFI, MachineLoopInfo *MLI,
250 MachineOptimizationRemarkEmitter *ORE)
251 : MDT(MDT), MPDT(MPDT), MBFI(MBFI), MLI(MLI), ORE(ORE) {}
252
253 /// Check if shrink wrapping is enabled for this target and function.
254 static bool isShrinkWrapEnabled(const MachineFunction &MF);
255
256 bool run(MachineFunction &MF);
257};
258
259class ShrinkWrapLegacy : public MachineFunctionPass {
260public:
261 static char ID;
262
263 ShrinkWrapLegacy() : MachineFunctionPass(ID) {}
264
265 void getAnalysisUsage(AnalysisUsage &AU) const override {
266 AU.setPreservesAll();
267 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
268 AU.addRequired<MachineDominatorTreeWrapperPass>();
269 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
270 AU.addRequired<MachineLoopInfoWrapperPass>();
271 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
272 MachineFunctionPass::getAnalysisUsage(AU);
273 }
274
275 MachineFunctionProperties getRequiredProperties() const override {
276 return MachineFunctionProperties().setNoVRegs();
277 }
278
279 StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
280
281 /// Perform the shrink-wrapping analysis and update
282 /// the MachineFrameInfo attached to \p MF with the results.
283 bool runOnMachineFunction(MachineFunction &MF) override;
284};
285
286} // end anonymous namespace
287
288char ShrinkWrapLegacy::ID = 0;
289
290char &llvm::ShrinkWrapID = ShrinkWrapLegacy::ID;
291
292INITIALIZE_PASS_BEGIN(ShrinkWrapLegacy, DEBUG_TYPE, "Shrink Wrap Pass", false,
293 false)
294INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
295INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
296INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTreeWrapperPass)
297INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
298INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
299INITIALIZE_PASS_END(ShrinkWrapLegacy, DEBUG_TYPE, "Shrink Wrap Pass", false,
300 false)
301
302bool ShrinkWrapImpl::useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS,
303 bool StackAddressUsed) const {
304 /// Check if \p Op is known to access an address not on the function's stack .
305 /// At the moment, accesses where the underlying object is a global, function
306 /// argument, or jump table are considered non-stack accesses. Note that the
307 /// caller's stack may get accessed when passing an argument via the stack,
308 /// but not the stack of the current function.
309 ///
310 auto IsKnownNonStackPtr = [](MachineMemOperand *Op) {
311 if (Op->getValue()) {
312 const Value *UO = getUnderlyingObject(V: Op->getValue());
313 if (!UO)
314 return false;
315 if (auto *Arg = dyn_cast<Argument>(Val: UO))
316 return !Arg->hasPassPointeeByValueCopyAttr();
317 return isa<GlobalValue>(Val: UO);
318 }
319 if (const PseudoSourceValue *PSV = Op->getPseudoValue())
320 return PSV->isJumpTable() || PSV->isConstantPool();
321 return false;
322 };
323 // Load/store operations may access the stack indirectly when we previously
324 // computed an address to a stack location.
325 if (StackAddressUsed && MI.mayLoadOrStore() &&
326 (MI.isCall() || MI.hasUnmodeledSideEffects() || MI.memoperands_empty() ||
327 !all_of(Range: MI.memoperands(), P: IsKnownNonStackPtr)))
328 return true;
329
330 if (MI.getOpcode() == FrameSetupOpcode ||
331 MI.getOpcode() == FrameDestroyOpcode) {
332 LLVM_DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
333 return true;
334 }
335 const MachineFunction *MF = MI.getParent()->getParent();
336 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
337 for (const MachineOperand &MO : MI.operands()) {
338 bool UseOrDefCSR = false;
339 if (MO.isReg()) {
340 // Ignore instructions like DBG_VALUE which don't read/def the register.
341 if (!MO.isDef() && !MO.readsReg())
342 continue;
343 Register PhysReg = MO.getReg();
344 if (!PhysReg)
345 continue;
346 assert(PhysReg.isPhysical() && "Unallocated register?!");
347 // The stack pointer is not normally described as a callee-saved register
348 // in calling convention definitions, so we need to watch for it
349 // separately. An SP mentioned by a call instruction, we can ignore,
350 // though, as it's harmless and we do not want to effectively disable tail
351 // calls by forcing the restore point to post-dominate them.
352 // PPC's LR is also not normally described as a callee-saved register in
353 // calling convention definitions, so we need to watch for it, too. An LR
354 // mentioned implicitly by a return (or "branch to link register")
355 // instruction we can ignore, otherwise we may pessimize shrinkwrapping.
356 // PPC's Frame pointer (FP) is also not described as a callee-saved
357 // register. Until the FP is assigned a Physical Register PPC's FP needs
358 // to be checked separately.
359 UseOrDefCSR = (!MI.isCall() && PhysReg == SP) ||
360 RCI.getLastCalleeSavedAlias(PhysReg) ||
361 (!MI.isReturn() &&
362 TRI->isNonallocatableRegisterCalleeSave(Reg: PhysReg)) ||
363 TRI->isVirtualFrameRegister(Reg: PhysReg);
364 } else if (MO.isRegMask()) {
365 // Check if this regmask clobbers any of the CSRs.
366 for (unsigned Reg : getCurrentCSRs(RS)) {
367 if (MO.clobbersPhysReg(PhysReg: Reg)) {
368 UseOrDefCSR = true;
369 break;
370 }
371 }
372 }
373 // Skip FrameIndex operands in DBG_VALUE instructions.
374 if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) {
375 LLVM_DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
376 << MO.isFI() << "): " << MI << '\n');
377 return true;
378 }
379 }
380 return false;
381}
382
383/// Helper function to find the immediate (post) dominator.
384template <typename ListOfBBs, typename DominanceAnalysis>
385static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
386 DominanceAnalysis &Dom, bool Strict = true) {
387 if (BBs.begin() == BBs.end())
388 return Strict ? nullptr : &Block;
389 MachineBasicBlock *IDom = Dom.findNearestCommonDominator(iterator_range(BBs));
390 if (Strict && IDom == &Block)
391 return nullptr;
392 return IDom;
393}
394
395static bool isAnalyzableBB(const TargetInstrInfo &TII,
396 MachineBasicBlock &Entry) {
397 // Check if the block is analyzable.
398 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
399 SmallVector<MachineOperand, 4> Cond;
400 return !TII.analyzeBranch(MBB&: Entry, TBB, FBB, Cond);
401}
402
403/// Determines if any predecessor of MBB is on the path from block that has use
404/// or def of CSRs/FI to MBB.
405/// ReachableByDirty: All blocks reachable from block that has use or def of
406/// CSR/FI.
407static bool
408hasDirtyPred(const DenseSet<const MachineBasicBlock *> &ReachableByDirty,
409 const MachineBasicBlock &MBB) {
410 for (const MachineBasicBlock *PredBB : MBB.predecessors())
411 if (ReachableByDirty.count(V: PredBB))
412 return true;
413 return false;
414}
415
416/// Derives the list of all the basic blocks reachable from MBB.
417static void markAllReachable(DenseSet<const MachineBasicBlock *> &Visited,
418 const MachineBasicBlock &MBB) {
419 SmallVector<MachineBasicBlock *, 4> Worklist(MBB.successors());
420 Visited.insert(V: &MBB);
421 while (!Worklist.empty()) {
422 MachineBasicBlock *SuccMBB = Worklist.pop_back_val();
423 if (!Visited.insert(V: SuccMBB).second)
424 continue;
425 Worklist.append(in_start: SuccMBB->succ_begin(), in_end: SuccMBB->succ_end());
426 }
427}
428
429/// Collect blocks reachable by use or def of CSRs/FI.
430static void collectBlocksReachableByDirty(
431 const DenseSet<const MachineBasicBlock *> &DirtyBBs,
432 DenseSet<const MachineBasicBlock *> &ReachableByDirty) {
433 for (const MachineBasicBlock *MBB : DirtyBBs) {
434 if (ReachableByDirty.count(V: MBB))
435 continue;
436 // Mark all offsprings as reachable.
437 markAllReachable(Visited&: ReachableByDirty, MBB: *MBB);
438 }
439}
440
441/// \return true if there is a clean path from SavePoint to the original
442/// Restore.
443static bool
444isSaveReachableThroughClean(const MachineBasicBlock *SavePoint,
445 ArrayRef<MachineBasicBlock *> CleanPreds) {
446 DenseSet<const MachineBasicBlock *> Visited;
447 SmallVector<MachineBasicBlock *, 4> Worklist(CleanPreds);
448 while (!Worklist.empty()) {
449 MachineBasicBlock *CleanBB = Worklist.pop_back_val();
450 if (CleanBB == SavePoint)
451 return true;
452 if (!Visited.insert(V: CleanBB).second || !CleanBB->pred_size())
453 continue;
454 Worklist.append(in_start: CleanBB->pred_begin(), in_end: CleanBB->pred_end());
455 }
456 return false;
457}
458
459/// This function updates the branches post restore point split.
460///
461/// Restore point has been split.
462/// Old restore point: MBB
463/// New restore point: NMBB
464/// Any basic block(say BBToUpdate) which had a fallthrough to MBB
465/// previously should
466/// 1. Fallthrough to NMBB iff NMBB is inserted immediately above MBB in the
467/// block layout OR
468/// 2. Branch unconditionally to NMBB iff NMBB is inserted at any other place.
469static void updateTerminator(MachineBasicBlock *BBToUpdate,
470 MachineBasicBlock *NMBB,
471 const TargetInstrInfo *TII) {
472 DebugLoc DL = BBToUpdate->findBranchDebugLoc();
473 // if NMBB isn't the new layout successor for BBToUpdate, insert unconditional
474 // branch to it
475 if (!BBToUpdate->isLayoutSuccessor(MBB: NMBB))
476 TII->insertUnconditionalBranch(MBB&: *BBToUpdate, DestBB: NMBB, DL);
477}
478
479/// This function splits the restore point and returns new restore point/BB.
480///
481/// DirtyPreds: Predessors of \p MBB that are ReachableByDirty
482///
483/// Decision has been made to split the restore point.
484/// old restore point: \p MBB
485/// new restore point: \p NMBB
486/// This function makes the necessary block layout changes so that
487/// 1. \p NMBB points to \p MBB unconditionally
488/// 2. All dirtyPreds that previously pointed to \p MBB point to \p NMBB
489static MachineBasicBlock *
490tryToSplitRestore(MachineBasicBlock *MBB,
491 ArrayRef<MachineBasicBlock *> DirtyPreds,
492 const TargetInstrInfo *TII) {
493 MachineFunction *MF = MBB->getParent();
494
495 // get the list of DirtyPreds who have a fallthrough to MBB
496 // before the block layout change. This is just to ensure that if the NMBB is
497 // inserted after MBB, then we create unconditional branch from
498 // DirtyPred/CleanPred to NMBB
499 SmallPtrSet<MachineBasicBlock *, 8> MBBFallthrough;
500 for (MachineBasicBlock *BB : DirtyPreds)
501 if (BB->getFallThrough(JumpToFallThrough: false) == MBB)
502 MBBFallthrough.insert(Ptr: BB);
503
504 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
505 // Insert this block at the end of the function. Inserting in between may
506 // interfere with control flow optimizer decisions.
507 MF->insert(MBBI: MF->end(), MBB: NMBB);
508
509 for (const MachineBasicBlock::RegisterMaskPair &LI : MBB->liveins())
510 NMBB->addLiveIn(PhysReg: LI.PhysReg);
511
512 TII->insertUnconditionalBranch(MBB&: *NMBB, DestBB: MBB, DL: DebugLoc());
513
514 // After splitting, all predecessors of the restore point should be dirty
515 // blocks.
516 for (MachineBasicBlock *SuccBB : DirtyPreds)
517 SuccBB->ReplaceUsesOfBlockWith(Old: MBB, New: NMBB);
518
519 NMBB->addSuccessor(Succ: MBB);
520
521 for (MachineBasicBlock *BBToUpdate : MBBFallthrough)
522 updateTerminator(BBToUpdate, NMBB, TII);
523
524 return NMBB;
525}
526
527/// This function undoes the restore point split done earlier.
528///
529/// DirtyPreds: All predecessors of \p NMBB that are ReachableByDirty.
530///
531/// Restore point was split and the change needs to be unrolled. Make necessary
532/// changes to reset restore point from \p NMBB to \p MBB.
533static void rollbackRestoreSplit(MachineFunction &MF, MachineBasicBlock *NMBB,
534 MachineBasicBlock *MBB,
535 ArrayRef<MachineBasicBlock *> DirtyPreds,
536 const TargetInstrInfo *TII) {
537 // For a BB, if NMBB is fallthrough in the current layout, then in the new
538 // layout a. BB should fallthrough to MBB OR b. BB should undconditionally
539 // branch to MBB
540 SmallPtrSet<MachineBasicBlock *, 8> NMBBFallthrough;
541 for (MachineBasicBlock *BB : DirtyPreds)
542 if (BB->getFallThrough(JumpToFallThrough: false) == NMBB)
543 NMBBFallthrough.insert(Ptr: BB);
544
545 NMBB->removeSuccessor(Succ: MBB);
546 for (MachineBasicBlock *SuccBB : DirtyPreds)
547 SuccBB->ReplaceUsesOfBlockWith(Old: NMBB, New: MBB);
548
549 NMBB->erase(I: NMBB->begin(), E: NMBB->end());
550 NMBB->eraseFromParent();
551
552 for (MachineBasicBlock *BBToUpdate : NMBBFallthrough)
553 updateTerminator(BBToUpdate, NMBB: MBB, TII);
554}
555
556// A block is deemed fit for restore point split iff there exist
557// 1. DirtyPreds - preds of CurRestore reachable from use or def of CSR/FI
558// 2. CleanPreds - preds of CurRestore that arent DirtyPreds
559bool ShrinkWrapImpl::checkIfRestoreSplittable(
560 const MachineBasicBlock *CurRestore,
561 const DenseSet<const MachineBasicBlock *> &ReachableByDirty,
562 SmallVectorImpl<MachineBasicBlock *> &DirtyPreds,
563 SmallVectorImpl<MachineBasicBlock *> &CleanPreds,
564 const TargetInstrInfo *TII, RegScavenger *RS) {
565 for (const MachineInstr &MI : *CurRestore)
566 if (useOrDefCSROrFI(MI, RS, /*StackAddressUsed=*/true))
567 return false;
568
569 for (MachineBasicBlock *PredBB : CurRestore->predecessors()) {
570 if (!isAnalyzableBB(TII: *TII, Entry&: *PredBB))
571 return false;
572
573 if (ReachableByDirty.count(V: PredBB))
574 DirtyPreds.push_back(Elt: PredBB);
575 else
576 CleanPreds.push_back(Elt: PredBB);
577 }
578
579 return !(CleanPreds.empty() || DirtyPreds.empty());
580}
581
582bool ShrinkWrapImpl::postShrinkWrapping(bool HasCandidate, MachineFunction &MF,
583 RegScavenger *RS) {
584 if (!EnablePostShrinkWrapOpt)
585 return false;
586
587 MachineBasicBlock *InitSave = nullptr;
588 MachineBasicBlock *InitRestore = nullptr;
589
590 if (HasCandidate) {
591 InitSave = Save;
592 InitRestore = Restore;
593 } else {
594 InitRestore = nullptr;
595 InitSave = &MF.front();
596 for (MachineBasicBlock &MBB : MF) {
597 if (MBB.isEHFuncletEntry())
598 return false;
599 if (MBB.isReturnBlock()) {
600 // Do not support multiple restore points.
601 if (InitRestore)
602 return false;
603 InitRestore = &MBB;
604 }
605 }
606 }
607
608 if (!InitSave || !InitRestore || InitRestore == InitSave ||
609 !MDT->dominates(A: InitSave, B: InitRestore) ||
610 !MPDT->dominates(A: InitRestore, B: InitSave))
611 return false;
612
613 // Bail out of the optimization if any of the basic block is target of
614 // INLINEASM_BR instruction
615 for (MachineBasicBlock &MBB : MF)
616 if (MBB.isInlineAsmBrIndirectTarget())
617 return false;
618
619 DenseSet<const MachineBasicBlock *> DirtyBBs;
620 for (MachineBasicBlock &MBB : MF) {
621 if (!MDT->isReachableFromEntry(A: &MBB))
622 continue;
623 if (MBB.isEHPad()) {
624 DirtyBBs.insert(V: &MBB);
625 continue;
626 }
627 for (const MachineInstr &MI : MBB)
628 if (useOrDefCSROrFI(MI, RS, /*StackAddressUsed=*/true)) {
629 DirtyBBs.insert(V: &MBB);
630 break;
631 }
632 }
633
634 // Find blocks reachable from the use or def of CSRs/FI.
635 DenseSet<const MachineBasicBlock *> ReachableByDirty;
636 collectBlocksReachableByDirty(DirtyBBs, ReachableByDirty);
637
638 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
639 SmallVector<MachineBasicBlock *, 2> DirtyPreds;
640 SmallVector<MachineBasicBlock *, 2> CleanPreds;
641 if (!checkIfRestoreSplittable(CurRestore: InitRestore, ReachableByDirty, DirtyPreds,
642 CleanPreds, TII, RS))
643 return false;
644
645 // Trying to reach out to the new save point which dominates all dirty blocks.
646 MachineBasicBlock *NewSave =
647 FindIDom<>(Block&: **DirtyPreds.begin(), BBs: DirtyPreds, Dom&: *MDT, Strict: false);
648
649 while (NewSave && (hasDirtyPred(ReachableByDirty, MBB: *NewSave) ||
650 EntryFreq < MBFI->getBlockFreq(MBB: NewSave) ||
651 /*Entry freq has been observed more than a loop block in
652 some cases*/
653 MLI->getLoopFor(BB: NewSave))) {
654 SmallVector<MachineBasicBlock*> ReachablePreds;
655 for (auto BB: NewSave->predecessors())
656 if (MDT->isReachableFromEntry(A: BB))
657 ReachablePreds.push_back(Elt: BB);
658 if (ReachablePreds.empty())
659 break;
660
661 NewSave = FindIDom<>(Block&: **ReachablePreds.begin(), BBs: ReachablePreds, Dom&: *MDT,
662 Strict: false);
663 }
664
665 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
666 if (!NewSave || NewSave == InitSave ||
667 isSaveReachableThroughClean(SavePoint: NewSave, CleanPreds) ||
668 !TFI->canUseAsPrologue(MBB: *NewSave))
669 return false;
670
671 // Now we know that splitting a restore point can isolate the restore point
672 // from clean blocks and doing so can shrink the save point.
673 MachineBasicBlock *NewRestore =
674 tryToSplitRestore(MBB: InitRestore, DirtyPreds, TII);
675
676 // Make sure if the new restore point is valid as an epilogue, depending on
677 // targets.
678 if (!TFI->canUseAsEpilogue(MBB: *NewRestore)) {
679 rollbackRestoreSplit(MF, NMBB: NewRestore, MBB: InitRestore, DirtyPreds, TII);
680 return false;
681 }
682
683 Save = NewSave;
684 Restore = NewRestore;
685
686 MDT->recalculate(Func&: MF);
687 MPDT->recalculate(Func&: MF);
688
689 assert((MDT->dominates(Save, Restore) && MPDT->dominates(Restore, Save)) &&
690 "Incorrect save or restore point due to dominance relations");
691 assert((!MLI->getLoopFor(Save) && !MLI->getLoopFor(Restore)) &&
692 "Unexpected save or restore point in a loop");
693 assert((EntryFreq >= MBFI->getBlockFreq(Save) &&
694 EntryFreq >= MBFI->getBlockFreq(Restore)) &&
695 "Incorrect save or restore point based on block frequency");
696 return true;
697}
698
699void ShrinkWrapImpl::updateSaveRestorePoints(MachineBasicBlock &MBB,
700 RegScavenger *RS) {
701 // Get rid of the easy cases first.
702 if (!Save)
703 Save = &MBB;
704 else
705 Save = MDT->findNearestCommonDominator(A: Save, B: &MBB);
706 assert(Save);
707
708 if (!Restore)
709 Restore = &MBB;
710 else if (MPDT->getNode(BB: &MBB)) // If the block is not in the post dom tree, it
711 // means the block never returns. If that's the
712 // case, we don't want to call
713 // `findNearestCommonDominator`, which will
714 // return `Restore`.
715 Restore = MPDT->findNearestCommonDominator(A: Restore, B: &MBB);
716 else
717 Restore = nullptr; // Abort, we can't find a restore point in this case.
718
719 // Make sure we would be able to insert the restore code before the
720 // terminator.
721 if (Restore == &MBB) {
722 for (const MachineInstr &Terminator : MBB.terminators()) {
723 if (!useOrDefCSROrFI(MI: Terminator, RS, /*StackAddressUsed=*/true))
724 continue;
725 // One of the terminator needs to happen before the restore point.
726 if (MBB.succ_empty()) {
727 Restore = nullptr; // Abort, we can't find a restore point in this case.
728 break;
729 }
730 // Look for a restore point that post-dominates all the successors.
731 // The immediate post-dominator is what we are looking for.
732 Restore = FindIDom<>(Block&: *Restore, BBs: Restore->successors(), Dom&: *MPDT);
733 break;
734 }
735 }
736
737 if (!Restore) {
738 LLVM_DEBUG(
739 dbgs() << "Restore point needs to be spanned on several blocks\n");
740 return;
741 }
742
743 // Make sure Save and Restore are suitable for shrink-wrapping:
744 // 1. all path from Save needs to lead to Restore before exiting.
745 // 2. all path to Restore needs to go through Save from Entry.
746 // We achieve that by making sure that:
747 // A. Save dominates Restore.
748 // B. Restore post-dominates Save.
749 // C. Save and Restore are in the same loop.
750 bool SaveDominatesRestore = false;
751 bool RestorePostDominatesSave = false;
752 while (Restore &&
753 (!(SaveDominatesRestore = MDT->dominates(A: Save, B: Restore)) ||
754 !(RestorePostDominatesSave = MPDT->dominates(A: Restore, B: Save)) ||
755 // Post-dominance is not enough in loops to ensure that all uses/defs
756 // are after the prologue and before the epilogue at runtime.
757 // E.g.,
758 // while(1) {
759 // Save
760 // Restore
761 // if (...)
762 // break;
763 // use/def CSRs
764 // }
765 // All the uses/defs of CSRs are dominated by Save and post-dominated
766 // by Restore. However, the CSRs uses are still reachable after
767 // Restore and before Save are executed.
768 //
769 // For now, just push the restore/save points outside of loops.
770 // FIXME: Refine the criteria to still find interesting cases
771 // for loops.
772 MLI->getLoopFor(BB: Save) || MLI->getLoopFor(BB: Restore))) {
773 // Fix (A).
774 if (!SaveDominatesRestore) {
775 Save = MDT->findNearestCommonDominator(A: Save, B: Restore);
776 continue;
777 }
778 // Fix (B).
779 if (!RestorePostDominatesSave)
780 Restore = MPDT->findNearestCommonDominator(A: Restore, B: Save);
781
782 // Fix (C).
783 if (Restore && (MLI->getLoopFor(BB: Save) || MLI->getLoopFor(BB: Restore))) {
784 if (MLI->getLoopDepth(BB: Save) > MLI->getLoopDepth(BB: Restore)) {
785 // Push Save outside of this loop if immediate dominator is different
786 // from save block. If immediate dominator is not different, bail out.
787 SmallVector<MachineBasicBlock *> Preds;
788 for (auto *PBB : Save->predecessors())
789 if (MDT->isReachableFromEntry(A: PBB))
790 Preds.push_back(Elt: PBB);
791 Save = FindIDom<>(Block&: *Save, BBs: Preds, Dom&: *MDT);
792 if (!Save)
793 break;
794 } else {
795 // If the loop does not exit, there is no point in looking
796 // for a post-dominator outside the loop.
797 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
798 MLI->getLoopFor(BB: Restore)->getExitingBlocks(ExitingBlocks&: ExitBlocks);
799 // Push Restore outside of this loop.
800 // Look for the immediate post-dominator of the loop exits.
801 MachineBasicBlock *IPdom = Restore;
802 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
803 IPdom = FindIDom<>(Block&: *IPdom, BBs: LoopExitBB->successors(), Dom&: *MPDT);
804 if (!IPdom)
805 break;
806 }
807 // If the immediate post-dominator is not in a less nested loop,
808 // then we are stuck in a program with an infinite loop.
809 // In that case, we will not find a safe point, hence, bail out.
810 if (IPdom && MLI->getLoopDepth(BB: IPdom) < MLI->getLoopDepth(BB: Restore))
811 Restore = IPdom;
812 else {
813 Restore = nullptr;
814 break;
815 }
816 }
817 }
818 }
819}
820
821static bool giveUpWithRemarks(MachineOptimizationRemarkEmitter *ORE,
822 StringRef RemarkName, StringRef RemarkMessage,
823 const DiagnosticLocation &Loc,
824 const MachineBasicBlock *MBB) {
825 ORE->emit(RemarkBuilder: [&]() {
826 return MachineOptimizationRemarkMissed(DEBUG_TYPE, RemarkName, Loc, MBB)
827 << RemarkMessage;
828 });
829
830 LLVM_DEBUG(dbgs() << RemarkMessage << '\n');
831 return false;
832}
833
834bool ShrinkWrapImpl::performShrinkWrapping(
835 const ReversePostOrderTraversal<MachineBasicBlock *> &RPOT,
836 RegScavenger *RS) {
837 for (MachineBasicBlock *MBB : RPOT) {
838 LLVM_DEBUG(dbgs() << "Look into: " << printMBBReference(*MBB) << '\n');
839
840 if (MBB->isEHFuncletEntry())
841 return giveUpWithRemarks(ORE, RemarkName: "UnsupportedEHFunclets",
842 RemarkMessage: "EH Funclets are not supported yet.",
843 Loc: MBB->front().getDebugLoc(), MBB);
844
845 if (MBB->isEHPad() || MBB->isInlineAsmBrIndirectTarget()) {
846 // Push the prologue and epilogue outside of the region that may throw (or
847 // jump out via inlineasm_br), by making sure that all the landing pads
848 // are at least at the boundary of the save and restore points. The
849 // problem is that a basic block can jump out from the middle in these
850 // cases, which we do not handle.
851 updateSaveRestorePoints(MBB&: *MBB, RS);
852 if (!ArePointsInteresting()) {
853 LLVM_DEBUG(dbgs() << "EHPad/inlineasm_br prevents shrink-wrapping\n");
854 return false;
855 }
856 continue;
857 }
858
859 bool StackAddressUsed = false;
860 // Check if we found any stack accesses in the predecessors. We are not
861 // doing a full dataflow analysis here to keep things simple but just
862 // rely on a reverse portorder traversal (RPOT) to guarantee predecessors
863 // are already processed except for loops (and accept the conservative
864 // result for loops).
865 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
866 if (StackAddressUsedBlockInfo.test(Idx: Pred->getNumber())) {
867 StackAddressUsed = true;
868 break;
869 }
870 }
871
872 for (const MachineInstr &MI : *MBB) {
873 if (useOrDefCSROrFI(MI, RS, StackAddressUsed)) {
874 // Save (resp. restore) point must dominate (resp. post dominate)
875 // MI. Look for the proper basic block for those.
876 updateSaveRestorePoints(MBB&: *MBB, RS);
877 // If we are at a point where we cannot improve the placement of
878 // save/restore instructions, just give up.
879 if (!ArePointsInteresting()) {
880 LLVM_DEBUG(dbgs() << "No Shrink wrap candidate found\n");
881 return false;
882 }
883 // No need to look for other instructions, this basic block
884 // will already be part of the handled region.
885 StackAddressUsed = true;
886 break;
887 }
888 }
889 StackAddressUsedBlockInfo[MBB->getNumber()] = StackAddressUsed;
890 }
891 if (!ArePointsInteresting()) {
892 // If the points are not interesting at this point, then they must be null
893 // because it means we did not encounter any frame/CSR related code.
894 // Otherwise, we would have returned from the previous loop.
895 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
896 LLVM_DEBUG(dbgs() << "Nothing to shrink-wrap\n");
897 return false;
898 }
899
900 LLVM_DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: "
901 << EntryFreq.getFrequency() << '\n');
902
903 const TargetFrameLowering *TFI =
904 MachineFunc->getSubtarget().getFrameLowering();
905 do {
906 LLVM_DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
907 << printMBBReference(*Save) << ' '
908 << printBlockFreq(*MBFI, *Save)
909 << "\nRestore: " << printMBBReference(*Restore) << ' '
910 << printBlockFreq(*MBFI, *Restore) << '\n');
911
912 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
913 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(MBB: Save)) &&
914 EntryFreq >= MBFI->getBlockFreq(MBB: Restore)) &&
915 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(MBB: *Save)) &&
916 TFI->canUseAsEpilogue(MBB: *Restore)))
917 break;
918 LLVM_DEBUG(
919 dbgs() << "New points are too expensive or invalid for the target\n");
920 MachineBasicBlock *NewBB;
921 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
922 Save = FindIDom<>(Block&: *Save, BBs: Save->predecessors(), Dom&: *MDT);
923 if (!Save)
924 break;
925 NewBB = Save;
926 } else {
927 // Restore is expensive.
928 Restore = FindIDom<>(Block&: *Restore, BBs: Restore->successors(), Dom&: *MPDT);
929 if (!Restore)
930 break;
931 NewBB = Restore;
932 }
933 updateSaveRestorePoints(MBB&: *NewBB, RS);
934 } while (Save && Restore);
935
936 if (!ArePointsInteresting()) {
937 ++NumCandidatesDropped;
938 return false;
939 }
940 return true;
941}
942
943bool ShrinkWrapImpl::run(MachineFunction &MF) {
944 LLVM_DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
945
946 init(MF);
947
948 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
949 if (containsIrreducibleCFG<MachineBasicBlock *>(RPOTraversal&: RPOT, LI: *MLI)) {
950 // If MF is irreducible, a block may be in a loop without
951 // MachineLoopInfo reporting it. I.e., we may use the
952 // post-dominance property in loops, which lead to incorrect
953 // results. Moreover, we may miss that the prologue and
954 // epilogue are not in the same loop, leading to unbalanced
955 // construction/deconstruction of the stack frame.
956 return giveUpWithRemarks(ORE, RemarkName: "UnsupportedIrreducibleCFG",
957 RemarkMessage: "Irreducible CFGs are not supported yet.",
958 Loc: MF.getFunction().getSubprogram(), MBB: &MF.front());
959 }
960
961 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
962 std::unique_ptr<RegScavenger> RS(
963 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
964
965 bool Changed = false;
966
967 // Initially, conservatively assume that stack addresses can be used in each
968 // basic block and change the state only for those basic blocks for which we
969 // were able to prove the opposite.
970 StackAddressUsedBlockInfo.resize(N: MF.getNumBlockIDs(), t: true);
971 bool HasCandidate = performShrinkWrapping(RPOT, RS: RS.get());
972 StackAddressUsedBlockInfo.clear();
973 Changed = postShrinkWrapping(HasCandidate, MF, RS: RS.get());
974 if (!HasCandidate && !Changed)
975 return false;
976 if (!ArePointsInteresting())
977 return Changed;
978
979 LLVM_DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: "
980 << printMBBReference(*Save) << ' '
981 << "\nRestore: " << printMBBReference(*Restore) << '\n');
982
983 MachineFrameInfo &MFI = MF.getFrameInfo();
984
985 // List of CalleeSavedInfo for registers will be added during prologepilog
986 // pass
987 SaveRestorePoints SavePoints({{Save, {}}});
988 SaveRestorePoints RestorePoints({{Restore, {}}});
989
990 MFI.setSavePoints(SavePoints);
991 MFI.setRestorePoints(RestorePoints);
992 ++NumCandidates;
993 return Changed;
994}
995
996bool ShrinkWrapLegacy::runOnMachineFunction(MachineFunction &MF) {
997 if (skipFunction(F: MF.getFunction()) || MF.empty() ||
998 !ShrinkWrapImpl::isShrinkWrapEnabled(MF))
999 return false;
1000
1001 MachineDominatorTree *MDT =
1002 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1003 MachinePostDominatorTree *MPDT =
1004 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
1005 MachineBlockFrequencyInfo *MBFI =
1006 &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
1007 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1008 MachineOptimizationRemarkEmitter *ORE =
1009 &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1010
1011 return ShrinkWrapImpl(MDT, MPDT, MBFI, MLI, ORE).run(MF);
1012}
1013
1014PreservedAnalyses ShrinkWrapPass::run(MachineFunction &MF,
1015 MachineFunctionAnalysisManager &MFAM) {
1016 MFPropsModifier _(*this, MF);
1017 if (MF.empty() || !ShrinkWrapImpl::isShrinkWrapEnabled(MF))
1018 return PreservedAnalyses::all();
1019
1020 MachineDominatorTree &MDT = MFAM.getResult<MachineDominatorTreeAnalysis>(IR&: MF);
1021 MachinePostDominatorTree &MPDT =
1022 MFAM.getResult<MachinePostDominatorTreeAnalysis>(IR&: MF);
1023 MachineBlockFrequencyInfo &MBFI =
1024 MFAM.getResult<MachineBlockFrequencyAnalysis>(IR&: MF);
1025 MachineLoopInfo &MLI = MFAM.getResult<MachineLoopAnalysis>(IR&: MF);
1026 MachineOptimizationRemarkEmitter &ORE =
1027 MFAM.getResult<MachineOptimizationRemarkEmitterAnalysis>(IR&: MF);
1028
1029 ShrinkWrapImpl(&MDT, &MPDT, &MBFI, &MLI, &ORE).run(MF);
1030 return PreservedAnalyses::all();
1031}
1032
1033bool ShrinkWrapImpl::isShrinkWrapEnabled(const MachineFunction &MF) {
1034 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1035
1036 switch (EnableShrinkWrapOpt) {
1037 case cl::boolOrDefault::BOU_UNSET:
1038 return TFI->enableShrinkWrapping(MF) &&
1039 // Windows with CFI has some limitations that make it impossible
1040 // to use shrink-wrapping.
1041 !MF.getTarget().getMCAsmInfo().usesWindowsCFI() &&
1042 // Sanitizers look at the value of the stack at the location
1043 // of the crash. Since a crash can happen anywhere, the
1044 // frame must be lowered before anything else happen for the
1045 // sanitizers to be able to get a correct stack frame.
1046 !(MF.getFunction().hasFnAttribute(Kind: Attribute::SanitizeAddress) ||
1047 MF.getFunction().hasFnAttribute(Kind: Attribute::SanitizeThread) ||
1048 MF.getFunction().hasFnAttribute(Kind: Attribute::SanitizeMemory) ||
1049 MF.getFunction().hasFnAttribute(Kind: Attribute::SanitizeType) ||
1050 MF.getFunction().hasFnAttribute(Kind: Attribute::SanitizeHWAddress));
1051 // If EnableShrinkWrap is set, it takes precedence on whatever the
1052 // target sets. The rational is that we assume we want to test
1053 // something related to shrink-wrapping.
1054 case cl::boolOrDefault::BOU_TRUE:
1055 return true;
1056 case cl::boolOrDefault::BOU_FALSE:
1057 return false;
1058 }
1059 llvm_unreachable("Invalid shrink-wrapping state");
1060}
1061