blob: d4fbe0a8df070ca6c8bdd3e6cea3fadd323cb705 [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"
Florian Hahn515acd62018-03-02 12:24:25 +000056#include "llvm/Analysis/CFG.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000057#include "llvm/CodeGen/MachineBasicBlock.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000058#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000059#include "llvm/CodeGen/MachineDominators.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000060#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000061#include "llvm/CodeGen/MachineFunction.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000062#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000063#include "llvm/CodeGen/MachineInstr.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000064#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000065#include "llvm/CodeGen/MachineOperand.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000066#include "llvm/CodeGen/MachinePostDominators.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000067#include "llvm/CodeGen/RegisterClassInfo.h"
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +000068#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000069#include "llvm/CodeGen/TargetFrameLowering.h"
70#include "llvm/CodeGen/TargetInstrInfo.h"
Momchil Velikove256ab82018-04-17 08:37:38 +000071#include "llvm/CodeGen/TargetLowering.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000072#include "llvm/CodeGen/TargetRegisterInfo.h"
73#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000074#include "llvm/IR/Attributes.h"
75#include "llvm/IR/Function.h"
Quentin Colombet94dc1e02015-11-12 18:13:42 +000076#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000077#include "llvm/Pass.h"
78#include "llvm/Support/CommandLine.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000079#include "llvm/Support/Debug.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000080#include "llvm/Support/ErrorHandling.h"
81#include "llvm/Support/raw_ostream.h"
Quentin Colombet94dc1e02015-11-12 18:13:42 +000082#include "llvm/Target/TargetMachine.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000083#include <cassert>
84#include <cstdint>
85#include <memory>
Quentin Colombet61b305e2015-05-05 17:38:16 +000086
87using namespace llvm;
88
Eugene Zelenko149178d2017-10-10 22:33:29 +000089#define DEBUG_TYPE "shrink-wrap"
90
Quentin Colombet61b305e2015-05-05 17:38:16 +000091STATISTIC(NumFunc, "Number of functions");
92STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
93STATISTIC(NumCandidatesDropped,
94 "Number of shrink-wrapping candidates dropped because of frequency");
95
Kit Bartond3cc1672015-08-31 18:26:45 +000096static cl::opt<cl::boolOrDefault>
Eugene Zelenko149178d2017-10-10 22:33:29 +000097EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
98 cl::desc("enable the shrink-wrapping pass"));
Kit Bartond3cc1672015-08-31 18:26:45 +000099
Quentin Colombet61b305e2015-05-05 17:38:16 +0000100namespace {
Eugene Zelenko149178d2017-10-10 22:33:29 +0000101
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000102/// Class to determine where the safe point to insert the
Quentin Colombet61b305e2015-05-05 17:38:16 +0000103/// prologue and epilogue are.
104/// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
105/// shrink-wrapping term for prologue/epilogue placement, this pass
106/// does not rely on expensive data-flow analysis. Instead we use the
107/// dominance properties and loop information to decide which point
108/// are safe for such insertion.
109class ShrinkWrap : public MachineFunctionPass {
110 /// Hold callee-saved information.
111 RegisterClassInfo RCI;
112 MachineDominatorTree *MDT;
113 MachinePostDominatorTree *MPDT;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000114
Quentin Colombet61b305e2015-05-05 17:38:16 +0000115 /// Current safe point found for the prologue.
116 /// The prologue will be inserted before the first instruction
117 /// in this basic block.
118 MachineBasicBlock *Save;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000119
Quentin Colombet61b305e2015-05-05 17:38:16 +0000120 /// Current safe point found for the epilogue.
121 /// The epilogue will be inserted before the first terminator instruction
122 /// in this basic block.
123 MachineBasicBlock *Restore;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000124
Quentin Colombet61b305e2015-05-05 17:38:16 +0000125 /// Hold the information of the basic block frequency.
126 /// Use to check the profitability of the new points.
127 MachineBlockFrequencyInfo *MBFI;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000128
Quentin Colombet61b305e2015-05-05 17:38:16 +0000129 /// Hold the loop information. Used to determine if Save and Restore
130 /// are in the same loop.
131 MachineLoopInfo *MLI;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000132
Quentin Colombet61b305e2015-05-05 17:38:16 +0000133 /// Frequency of the Entry block.
134 uint64_t EntryFreq;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000135
Quentin Colombet61b305e2015-05-05 17:38:16 +0000136 /// Current opcode for frame setup.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000137 unsigned FrameSetupOpcode;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000138
Quentin Colombet61b305e2015-05-05 17:38:16 +0000139 /// Current opcode for frame destroy.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000140 unsigned FrameDestroyOpcode;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000141
Momchil Velikove256ab82018-04-17 08:37:38 +0000142 /// Stack pointer register, used by llvm.{savestack,restorestack}
143 unsigned SP;
144
Quentin Colombet61b305e2015-05-05 17:38:16 +0000145 /// Entry block.
146 const MachineBasicBlock *Entry;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000147
148 using SetOfRegs = SmallSetVector<unsigned, 16>;
149
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000150 /// Registers that need to be saved for the current function.
151 mutable SetOfRegs CurrentCSRs;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000152
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000153 /// Current MachineFunction.
154 MachineFunction *MachineFunc;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000155
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000156 /// Check if \p MI uses or defines a callee-saved register or
Quentin Colombet61b305e2015-05-05 17:38:16 +0000157 /// a frame index. If this is the case, this means \p MI must happen
158 /// after Save and before Restore.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000159 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS) const;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000160
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000161 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000162 if (CurrentCSRs.empty()) {
163 BitVector SavedRegs;
164 const TargetFrameLowering *TFI =
165 MachineFunc->getSubtarget().getFrameLowering();
166
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000167 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS);
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000168
169 for (int Reg = SavedRegs.find_first(); Reg != -1;
170 Reg = SavedRegs.find_next(Reg))
171 CurrentCSRs.insert((unsigned)Reg);
172 }
173 return CurrentCSRs;
174 }
175
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000176 /// Update the Save and Restore points such that \p MBB is in
Quentin Colombet61b305e2015-05-05 17:38:16 +0000177 /// the region that is dominated by Save and post-dominated by Restore
178 /// and Save and Restore still match the safe point definition.
179 /// Such point may not exist and Save and/or Restore may be null after
180 /// this call.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000181 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
Quentin Colombet61b305e2015-05-05 17:38:16 +0000182
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000183 /// Initialize the pass for \p MF.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000184 void init(MachineFunction &MF) {
185 RCI.runOnMachineFunction(MF);
186 MDT = &getAnalysis<MachineDominatorTree>();
187 MPDT = &getAnalysis<MachinePostDominatorTree>();
188 Save = nullptr;
189 Restore = nullptr;
190 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
191 MLI = &getAnalysis<MachineLoopInfo>();
192 EntryFreq = MBFI->getEntryFreq();
Momchil Velikove256ab82018-04-17 08:37:38 +0000193 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
194 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000195 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
196 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
Momchil Velikove256ab82018-04-17 08:37:38 +0000197 SP = Subtarget.getTargetLowering()->getStackPointerRegisterToSaveRestore();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000198 Entry = &MF.front();
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000199 CurrentCSRs.clear();
200 MachineFunc = &MF;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000201
202 ++NumFunc;
203 }
204
205 /// Check whether or not Save and Restore points are still interesting for
206 /// shrink-wrapping.
207 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
208
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000209 /// Check if shrink wrapping is enabled for this target and function.
Kit Bartond3cc1672015-08-31 18:26:45 +0000210 static bool isShrinkWrapEnabled(const MachineFunction &MF);
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000211
Quentin Colombet61b305e2015-05-05 17:38:16 +0000212public:
213 static char ID;
214
215 ShrinkWrap() : MachineFunctionPass(ID) {
216 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
217 }
218
219 void getAnalysisUsage(AnalysisUsage &AU) const override {
220 AU.setPreservesAll();
221 AU.addRequired<MachineBlockFrequencyInfo>();
222 AU.addRequired<MachineDominatorTree>();
223 AU.addRequired<MachinePostDominatorTree>();
224 AU.addRequired<MachineLoopInfo>();
225 MachineFunctionPass::getAnalysisUsage(AU);
226 }
227
Jun Bum Lim7ab1b322018-04-03 18:17:34 +0000228 MachineFunctionProperties getRequiredProperties() const override {
229 return MachineFunctionProperties().set(
230 MachineFunctionProperties::Property::NoVRegs);
231 }
232
Mehdi Amini117296c2016-10-01 02:56:57 +0000233 StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000234
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000235 /// Perform the shrink-wrapping analysis and update
Quentin Colombet61b305e2015-05-05 17:38:16 +0000236 /// the MachineFrameInfo attached to \p MF with the results.
237 bool runOnMachineFunction(MachineFunction &MF) override;
238};
Eugene Zelenko149178d2017-10-10 22:33:29 +0000239
240} // end anonymous namespace
Quentin Colombet61b305e2015-05-05 17:38:16 +0000241
242char ShrinkWrap::ID = 0;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000243
Quentin Colombet61b305e2015-05-05 17:38:16 +0000244char &llvm::ShrinkWrapID = ShrinkWrap::ID;
245
Matthias Braun1527baa2017-05-25 21:26:32 +0000246INITIALIZE_PASS_BEGIN(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet61b305e2015-05-05 17:38:16 +0000247INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
248INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
249INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
250INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +0000251INITIALIZE_PASS_END(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet61b305e2015-05-05 17:38:16 +0000252
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000253bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI,
254 RegScavenger *RS) const {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000255 if (MI.getOpcode() == FrameSetupOpcode ||
256 MI.getOpcode() == FrameDestroyOpcode) {
257 DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
258 return true;
259 }
260 for (const MachineOperand &MO : MI.operands()) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000261 bool UseOrDefCSR = false;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000262 if (MO.isReg()) {
Francis Visoiu Mistrih54a9e7a2018-01-16 18:55:26 +0000263 // Ignore instructions like DBG_VALUE which don't read/def the register.
264 if (!MO.isDef() && !MO.readsReg())
265 continue;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000266 unsigned PhysReg = MO.getReg();
267 if (!PhysReg)
268 continue;
269 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
270 "Unallocated register?!");
Momchil Velikove256ab82018-04-17 08:37:38 +0000271 // The stack pointer is not normally described as a callee-saved register
272 // in calling convention definitions, so we need to watch for it
273 // separately. An SP mentioned by a call instruction, we can ignore,
274 // though, as it's harmless and we do not want to effectively disable tail
275 // calls by forcing the restore point to post-dominate them.
276 UseOrDefCSR = (!MI.isCall() && PhysReg == SP) ||
277 RCI.getLastCalleeSavedAlias(PhysReg);
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000278 } else if (MO.isRegMask()) {
279 // Check if this regmask clobbers any of the CSRs.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000280 for (unsigned Reg : getCurrentCSRs(RS)) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000281 if (MO.clobbersPhysReg(Reg)) {
282 UseOrDefCSR = true;
283 break;
284 }
285 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000286 }
Francis Visoiu Mistrih54a9e7a2018-01-16 18:55:26 +0000287 // Skip FrameIndex operands in DBG_VALUE instructions.
288 if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000289 DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
290 << MO.isFI() << "): " << MI << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000291 return true;
292 }
293 }
294 return false;
295}
296
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000297/// Helper function to find the immediate (post) dominator.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000298template <typename ListOfBBs, typename DominanceAnalysis>
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000299static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
300 DominanceAnalysis &Dom) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000301 MachineBasicBlock *IDom = &Block;
302 for (MachineBasicBlock *BB : BBs) {
303 IDom = Dom.findNearestCommonDominator(IDom, BB);
304 if (!IDom)
305 break;
306 }
Michael Kuperstein037c9982016-01-06 18:40:11 +0000307 if (IDom == &Block)
308 return nullptr;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000309 return IDom;
310}
311
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000312void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB,
313 RegScavenger *RS) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000314 // Get rid of the easy cases first.
315 if (!Save)
316 Save = &MBB;
317 else
318 Save = MDT->findNearestCommonDominator(Save, &MBB);
319
320 if (!Save) {
321 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
322 return;
323 }
324
325 if (!Restore)
326 Restore = &MBB;
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000327 else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it
328 // means the block never returns. If that's the
329 // case, we don't want to call
330 // `findNearestCommonDominator`, which will
331 // return `Restore`.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000332 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000333 else
334 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000335
336 // Make sure we would be able to insert the restore code before the
337 // terminator.
338 if (Restore == &MBB) {
339 for (const MachineInstr &Terminator : MBB.terminators()) {
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000340 if (!useOrDefCSROrFI(Terminator, RS))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000341 continue;
342 // One of the terminator needs to happen before the restore point.
343 if (MBB.succ_empty()) {
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000344 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000345 break;
346 }
347 // Look for a restore point that post-dominates all the successors.
348 // The immediate post-dominator is what we are looking for.
349 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
350 break;
351 }
352 }
353
354 if (!Restore) {
355 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
356 return;
357 }
358
359 // Make sure Save and Restore are suitable for shrink-wrapping:
360 // 1. all path from Save needs to lead to Restore before exiting.
361 // 2. all path to Restore needs to go through Save from Entry.
362 // We achieve that by making sure that:
363 // A. Save dominates Restore.
364 // B. Restore post-dominates Save.
365 // C. Save and Restore are in the same loop.
366 bool SaveDominatesRestore = false;
367 bool RestorePostDominatesSave = false;
368 while (Save && Restore &&
369 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
370 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
Quentin Colombetb82786e2015-12-15 03:28:11 +0000371 // Post-dominance is not enough in loops to ensure that all uses/defs
372 // are after the prologue and before the epilogue at runtime.
373 // E.g.,
374 // while(1) {
375 // Save
376 // Restore
377 // if (...)
378 // break;
379 // use/def CSRs
380 // }
381 // All the uses/defs of CSRs are dominated by Save and post-dominated
382 // by Restore. However, the CSRs uses are still reachable after
383 // Restore and before Save are executed.
384 //
385 // For now, just push the restore/save points outside of loops.
386 // FIXME: Refine the criteria to still find interesting cases
387 // for loops.
388 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000389 // Fix (A).
390 if (!SaveDominatesRestore) {
391 Save = MDT->findNearestCommonDominator(Save, Restore);
392 continue;
393 }
394 // Fix (B).
395 if (!RestorePostDominatesSave)
396 Restore = MPDT->findNearestCommonDominator(Restore, Save);
397
398 // Fix (C).
Quentin Colombetb82786e2015-12-15 03:28:11 +0000399 if (Save && Restore &&
400 (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Kit Bartona7bf96a2015-08-06 19:01:57 +0000401 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
402 // Push Save outside of this loop if immediate dominator is different
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000403 // from save block. If immediate dominator is not different, bail out.
Michael Kuperstein037c9982016-01-06 18:40:11 +0000404 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
405 if (!Save)
Kit Bartona7bf96a2015-08-06 19:01:57 +0000406 break;
Quentin Colombetb82786e2015-12-15 03:28:11 +0000407 } else {
Quentin Colombetdc29c972015-09-15 18:19:39 +0000408 // If the loop does not exit, there is no point in looking
409 // for a post-dominator outside the loop.
410 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
411 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
Quentin Colombetb4c68862015-09-17 23:21:34 +0000412 // Push Restore outside of this loop.
413 // Look for the immediate post-dominator of the loop exits.
414 MachineBasicBlock *IPdom = Restore;
415 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
416 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
417 if (!IPdom)
418 break;
Quentin Colombetdc29c972015-09-15 18:19:39 +0000419 }
Quentin Colombetb4c68862015-09-17 23:21:34 +0000420 // If the immediate post-dominator is not in a less nested loop,
421 // then we are stuck in a program with an infinite loop.
422 // In that case, we will not find a safe point, hence, bail out.
423 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000424 Restore = IPdom;
Kit Bartona7bf96a2015-08-06 19:01:57 +0000425 else {
426 Restore = nullptr;
427 break;
428 }
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000429 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000430 }
431 }
432}
433
434bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000435 if (skipFunction(MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000436 return false;
Kit Bartond3cc1672015-08-31 18:26:45 +0000437
Quentin Colombet61b305e2015-05-05 17:38:16 +0000438 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
439
440 init(MF);
441
Florian Hahn515acd62018-03-02 12:24:25 +0000442 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
443 if (containsIrreducibleCFG<MachineBasicBlock *>(RPOT, *MLI)) {
Quentin Colombet9ed52e92016-01-07 01:23:49 +0000444 // If MF is irreducible, a block may be in a loop without
445 // MachineLoopInfo reporting it. I.e., we may use the
446 // post-dominance property in loops, which lead to incorrect
447 // results. Moreover, we may miss that the prologue and
448 // epilogue are not in the same loop, leading to unbalanced
449 // construction/deconstruction of the stack frame.
450 DEBUG(dbgs() << "Irreducible CFGs are not supported yet\n");
451 return false;
452 }
453
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000454 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
455 std::unique_ptr<RegScavenger> RS(
456 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
457
Quentin Colombet61b305e2015-05-05 17:38:16 +0000458 for (MachineBasicBlock &MBB : MF) {
459 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
460 << '\n');
461
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000462 if (MBB.isEHFuncletEntry()) {
463 DEBUG(dbgs() << "EH Funclets are not supported yet.\n");
464 return false;
465 }
466
Quentin Colombet508f6822018-03-20 02:44:40 +0000467 if (MBB.isEHPad()) {
468 // Push the prologue and epilogue outside of
469 // the region that may throw by making sure
470 // that all the landing pads are at least at the
471 // boundary of the save and restore points.
472 // The problem with exceptions is that the throw
473 // is not properly modeled and in particular, a
474 // basic block can jump out from the middle.
475 updateSaveRestorePoints(MBB, RS.get());
476 if (!ArePointsInteresting()) {
477 DEBUG(dbgs() << "EHPad prevents shrink-wrapping\n");
478 return false;
479 }
480 continue;
481 }
482
Quentin Colombet61b305e2015-05-05 17:38:16 +0000483 for (const MachineInstr &MI : MBB) {
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000484 if (!useOrDefCSROrFI(MI, RS.get()))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000485 continue;
486 // Save (resp. restore) point must dominate (resp. post dominate)
487 // MI. Look for the proper basic block for those.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000488 updateSaveRestorePoints(MBB, RS.get());
Quentin Colombet61b305e2015-05-05 17:38:16 +0000489 // If we are at a point where we cannot improve the placement of
490 // save/restore instructions, just give up.
491 if (!ArePointsInteresting()) {
492 DEBUG(dbgs() << "No Shrink wrap candidate found\n");
493 return false;
494 }
495 // No need to look for other instructions, this basic block
496 // will already be part of the handled region.
497 break;
498 }
499 }
500 if (!ArePointsInteresting()) {
501 // If the points are not interesting at this point, then they must be null
502 // because it means we did not encounter any frame/CSR related code.
503 // Otherwise, we would have returned from the previous loop.
504 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
505 DEBUG(dbgs() << "Nothing to shrink-wrap\n");
506 return false;
507 }
508
509 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
510 << '\n');
511
Quentin Colombet80835882015-05-27 06:25:48 +0000512 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000513 do {
514 DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
515 << Save->getNumber() << ' ' << Save->getName() << ' '
516 << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: "
517 << Restore->getNumber() << ' ' << Restore->getName() << ' '
518 << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
519
Quentin Colombet80835882015-05-27 06:25:48 +0000520 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
521 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
522 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
523 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
524 TFI->canUseAsEpilogue(*Restore)))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000525 break;
Quentin Colombet80835882015-05-27 06:25:48 +0000526 DEBUG(dbgs() << "New points are too expensive or invalid for the target\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000527 MachineBasicBlock *NewBB;
Quentin Colombet80835882015-05-27 06:25:48 +0000528 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000529 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
530 if (!Save)
531 break;
532 NewBB = Save;
533 } else {
534 // Restore is expensive.
535 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
536 if (!Restore)
537 break;
538 NewBB = Restore;
539 }
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000540 updateSaveRestorePoints(*NewBB, RS.get());
Quentin Colombet61b305e2015-05-05 17:38:16 +0000541 } while (Save && Restore);
542
543 if (!ArePointsInteresting()) {
544 ++NumCandidatesDropped;
545 return false;
546 }
547
548 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
549 << ' ' << Save->getName() << "\nRestore: "
550 << Restore->getNumber() << ' ' << Restore->getName() << '\n');
551
Matthias Braun941a7052016-07-28 18:40:00 +0000552 MachineFrameInfo &MFI = MF.getFrameInfo();
553 MFI.setSavePoint(Save);
554 MFI.setRestorePoint(Restore);
Quentin Colombet61b305e2015-05-05 17:38:16 +0000555 ++NumCandidates;
556 return false;
557}
Kit Bartond3cc1672015-08-31 18:26:45 +0000558
559bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
560 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
561
562 switch (EnableShrinkWrapOpt) {
563 case cl::BOU_UNSET:
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000564 return TFI->enableShrinkWrapping(MF) &&
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +0000565 // Windows with CFI has some limitations that make it impossible
566 // to use shrink-wrapping.
567 !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
568 // Sanitizers look at the value of the stack at the location
569 // of the crash. Since a crash can happen anywhere, the
570 // frame must be lowered before anything else happen for the
571 // sanitizers to be able to get a correct stack frame.
Matthias Braunf1caa282017-12-15 22:22:58 +0000572 !(MF.getFunction().hasFnAttribute(Attribute::SanitizeAddress) ||
573 MF.getFunction().hasFnAttribute(Attribute::SanitizeThread) ||
574 MF.getFunction().hasFnAttribute(Attribute::SanitizeMemory) ||
575 MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress));
Kit Bartond3cc1672015-08-31 18:26:45 +0000576 // If EnableShrinkWrap is set, it takes precedence on whatever the
577 // target sets. The rational is that we assume we want to test
578 // something related to shrink-wrapping.
579 case cl::BOU_TRUE:
580 return true;
581 case cl::BOU_FALSE:
582 return false;
583 }
584 llvm_unreachable("Invalid shrink-wrapping state");
585}