blob: a7d157b0dadb80c06215728ab4c3c64ba1e20b54 [file] [log] [blame]
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001//===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a pass that optimizes call sequences on x86.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000011// Currently, it converts movs of function parameters onto the stack into
Michael Kuperstein13fbd452015-02-01 16:56:04 +000012// pushes. This is beneficial for two main reasons:
David L Kreitzerd5cb3412016-04-19 17:43:44 +000013// 1) The push instruction encoding is much smaller than a stack-ptr-based mov.
Michael Kuperstein13fbd452015-02-01 16:56:04 +000014// 2) It is possible to push memory arguments directly. So, if the
David L Kreitzer99775c12016-04-12 21:45:09 +000015// the transformation is performed pre-reg-alloc, it can help relieve
Michael Kuperstein13fbd452015-02-01 16:56:04 +000016// register pressure.
17//
18//===----------------------------------------------------------------------===//
19
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000020#include "MCTargetDesc/X86BaseInfo.h"
21#include "X86FrameLowering.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000022#include "X86InstrInfo.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000023#include "X86MachineFunctionInfo.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000024#include "X86RegisterInfo.h"
David L Kreitzer99775c12016-04-12 21:45:09 +000025#include "X86Subtarget.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000026#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000032#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000033#include "llvm/CodeGen/MachineInstr.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000034#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000035#include "llvm/CodeGen/MachineOperand.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000037#include "llvm/IR/DebugLoc.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000038#include "llvm/IR/Function.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000039#include "llvm/MC/MCDwarf.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/MathExtras.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000043#include "llvm/Target/TargetInstrInfo.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000044#include "llvm/Target/TargetRegisterInfo.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <iterator>
Michael Kuperstein13fbd452015-02-01 16:56:04 +000049
50using namespace llvm;
51
52#define DEBUG_TYPE "x86-cf-opt"
53
Benjamin Kramer970eac42015-02-06 17:51:54 +000054static cl::opt<bool>
55 NoX86CFOpt("no-x86-call-frame-opt",
56 cl::desc("Avoid optimizing x86 call frames for size"),
57 cl::init(false), cl::Hidden);
Michael Kuperstein13fbd452015-02-01 16:56:04 +000058
59namespace {
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000060
Michael Kuperstein13fbd452015-02-01 16:56:04 +000061class X86CallFrameOptimization : public MachineFunctionPass {
62public:
63 X86CallFrameOptimization() : MachineFunctionPass(ID) {}
64
65 bool runOnMachineFunction(MachineFunction &MF) override;
66
67private:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000068 // Information we know about a particular call site
69 struct CallContext {
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000070 CallContext() : FrameSetup(nullptr), MovVector(4, nullptr) {}
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000071
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000072 // Iterator referring to the frame setup instruction
73 MachineBasicBlock::iterator FrameSetup;
74
75 // Actual call instruction
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000076 MachineInstr *Call = nullptr;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000077
78 // A copy of the stack pointer
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000079 MachineInstr *SPCopy = nullptr;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000080
81 // The total displacement of all passed parameters
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000082 int64_t ExpectedDist = 0;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000083
84 // The sequence of movs used to pass the parameters
85 SmallVector<MachineInstr *, 4> MovVector;
86
Michael Kupersteindb95d042015-02-12 08:36:35 +000087 // True if this call site has no stack parameters
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000088 bool NoStackParams = false;
Michael Kupersteindb95d042015-02-12 08:36:35 +000089
David L Kreitzer99775c12016-04-12 21:45:09 +000090 // True if this call site can use push instructions
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000091 bool UsePush = false;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000092 };
93
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000094 typedef SmallVector<CallContext, 8> ContextVector;
Michael Kupersteindb95d042015-02-12 08:36:35 +000095
96 bool isLegal(MachineFunction &MF);
Michael Kupersteindadb8472015-07-16 13:54:14 +000097
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000098 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
Michael Kupersteindb95d042015-02-12 08:36:35 +000099
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000100 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
101 MachineBasicBlock::iterator I, CallContext &Context);
102
Hans Wennborg501e7392016-05-05 16:39:31 +0000103 void adjustCallSequence(MachineFunction &MF, const CallContext &Context);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000104
105 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
106 unsigned Reg);
107
Michael Kupersteindadb8472015-07-16 13:54:14 +0000108 enum InstClassification { Convert, Skip, Exit };
109
110 InstClassification classifyInstruction(MachineBasicBlock &MBB,
111 MachineBasicBlock::iterator MI,
112 const X86RegisterInfo &RegInfo,
113 DenseSet<unsigned int> &UsedRegs);
114
Mehdi Amini117296c2016-10-01 02:56:57 +0000115 StringRef getPassName() const override { return "X86 Optimize Call Frame"; }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000116
Serge Pavlov49acf9c2017-04-13 14:10:52 +0000117 const X86InstrInfo *TII;
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000118 const X86FrameLowering *TFL;
119 const X86Subtarget *STI;
David L Kreitzer0fe46322016-05-02 13:45:25 +0000120 MachineRegisterInfo *MRI;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000121 unsigned SlotSize;
122 unsigned Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000123 static char ID;
124};
125
126char X86CallFrameOptimization::ID = 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000127
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000128} // end anonymous namespace
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000129
Michael Kupersteindadb8472015-07-16 13:54:14 +0000130// This checks whether the transformation is legal.
Michael Kupersteindb95d042015-02-12 08:36:35 +0000131// Also returns false in cases where it's potentially legal, but
132// we don't even want to try.
133bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000134 if (NoX86CFOpt.getValue())
135 return false;
136
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000137 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
138 // in the compact unwind encoding that Darwin uses. So, bail if there
139 // is a danger of that being generated.
David L Kreitzer99775c12016-04-12 21:45:09 +0000140 if (STI->isTargetDarwin() &&
Matthias Braund0ee66c2016-12-01 19:32:15 +0000141 (!MF.getLandingPads().empty() ||
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000142 (MF.getFunction()->needsUnwindTableEntry() && !TFL->hasFP(MF))))
Frederic Riss263b7722015-10-08 15:45:08 +0000143 return false;
144
David L Kreitzer0fe46322016-05-02 13:45:25 +0000145 // It is not valid to change the stack pointer outside the prolog/epilog
146 // on 64-bit Windows.
147 if (STI->isTargetWin64())
148 return false;
149
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000150 // You would expect straight-line code between call-frame setup and
151 // call-frame destroy. You would be wrong. There are circumstances (e.g.
152 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
153 // end up with the setup and the destroy in different basic blocks.
154 // This is bad, and breaks SP adjustment.
155 // So, check that all of the frames in the function are closed inside
156 // the same block, and, for good measure, that there are no nested frames.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000157 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
158 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000159 for (MachineBasicBlock &BB : MF) {
160 bool InsideFrameSequence = false;
161 for (MachineInstr &MI : BB) {
162 if (MI.getOpcode() == FrameSetupOpcode) {
163 if (InsideFrameSequence)
164 return false;
165 InsideFrameSequence = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000166 } else if (MI.getOpcode() == FrameDestroyOpcode) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000167 if (!InsideFrameSequence)
168 return false;
169 InsideFrameSequence = false;
170 }
171 }
172
173 if (InsideFrameSequence)
174 return false;
175 }
176
Michael Kupersteindb95d042015-02-12 08:36:35 +0000177 return true;
178}
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000179
Joerg Sonnenberger772bb5b2016-03-22 22:24:52 +0000180// Check whether this transformation is profitable for a particular
Michael Kupersteindb95d042015-02-12 08:36:35 +0000181// function - in terms of code size.
David L Kreitzer99775c12016-04-12 21:45:09 +0000182bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
183 ContextVector &CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000184 // This transformation is always a win when we do not expect to have
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000185 // a reserved call frame. Under other circumstances, it may be either
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000186 // a win or a loss, and requires a heuristic.
Matthias Braun941a7052016-07-28 18:40:00 +0000187 bool CannotReserveFrame = MF.getFrameInfo().hasVarSizedObjects();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000188 if (CannotReserveFrame)
189 return true;
190
Reid Kleckner938bd6f2015-07-16 01:30:00 +0000191 unsigned StackAlign = TFL->getStackAlignment();
Michael Kupersteindadb8472015-07-16 13:54:14 +0000192
Michael Kupersteindb95d042015-02-12 08:36:35 +0000193 int64_t Advantage = 0;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000194 for (auto CC : CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000195 // Call sites where no parameters are passed on the stack
196 // do not affect the cost, since there needs to be no
197 // stack adjustment.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000198 if (CC.NoStackParams)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000199 continue;
200
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000201 if (!CC.UsePush) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000202 // If we don't use pushes for a particular call site,
203 // we pay for not having a reserved call frame with an
204 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
205 // depending on the size of the constant.
206 // TODO: Callee-pop functions should have a smaller penalty, because
207 // an add is needed even with a reserved call frame.
208 Advantage -= 6;
209 } else {
210 // We can use pushes. First, account for the fixed costs.
211 // We'll need a add after the call.
212 Advantage -= 3;
David L Kreitzer0fe46322016-05-02 13:45:25 +0000213 // If we have to realign the stack, we'll also need a sub before
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000214 if (CC.ExpectedDist % StackAlign)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000215 Advantage -= 3;
216 // Now, for each push, we save ~3 bytes. For small constants, we actually,
217 // save more (up to 5 bytes), but 3 should be a good approximation.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000218 Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
Michael Kupersteindb95d042015-02-12 08:36:35 +0000219 }
220 }
221
David L Kreitzer99775c12016-04-12 21:45:09 +0000222 return Advantage >= 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000223}
224
225bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000226 STI = &MF.getSubtarget<X86Subtarget>();
227 TII = STI->getInstrInfo();
228 TFL = STI->getFrameLowering();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000229 MRI = &MF.getRegInfo();
230
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000231 const X86RegisterInfo &RegInfo =
232 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
233 SlotSize = RegInfo.getSlotSize();
234 assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
235 Log2SlotSize = Log2_32(SlotSize);
236
Petar Jovanovic7b3a38e2017-06-28 10:21:17 +0000237 // Set initial incoming and outgoing cfa offset and register values for basic
238 // blocks. This is done here because this pass runs before PEI and can insert
239 // CFI instructions.
240 // TODO: Find a better solution to this problem.
241 TFL->initializeCFIInfo(MF);
242
Andrew Kaylor81901d62016-08-18 22:49:51 +0000243 if (skipFunction(*MF.getFunction()) || !isLegal(MF))
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000244 return false;
245
Matthias Braunfa3872e2015-05-18 20:27:55 +0000246 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000247
248 bool Changed = false;
249
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000250 ContextVector CallSeqVector;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000251
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000252 for (auto &MBB : MF)
253 for (auto &MI : MBB)
254 if (MI.getOpcode() == FrameSetupOpcode) {
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000255 CallContext Context;
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000256 collectCallInfo(MF, MBB, MI, Context);
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000257 CallSeqVector.push_back(Context);
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000258 }
259
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000260 if (!isProfitable(MF, CallSeqVector))
Michael Kupersteindb95d042015-02-12 08:36:35 +0000261 return false;
262
Hans Wennborg501e7392016-05-05 16:39:31 +0000263 for (auto CC : CallSeqVector) {
264 if (CC.UsePush) {
265 adjustCallSequence(MF, CC);
266 Changed = true;
267 }
268 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000269
270 return Changed;
271}
272
Michael Kupersteindadb8472015-07-16 13:54:14 +0000273X86CallFrameOptimization::InstClassification
274X86CallFrameOptimization::classifyInstruction(
275 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
276 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
277 if (MI == MBB.end())
278 return Exit;
279
280 // The instructions we actually care about are movs onto the stack
281 int Opcode = MI->getOpcode();
David L Kreitzer0fe46322016-05-02 13:45:25 +0000282 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr ||
283 Opcode == X86::MOV64mi32 || Opcode == X86::MOV64mr)
Michael Kupersteindadb8472015-07-16 13:54:14 +0000284 return Convert;
285
286 // Not all calling conventions have only stack MOVs between the stack
287 // adjust and the call.
288
289 // We want to tolerate other instructions, to cover more cases.
290 // In particular:
291 // a) PCrel calls, where we expect an additional COPY of the basereg.
292 // b) Passing frame-index addresses.
293 // c) Calling conventions that have inreg parameters. These generate
294 // both copies and movs into registers.
295 // To avoid creating lots of special cases, allow any instruction
296 // that does not write into memory, does not def or use the stack
297 // pointer, and does not def any register that was used by a preceding
298 // push.
299 // (Reading from memory is allowed, even if referenced through a
300 // frame index, since these will get adjusted properly in PEI)
301
302 // The reason for the last condition is that the pushes can't replace
303 // the movs in place, because the order must be reversed.
304 // So if we have a MOV32mr that uses EDX, then an instruction that defs
305 // EDX, and then the call, after the transformation the push will use
306 // the modified version of EDX, and not the original one.
307 // Since we are still in SSA form at this point, we only need to
308 // make sure we don't clobber any *physical* registers that were
309 // used by an earlier mov that will become a push.
310
311 if (MI->isCall() || MI->mayStore())
312 return Exit;
313
314 for (const MachineOperand &MO : MI->operands()) {
315 if (!MO.isReg())
316 continue;
317 unsigned int Reg = MO.getReg();
318 if (!RegInfo.isPhysicalRegister(Reg))
319 continue;
320 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
321 return Exit;
322 if (MO.isDef()) {
323 for (unsigned int U : UsedRegs)
324 if (RegInfo.regsOverlap(Reg, U))
325 return Exit;
326 }
327 }
328
329 return Skip;
330}
331
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000332void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
333 MachineBasicBlock &MBB,
334 MachineBasicBlock::iterator I,
335 CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000336 // Check that this particular call sequence is amenable to the
337 // transformation.
David L Kreitzer99775c12016-04-12 21:45:09 +0000338 const X86RegisterInfo &RegInfo =
339 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000340
341 // We expect to enter this at the beginning of a call sequence
342 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
343 MachineBasicBlock::iterator FrameSetup = I++;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000344 Context.FrameSetup = FrameSetup;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000345
Michael Kupersteindb95d042015-02-12 08:36:35 +0000346 // How much do we adjust the stack? This puts an upper bound on
347 // the number of parameters actually passed on it.
Serge Pavlov49acf9c2017-04-13 14:10:52 +0000348 unsigned int MaxAdjust = TII->getFrameSize(*FrameSetup) >> Log2SlotSize;
Michael Kupersteindadb8472015-07-16 13:54:14 +0000349
Michael Kupersteindb95d042015-02-12 08:36:35 +0000350 // A zero adjustment means no stack parameters
351 if (!MaxAdjust) {
352 Context.NoStackParams = true;
353 return;
354 }
355
Michael Kuperstein5842b202016-12-07 19:31:08 +0000356 // Skip over DEBUG_VALUE.
357 // For globals in PIC mode, we can have some LEAs here. Skip them as well.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000358 // TODO: Extend this to something that covers more cases.
Michael Kuperstein5842b202016-12-07 19:31:08 +0000359 while (I->getOpcode() == X86::LEA32r || I->isDebugValue())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000360 ++I;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000361
Nico Webereb9488b2016-07-13 21:38:27 +0000362 unsigned StackPtr = RegInfo.getStackRegister();
363 // SelectionDAG (but not FastISel) inserts a copy of ESP into a virtual
364 // register here. If it's there, use that virtual register as stack pointer
365 // instead.
366 if (I->isCopy() && I->getOperand(0).isReg() && I->getOperand(1).isReg() &&
367 I->getOperand(1).getReg() == StackPtr) {
368 Context.SPCopy = &*I++;
369 StackPtr = Context.SPCopy->getOperand(0).getReg();
370 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000371
372 // Scan the call setup sequence for the pattern we're looking for.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000373 // We only handle a simple case - a sequence of store instructions that
374 // push a sequence of stack-slot-aligned values onto the stack, with
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000375 // no gaps between them.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000376 if (MaxAdjust > 4)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000377 Context.MovVector.resize(MaxAdjust, nullptr);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000378
Michael Kupersteindadb8472015-07-16 13:54:14 +0000379 InstClassification Classification;
380 DenseSet<unsigned int> UsedRegs;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000381
Michael Kupersteindadb8472015-07-16 13:54:14 +0000382 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) !=
383 Exit) {
384 if (Classification == Skip) {
385 ++I;
386 continue;
387 }
388
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000389 // We know the instruction has a supported store opcode.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000390 // We only want movs of the form:
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000391 // mov imm/reg, k(%StackPtr)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000392 // If we run into something else, bail.
393 // Note that AddrBaseReg may, counter to its name, not be a register,
394 // but rather a frame index.
395 // TODO: Support the fi case. This should probably work now that we
396 // have the infrastructure to track the stack pointer within a call
397 // sequence.
398 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
399 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
400 !I->getOperand(X86::AddrScaleAmt).isImm() ||
401 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
402 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
403 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
404 !I->getOperand(X86::AddrDisp).isImm())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000405 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000406
407 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000408 assert(StackDisp >= 0 &&
409 "Negative stack displacement when passing parameters");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000410
411 // We really don't want to consider the unaligned case.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000412 if (StackDisp & (SlotSize - 1))
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000413 return;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000414 StackDisp >>= Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000415
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000416 assert((size_t)StackDisp < Context.MovVector.size() &&
417 "Function call has more parameters than the stack is adjusted for.");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000418
419 // If the same stack slot is being filled twice, something's fishy.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000420 if (Context.MovVector[StackDisp] != nullptr)
421 return;
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000422 Context.MovVector[StackDisp] = &*I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000423
Michael Kupersteindadb8472015-07-16 13:54:14 +0000424 for (const MachineOperand &MO : I->uses()) {
425 if (!MO.isReg())
426 continue;
427 unsigned int Reg = MO.getReg();
428 if (RegInfo.isPhysicalRegister(Reg))
429 UsedRegs.insert(Reg);
430 }
431
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000432 ++I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000433 }
434
Michael Kupersteindadb8472015-07-16 13:54:14 +0000435 // We now expect the end of the sequence. If we stopped early,
436 // or reached the end of the block without finding a call, bail.
437 if (I == MBB.end() || !I->isCall())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000438 return;
439
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000440 Context.Call = &*I;
Serge Pavlov49acf9c2017-04-13 14:10:52 +0000441 if ((++I)->getOpcode() != TII->getCallFrameDestroyOpcode())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000442 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000443
444 // Now, go through the vector, and see that we don't have any gaps,
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000445 // but only a series of MOVs.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000446 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000447 for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000448 if (*MMI == nullptr)
449 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000450
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000451 // If the call had no parameters, do nothing
452 if (MMI == Context.MovVector.begin())
453 return;
454
455 // We are either at the last parameter, or a gap.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000456 // Make sure it's not a gap
457 for (; MMI != MME; ++MMI)
458 if (*MMI != nullptr)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000459 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000460
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000461 Context.UsePush = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000462}
463
Hans Wennborg501e7392016-05-05 16:39:31 +0000464void X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000465 const CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000466 // Ok, we can in fact do the transformation for this call.
467 // Do not remove the FrameSetup instruction, but adjust the parameters.
468 // PEI will end up finalizing the handling of this.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000469 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
470 MachineBasicBlock &MBB = *(FrameSetup->getParent());
Serge Pavlov49acf9c2017-04-13 14:10:52 +0000471 TII->setFrameAdjustment(*FrameSetup, Context.ExpectedDist);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000472
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000473 DebugLoc DL = FrameSetup->getDebugLoc();
David L Kreitzer0fe46322016-05-02 13:45:25 +0000474 bool Is64Bit = STI->is64Bit();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000475 // Now, iterate through the vector in reverse order, and replace the movs
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000476 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000477 // replace uses.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000478 for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000479 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000480 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000481 MachineBasicBlock::iterator Push = nullptr;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000482 unsigned PushOpcode;
483 switch (MOV->getOpcode()) {
484 default:
485 llvm_unreachable("Unexpected Opcode!");
486 case X86::MOV32mi:
David L Kreitzer0fe46322016-05-02 13:45:25 +0000487 case X86::MOV64mi32:
488 PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSHi32;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000489 // If the operand is a small (8-bit) immediate, we can use a
490 // PUSH instruction with a shorter encoding.
491 // Note that isImm() may fail even though this is a MOVmi, because
492 // the operand can also be a symbol.
493 if (PushOp.isImm()) {
494 int64_t Val = PushOp.getImm();
495 if (isInt<8>(Val))
David L Kreitzer0fe46322016-05-02 13:45:25 +0000496 PushOpcode = Is64Bit ? X86::PUSH64i8 : X86::PUSH32i8;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000497 }
Diana Picus116bbab2017-01-13 09:58:52 +0000498 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).add(PushOp);
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000499 break;
500 case X86::MOV32mr:
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000501 case X86::MOV64mr: {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000502 unsigned int Reg = PushOp.getReg();
503
David L Kreitzer0fe46322016-05-02 13:45:25 +0000504 // If storing a 32-bit vreg on 64-bit targets, extend to a 64-bit vreg
505 // in preparation for the PUSH64. The upper 32 bits can be undef.
506 if (Is64Bit && MOV->getOpcode() == X86::MOV32mr) {
507 unsigned UndefReg = MRI->createVirtualRegister(&X86::GR64RegClass);
508 Reg = MRI->createVirtualRegister(&X86::GR64RegClass);
509 BuildMI(MBB, Context.Call, DL, TII->get(X86::IMPLICIT_DEF), UndefReg);
510 BuildMI(MBB, Context.Call, DL, TII->get(X86::INSERT_SUBREG), Reg)
Diana Picus116bbab2017-01-13 09:58:52 +0000511 .addReg(UndefReg)
512 .add(PushOp)
513 .addImm(X86::sub_32bit);
David L Kreitzer0fe46322016-05-02 13:45:25 +0000514 }
515
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000516 // If PUSHrmm is not slow on this target, try to fold the source of the
517 // push into the instruction.
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000518 bool SlowPUSHrmm = STI->isAtom() || STI->isSLM();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000519
520 // Check that this is legal to fold. Right now, we're extremely
521 // conservative about that.
522 MachineInstr *DefMov = nullptr;
523 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000524 PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000525 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000526
527 unsigned NumOps = DefMov->getDesc().getNumOperands();
528 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
529 Push->addOperand(DefMov->getOperand(i));
530
531 DefMov->eraseFromParent();
532 } else {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000533 PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000534 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
David L Kreitzer99775c12016-04-12 21:45:09 +0000535 .addReg(Reg)
536 .getInstr();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000537 }
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000538 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000539 }
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000540 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000541
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000542 // For debugging, when using SP-based CFA, we need to adjust the CFA
543 // offset after each push.
Michael Kuperstein77ce9d32015-12-06 13:06:20 +0000544 // TODO: This is needed only if we require precise CFA.
Petar Jovanovic7b3a38e2017-06-28 10:21:17 +0000545 if (!TFL->hasFP(MF)) {
546 TFL->BuildCFI(MBB, std::next(Push), DL,
547 MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
548 // Update the CFI information for MBB and it's successors.
549 MBB.updateCFIInfo(std::next(Push));
550 MBB.updateCFIInfoSucc();
551 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000552 MBB.erase(MOV);
553 }
554
555 // The stack-pointer copy is no longer used in the call sequences.
556 // There should not be any other users, but we can't commit to that, so:
Nico Webereb9488b2016-07-13 21:38:27 +0000557 if (Context.SPCopy && MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000558 Context.SPCopy->eraseFromParent();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000559
560 // Once we've done this, we need to make sure PEI doesn't assume a reserved
561 // frame.
562 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
563 FuncInfo->setHasPushSequences(true);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000564}
565
566MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
567 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
568 // Do an extremely restricted form of load folding.
569 // ISel will often create patterns like:
570 // movl 4(%edi), %eax
571 // movl 8(%edi), %ecx
572 // movl 12(%edi), %edx
573 // movl %edx, 8(%esp)
574 // movl %ecx, 4(%esp)
575 // movl %eax, (%esp)
576 // call
577 // Get rid of those with prejudice.
578 if (!TargetRegisterInfo::isVirtualRegister(Reg))
579 return nullptr;
580
581 // Make sure this is the only use of Reg.
582 if (!MRI->hasOneNonDBGUse(Reg))
583 return nullptr;
584
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000585 MachineInstr &DefMI = *MRI->getVRegDef(Reg);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000586
587 // Make sure the def is a MOV from memory.
David L Kreitzer29711c02016-06-30 21:43:11 +0000588 // If the def is in another block, give up.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000589 if ((DefMI.getOpcode() != X86::MOV32rm &&
590 DefMI.getOpcode() != X86::MOV64rm) ||
591 DefMI.getParent() != FrameSetup->getParent())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000592 return nullptr;
593
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000594 // Make sure we don't have any instructions between DefMI and the
595 // push that make folding the load illegal.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000596 for (MachineBasicBlock::iterator I = DefMI; I != FrameSetup; ++I)
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000597 if (I->isLoadFoldBarrier())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000598 return nullptr;
599
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000600 return &DefMI;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000601}
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000602
603FunctionPass *llvm::createX86CallFrameOptimization() {
604 return new X86CallFrameOptimization();
605}