blob: c406c149c0071a5a8443f74c0f9f87b263ce02ab [file] [log] [blame]
Quentin Colombet61b305e2015-05-05 17:38:16 +00001//===-- 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 this properties, then
47// MachineFrameInfo is updated this that information.
48//===----------------------------------------------------------------------===//
49#include "llvm/ADT/Statistic.h"
50// To check for profitability.
51#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
52// For property #1 for Save.
53#include "llvm/CodeGen/MachineDominators.h"
54#include "llvm/CodeGen/MachineFunctionPass.h"
55// To record the result of the analysis.
56#include "llvm/CodeGen/MachineFrameInfo.h"
57// For property #2.
58#include "llvm/CodeGen/MachineLoopInfo.h"
59// For property #1 for Restore.
60#include "llvm/CodeGen/MachinePostDominators.h"
61#include "llvm/CodeGen/Passes.h"
62// To know about callee-saved.
63#include "llvm/CodeGen/RegisterClassInfo.h"
64#include "llvm/Support/Debug.h"
Quentin Colombet80835882015-05-27 06:25:48 +000065// To query the target about frame lowering.
66#include "llvm/Target/TargetFrameLowering.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000067// To know about frame setup operation.
68#include "llvm/Target/TargetInstrInfo.h"
69// To access TargetInstrInfo.
70#include "llvm/Target/TargetSubtargetInfo.h"
71
72#define DEBUG_TYPE "shrink-wrap"
73
74using namespace llvm;
75
76STATISTIC(NumFunc, "Number of functions");
77STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
78STATISTIC(NumCandidatesDropped,
79 "Number of shrink-wrapping candidates dropped because of frequency");
80
Kit Bartond3cc1672015-08-31 18:26:45 +000081static cl::opt<cl::boolOrDefault>
82 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
83 cl::desc("enable the shrink-wrapping pass"));
84
Quentin Colombet61b305e2015-05-05 17:38:16 +000085namespace {
86/// \brief Class to determine where the safe point to insert the
87/// prologue and epilogue are.
88/// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
89/// shrink-wrapping term for prologue/epilogue placement, this pass
90/// does not rely on expensive data-flow analysis. Instead we use the
91/// dominance properties and loop information to decide which point
92/// are safe for such insertion.
93class ShrinkWrap : public MachineFunctionPass {
94 /// Hold callee-saved information.
95 RegisterClassInfo RCI;
96 MachineDominatorTree *MDT;
97 MachinePostDominatorTree *MPDT;
98 /// Current safe point found for the prologue.
99 /// The prologue will be inserted before the first instruction
100 /// in this basic block.
101 MachineBasicBlock *Save;
102 /// Current safe point found for the epilogue.
103 /// The epilogue will be inserted before the first terminator instruction
104 /// in this basic block.
105 MachineBasicBlock *Restore;
106 /// Hold the information of the basic block frequency.
107 /// Use to check the profitability of the new points.
108 MachineBlockFrequencyInfo *MBFI;
109 /// Hold the loop information. Used to determine if Save and Restore
110 /// are in the same loop.
111 MachineLoopInfo *MLI;
112 /// Frequency of the Entry block.
113 uint64_t EntryFreq;
114 /// Current opcode for frame setup.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000115 unsigned FrameSetupOpcode;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000116 /// Current opcode for frame destroy.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000117 unsigned FrameDestroyOpcode;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000118 /// Entry block.
119 const MachineBasicBlock *Entry;
120
121 /// \brief Check if \p MI uses or defines a callee-saved register or
122 /// a frame index. If this is the case, this means \p MI must happen
123 /// after Save and before Restore.
124 bool useOrDefCSROrFI(const MachineInstr &MI) const;
125
126 /// \brief Update the Save and Restore points such that \p MBB is in
127 /// the region that is dominated by Save and post-dominated by Restore
128 /// and Save and Restore still match the safe point definition.
129 /// Such point may not exist and Save and/or Restore may be null after
130 /// this call.
131 void updateSaveRestorePoints(MachineBasicBlock &MBB);
132
133 /// \brief Initialize the pass for \p MF.
134 void init(MachineFunction &MF) {
135 RCI.runOnMachineFunction(MF);
136 MDT = &getAnalysis<MachineDominatorTree>();
137 MPDT = &getAnalysis<MachinePostDominatorTree>();
138 Save = nullptr;
139 Restore = nullptr;
140 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
141 MLI = &getAnalysis<MachineLoopInfo>();
142 EntryFreq = MBFI->getEntryFreq();
143 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
144 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
145 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
146 Entry = &MF.front();
147
148 ++NumFunc;
149 }
150
151 /// Check whether or not Save and Restore points are still interesting for
152 /// shrink-wrapping.
153 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
154
Kit Bartond3cc1672015-08-31 18:26:45 +0000155 /// \brief Check if shrink wrapping is enabled for this target and function.
156 static bool isShrinkWrapEnabled(const MachineFunction &MF);
157
Quentin Colombet61b305e2015-05-05 17:38:16 +0000158public:
159 static char ID;
160
161 ShrinkWrap() : MachineFunctionPass(ID) {
162 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
163 }
164
165 void getAnalysisUsage(AnalysisUsage &AU) const override {
166 AU.setPreservesAll();
167 AU.addRequired<MachineBlockFrequencyInfo>();
168 AU.addRequired<MachineDominatorTree>();
169 AU.addRequired<MachinePostDominatorTree>();
170 AU.addRequired<MachineLoopInfo>();
171 MachineFunctionPass::getAnalysisUsage(AU);
172 }
173
174 const char *getPassName() const override {
175 return "Shrink Wrapping analysis";
176 }
177
178 /// \brief Perform the shrink-wrapping analysis and update
179 /// the MachineFrameInfo attached to \p MF with the results.
180 bool runOnMachineFunction(MachineFunction &MF) override;
181};
182} // End anonymous namespace.
183
184char ShrinkWrap::ID = 0;
185char &llvm::ShrinkWrapID = ShrinkWrap::ID;
186
187INITIALIZE_PASS_BEGIN(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false,
188 false)
189INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
190INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
191INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
192INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
193INITIALIZE_PASS_END(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false, false)
194
195bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI) const {
196 if (MI.getOpcode() == FrameSetupOpcode ||
197 MI.getOpcode() == FrameDestroyOpcode) {
198 DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
199 return true;
200 }
201 for (const MachineOperand &MO : MI.operands()) {
202 bool UseCSR = false;
203 if (MO.isReg()) {
204 unsigned PhysReg = MO.getReg();
205 if (!PhysReg)
206 continue;
207 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
208 "Unallocated register?!");
209 UseCSR = RCI.getLastCalleeSavedAlias(PhysReg);
210 }
211 // TODO: Handle regmask more accurately.
212 // For now, be conservative about them.
213 if (UseCSR || MO.isFI() || MO.isRegMask()) {
214 DEBUG(dbgs() << "Use or define CSR(" << UseCSR << ") or FI(" << MO.isFI()
215 << "): " << MI << '\n');
216 return true;
217 }
218 }
219 return false;
220}
221
222/// \brief Helper function to find the immediate (post) dominator.
223template <typename ListOfBBs, typename DominanceAnalysis>
224MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
225 DominanceAnalysis &Dom) {
226 MachineBasicBlock *IDom = &Block;
227 for (MachineBasicBlock *BB : BBs) {
228 IDom = Dom.findNearestCommonDominator(IDom, BB);
229 if (!IDom)
230 break;
231 }
232 return IDom;
233}
234
235void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB) {
236 // Get rid of the easy cases first.
237 if (!Save)
238 Save = &MBB;
239 else
240 Save = MDT->findNearestCommonDominator(Save, &MBB);
241
242 if (!Save) {
243 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
244 return;
245 }
246
247 if (!Restore)
248 Restore = &MBB;
249 else
250 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
251
252 // Make sure we would be able to insert the restore code before the
253 // terminator.
254 if (Restore == &MBB) {
255 for (const MachineInstr &Terminator : MBB.terminators()) {
256 if (!useOrDefCSROrFI(Terminator))
257 continue;
258 // One of the terminator needs to happen before the restore point.
259 if (MBB.succ_empty()) {
260 Restore = nullptr;
261 break;
262 }
263 // Look for a restore point that post-dominates all the successors.
264 // The immediate post-dominator is what we are looking for.
265 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
266 break;
267 }
268 }
269
270 if (!Restore) {
271 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
272 return;
273 }
274
275 // Make sure Save and Restore are suitable for shrink-wrapping:
276 // 1. all path from Save needs to lead to Restore before exiting.
277 // 2. all path to Restore needs to go through Save from Entry.
278 // We achieve that by making sure that:
279 // A. Save dominates Restore.
280 // B. Restore post-dominates Save.
281 // C. Save and Restore are in the same loop.
282 bool SaveDominatesRestore = false;
283 bool RestorePostDominatesSave = false;
284 while (Save && Restore &&
285 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
286 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
287 MLI->getLoopFor(Save) != MLI->getLoopFor(Restore))) {
288 // Fix (A).
289 if (!SaveDominatesRestore) {
290 Save = MDT->findNearestCommonDominator(Save, Restore);
291 continue;
292 }
293 // Fix (B).
294 if (!RestorePostDominatesSave)
295 Restore = MPDT->findNearestCommonDominator(Restore, Save);
296
297 // Fix (C).
298 if (Save && Restore && Save != Restore &&
299 MLI->getLoopFor(Save) != MLI->getLoopFor(Restore)) {
Kit Bartona7bf96a2015-08-06 19:01:57 +0000300 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
301 // Push Save outside of this loop if immediate dominator is different
302 // from save block. If immediate dominator is not different, bail out.
303 MachineBasicBlock *IDom = FindIDom<>(*Save, Save->predecessors(), *MDT);
304 if (IDom != Save)
305 Save = IDom;
306 else {
307 Save = nullptr;
308 break;
309 }
310 }
311 else {
Quentin Colombetdc29c972015-09-15 18:19:39 +0000312 // If the loop does not exit, there is no point in looking
313 // for a post-dominator outside the loop.
314 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
315 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
316 if (ExitBlocks.empty()) {
317 Restore = nullptr;
318 break;
319 }
Kit Bartona7bf96a2015-08-06 19:01:57 +0000320 // Push Restore outside of this loop if immediate post-dominator is
321 // different from restore block. If immediate post-dominator is not
322 // different, bail out.
323 MachineBasicBlock *IPdom =
324 FindIDom<>(*Restore, Restore->successors(), *MPDT);
325 if (IPdom != Restore)
326 Restore = IPdom;
327 else {
328 Restore = nullptr;
329 break;
330 }
331 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000332 }
333 }
334}
335
336bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
Kit Bartond3cc1672015-08-31 18:26:45 +0000337 if (MF.empty() || !isShrinkWrapEnabled(MF))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000338 return false;
Kit Bartond3cc1672015-08-31 18:26:45 +0000339
Quentin Colombet61b305e2015-05-05 17:38:16 +0000340 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
341
342 init(MF);
343
344 for (MachineBasicBlock &MBB : MF) {
345 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
346 << '\n');
347
348 for (const MachineInstr &MI : MBB) {
349 if (!useOrDefCSROrFI(MI))
350 continue;
351 // Save (resp. restore) point must dominate (resp. post dominate)
352 // MI. Look for the proper basic block for those.
353 updateSaveRestorePoints(MBB);
354 // If we are at a point where we cannot improve the placement of
355 // save/restore instructions, just give up.
356 if (!ArePointsInteresting()) {
357 DEBUG(dbgs() << "No Shrink wrap candidate found\n");
358 return false;
359 }
360 // No need to look for other instructions, this basic block
361 // will already be part of the handled region.
362 break;
363 }
364 }
365 if (!ArePointsInteresting()) {
366 // If the points are not interesting at this point, then they must be null
367 // because it means we did not encounter any frame/CSR related code.
368 // Otherwise, we would have returned from the previous loop.
369 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
370 DEBUG(dbgs() << "Nothing to shrink-wrap\n");
371 return false;
372 }
373
374 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
375 << '\n');
376
Quentin Colombet80835882015-05-27 06:25:48 +0000377 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000378 do {
379 DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
380 << Save->getNumber() << ' ' << Save->getName() << ' '
381 << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: "
382 << Restore->getNumber() << ' ' << Restore->getName() << ' '
383 << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
384
Quentin Colombet80835882015-05-27 06:25:48 +0000385 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
386 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
387 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
388 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
389 TFI->canUseAsEpilogue(*Restore)))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000390 break;
Quentin Colombet80835882015-05-27 06:25:48 +0000391 DEBUG(dbgs() << "New points are too expensive or invalid for the target\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000392 MachineBasicBlock *NewBB;
Quentin Colombet80835882015-05-27 06:25:48 +0000393 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000394 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
395 if (!Save)
396 break;
397 NewBB = Save;
398 } else {
399 // Restore is expensive.
400 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
401 if (!Restore)
402 break;
403 NewBB = Restore;
404 }
405 updateSaveRestorePoints(*NewBB);
406 } while (Save && Restore);
407
408 if (!ArePointsInteresting()) {
409 ++NumCandidatesDropped;
410 return false;
411 }
412
413 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
414 << ' ' << Save->getName() << "\nRestore: "
415 << Restore->getNumber() << ' ' << Restore->getName() << '\n');
416
417 MachineFrameInfo *MFI = MF.getFrameInfo();
418 MFI->setSavePoint(Save);
419 MFI->setRestorePoint(Restore);
420 ++NumCandidates;
421 return false;
422}
Kit Bartond3cc1672015-08-31 18:26:45 +0000423
424bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
425 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
426
427 switch (EnableShrinkWrapOpt) {
428 case cl::BOU_UNSET:
429 return TFI->enableShrinkWrapping(MF);
430 // If EnableShrinkWrap is set, it takes precedence on whatever the
431 // target sets. The rational is that we assume we want to test
432 // something related to shrink-wrapping.
433 case cl::BOU_TRUE:
434 return true;
435 case cl::BOU_FALSE:
436 return false;
437 }
438 llvm_unreachable("Invalid shrink-wrapping state");
439}