blob: d3454ca6ba6ae992ee19971c00f82cfed3dce714 [file] [log] [blame]
Eugene Zelenko887aef72017-10-10 22:33:29 +00001//===- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ----===//
Quentin Colombet2f7322b2015-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 Colombet1cc0c432015-11-06 21:00:13 +000046// If this pass found points matching all these properties, then
Chad Rosierccbb5bd2015-12-22 15:06:47 +000047// MachineFrameInfo is updated with this information.
Eugene Zelenko887aef72017-10-10 22:33:29 +000048//
Quentin Colombet2f7322b2015-05-05 17:38:16 +000049//===----------------------------------------------------------------------===//
Eugene Zelenko887aef72017-10-10 22:33:29 +000050
Quentin Colombet1cc0c432015-11-06 21:00:13 +000051#include "llvm/ADT/BitVector.h"
Quentin Colombet55c7a222016-01-07 01:23:49 +000052#include "llvm/ADT/PostOrderIterator.h"
Quentin Colombet1cc0c432015-11-06 21:00:13 +000053#include "llvm/ADT/SetVector.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000054#include "llvm/ADT/SmallVector.h"
Quentin Colombet2f7322b2015-05-05 17:38:16 +000055#include "llvm/ADT/Statistic.h"
Florian Hahn9b9abca2018-03-02 12:24:25 +000056#include "llvm/Analysis/CFG.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000057#include "llvm/CodeGen/MachineBasicBlock.h"
Quentin Colombet2f7322b2015-05-05 17:38:16 +000058#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Quentin Colombet2f7322b2015-05-05 17:38:16 +000059#include "llvm/CodeGen/MachineDominators.h"
David Blaikie48319232017-11-08 01:01:31 +000060#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000061#include "llvm/CodeGen/MachineFunction.h"
Quentin Colombet2f7322b2015-05-05 17:38:16 +000062#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000063#include "llvm/CodeGen/MachineInstr.h"
Quentin Colombet2f7322b2015-05-05 17:38:16 +000064#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000065#include "llvm/CodeGen/MachineOperand.h"
Francis Visoiu Mistrihe70aaf72018-06-05 00:27:24 +000066#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Quentin Colombet2f7322b2015-05-05 17:38:16 +000067#include "llvm/CodeGen/MachinePostDominators.h"
Quentin Colombet2f7322b2015-05-05 17:38:16 +000068#include "llvm/CodeGen/RegisterClassInfo.h"
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +000069#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie48319232017-11-08 01:01:31 +000070#include "llvm/CodeGen/TargetFrameLowering.h"
71#include "llvm/CodeGen/TargetInstrInfo.h"
Momchil Velikovafb8c1f2018-04-17 08:37:38 +000072#include "llvm/CodeGen/TargetLowering.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000073#include "llvm/CodeGen/TargetRegisterInfo.h"
74#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000075#include "llvm/IR/Attributes.h"
76#include "llvm/IR/Function.h"
Quentin Colombet88d45c62015-11-12 18:13:42 +000077#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000078#include "llvm/Pass.h"
79#include "llvm/Support/CommandLine.h"
Quentin Colombet2f7322b2015-05-05 17:38:16 +000080#include "llvm/Support/Debug.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000081#include "llvm/Support/ErrorHandling.h"
82#include "llvm/Support/raw_ostream.h"
Quentin Colombet88d45c62015-11-12 18:13:42 +000083#include "llvm/Target/TargetMachine.h"
Eugene Zelenko887aef72017-10-10 22:33:29 +000084#include <cassert>
85#include <cstdint>
86#include <memory>
Quentin Colombet2f7322b2015-05-05 17:38:16 +000087
88using namespace llvm;
89
Eugene Zelenko887aef72017-10-10 22:33:29 +000090#define DEBUG_TYPE "shrink-wrap"
91
Quentin Colombet2f7322b2015-05-05 17:38:16 +000092STATISTIC(NumFunc, "Number of functions");
93STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
94STATISTIC(NumCandidatesDropped,
95 "Number of shrink-wrapping candidates dropped because of frequency");
96
Kit Barton21b967e2015-08-31 18:26:45 +000097static cl::opt<cl::boolOrDefault>
Eugene Zelenko887aef72017-10-10 22:33:29 +000098EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
99 cl::desc("enable the shrink-wrapping pass"));
Kit Barton21b967e2015-08-31 18:26:45 +0000100
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000101namespace {
Eugene Zelenko887aef72017-10-10 22:33:29 +0000102
Adrian Prantl26b584c2018-05-01 15:54:18 +0000103/// Class to determine where the safe point to insert the
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000104/// prologue and epilogue are.
105/// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
106/// shrink-wrapping term for prologue/epilogue placement, this pass
107/// does not rely on expensive data-flow analysis. Instead we use the
108/// dominance properties and loop information to decide which point
109/// are safe for such insertion.
110class ShrinkWrap : public MachineFunctionPass {
111 /// Hold callee-saved information.
112 RegisterClassInfo RCI;
113 MachineDominatorTree *MDT;
114 MachinePostDominatorTree *MPDT;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000115
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000116 /// Current safe point found for the prologue.
117 /// The prologue will be inserted before the first instruction
118 /// in this basic block.
119 MachineBasicBlock *Save;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000120
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000121 /// Current safe point found for the epilogue.
122 /// The epilogue will be inserted before the first terminator instruction
123 /// in this basic block.
124 MachineBasicBlock *Restore;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000125
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000126 /// Hold the information of the basic block frequency.
127 /// Use to check the profitability of the new points.
128 MachineBlockFrequencyInfo *MBFI;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000129
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000130 /// Hold the loop information. Used to determine if Save and Restore
131 /// are in the same loop.
132 MachineLoopInfo *MLI;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000133
Francis Visoiu Mistrihe70aaf72018-06-05 00:27:24 +0000134 // Emit remarks.
135 MachineOptimizationRemarkEmitter *ORE = nullptr;
136
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000137 /// Frequency of the Entry block.
138 uint64_t EntryFreq;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000139
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000140 /// Current opcode for frame setup.
Matthias Braune4603f02015-05-18 20:27:55 +0000141 unsigned FrameSetupOpcode;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000142
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000143 /// Current opcode for frame destroy.
Matthias Braune4603f02015-05-18 20:27:55 +0000144 unsigned FrameDestroyOpcode;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000145
Momchil Velikovafb8c1f2018-04-17 08:37:38 +0000146 /// Stack pointer register, used by llvm.{savestack,restorestack}
147 unsigned SP;
148
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000149 /// Entry block.
150 const MachineBasicBlock *Entry;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000151
152 using SetOfRegs = SmallSetVector<unsigned, 16>;
153
Quentin Colombet1cc0c432015-11-06 21:00:13 +0000154 /// Registers that need to be saved for the current function.
155 mutable SetOfRegs CurrentCSRs;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000156
Quentin Colombet1cc0c432015-11-06 21:00:13 +0000157 /// Current MachineFunction.
158 MachineFunction *MachineFunc;
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000159
Adrian Prantl26b584c2018-05-01 15:54:18 +0000160 /// Check if \p MI uses or defines a callee-saved register or
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000161 /// a frame index. If this is the case, this means \p MI must happen
162 /// after Save and before Restore.
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000163 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS) const;
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000164
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000165 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
Quentin Colombet1cc0c432015-11-06 21:00:13 +0000166 if (CurrentCSRs.empty()) {
167 BitVector SavedRegs;
168 const TargetFrameLowering *TFI =
169 MachineFunc->getSubtarget().getFrameLowering();
170
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000171 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS);
Quentin Colombet1cc0c432015-11-06 21:00:13 +0000172
173 for (int Reg = SavedRegs.find_first(); Reg != -1;
174 Reg = SavedRegs.find_next(Reg))
175 CurrentCSRs.insert((unsigned)Reg);
176 }
177 return CurrentCSRs;
178 }
179
Adrian Prantl26b584c2018-05-01 15:54:18 +0000180 /// Update the Save and Restore points such that \p MBB is in
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000181 /// the region that is dominated by Save and post-dominated by Restore
182 /// and Save and Restore still match the safe point definition.
183 /// Such point may not exist and Save and/or Restore may be null after
184 /// this call.
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000185 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000186
Adrian Prantl26b584c2018-05-01 15:54:18 +0000187 /// Initialize the pass for \p MF.
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000188 void init(MachineFunction &MF) {
189 RCI.runOnMachineFunction(MF);
190 MDT = &getAnalysis<MachineDominatorTree>();
191 MPDT = &getAnalysis<MachinePostDominatorTree>();
192 Save = nullptr;
193 Restore = nullptr;
194 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
195 MLI = &getAnalysis<MachineLoopInfo>();
Francis Visoiu Mistrihe70aaf72018-06-05 00:27:24 +0000196 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000197 EntryFreq = MBFI->getEntryFreq();
Momchil Velikovafb8c1f2018-04-17 08:37:38 +0000198 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
199 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000200 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
201 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
Momchil Velikovafb8c1f2018-04-17 08:37:38 +0000202 SP = Subtarget.getTargetLowering()->getStackPointerRegisterToSaveRestore();
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000203 Entry = &MF.front();
Quentin Colombet1cc0c432015-11-06 21:00:13 +0000204 CurrentCSRs.clear();
205 MachineFunc = &MF;
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000206
207 ++NumFunc;
208 }
209
210 /// Check whether or not Save and Restore points are still interesting for
211 /// shrink-wrapping.
212 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
213
Adrian Prantl26b584c2018-05-01 15:54:18 +0000214 /// Check if shrink wrapping is enabled for this target and function.
Kit Barton21b967e2015-08-31 18:26:45 +0000215 static bool isShrinkWrapEnabled(const MachineFunction &MF);
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000216
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000217public:
218 static char ID;
219
220 ShrinkWrap() : MachineFunctionPass(ID) {
221 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
222 }
223
224 void getAnalysisUsage(AnalysisUsage &AU) const override {
225 AU.setPreservesAll();
226 AU.addRequired<MachineBlockFrequencyInfo>();
227 AU.addRequired<MachineDominatorTree>();
228 AU.addRequired<MachinePostDominatorTree>();
229 AU.addRequired<MachineLoopInfo>();
Francis Visoiu Mistrihe70aaf72018-06-05 00:27:24 +0000230 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000231 MachineFunctionPass::getAnalysisUsage(AU);
232 }
233
Jun Bum Limc23bb982018-04-03 18:17:34 +0000234 MachineFunctionProperties getRequiredProperties() const override {
235 return MachineFunctionProperties().set(
236 MachineFunctionProperties::Property::NoVRegs);
237 }
238
Mehdi Amini67f335d2016-10-01 02:56:57 +0000239 StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000240
Adrian Prantl26b584c2018-05-01 15:54:18 +0000241 /// Perform the shrink-wrapping analysis and update
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000242 /// the MachineFrameInfo attached to \p MF with the results.
243 bool runOnMachineFunction(MachineFunction &MF) override;
244};
Eugene Zelenko887aef72017-10-10 22:33:29 +0000245
246} // end anonymous namespace
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000247
248char ShrinkWrap::ID = 0;
Eugene Zelenko887aef72017-10-10 22:33:29 +0000249
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000250char &llvm::ShrinkWrapID = ShrinkWrap::ID;
251
Matthias Braun94c49042017-05-25 21:26:32 +0000252INITIALIZE_PASS_BEGIN(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000253INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
254INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
255INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
256INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Francis Visoiu Mistrihe70aaf72018-06-05 00:27:24 +0000257INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
Matthias Braun94c49042017-05-25 21:26:32 +0000258INITIALIZE_PASS_END(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000259
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000260bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI,
261 RegScavenger *RS) const {
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000262 if (MI.getOpcode() == FrameSetupOpcode ||
263 MI.getOpcode() == FrameDestroyOpcode) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000264 LLVM_DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000265 return true;
266 }
267 for (const MachineOperand &MO : MI.operands()) {
Quentin Colombet1cc0c432015-11-06 21:00:13 +0000268 bool UseOrDefCSR = false;
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000269 if (MO.isReg()) {
Francis Visoiu Mistrih1aee8482018-01-16 18:55:26 +0000270 // Ignore instructions like DBG_VALUE which don't read/def the register.
271 if (!MO.isDef() && !MO.readsReg())
272 continue;
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000273 unsigned PhysReg = MO.getReg();
274 if (!PhysReg)
275 continue;
276 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
277 "Unallocated register?!");
Momchil Velikovafb8c1f2018-04-17 08:37:38 +0000278 // The stack pointer is not normally described as a callee-saved register
279 // in calling convention definitions, so we need to watch for it
280 // separately. An SP mentioned by a call instruction, we can ignore,
281 // though, as it's harmless and we do not want to effectively disable tail
282 // calls by forcing the restore point to post-dominate them.
283 UseOrDefCSR = (!MI.isCall() && PhysReg == SP) ||
284 RCI.getLastCalleeSavedAlias(PhysReg);
Quentin Colombet1cc0c432015-11-06 21:00:13 +0000285 } else if (MO.isRegMask()) {
286 // Check if this regmask clobbers any of the CSRs.
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000287 for (unsigned Reg : getCurrentCSRs(RS)) {
Quentin Colombet1cc0c432015-11-06 21:00:13 +0000288 if (MO.clobbersPhysReg(Reg)) {
289 UseOrDefCSR = true;
290 break;
291 }
292 }
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000293 }
Francis Visoiu Mistrih1aee8482018-01-16 18:55:26 +0000294 // Skip FrameIndex operands in DBG_VALUE instructions.
295 if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000296 LLVM_DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
297 << MO.isFI() << "): " << MI << '\n');
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000298 return true;
299 }
300 }
301 return false;
302}
303
Adrian Prantl26b584c2018-05-01 15:54:18 +0000304/// Helper function to find the immediate (post) dominator.
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000305template <typename ListOfBBs, typename DominanceAnalysis>
Benjamin Kramer284030a2016-08-06 11:13:10 +0000306static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
307 DominanceAnalysis &Dom) {
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000308 MachineBasicBlock *IDom = &Block;
309 for (MachineBasicBlock *BB : BBs) {
310 IDom = Dom.findNearestCommonDominator(IDom, BB);
311 if (!IDom)
312 break;
313 }
Michael Kupersteinf8ab3ef2016-01-06 18:40:11 +0000314 if (IDom == &Block)
315 return nullptr;
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000316 return IDom;
317}
318
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000319void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB,
320 RegScavenger *RS) {
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000321 // Get rid of the easy cases first.
322 if (!Save)
323 Save = &MBB;
324 else
325 Save = MDT->findNearestCommonDominator(Save, &MBB);
326
327 if (!Save) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000328 LLVM_DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000329 return;
330 }
331
332 if (!Restore)
333 Restore = &MBB;
Francis Visoiu Mistrihcc8486f2017-05-15 23:13:35 +0000334 else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it
335 // means the block never returns. If that's the
336 // case, we don't want to call
337 // `findNearestCommonDominator`, which will
338 // return `Restore`.
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000339 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
Francis Visoiu Mistrihcc8486f2017-05-15 23:13:35 +0000340 else
341 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000342
343 // Make sure we would be able to insert the restore code before the
344 // terminator.
345 if (Restore == &MBB) {
346 for (const MachineInstr &Terminator : MBB.terminators()) {
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000347 if (!useOrDefCSROrFI(Terminator, RS))
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000348 continue;
349 // One of the terminator needs to happen before the restore point.
350 if (MBB.succ_empty()) {
Francis Visoiu Mistrihcc8486f2017-05-15 23:13:35 +0000351 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000352 break;
353 }
354 // Look for a restore point that post-dominates all the successors.
355 // The immediate post-dominator is what we are looking for.
356 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
357 break;
358 }
359 }
360
361 if (!Restore) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000362 LLVM_DEBUG(
363 dbgs() << "Restore point needs to be spanned on several blocks\n");
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000364 return;
365 }
366
367 // Make sure Save and Restore are suitable for shrink-wrapping:
368 // 1. all path from Save needs to lead to Restore before exiting.
369 // 2. all path to Restore needs to go through Save from Entry.
370 // We achieve that by making sure that:
371 // A. Save dominates Restore.
372 // B. Restore post-dominates Save.
373 // C. Save and Restore are in the same loop.
374 bool SaveDominatesRestore = false;
375 bool RestorePostDominatesSave = false;
376 while (Save && Restore &&
377 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
378 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
Quentin Colombet8d412e82015-12-15 03:28:11 +0000379 // Post-dominance is not enough in loops to ensure that all uses/defs
380 // are after the prologue and before the epilogue at runtime.
381 // E.g.,
382 // while(1) {
383 // Save
384 // Restore
385 // if (...)
386 // break;
387 // use/def CSRs
388 // }
389 // All the uses/defs of CSRs are dominated by Save and post-dominated
390 // by Restore. However, the CSRs uses are still reachable after
391 // Restore and before Save are executed.
392 //
393 // For now, just push the restore/save points outside of loops.
394 // FIXME: Refine the criteria to still find interesting cases
395 // for loops.
396 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000397 // Fix (A).
398 if (!SaveDominatesRestore) {
399 Save = MDT->findNearestCommonDominator(Save, Restore);
400 continue;
401 }
402 // Fix (B).
403 if (!RestorePostDominatesSave)
404 Restore = MPDT->findNearestCommonDominator(Restore, Save);
405
406 // Fix (C).
Quentin Colombet8d412e82015-12-15 03:28:11 +0000407 if (Save && Restore &&
408 (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Kit Barton1c618a42015-08-06 19:01:57 +0000409 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
410 // Push Save outside of this loop if immediate dominator is different
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000411 // from save block. If immediate dominator is not different, bail out.
Michael Kupersteinf8ab3ef2016-01-06 18:40:11 +0000412 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
413 if (!Save)
Kit Barton1c618a42015-08-06 19:01:57 +0000414 break;
Quentin Colombet8d412e82015-12-15 03:28:11 +0000415 } else {
Quentin Colombet07400ea2015-09-15 18:19:39 +0000416 // If the loop does not exit, there is no point in looking
417 // for a post-dominator outside the loop.
418 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
419 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
Quentin Colombetd68bf2b2015-09-17 23:21:34 +0000420 // Push Restore outside of this loop.
421 // Look for the immediate post-dominator of the loop exits.
422 MachineBasicBlock *IPdom = Restore;
423 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
424 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
425 if (!IPdom)
426 break;
Quentin Colombet07400ea2015-09-15 18:19:39 +0000427 }
Quentin Colombetd68bf2b2015-09-17 23:21:34 +0000428 // If the immediate post-dominator is not in a less nested loop,
429 // then we are stuck in a program with an infinite loop.
430 // In that case, we will not find a safe point, hence, bail out.
431 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000432 Restore = IPdom;
Kit Barton1c618a42015-08-06 19:01:57 +0000433 else {
434 Restore = nullptr;
435 break;
436 }
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000437 }
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000438 }
439 }
440}
441
Francis Visoiu Mistrihe70aaf72018-06-05 00:27:24 +0000442static bool giveUpWithRemarks(MachineOptimizationRemarkEmitter *ORE,
443 StringRef RemarkName, StringRef RemarkMessage,
444 const DiagnosticLocation &Loc,
445 const MachineBasicBlock *MBB) {
446 ORE->emit([&]() {
447 return MachineOptimizationRemarkMissed(DEBUG_TYPE, RemarkName, Loc, MBB)
448 << RemarkMessage;
449 });
450
451 LLVM_DEBUG(dbgs() << RemarkMessage << '\n');
452 return false;
453}
454
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000455bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
Matthias Braund3181392017-12-15 22:22:58 +0000456 if (skipFunction(MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF))
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000457 return false;
Kit Barton21b967e2015-08-31 18:26:45 +0000458
Nicola Zaghen0818e782018-05-14 12:53:11 +0000459 LLVM_DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000460
461 init(MF);
462
Florian Hahn9b9abca2018-03-02 12:24:25 +0000463 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
464 if (containsIrreducibleCFG<MachineBasicBlock *>(RPOT, *MLI)) {
Quentin Colombet55c7a222016-01-07 01:23:49 +0000465 // If MF is irreducible, a block may be in a loop without
466 // MachineLoopInfo reporting it. I.e., we may use the
467 // post-dominance property in loops, which lead to incorrect
468 // results. Moreover, we may miss that the prologue and
469 // epilogue are not in the same loop, leading to unbalanced
470 // construction/deconstruction of the stack frame.
Francis Visoiu Mistrihe70aaf72018-06-05 00:27:24 +0000471 return giveUpWithRemarks(ORE, "UnsupportedIrreducibleCFG",
472 "Irreducible CFGs are not supported yet.",
473 MF.getFunction().getSubprogram(), &MF.front());
Quentin Colombet55c7a222016-01-07 01:23:49 +0000474 }
475
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000476 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
477 std::unique_ptr<RegScavenger> RS(
478 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
479
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000480 for (MachineBasicBlock &MBB : MF) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000481 LLVM_DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' '
482 << MBB.getName() << '\n');
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000483
Francis Visoiu Mistrihe70aaf72018-06-05 00:27:24 +0000484 if (MBB.isEHFuncletEntry())
485 return giveUpWithRemarks(ORE, "UnsupportedEHFunclets",
486 "EH Funclets are not supported yet.",
487 MBB.front().getDebugLoc(), &MBB);
Quentin Colombet88d45c62015-11-12 18:13:42 +0000488
Quentin Colombetc83d7542018-03-20 02:44:40 +0000489 if (MBB.isEHPad()) {
490 // Push the prologue and epilogue outside of
491 // the region that may throw by making sure
492 // that all the landing pads are at least at the
493 // boundary of the save and restore points.
494 // The problem with exceptions is that the throw
495 // is not properly modeled and in particular, a
496 // basic block can jump out from the middle.
497 updateSaveRestorePoints(MBB, RS.get());
498 if (!ArePointsInteresting()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000499 LLVM_DEBUG(dbgs() << "EHPad prevents shrink-wrapping\n");
Quentin Colombetc83d7542018-03-20 02:44:40 +0000500 return false;
501 }
502 continue;
503 }
504
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000505 for (const MachineInstr &MI : MBB) {
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000506 if (!useOrDefCSROrFI(MI, RS.get()))
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000507 continue;
508 // Save (resp. restore) point must dominate (resp. post dominate)
509 // MI. Look for the proper basic block for those.
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000510 updateSaveRestorePoints(MBB, RS.get());
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000511 // If we are at a point where we cannot improve the placement of
512 // save/restore instructions, just give up.
513 if (!ArePointsInteresting()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000514 LLVM_DEBUG(dbgs() << "No Shrink wrap candidate found\n");
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000515 return false;
516 }
517 // No need to look for other instructions, this basic block
518 // will already be part of the handled region.
519 break;
520 }
521 }
522 if (!ArePointsInteresting()) {
523 // If the points are not interesting at this point, then they must be null
524 // because it means we did not encounter any frame/CSR related code.
525 // Otherwise, we would have returned from the previous loop.
526 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
Nicola Zaghen0818e782018-05-14 12:53:11 +0000527 LLVM_DEBUG(dbgs() << "Nothing to shrink-wrap\n");
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000528 return false;
529 }
530
Nicola Zaghen0818e782018-05-14 12:53:11 +0000531 LLVM_DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
532 << '\n');
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000533
Quentin Colombetbdfc1172015-05-27 06:25:48 +0000534 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000535 do {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000536 LLVM_DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
537 << Save->getNumber() << ' ' << Save->getName() << ' '
538 << MBFI->getBlockFreq(Save).getFrequency()
539 << "\nRestore: " << Restore->getNumber() << ' '
540 << Restore->getName() << ' '
541 << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000542
Quentin Colombetbdfc1172015-05-27 06:25:48 +0000543 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
544 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
545 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
546 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
547 TFI->canUseAsEpilogue(*Restore)))
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000548 break;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000549 LLVM_DEBUG(
550 dbgs() << "New points are too expensive or invalid for the target\n");
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000551 MachineBasicBlock *NewBB;
Quentin Colombetbdfc1172015-05-27 06:25:48 +0000552 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000553 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
554 if (!Save)
555 break;
556 NewBB = Save;
557 } else {
558 // Restore is expensive.
559 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
560 if (!Restore)
561 break;
562 NewBB = Restore;
563 }
Arnaud A. de Grandmaison8ba4bf92015-11-20 21:54:27 +0000564 updateSaveRestorePoints(*NewBB, RS.get());
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000565 } while (Save && Restore);
566
567 if (!ArePointsInteresting()) {
568 ++NumCandidatesDropped;
569 return false;
570 }
571
Nicola Zaghen0818e782018-05-14 12:53:11 +0000572 LLVM_DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: "
573 << Save->getNumber() << ' ' << Save->getName()
574 << "\nRestore: " << Restore->getNumber() << ' '
575 << Restore->getName() << '\n');
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000576
Matthias Braunf79c57a2016-07-28 18:40:00 +0000577 MachineFrameInfo &MFI = MF.getFrameInfo();
578 MFI.setSavePoint(Save);
579 MFI.setRestorePoint(Restore);
Quentin Colombet2f7322b2015-05-05 17:38:16 +0000580 ++NumCandidates;
581 return false;
582}
Kit Barton21b967e2015-08-31 18:26:45 +0000583
584bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
585 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
586
587 switch (EnableShrinkWrapOpt) {
588 case cl::BOU_UNSET:
Quentin Colombet88d45c62015-11-12 18:13:42 +0000589 return TFI->enableShrinkWrapping(MF) &&
Evgeniy Stepanovd47b5b32017-12-09 00:21:41 +0000590 // Windows with CFI has some limitations that make it impossible
591 // to use shrink-wrapping.
592 !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
593 // Sanitizers look at the value of the stack at the location
594 // of the crash. Since a crash can happen anywhere, the
595 // frame must be lowered before anything else happen for the
596 // sanitizers to be able to get a correct stack frame.
Matthias Braund3181392017-12-15 22:22:58 +0000597 !(MF.getFunction().hasFnAttribute(Attribute::SanitizeAddress) ||
598 MF.getFunction().hasFnAttribute(Attribute::SanitizeThread) ||
599 MF.getFunction().hasFnAttribute(Attribute::SanitizeMemory) ||
600 MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress));
Kit Barton21b967e2015-08-31 18:26:45 +0000601 // If EnableShrinkWrap is set, it takes precedence on whatever the
602 // target sets. The rational is that we assume we want to test
603 // something related to shrink-wrapping.
604 case cl::BOU_TRUE:
605 return true;
606 case cl::BOU_FALSE:
607 return false;
608 }
609 llvm_unreachable("Invalid shrink-wrapping state");
610}