blob: 3230aff5ed82cf3d3c1d7de1b345dbbad1d616de [file] [log] [blame]
Eugene Zelenko149178d2017-10-10 22:33:29 +00001//===- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ----===//
Quentin Colombet61b305e2015-05-05 17:38:16 +00002//
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//
Quentin Colombet9a8efc02015-11-06 21:00:13 +000046// If this pass found points matching all these properties, then
Chad Rosiera1080102015-12-22 15:06:47 +000047// MachineFrameInfo is updated with this information.
Eugene Zelenko149178d2017-10-10 22:33:29 +000048//
Quentin Colombet61b305e2015-05-05 17:38:16 +000049//===----------------------------------------------------------------------===//
Eugene Zelenko149178d2017-10-10 22:33:29 +000050
Quentin Colombet9a8efc02015-11-06 21:00:13 +000051#include "llvm/ADT/BitVector.h"
Quentin Colombet9ed52e92016-01-07 01:23:49 +000052#include "llvm/ADT/PostOrderIterator.h"
Quentin Colombet9a8efc02015-11-06 21:00:13 +000053#include "llvm/ADT/SetVector.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000054#include "llvm/ADT/SmallVector.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000055#include "llvm/ADT/Statistic.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000056#include "llvm/CodeGen/MachineBasicBlock.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000057#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000058#include "llvm/CodeGen/MachineDominators.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000059#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000060#include "llvm/CodeGen/MachineFunction.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000061#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000062#include "llvm/CodeGen/MachineInstr.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000063#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000064#include "llvm/CodeGen/MachineOperand.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000065#include "llvm/CodeGen/MachinePostDominators.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000066#include "llvm/CodeGen/RegisterClassInfo.h"
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +000067#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000068#include "llvm/CodeGen/TargetFrameLowering.h"
69#include "llvm/CodeGen/TargetInstrInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000070#include "llvm/IR/Attributes.h"
71#include "llvm/IR/Function.h"
Quentin Colombet94dc1e02015-11-12 18:13:42 +000072#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000073#include "llvm/Pass.h"
74#include "llvm/Support/CommandLine.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000075#include "llvm/Support/Debug.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000076#include "llvm/Support/ErrorHandling.h"
77#include "llvm/Support/raw_ostream.h"
Quentin Colombet94dc1e02015-11-12 18:13:42 +000078#include "llvm/Target/TargetMachine.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000079#include "llvm/Target/TargetRegisterInfo.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000080#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000081#include <cassert>
82#include <cstdint>
83#include <memory>
Quentin Colombet61b305e2015-05-05 17:38:16 +000084
85using namespace llvm;
86
Eugene Zelenko149178d2017-10-10 22:33:29 +000087#define DEBUG_TYPE "shrink-wrap"
88
Quentin Colombet61b305e2015-05-05 17:38:16 +000089STATISTIC(NumFunc, "Number of functions");
90STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
91STATISTIC(NumCandidatesDropped,
92 "Number of shrink-wrapping candidates dropped because of frequency");
93
Kit Bartond3cc1672015-08-31 18:26:45 +000094static cl::opt<cl::boolOrDefault>
Eugene Zelenko149178d2017-10-10 22:33:29 +000095EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
96 cl::desc("enable the shrink-wrapping pass"));
Kit Bartond3cc1672015-08-31 18:26:45 +000097
Quentin Colombet61b305e2015-05-05 17:38:16 +000098namespace {
Eugene Zelenko149178d2017-10-10 22:33:29 +000099
Quentin Colombet61b305e2015-05-05 17:38:16 +0000100/// \brief Class to determine where the safe point to insert the
101/// prologue and epilogue are.
102/// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
103/// shrink-wrapping term for prologue/epilogue placement, this pass
104/// does not rely on expensive data-flow analysis. Instead we use the
105/// dominance properties and loop information to decide which point
106/// are safe for such insertion.
107class ShrinkWrap : public MachineFunctionPass {
108 /// Hold callee-saved information.
109 RegisterClassInfo RCI;
110 MachineDominatorTree *MDT;
111 MachinePostDominatorTree *MPDT;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000112
Quentin Colombet61b305e2015-05-05 17:38:16 +0000113 /// Current safe point found for the prologue.
114 /// The prologue will be inserted before the first instruction
115 /// in this basic block.
116 MachineBasicBlock *Save;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000117
Quentin Colombet61b305e2015-05-05 17:38:16 +0000118 /// Current safe point found for the epilogue.
119 /// The epilogue will be inserted before the first terminator instruction
120 /// in this basic block.
121 MachineBasicBlock *Restore;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000122
Quentin Colombet61b305e2015-05-05 17:38:16 +0000123 /// Hold the information of the basic block frequency.
124 /// Use to check the profitability of the new points.
125 MachineBlockFrequencyInfo *MBFI;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000126
Quentin Colombet61b305e2015-05-05 17:38:16 +0000127 /// Hold the loop information. Used to determine if Save and Restore
128 /// are in the same loop.
129 MachineLoopInfo *MLI;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000130
Quentin Colombet61b305e2015-05-05 17:38:16 +0000131 /// Frequency of the Entry block.
132 uint64_t EntryFreq;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000133
Quentin Colombet61b305e2015-05-05 17:38:16 +0000134 /// Current opcode for frame setup.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000135 unsigned FrameSetupOpcode;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000136
Quentin Colombet61b305e2015-05-05 17:38:16 +0000137 /// Current opcode for frame destroy.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000138 unsigned FrameDestroyOpcode;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000139
Quentin Colombet61b305e2015-05-05 17:38:16 +0000140 /// Entry block.
141 const MachineBasicBlock *Entry;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000142
143 using SetOfRegs = SmallSetVector<unsigned, 16>;
144
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000145 /// Registers that need to be saved for the current function.
146 mutable SetOfRegs CurrentCSRs;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000147
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000148 /// Current MachineFunction.
149 MachineFunction *MachineFunc;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000150
151 /// \brief Check if \p MI uses or defines a callee-saved register or
152 /// a frame index. If this is the case, this means \p MI must happen
153 /// after Save and before Restore.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000154 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS) const;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000155
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000156 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000157 if (CurrentCSRs.empty()) {
158 BitVector SavedRegs;
159 const TargetFrameLowering *TFI =
160 MachineFunc->getSubtarget().getFrameLowering();
161
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000162 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS);
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000163
164 for (int Reg = SavedRegs.find_first(); Reg != -1;
165 Reg = SavedRegs.find_next(Reg))
166 CurrentCSRs.insert((unsigned)Reg);
167 }
168 return CurrentCSRs;
169 }
170
Quentin Colombet61b305e2015-05-05 17:38:16 +0000171 /// \brief Update the Save and Restore points such that \p MBB is in
172 /// the region that is dominated by Save and post-dominated by Restore
173 /// and Save and Restore still match the safe point definition.
174 /// Such point may not exist and Save and/or Restore may be null after
175 /// this call.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000176 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
Quentin Colombet61b305e2015-05-05 17:38:16 +0000177
178 /// \brief Initialize the pass for \p MF.
179 void init(MachineFunction &MF) {
180 RCI.runOnMachineFunction(MF);
181 MDT = &getAnalysis<MachineDominatorTree>();
182 MPDT = &getAnalysis<MachinePostDominatorTree>();
183 Save = nullptr;
184 Restore = nullptr;
185 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
186 MLI = &getAnalysis<MachineLoopInfo>();
187 EntryFreq = MBFI->getEntryFreq();
188 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
189 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
190 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
191 Entry = &MF.front();
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000192 CurrentCSRs.clear();
193 MachineFunc = &MF;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000194
195 ++NumFunc;
196 }
197
198 /// Check whether or not Save and Restore points are still interesting for
199 /// shrink-wrapping.
200 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
201
Kit Bartond3cc1672015-08-31 18:26:45 +0000202 /// \brief Check if shrink wrapping is enabled for this target and function.
203 static bool isShrinkWrapEnabled(const MachineFunction &MF);
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000204
Quentin Colombet61b305e2015-05-05 17:38:16 +0000205public:
206 static char ID;
207
208 ShrinkWrap() : MachineFunctionPass(ID) {
209 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
210 }
211
212 void getAnalysisUsage(AnalysisUsage &AU) const override {
213 AU.setPreservesAll();
214 AU.addRequired<MachineBlockFrequencyInfo>();
215 AU.addRequired<MachineDominatorTree>();
216 AU.addRequired<MachinePostDominatorTree>();
217 AU.addRequired<MachineLoopInfo>();
218 MachineFunctionPass::getAnalysisUsage(AU);
219 }
220
Mehdi Amini117296c2016-10-01 02:56:57 +0000221 StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000222
223 /// \brief Perform the shrink-wrapping analysis and update
224 /// the MachineFrameInfo attached to \p MF with the results.
225 bool runOnMachineFunction(MachineFunction &MF) override;
226};
Eugene Zelenko149178d2017-10-10 22:33:29 +0000227
228} // end anonymous namespace
Quentin Colombet61b305e2015-05-05 17:38:16 +0000229
230char ShrinkWrap::ID = 0;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000231
Quentin Colombet61b305e2015-05-05 17:38:16 +0000232char &llvm::ShrinkWrapID = ShrinkWrap::ID;
233
Matthias Braun1527baa2017-05-25 21:26:32 +0000234INITIALIZE_PASS_BEGIN(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet61b305e2015-05-05 17:38:16 +0000235INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
236INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
237INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
238INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +0000239INITIALIZE_PASS_END(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet61b305e2015-05-05 17:38:16 +0000240
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000241bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI,
242 RegScavenger *RS) const {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000243 if (MI.getOpcode() == FrameSetupOpcode ||
244 MI.getOpcode() == FrameDestroyOpcode) {
245 DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
246 return true;
247 }
248 for (const MachineOperand &MO : MI.operands()) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000249 bool UseOrDefCSR = false;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000250 if (MO.isReg()) {
251 unsigned PhysReg = MO.getReg();
252 if (!PhysReg)
253 continue;
254 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
255 "Unallocated register?!");
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000256 UseOrDefCSR = RCI.getLastCalleeSavedAlias(PhysReg);
257 } else if (MO.isRegMask()) {
258 // Check if this regmask clobbers any of the CSRs.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000259 for (unsigned Reg : getCurrentCSRs(RS)) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000260 if (MO.clobbersPhysReg(Reg)) {
261 UseOrDefCSR = true;
262 break;
263 }
264 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000265 }
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000266 if (UseOrDefCSR || MO.isFI()) {
267 DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
268 << MO.isFI() << "): " << MI << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000269 return true;
270 }
271 }
272 return false;
273}
274
275/// \brief Helper function to find the immediate (post) dominator.
276template <typename ListOfBBs, typename DominanceAnalysis>
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000277static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
278 DominanceAnalysis &Dom) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000279 MachineBasicBlock *IDom = &Block;
280 for (MachineBasicBlock *BB : BBs) {
281 IDom = Dom.findNearestCommonDominator(IDom, BB);
282 if (!IDom)
283 break;
284 }
Michael Kuperstein037c9982016-01-06 18:40:11 +0000285 if (IDom == &Block)
286 return nullptr;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000287 return IDom;
288}
289
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000290void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB,
291 RegScavenger *RS) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000292 // Get rid of the easy cases first.
293 if (!Save)
294 Save = &MBB;
295 else
296 Save = MDT->findNearestCommonDominator(Save, &MBB);
297
298 if (!Save) {
299 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
300 return;
301 }
302
303 if (!Restore)
304 Restore = &MBB;
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000305 else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it
306 // means the block never returns. If that's the
307 // case, we don't want to call
308 // `findNearestCommonDominator`, which will
309 // return `Restore`.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000310 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000311 else
312 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000313
314 // Make sure we would be able to insert the restore code before the
315 // terminator.
316 if (Restore == &MBB) {
317 for (const MachineInstr &Terminator : MBB.terminators()) {
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000318 if (!useOrDefCSROrFI(Terminator, RS))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000319 continue;
320 // One of the terminator needs to happen before the restore point.
321 if (MBB.succ_empty()) {
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000322 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000323 break;
324 }
325 // Look for a restore point that post-dominates all the successors.
326 // The immediate post-dominator is what we are looking for.
327 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
328 break;
329 }
330 }
331
332 if (!Restore) {
333 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
334 return;
335 }
336
337 // Make sure Save and Restore are suitable for shrink-wrapping:
338 // 1. all path from Save needs to lead to Restore before exiting.
339 // 2. all path to Restore needs to go through Save from Entry.
340 // We achieve that by making sure that:
341 // A. Save dominates Restore.
342 // B. Restore post-dominates Save.
343 // C. Save and Restore are in the same loop.
344 bool SaveDominatesRestore = false;
345 bool RestorePostDominatesSave = false;
346 while (Save && Restore &&
347 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
348 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
Quentin Colombetb82786e2015-12-15 03:28:11 +0000349 // Post-dominance is not enough in loops to ensure that all uses/defs
350 // are after the prologue and before the epilogue at runtime.
351 // E.g.,
352 // while(1) {
353 // Save
354 // Restore
355 // if (...)
356 // break;
357 // use/def CSRs
358 // }
359 // All the uses/defs of CSRs are dominated by Save and post-dominated
360 // by Restore. However, the CSRs uses are still reachable after
361 // Restore and before Save are executed.
362 //
363 // For now, just push the restore/save points outside of loops.
364 // FIXME: Refine the criteria to still find interesting cases
365 // for loops.
366 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000367 // Fix (A).
368 if (!SaveDominatesRestore) {
369 Save = MDT->findNearestCommonDominator(Save, Restore);
370 continue;
371 }
372 // Fix (B).
373 if (!RestorePostDominatesSave)
374 Restore = MPDT->findNearestCommonDominator(Restore, Save);
375
376 // Fix (C).
Quentin Colombetb82786e2015-12-15 03:28:11 +0000377 if (Save && Restore &&
378 (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Kit Bartona7bf96a2015-08-06 19:01:57 +0000379 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
380 // Push Save outside of this loop if immediate dominator is different
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000381 // from save block. If immediate dominator is not different, bail out.
Michael Kuperstein037c9982016-01-06 18:40:11 +0000382 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
383 if (!Save)
Kit Bartona7bf96a2015-08-06 19:01:57 +0000384 break;
Quentin Colombetb82786e2015-12-15 03:28:11 +0000385 } else {
Quentin Colombetdc29c972015-09-15 18:19:39 +0000386 // If the loop does not exit, there is no point in looking
387 // for a post-dominator outside the loop.
388 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
389 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
Quentin Colombetb4c68862015-09-17 23:21:34 +0000390 // Push Restore outside of this loop.
391 // Look for the immediate post-dominator of the loop exits.
392 MachineBasicBlock *IPdom = Restore;
393 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
394 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
395 if (!IPdom)
396 break;
Quentin Colombetdc29c972015-09-15 18:19:39 +0000397 }
Quentin Colombetb4c68862015-09-17 23:21:34 +0000398 // If the immediate post-dominator is not in a less nested loop,
399 // then we are stuck in a program with an infinite loop.
400 // In that case, we will not find a safe point, hence, bail out.
401 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000402 Restore = IPdom;
Kit Bartona7bf96a2015-08-06 19:01:57 +0000403 else {
404 Restore = nullptr;
405 break;
406 }
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000407 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000408 }
409 }
410}
411
Quentin Colombet9ed52e92016-01-07 01:23:49 +0000412/// Check whether the edge (\p SrcBB, \p DestBB) is a backedge according to MLI.
413/// I.e., check if it exists a loop that contains SrcBB and where DestBB is the
414/// loop header.
415static bool isProperBackedge(const MachineLoopInfo &MLI,
416 const MachineBasicBlock *SrcBB,
417 const MachineBasicBlock *DestBB) {
418 for (const MachineLoop *Loop = MLI.getLoopFor(SrcBB); Loop;
419 Loop = Loop->getParentLoop()) {
420 if (Loop->getHeader() == DestBB)
421 return true;
422 }
423 return false;
424}
425
426/// Check if the CFG of \p MF is irreducible.
427static bool isIrreducibleCFG(const MachineFunction &MF,
428 const MachineLoopInfo &MLI) {
429 const MachineBasicBlock *Entry = &*MF.begin();
430 ReversePostOrderTraversal<const MachineBasicBlock *> RPOT(Entry);
431 BitVector VisitedBB(MF.getNumBlockIDs());
432 for (const MachineBasicBlock *MBB : RPOT) {
433 VisitedBB.set(MBB->getNumber());
434 for (const MachineBasicBlock *SuccBB : MBB->successors()) {
435 if (!VisitedBB.test(SuccBB->getNumber()))
436 continue;
437 // We already visited SuccBB, thus MBB->SuccBB must be a backedge.
438 // Check that the head matches what we have in the loop information.
439 // Otherwise, we have an irreducible graph.
440 if (!isProperBackedge(MLI, MBB, SuccBB))
441 return true;
442 }
443 }
444 return false;
445}
446
Quentin Colombet61b305e2015-05-05 17:38:16 +0000447bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
Matthias Braund625bed2017-05-16 18:43:30 +0000448 if (skipFunction(*MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000449 return false;
Kit Bartond3cc1672015-08-31 18:26:45 +0000450
Quentin Colombet61b305e2015-05-05 17:38:16 +0000451 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
452
453 init(MF);
454
Quentin Colombet9ed52e92016-01-07 01:23:49 +0000455 if (isIrreducibleCFG(MF, *MLI)) {
456 // If MF is irreducible, a block may be in a loop without
457 // MachineLoopInfo reporting it. I.e., we may use the
458 // post-dominance property in loops, which lead to incorrect
459 // results. Moreover, we may miss that the prologue and
460 // epilogue are not in the same loop, leading to unbalanced
461 // construction/deconstruction of the stack frame.
462 DEBUG(dbgs() << "Irreducible CFGs are not supported yet\n");
463 return false;
464 }
465
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000466 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
467 std::unique_ptr<RegScavenger> RS(
468 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
469
Quentin Colombet61b305e2015-05-05 17:38:16 +0000470 for (MachineBasicBlock &MBB : MF) {
471 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
472 << '\n');
473
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000474 if (MBB.isEHFuncletEntry()) {
475 DEBUG(dbgs() << "EH Funclets are not supported yet.\n");
476 return false;
477 }
478
Quentin Colombet61b305e2015-05-05 17:38:16 +0000479 for (const MachineInstr &MI : MBB) {
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000480 if (!useOrDefCSROrFI(MI, RS.get()))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000481 continue;
482 // Save (resp. restore) point must dominate (resp. post dominate)
483 // MI. Look for the proper basic block for those.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000484 updateSaveRestorePoints(MBB, RS.get());
Quentin Colombet61b305e2015-05-05 17:38:16 +0000485 // If we are at a point where we cannot improve the placement of
486 // save/restore instructions, just give up.
487 if (!ArePointsInteresting()) {
488 DEBUG(dbgs() << "No Shrink wrap candidate found\n");
489 return false;
490 }
491 // No need to look for other instructions, this basic block
492 // will already be part of the handled region.
493 break;
494 }
495 }
496 if (!ArePointsInteresting()) {
497 // If the points are not interesting at this point, then they must be null
498 // because it means we did not encounter any frame/CSR related code.
499 // Otherwise, we would have returned from the previous loop.
500 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
501 DEBUG(dbgs() << "Nothing to shrink-wrap\n");
502 return false;
503 }
504
505 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
506 << '\n');
507
Quentin Colombet80835882015-05-27 06:25:48 +0000508 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000509 do {
510 DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
511 << Save->getNumber() << ' ' << Save->getName() << ' '
512 << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: "
513 << Restore->getNumber() << ' ' << Restore->getName() << ' '
514 << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
515
Quentin Colombet80835882015-05-27 06:25:48 +0000516 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
517 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
518 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
519 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
520 TFI->canUseAsEpilogue(*Restore)))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000521 break;
Quentin Colombet80835882015-05-27 06:25:48 +0000522 DEBUG(dbgs() << "New points are too expensive or invalid for the target\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000523 MachineBasicBlock *NewBB;
Quentin Colombet80835882015-05-27 06:25:48 +0000524 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000525 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
526 if (!Save)
527 break;
528 NewBB = Save;
529 } else {
530 // Restore is expensive.
531 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
532 if (!Restore)
533 break;
534 NewBB = Restore;
535 }
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000536 updateSaveRestorePoints(*NewBB, RS.get());
Quentin Colombet61b305e2015-05-05 17:38:16 +0000537 } while (Save && Restore);
538
539 if (!ArePointsInteresting()) {
540 ++NumCandidatesDropped;
541 return false;
542 }
543
544 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
545 << ' ' << Save->getName() << "\nRestore: "
546 << Restore->getNumber() << ' ' << Restore->getName() << '\n');
547
Matthias Braun941a7052016-07-28 18:40:00 +0000548 MachineFrameInfo &MFI = MF.getFrameInfo();
549 MFI.setSavePoint(Save);
550 MFI.setRestorePoint(Restore);
Quentin Colombet61b305e2015-05-05 17:38:16 +0000551 ++NumCandidates;
552 return false;
553}
Kit Bartond3cc1672015-08-31 18:26:45 +0000554
555bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
556 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
557
558 switch (EnableShrinkWrapOpt) {
559 case cl::BOU_UNSET:
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000560 return TFI->enableShrinkWrapping(MF) &&
Quentin Colombetaeb85932015-11-12 18:16:27 +0000561 // Windows with CFI has some limitations that make it impossible
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000562 // to use shrink-wrapping.
Quentin Colombet2cdcfd22015-11-14 01:55:17 +0000563 !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
564 // Sanitizers look at the value of the stack at the location
565 // of the crash. Since a crash can happen anywhere, the
566 // frame must be lowered before anything else happen for the
567 // sanitizers to be able to get a correct stack frame.
568 !(MF.getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
569 MF.getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
570 MF.getFunction()->hasFnAttribute(Attribute::SanitizeMemory));
Kit Bartond3cc1672015-08-31 18:26:45 +0000571 // If EnableShrinkWrap is set, it takes precedence on whatever the
572 // target sets. The rational is that we assume we want to test
573 // something related to shrink-wrapping.
574 case cl::BOU_TRUE:
575 return true;
576 case cl::BOU_FALSE:
577 return false;
578 }
579 llvm_unreachable("Invalid shrink-wrapping state");
580}