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   StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
223 
224   /// \brief Perform the shrink-wrapping analysis and update
225   /// the MachineFrameInfo attached to \p MF with the results.
226   bool runOnMachineFunction(MachineFunction &MF) override;
227 };
228 
229 } // end anonymous namespace
230 
231 char ShrinkWrap::ID = 0;
232 
233 char &llvm::ShrinkWrapID = ShrinkWrap::ID;
234 
235 INITIALIZE_PASS_BEGIN(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
236 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
237 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
238 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
239 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
240 INITIALIZE_PASS_END(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
241 
242 bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI,
243                                  RegScavenger *RS) const {
244   if (MI.getOpcode() == FrameSetupOpcode ||
245       MI.getOpcode() == FrameDestroyOpcode) {
246     DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
247     return true;
248   }
249   for (const MachineOperand &MO : MI.operands()) {
250     bool UseOrDefCSR = false;
251     if (MO.isReg()) {
252       // Ignore instructions like DBG_VALUE which don't read/def the register.
253       if (!MO.isDef() && !MO.readsReg())
254         continue;
255       unsigned PhysReg = MO.getReg();
256       if (!PhysReg)
257         continue;
258       assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
259              "Unallocated register?!");
260       UseOrDefCSR = RCI.getLastCalleeSavedAlias(PhysReg);
261     } else if (MO.isRegMask()) {
262       // Check if this regmask clobbers any of the CSRs.
263       for (unsigned Reg : getCurrentCSRs(RS)) {
264         if (MO.clobbersPhysReg(Reg)) {
265           UseOrDefCSR = true;
266           break;
267         }
268       }
269     }
270     // Skip FrameIndex operands in DBG_VALUE instructions.
271     if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) {
272       DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
273                    << MO.isFI() << "): " << MI << '\n');
274       return true;
275     }
276   }
277   return false;
278 }
279 
280 /// \brief Helper function to find the immediate (post) dominator.
281 template <typename ListOfBBs, typename DominanceAnalysis>
282 static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
283                                    DominanceAnalysis &Dom) {
284   MachineBasicBlock *IDom = &Block;
285   for (MachineBasicBlock *BB : BBs) {
286     IDom = Dom.findNearestCommonDominator(IDom, BB);
287     if (!IDom)
288       break;
289   }
290   if (IDom == &Block)
291     return nullptr;
292   return IDom;
293 }
294 
295 void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB,
296                                          RegScavenger *RS) {
297   // Get rid of the easy cases first.
298   if (!Save)
299     Save = &MBB;
300   else
301     Save = MDT->findNearestCommonDominator(Save, &MBB);
302 
303   if (!Save) {
304     DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
305     return;
306   }
307 
308   if (!Restore)
309     Restore = &MBB;
310   else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it
311                                 // means the block never returns. If that's the
312                                 // case, we don't want to call
313                                 // `findNearestCommonDominator`, which will
314                                 // return `Restore`.
315     Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
316   else
317     Restore = nullptr; // Abort, we can't find a restore point in this case.
318 
319   // Make sure we would be able to insert the restore code before the
320   // terminator.
321   if (Restore == &MBB) {
322     for (const MachineInstr &Terminator : MBB.terminators()) {
323       if (!useOrDefCSROrFI(Terminator, RS))
324         continue;
325       // One of the terminator needs to happen before the restore point.
326       if (MBB.succ_empty()) {
327         Restore = nullptr; // Abort, we can't find a restore point in this case.
328         break;
329       }
330       // Look for a restore point that post-dominates all the successors.
331       // The immediate post-dominator is what we are looking for.
332       Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
333       break;
334     }
335   }
336 
337   if (!Restore) {
338     DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
339     return;
340   }
341 
342   // Make sure Save and Restore are suitable for shrink-wrapping:
343   // 1. all path from Save needs to lead to Restore before exiting.
344   // 2. all path to Restore needs to go through Save from Entry.
345   // We achieve that by making sure that:
346   // A. Save dominates Restore.
347   // B. Restore post-dominates Save.
348   // C. Save and Restore are in the same loop.
349   bool SaveDominatesRestore = false;
350   bool RestorePostDominatesSave = false;
351   while (Save && Restore &&
352          (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
353           !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
354           // Post-dominance is not enough in loops to ensure that all uses/defs
355           // are after the prologue and before the epilogue at runtime.
356           // E.g.,
357           // while(1) {
358           //  Save
359           //  Restore
360           //   if (...)
361           //     break;
362           //  use/def CSRs
363           // }
364           // All the uses/defs of CSRs are dominated by Save and post-dominated
365           // by Restore. However, the CSRs uses are still reachable after
366           // Restore and before Save are executed.
367           //
368           // For now, just push the restore/save points outside of loops.
369           // FIXME: Refine the criteria to still find interesting cases
370           // for loops.
371           MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
372     // Fix (A).
373     if (!SaveDominatesRestore) {
374       Save = MDT->findNearestCommonDominator(Save, Restore);
375       continue;
376     }
377     // Fix (B).
378     if (!RestorePostDominatesSave)
379       Restore = MPDT->findNearestCommonDominator(Restore, Save);
380 
381     // Fix (C).
382     if (Save && Restore &&
383         (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
384       if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
385         // Push Save outside of this loop if immediate dominator is different
386         // from save block. If immediate dominator is not different, bail out.
387         Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
388         if (!Save)
389           break;
390       } else {
391         // If the loop does not exit, there is no point in looking
392         // for a post-dominator outside the loop.
393         SmallVector<MachineBasicBlock*, 4> ExitBlocks;
394         MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
395         // Push Restore outside of this loop.
396         // Look for the immediate post-dominator of the loop exits.
397         MachineBasicBlock *IPdom = Restore;
398         for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
399           IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
400           if (!IPdom)
401             break;
402         }
403         // If the immediate post-dominator is not in a less nested loop,
404         // then we are stuck in a program with an infinite loop.
405         // In that case, we will not find a safe point, hence, bail out.
406         if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
407           Restore = IPdom;
408         else {
409           Restore = nullptr;
410           break;
411         }
412       }
413     }
414   }
415 }
416 
417 bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
418   if (skipFunction(MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF))
419     return false;
420 
421   DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
422 
423   init(MF);
424 
425   ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
426   if (containsIrreducibleCFG<MachineBasicBlock *>(RPOT, *MLI)) {
427     // If MF is irreducible, a block may be in a loop without
428     // MachineLoopInfo reporting it. I.e., we may use the
429     // post-dominance property in loops, which lead to incorrect
430     // results. Moreover, we may miss that the prologue and
431     // epilogue are not in the same loop, leading to unbalanced
432     // construction/deconstruction of the stack frame.
433     DEBUG(dbgs() << "Irreducible CFGs are not supported yet\n");
434     return false;
435   }
436 
437   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
438   std::unique_ptr<RegScavenger> RS(
439       TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
440 
441   for (MachineBasicBlock &MBB : MF) {
442     DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
443                  << '\n');
444 
445     if (MBB.isEHFuncletEntry()) {
446       DEBUG(dbgs() << "EH Funclets are not supported yet.\n");
447       return false;
448     }
449 
450     for (const MachineInstr &MI : MBB) {
451       if (!useOrDefCSROrFI(MI, RS.get()))
452         continue;
453       // Save (resp. restore) point must dominate (resp. post dominate)
454       // MI. Look for the proper basic block for those.
455       updateSaveRestorePoints(MBB, RS.get());
456       // If we are at a point where we cannot improve the placement of
457       // save/restore instructions, just give up.
458       if (!ArePointsInteresting()) {
459         DEBUG(dbgs() << "No Shrink wrap candidate found\n");
460         return false;
461       }
462       // No need to look for other instructions, this basic block
463       // will already be part of the handled region.
464       break;
465     }
466   }
467   if (!ArePointsInteresting()) {
468     // If the points are not interesting at this point, then they must be null
469     // because it means we did not encounter any frame/CSR related code.
470     // Otherwise, we would have returned from the previous loop.
471     assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
472     DEBUG(dbgs() << "Nothing to shrink-wrap\n");
473     return false;
474   }
475 
476   DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
477                << '\n');
478 
479   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
480   do {
481     DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
482                  << Save->getNumber() << ' ' << Save->getName() << ' '
483                  << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: "
484                  << Restore->getNumber() << ' ' << Restore->getName() << ' '
485                  << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
486 
487     bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
488     if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
489          EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
490         ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
491          TFI->canUseAsEpilogue(*Restore)))
492       break;
493     DEBUG(dbgs() << "New points are too expensive or invalid for the target\n");
494     MachineBasicBlock *NewBB;
495     if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
496       Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
497       if (!Save)
498         break;
499       NewBB = Save;
500     } else {
501       // Restore is expensive.
502       Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
503       if (!Restore)
504         break;
505       NewBB = Restore;
506     }
507     updateSaveRestorePoints(*NewBB, RS.get());
508   } while (Save && Restore);
509 
510   if (!ArePointsInteresting()) {
511     ++NumCandidatesDropped;
512     return false;
513   }
514 
515   DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
516                << ' ' << Save->getName() << "\nRestore: "
517                << Restore->getNumber() << ' ' << Restore->getName() << '\n');
518 
519   MachineFrameInfo &MFI = MF.getFrameInfo();
520   MFI.setSavePoint(Save);
521   MFI.setRestorePoint(Restore);
522   ++NumCandidates;
523   return false;
524 }
525 
526 bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
527   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
528 
529   switch (EnableShrinkWrapOpt) {
530   case cl::BOU_UNSET:
531     return TFI->enableShrinkWrapping(MF) &&
532            // Windows with CFI has some limitations that make it impossible
533            // to use shrink-wrapping.
534            !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
535            // Sanitizers look at the value of the stack at the location
536            // of the crash. Since a crash can happen anywhere, the
537            // frame must be lowered before anything else happen for the
538            // sanitizers to be able to get a correct stack frame.
539            !(MF.getFunction().hasFnAttribute(Attribute::SanitizeAddress) ||
540              MF.getFunction().hasFnAttribute(Attribute::SanitizeThread) ||
541              MF.getFunction().hasFnAttribute(Attribute::SanitizeMemory) ||
542              MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress));
543   // If EnableShrinkWrap is set, it takes precedence on whatever the
544   // target sets. The rational is that we assume we want to test
545   // something related to shrink-wrapping.
546   case cl::BOU_TRUE:
547     return true;
548   case cl::BOU_FALSE:
549     return false;
550   }
551   llvm_unreachable("Invalid shrink-wrapping state");
552 }
553