blob: 70d29e4cb27c300b5018138f52326c85c5b7fd92 [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:
13// 1) The push instruction encoding is much smaller than an esp-relative mov
14// 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
20#include <algorithm>
21
22#include "X86.h"
23#include "X86InstrInfo.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000024#include "X86MachineFunctionInfo.h"
David L Kreitzer99775c12016-04-12 21:45:09 +000025#include "X86Subtarget.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000026#include "llvm/ADT/Statistic.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
28#include "llvm/CodeGen/MachineInstrBuilder.h"
Frederic Riss263b7722015-10-08 15:45:08 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/IR/Function.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetInstrInfo.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "x86-cf-opt"
40
Benjamin Kramer970eac42015-02-06 17:51:54 +000041static cl::opt<bool>
42 NoX86CFOpt("no-x86-call-frame-opt",
43 cl::desc("Avoid optimizing x86 call frames for size"),
44 cl::init(false), cl::Hidden);
Michael Kuperstein13fbd452015-02-01 16:56:04 +000045
46namespace {
47class X86CallFrameOptimization : public MachineFunctionPass {
48public:
49 X86CallFrameOptimization() : MachineFunctionPass(ID) {}
50
51 bool runOnMachineFunction(MachineFunction &MF) override;
52
53private:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000054 // Information we know about a particular call site
55 struct CallContext {
56 CallContext()
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000057 : FrameSetup(nullptr), Call(nullptr), SPCopy(nullptr), ExpectedDist(0),
David L Kreitzer99775c12016-04-12 21:45:09 +000058 MovVector(4, nullptr), NoStackParams(false), UsePush(false) {}
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000059
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000060 // Iterator referring to the frame setup instruction
61 MachineBasicBlock::iterator FrameSetup;
62
63 // Actual call instruction
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000064 MachineInstr *Call;
65
66 // A copy of the stack pointer
67 MachineInstr *SPCopy;
68
69 // The total displacement of all passed parameters
70 int64_t ExpectedDist;
71
72 // The sequence of movs used to pass the parameters
73 SmallVector<MachineInstr *, 4> MovVector;
74
Michael Kupersteindb95d042015-02-12 08:36:35 +000075 // True if this call site has no stack parameters
76 bool NoStackParams;
77
David L Kreitzer99775c12016-04-12 21:45:09 +000078 // True if this call site can use push instructions
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000079 bool UsePush;
80 };
81
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000082 typedef SmallVector<CallContext, 8> ContextVector;
Michael Kupersteindb95d042015-02-12 08:36:35 +000083
84 bool isLegal(MachineFunction &MF);
Michael Kupersteindadb8472015-07-16 13:54:14 +000085
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000086 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
Michael Kupersteindb95d042015-02-12 08:36:35 +000087
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000088 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
89 MachineBasicBlock::iterator I, CallContext &Context);
90
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000091 bool adjustCallSequence(MachineFunction &MF, const CallContext &Context);
Michael Kuperstein13fbd452015-02-01 16:56:04 +000092
93 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
94 unsigned Reg);
95
Michael Kupersteindadb8472015-07-16 13:54:14 +000096 enum InstClassification { Convert, Skip, Exit };
97
98 InstClassification classifyInstruction(MachineBasicBlock &MBB,
99 MachineBasicBlock::iterator MI,
100 const X86RegisterInfo &RegInfo,
101 DenseSet<unsigned int> &UsedRegs);
102
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000103 const char *getPassName() const override { return "X86 Optimize Call Frame"; }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000104
105 const TargetInstrInfo *TII;
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000106 const X86FrameLowering *TFL;
107 const X86Subtarget *STI;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000108 const MachineRegisterInfo *MRI;
109 static char ID;
110};
111
112char X86CallFrameOptimization::ID = 0;
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000113} // end anonymous namespace
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000114
115FunctionPass *llvm::createX86CallFrameOptimization() {
116 return new X86CallFrameOptimization();
117}
118
Michael Kupersteindadb8472015-07-16 13:54:14 +0000119// This checks whether the transformation is legal.
Michael Kupersteindb95d042015-02-12 08:36:35 +0000120// Also returns false in cases where it's potentially legal, but
121// we don't even want to try.
122bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000123 if (NoX86CFOpt.getValue())
124 return false;
125
126 // We currently only support call sequences where *all* parameters.
127 // are passed on the stack.
128 // No point in running this in 64-bit mode, since some arguments are
129 // passed in-register in all common calling conventions, so the pattern
130 // we're looking for will never match.
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000131 if (STI->is64Bit())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000132 return false;
133
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000134 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
135 // in the compact unwind encoding that Darwin uses. So, bail if there
136 // is a danger of that being generated.
David L Kreitzer99775c12016-04-12 21:45:09 +0000137 if (STI->isTargetDarwin() &&
138 (!MF.getMMI().getLandingPads().empty() ||
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000139 (MF.getFunction()->needsUnwindTableEntry() && !TFL->hasFP(MF))))
Frederic Riss263b7722015-10-08 15:45:08 +0000140 return false;
141
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000142 // You would expect straight-line code between call-frame setup and
143 // call-frame destroy. You would be wrong. There are circumstances (e.g.
144 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
145 // end up with the setup and the destroy in different basic blocks.
146 // This is bad, and breaks SP adjustment.
147 // So, check that all of the frames in the function are closed inside
148 // the same block, and, for good measure, that there are no nested frames.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000149 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
150 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000151 for (MachineBasicBlock &BB : MF) {
152 bool InsideFrameSequence = false;
153 for (MachineInstr &MI : BB) {
154 if (MI.getOpcode() == FrameSetupOpcode) {
155 if (InsideFrameSequence)
156 return false;
157 InsideFrameSequence = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000158 } else if (MI.getOpcode() == FrameDestroyOpcode) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000159 if (!InsideFrameSequence)
160 return false;
161 InsideFrameSequence = false;
162 }
163 }
164
165 if (InsideFrameSequence)
166 return false;
167 }
168
Michael Kupersteindb95d042015-02-12 08:36:35 +0000169 return true;
170}
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000171
Joerg Sonnenberger772bb5b2016-03-22 22:24:52 +0000172// Check whether this transformation is profitable for a particular
Michael Kupersteindb95d042015-02-12 08:36:35 +0000173// function - in terms of code size.
David L Kreitzer99775c12016-04-12 21:45:09 +0000174bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
175 ContextVector &CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000176 // This transformation is always a win when we do not expect to have
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000177 // a reserved call frame. Under other circumstances, it may be either
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000178 // a win or a loss, and requires a heuristic.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000179 bool CannotReserveFrame = MF.getFrameInfo()->hasVarSizedObjects();
180 if (CannotReserveFrame)
181 return true;
182
Reid Kleckner938bd6f2015-07-16 01:30:00 +0000183 unsigned StackAlign = TFL->getStackAlignment();
Michael Kupersteindadb8472015-07-16 13:54:14 +0000184
Michael Kupersteindb95d042015-02-12 08:36:35 +0000185 int64_t Advantage = 0;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000186 for (auto CC : CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000187 // Call sites where no parameters are passed on the stack
188 // do not affect the cost, since there needs to be no
189 // stack adjustment.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000190 if (CC.NoStackParams)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000191 continue;
192
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000193 if (!CC.UsePush) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000194 // If we don't use pushes for a particular call site,
195 // we pay for not having a reserved call frame with an
196 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
197 // depending on the size of the constant.
198 // TODO: Callee-pop functions should have a smaller penalty, because
199 // an add is needed even with a reserved call frame.
200 Advantage -= 6;
201 } else {
202 // We can use pushes. First, account for the fixed costs.
203 // We'll need a add after the call.
204 Advantage -= 3;
205 // If we have to realign the stack, we'll also need and sub before
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000206 if (CC.ExpectedDist % StackAlign)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000207 Advantage -= 3;
208 // Now, for each push, we save ~3 bytes. For small constants, we actually,
209 // save more (up to 5 bytes), but 3 should be a good approximation.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000210 Advantage += (CC.ExpectedDist / 4) * 3;
Michael Kupersteindb95d042015-02-12 08:36:35 +0000211 }
212 }
213
David L Kreitzer99775c12016-04-12 21:45:09 +0000214 return Advantage >= 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000215}
216
217bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000218 STI = &MF.getSubtarget<X86Subtarget>();
219 TII = STI->getInstrInfo();
220 TFL = STI->getFrameLowering();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000221 MRI = &MF.getRegInfo();
222
Michael Kupersteindb95d042015-02-12 08:36:35 +0000223 if (!isLegal(MF))
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000224 return false;
225
Matthias Braunfa3872e2015-05-18 20:27:55 +0000226 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000227
228 bool Changed = false;
229
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000230 ContextVector CallSeqVector;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000231
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000232 for (auto &MBB : MF)
233 for (auto &MI : MBB)
234 if (MI.getOpcode() == FrameSetupOpcode) {
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000235 CallContext Context;
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000236 collectCallInfo(MF, MBB, MI, Context);
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000237 CallSeqVector.push_back(Context);
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000238 }
239
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000240 if (!isProfitable(MF, CallSeqVector))
Michael Kupersteindb95d042015-02-12 08:36:35 +0000241 return false;
242
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000243 for (auto CC : CallSeqVector)
244 if (CC.UsePush)
245 Changed |= adjustCallSequence(MF, CC);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000246
247 return Changed;
248}
249
Michael Kupersteindadb8472015-07-16 13:54:14 +0000250X86CallFrameOptimization::InstClassification
251X86CallFrameOptimization::classifyInstruction(
252 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
253 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
254 if (MI == MBB.end())
255 return Exit;
256
257 // The instructions we actually care about are movs onto the stack
258 int Opcode = MI->getOpcode();
259 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr)
260 return Convert;
261
262 // Not all calling conventions have only stack MOVs between the stack
263 // adjust and the call.
264
265 // We want to tolerate other instructions, to cover more cases.
266 // In particular:
267 // a) PCrel calls, where we expect an additional COPY of the basereg.
268 // b) Passing frame-index addresses.
269 // c) Calling conventions that have inreg parameters. These generate
270 // both copies and movs into registers.
271 // To avoid creating lots of special cases, allow any instruction
272 // that does not write into memory, does not def or use the stack
273 // pointer, and does not def any register that was used by a preceding
274 // push.
275 // (Reading from memory is allowed, even if referenced through a
276 // frame index, since these will get adjusted properly in PEI)
277
278 // The reason for the last condition is that the pushes can't replace
279 // the movs in place, because the order must be reversed.
280 // So if we have a MOV32mr that uses EDX, then an instruction that defs
281 // EDX, and then the call, after the transformation the push will use
282 // the modified version of EDX, and not the original one.
283 // Since we are still in SSA form at this point, we only need to
284 // make sure we don't clobber any *physical* registers that were
285 // used by an earlier mov that will become a push.
286
287 if (MI->isCall() || MI->mayStore())
288 return Exit;
289
290 for (const MachineOperand &MO : MI->operands()) {
291 if (!MO.isReg())
292 continue;
293 unsigned int Reg = MO.getReg();
294 if (!RegInfo.isPhysicalRegister(Reg))
295 continue;
296 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
297 return Exit;
298 if (MO.isDef()) {
299 for (unsigned int U : UsedRegs)
300 if (RegInfo.regsOverlap(Reg, U))
301 return Exit;
302 }
303 }
304
305 return Skip;
306}
307
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000308void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
309 MachineBasicBlock &MBB,
310 MachineBasicBlock::iterator I,
311 CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000312 // Check that this particular call sequence is amenable to the
313 // transformation.
David L Kreitzer99775c12016-04-12 21:45:09 +0000314 const X86RegisterInfo &RegInfo =
315 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
Matthias Braunfa3872e2015-05-18 20:27:55 +0000316 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000317
318 // We expect to enter this at the beginning of a call sequence
319 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
320 MachineBasicBlock::iterator FrameSetup = I++;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000321 Context.FrameSetup = FrameSetup;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000322
Michael Kupersteindb95d042015-02-12 08:36:35 +0000323 // How much do we adjust the stack? This puts an upper bound on
324 // the number of parameters actually passed on it.
Michael Kupersteindadb8472015-07-16 13:54:14 +0000325 unsigned int MaxAdjust = FrameSetup->getOperand(0).getImm() / 4;
326
Michael Kupersteindb95d042015-02-12 08:36:35 +0000327 // A zero adjustment means no stack parameters
328 if (!MaxAdjust) {
329 Context.NoStackParams = true;
330 return;
331 }
332
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000333 // For globals in PIC mode, we can have some LEAs here.
334 // Ignore them, they don't bother us.
335 // TODO: Extend this to something that covers more cases.
336 while (I->getOpcode() == X86::LEA32r)
337 ++I;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000338
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000339 // We expect a copy instruction here.
340 // TODO: The copy instruction is a lowering artifact.
341 // We should also support a copy-less version, where the stack
342 // pointer is used directly.
343 if (!I->isCopy() || !I->getOperand(0).isReg())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000344 return;
345 Context.SPCopy = I++;
Saleem Abdulrasool6bc5ed32015-08-09 20:39:09 +0000346
347 unsigned StackPtr = Context.SPCopy->getOperand(0).getReg();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000348
349 // Scan the call setup sequence for the pattern we're looking for.
350 // We only handle a simple case - a sequence of MOV32mi or MOV32mr
351 // instructions, that push a sequence of 32-bit values onto the stack, with
352 // no gaps between them.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000353 if (MaxAdjust > 4)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000354 Context.MovVector.resize(MaxAdjust, nullptr);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000355
Michael Kupersteindadb8472015-07-16 13:54:14 +0000356 InstClassification Classification;
357 DenseSet<unsigned int> UsedRegs;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000358
Michael Kupersteindadb8472015-07-16 13:54:14 +0000359 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) !=
360 Exit) {
361 if (Classification == Skip) {
362 ++I;
363 continue;
364 }
365
366 // We know the instruction is a MOV32mi/MOV32mr.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000367 // We only want movs of the form:
368 // movl imm/r32, k(%esp)
369 // If we run into something else, bail.
370 // Note that AddrBaseReg may, counter to its name, not be a register,
371 // but rather a frame index.
372 // TODO: Support the fi case. This should probably work now that we
373 // have the infrastructure to track the stack pointer within a call
374 // sequence.
375 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
376 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
377 !I->getOperand(X86::AddrScaleAmt).isImm() ||
378 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
379 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
380 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
381 !I->getOperand(X86::AddrDisp).isImm())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000382 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000383
384 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000385 assert(StackDisp >= 0 &&
386 "Negative stack displacement when passing parameters");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000387
388 // We really don't want to consider the unaligned case.
389 if (StackDisp % 4)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000390 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000391 StackDisp /= 4;
392
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000393 assert((size_t)StackDisp < Context.MovVector.size() &&
394 "Function call has more parameters than the stack is adjusted for.");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000395
396 // If the same stack slot is being filled twice, something's fishy.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000397 if (Context.MovVector[StackDisp] != nullptr)
398 return;
399 Context.MovVector[StackDisp] = I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000400
Michael Kupersteindadb8472015-07-16 13:54:14 +0000401 for (const MachineOperand &MO : I->uses()) {
402 if (!MO.isReg())
403 continue;
404 unsigned int Reg = MO.getReg();
405 if (RegInfo.isPhysicalRegister(Reg))
406 UsedRegs.insert(Reg);
407 }
408
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000409 ++I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000410 }
411
Michael Kupersteindadb8472015-07-16 13:54:14 +0000412 // We now expect the end of the sequence. If we stopped early,
413 // or reached the end of the block without finding a call, bail.
414 if (I == MBB.end() || !I->isCall())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000415 return;
416
417 Context.Call = I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000418 if ((++I)->getOpcode() != FrameDestroyOpcode)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000419 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000420
421 // Now, go through the vector, and see that we don't have any gaps,
422 // but only a series of 32-bit MOVs.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000423 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
424 for (; MMI != MME; ++MMI, Context.ExpectedDist += 4)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000425 if (*MMI == nullptr)
426 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000427
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000428 // If the call had no parameters, do nothing
429 if (MMI == Context.MovVector.begin())
430 return;
431
432 // We are either at the last parameter, or a gap.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000433 // Make sure it's not a gap
434 for (; MMI != MME; ++MMI)
435 if (*MMI != nullptr)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000436 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000437
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000438 Context.UsePush = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000439}
440
441bool X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000442 const CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000443 // Ok, we can in fact do the transformation for this call.
444 // Do not remove the FrameSetup instruction, but adjust the parameters.
445 // PEI will end up finalizing the handling of this.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000446 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
447 MachineBasicBlock &MBB = *(FrameSetup->getParent());
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000448 FrameSetup->getOperand(1).setImm(Context.ExpectedDist);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000449
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000450 DebugLoc DL = FrameSetup->getDebugLoc();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000451 // Now, iterate through the vector in reverse order, and replace the movs
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000452 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000453 // replace uses.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000454 for (int Idx = (Context.ExpectedDist / 4) - 1; Idx >= 0; --Idx) {
455 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000456 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000457 MachineBasicBlock::iterator Push = nullptr;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000458 if (MOV->getOpcode() == X86::MOV32mi) {
459 unsigned PushOpcode = X86::PUSHi32;
460 // If the operand is a small (8-bit) immediate, we can use a
461 // PUSH instruction with a shorter encoding.
462 // Note that isImm() may fail even though this is a MOVmi, because
463 // the operand can also be a symbol.
464 if (PushOp.isImm()) {
465 int64_t Val = PushOp.getImm();
466 if (isInt<8>(Val))
467 PushOpcode = X86::PUSH32i8;
468 }
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000469 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
David L Kreitzer99775c12016-04-12 21:45:09 +0000470 .addOperand(PushOp);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000471 } else {
472 unsigned int Reg = PushOp.getReg();
473
474 // If PUSHrmm is not slow on this target, try to fold the source of the
475 // push into the instruction.
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000476 bool SlowPUSHrmm = STI->isAtom() || STI->isSLM();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000477
478 // Check that this is legal to fold. Right now, we're extremely
479 // conservative about that.
480 MachineInstr *DefMov = nullptr;
481 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000482 Push = BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32rmm));
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000483
484 unsigned NumOps = DefMov->getDesc().getNumOperands();
485 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
486 Push->addOperand(DefMov->getOperand(i));
487
488 DefMov->eraseFromParent();
489 } else {
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000490 Push = BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32r))
David L Kreitzer99775c12016-04-12 21:45:09 +0000491 .addReg(Reg)
492 .getInstr();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000493 }
494 }
495
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000496 // For debugging, when using SP-based CFA, we need to adjust the CFA
497 // offset after each push.
Michael Kuperstein77ce9d32015-12-06 13:06:20 +0000498 // TODO: This is needed only if we require precise CFA.
499 if (!TFL->hasFP(MF))
David L Kreitzer99775c12016-04-12 21:45:09 +0000500 TFL->BuildCFI(MBB, std::next(Push), DL,
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000501 MCCFIInstruction::createAdjustCfaOffset(nullptr, 4));
502
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000503 MBB.erase(MOV);
504 }
505
506 // The stack-pointer copy is no longer used in the call sequences.
507 // There should not be any other users, but we can't commit to that, so:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000508 if (MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
509 Context.SPCopy->eraseFromParent();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000510
511 // Once we've done this, we need to make sure PEI doesn't assume a reserved
512 // frame.
513 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
514 FuncInfo->setHasPushSequences(true);
515
516 return true;
517}
518
519MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
520 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
521 // Do an extremely restricted form of load folding.
522 // ISel will often create patterns like:
523 // movl 4(%edi), %eax
524 // movl 8(%edi), %ecx
525 // movl 12(%edi), %edx
526 // movl %edx, 8(%esp)
527 // movl %ecx, 4(%esp)
528 // movl %eax, (%esp)
529 // call
530 // Get rid of those with prejudice.
531 if (!TargetRegisterInfo::isVirtualRegister(Reg))
532 return nullptr;
533
534 // Make sure this is the only use of Reg.
535 if (!MRI->hasOneNonDBGUse(Reg))
536 return nullptr;
537
538 MachineBasicBlock::iterator DefMI = MRI->getVRegDef(Reg);
539
540 // Make sure the def is a MOV from memory.
541 // If the def is an another block, give up.
542 if (DefMI->getOpcode() != X86::MOV32rm ||
543 DefMI->getParent() != FrameSetup->getParent())
544 return nullptr;
545
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000546 // Make sure we don't have any instructions between DefMI and the
547 // push that make folding the load illegal.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000548 for (auto I = DefMI; I != FrameSetup; ++I)
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000549 if (I->isLoadFoldBarrier())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000550 return nullptr;
551
552 return DefMI;
553}