blob: ac71fc2e5bd4e4e5bfe201cc279749cfbfcf9657 [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
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;
David L Kreitzer0fe46322016-05-02 13:45:25 +0000108 MachineRegisterInfo *MRI;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000109 unsigned SlotSize;
110 unsigned Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000111 static char ID;
112};
113
114char X86CallFrameOptimization::ID = 0;
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000115} // end anonymous namespace
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000116
117FunctionPass *llvm::createX86CallFrameOptimization() {
118 return new X86CallFrameOptimization();
119}
120
Michael Kupersteindadb8472015-07-16 13:54:14 +0000121// This checks whether the transformation is legal.
Michael Kupersteindb95d042015-02-12 08:36:35 +0000122// Also returns false in cases where it's potentially legal, but
123// we don't even want to try.
124bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000125 if (NoX86CFOpt.getValue())
126 return false;
127
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000128 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
129 // in the compact unwind encoding that Darwin uses. So, bail if there
130 // is a danger of that being generated.
David L Kreitzer99775c12016-04-12 21:45:09 +0000131 if (STI->isTargetDarwin() &&
132 (!MF.getMMI().getLandingPads().empty() ||
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000133 (MF.getFunction()->needsUnwindTableEntry() && !TFL->hasFP(MF))))
Frederic Riss263b7722015-10-08 15:45:08 +0000134 return false;
135
David L Kreitzer0fe46322016-05-02 13:45:25 +0000136 // It is not valid to change the stack pointer outside the prolog/epilog
137 // on 64-bit Windows.
138 if (STI->isTargetWin64())
139 return false;
140
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000141 // You would expect straight-line code between call-frame setup and
142 // call-frame destroy. You would be wrong. There are circumstances (e.g.
143 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
144 // end up with the setup and the destroy in different basic blocks.
145 // This is bad, and breaks SP adjustment.
146 // So, check that all of the frames in the function are closed inside
147 // the same block, and, for good measure, that there are no nested frames.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000148 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
149 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000150 for (MachineBasicBlock &BB : MF) {
151 bool InsideFrameSequence = false;
152 for (MachineInstr &MI : BB) {
153 if (MI.getOpcode() == FrameSetupOpcode) {
154 if (InsideFrameSequence)
155 return false;
156 InsideFrameSequence = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000157 } else if (MI.getOpcode() == FrameDestroyOpcode) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000158 if (!InsideFrameSequence)
159 return false;
160 InsideFrameSequence = false;
161 }
162 }
163
164 if (InsideFrameSequence)
165 return false;
166 }
167
Michael Kupersteindb95d042015-02-12 08:36:35 +0000168 return true;
169}
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000170
Joerg Sonnenberger772bb5b2016-03-22 22:24:52 +0000171// Check whether this transformation is profitable for a particular
Michael Kupersteindb95d042015-02-12 08:36:35 +0000172// function - in terms of code size.
David L Kreitzer99775c12016-04-12 21:45:09 +0000173bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
174 ContextVector &CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000175 // This transformation is always a win when we do not expect to have
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000176 // a reserved call frame. Under other circumstances, it may be either
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000177 // a win or a loss, and requires a heuristic.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000178 bool CannotReserveFrame = MF.getFrameInfo()->hasVarSizedObjects();
179 if (CannotReserveFrame)
180 return true;
181
Reid Kleckner938bd6f2015-07-16 01:30:00 +0000182 unsigned StackAlign = TFL->getStackAlignment();
Michael Kupersteindadb8472015-07-16 13:54:14 +0000183
Michael Kupersteindb95d042015-02-12 08:36:35 +0000184 int64_t Advantage = 0;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000185 for (auto CC : CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000186 // Call sites where no parameters are passed on the stack
187 // do not affect the cost, since there needs to be no
188 // stack adjustment.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000189 if (CC.NoStackParams)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000190 continue;
191
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000192 if (!CC.UsePush) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000193 // If we don't use pushes for a particular call site,
194 // we pay for not having a reserved call frame with an
195 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
196 // depending on the size of the constant.
197 // TODO: Callee-pop functions should have a smaller penalty, because
198 // an add is needed even with a reserved call frame.
199 Advantage -= 6;
200 } else {
201 // We can use pushes. First, account for the fixed costs.
202 // We'll need a add after the call.
203 Advantage -= 3;
David L Kreitzer0fe46322016-05-02 13:45:25 +0000204 // If we have to realign the stack, we'll also need a sub before
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000205 if (CC.ExpectedDist % StackAlign)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000206 Advantage -= 3;
207 // Now, for each push, we save ~3 bytes. For small constants, we actually,
208 // save more (up to 5 bytes), but 3 should be a good approximation.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000209 Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
Michael Kupersteindb95d042015-02-12 08:36:35 +0000210 }
211 }
212
David L Kreitzer99775c12016-04-12 21:45:09 +0000213 return Advantage >= 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000214}
215
216bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000217 STI = &MF.getSubtarget<X86Subtarget>();
218 TII = STI->getInstrInfo();
219 TFL = STI->getFrameLowering();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000220 MRI = &MF.getRegInfo();
221
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000222 const X86RegisterInfo &RegInfo =
223 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
224 SlotSize = RegInfo.getSlotSize();
225 assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
226 Log2SlotSize = Log2_32(SlotSize);
227
Michael Kupersteindb95d042015-02-12 08:36:35 +0000228 if (!isLegal(MF))
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000229 return false;
230
Matthias Braunfa3872e2015-05-18 20:27:55 +0000231 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000232
233 bool Changed = false;
234
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000235 ContextVector CallSeqVector;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000236
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000237 for (auto &MBB : MF)
238 for (auto &MI : MBB)
239 if (MI.getOpcode() == FrameSetupOpcode) {
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000240 CallContext Context;
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000241 collectCallInfo(MF, MBB, MI, Context);
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000242 CallSeqVector.push_back(Context);
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000243 }
244
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000245 if (!isProfitable(MF, CallSeqVector))
Michael Kupersteindb95d042015-02-12 08:36:35 +0000246 return false;
247
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000248 for (auto CC : CallSeqVector)
249 if (CC.UsePush)
250 Changed |= adjustCallSequence(MF, CC);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000251
252 return Changed;
253}
254
Michael Kupersteindadb8472015-07-16 13:54:14 +0000255X86CallFrameOptimization::InstClassification
256X86CallFrameOptimization::classifyInstruction(
257 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
258 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
259 if (MI == MBB.end())
260 return Exit;
261
262 // The instructions we actually care about are movs onto the stack
263 int Opcode = MI->getOpcode();
David L Kreitzer0fe46322016-05-02 13:45:25 +0000264 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr ||
265 Opcode == X86::MOV64mi32 || Opcode == X86::MOV64mr)
Michael Kupersteindadb8472015-07-16 13:54:14 +0000266 return Convert;
267
268 // Not all calling conventions have only stack MOVs between the stack
269 // adjust and the call.
270
271 // We want to tolerate other instructions, to cover more cases.
272 // In particular:
273 // a) PCrel calls, where we expect an additional COPY of the basereg.
274 // b) Passing frame-index addresses.
275 // c) Calling conventions that have inreg parameters. These generate
276 // both copies and movs into registers.
277 // To avoid creating lots of special cases, allow any instruction
278 // that does not write into memory, does not def or use the stack
279 // pointer, and does not def any register that was used by a preceding
280 // push.
281 // (Reading from memory is allowed, even if referenced through a
282 // frame index, since these will get adjusted properly in PEI)
283
284 // The reason for the last condition is that the pushes can't replace
285 // the movs in place, because the order must be reversed.
286 // So if we have a MOV32mr that uses EDX, then an instruction that defs
287 // EDX, and then the call, after the transformation the push will use
288 // the modified version of EDX, and not the original one.
289 // Since we are still in SSA form at this point, we only need to
290 // make sure we don't clobber any *physical* registers that were
291 // used by an earlier mov that will become a push.
292
293 if (MI->isCall() || MI->mayStore())
294 return Exit;
295
296 for (const MachineOperand &MO : MI->operands()) {
297 if (!MO.isReg())
298 continue;
299 unsigned int Reg = MO.getReg();
300 if (!RegInfo.isPhysicalRegister(Reg))
301 continue;
302 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
303 return Exit;
304 if (MO.isDef()) {
305 for (unsigned int U : UsedRegs)
306 if (RegInfo.regsOverlap(Reg, U))
307 return Exit;
308 }
309 }
310
311 return Skip;
312}
313
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000314void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
315 MachineBasicBlock &MBB,
316 MachineBasicBlock::iterator I,
317 CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000318 // Check that this particular call sequence is amenable to the
319 // transformation.
David L Kreitzer99775c12016-04-12 21:45:09 +0000320 const X86RegisterInfo &RegInfo =
321 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
Matthias Braunfa3872e2015-05-18 20:27:55 +0000322 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000323
324 // We expect to enter this at the beginning of a call sequence
325 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
326 MachineBasicBlock::iterator FrameSetup = I++;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000327 Context.FrameSetup = FrameSetup;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000328
Michael Kupersteindb95d042015-02-12 08:36:35 +0000329 // How much do we adjust the stack? This puts an upper bound on
330 // the number of parameters actually passed on it.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000331 unsigned int MaxAdjust =
332 FrameSetup->getOperand(0).getImm() >> Log2SlotSize;
Michael Kupersteindadb8472015-07-16 13:54:14 +0000333
Michael Kupersteindb95d042015-02-12 08:36:35 +0000334 // A zero adjustment means no stack parameters
335 if (!MaxAdjust) {
336 Context.NoStackParams = true;
337 return;
338 }
339
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000340 // For globals in PIC mode, we can have some LEAs here.
341 // Ignore them, they don't bother us.
342 // TODO: Extend this to something that covers more cases.
343 while (I->getOpcode() == X86::LEA32r)
344 ++I;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000345
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000346 // We expect a copy instruction here.
347 // TODO: The copy instruction is a lowering artifact.
348 // We should also support a copy-less version, where the stack
349 // pointer is used directly.
350 if (!I->isCopy() || !I->getOperand(0).isReg())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000351 return;
352 Context.SPCopy = I++;
Saleem Abdulrasool6bc5ed32015-08-09 20:39:09 +0000353
354 unsigned StackPtr = Context.SPCopy->getOperand(0).getReg();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000355
356 // Scan the call setup sequence for the pattern we're looking for.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000357 // We only handle a simple case - a sequence of store instructions that
358 // push a sequence of stack-slot-aligned values onto the stack, with
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000359 // no gaps between them.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000360 if (MaxAdjust > 4)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000361 Context.MovVector.resize(MaxAdjust, nullptr);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000362
Michael Kupersteindadb8472015-07-16 13:54:14 +0000363 InstClassification Classification;
364 DenseSet<unsigned int> UsedRegs;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000365
Michael Kupersteindadb8472015-07-16 13:54:14 +0000366 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) !=
367 Exit) {
368 if (Classification == Skip) {
369 ++I;
370 continue;
371 }
372
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000373 // We know the instruction has a supported store opcode.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000374 // We only want movs of the form:
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000375 // mov imm/reg, k(%StackPtr)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000376 // If we run into something else, bail.
377 // Note that AddrBaseReg may, counter to its name, not be a register,
378 // but rather a frame index.
379 // TODO: Support the fi case. This should probably work now that we
380 // have the infrastructure to track the stack pointer within a call
381 // sequence.
382 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
383 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
384 !I->getOperand(X86::AddrScaleAmt).isImm() ||
385 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
386 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
387 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
388 !I->getOperand(X86::AddrDisp).isImm())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000389 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000390
391 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000392 assert(StackDisp >= 0 &&
393 "Negative stack displacement when passing parameters");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000394
395 // We really don't want to consider the unaligned case.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000396 if (StackDisp & (SlotSize - 1))
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000397 return;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000398 StackDisp >>= Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000399
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000400 assert((size_t)StackDisp < Context.MovVector.size() &&
401 "Function call has more parameters than the stack is adjusted for.");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000402
403 // If the same stack slot is being filled twice, something's fishy.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000404 if (Context.MovVector[StackDisp] != nullptr)
405 return;
406 Context.MovVector[StackDisp] = I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000407
Michael Kupersteindadb8472015-07-16 13:54:14 +0000408 for (const MachineOperand &MO : I->uses()) {
409 if (!MO.isReg())
410 continue;
411 unsigned int Reg = MO.getReg();
412 if (RegInfo.isPhysicalRegister(Reg))
413 UsedRegs.insert(Reg);
414 }
415
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000416 ++I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000417 }
418
Michael Kupersteindadb8472015-07-16 13:54:14 +0000419 // We now expect the end of the sequence. If we stopped early,
420 // or reached the end of the block without finding a call, bail.
421 if (I == MBB.end() || !I->isCall())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000422 return;
423
424 Context.Call = I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000425 if ((++I)->getOpcode() != FrameDestroyOpcode)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000426 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000427
428 // Now, go through the vector, and see that we don't have any gaps,
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000429 // but only a series of MOVs.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000430 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000431 for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000432 if (*MMI == nullptr)
433 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000434
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000435 // If the call had no parameters, do nothing
436 if (MMI == Context.MovVector.begin())
437 return;
438
439 // We are either at the last parameter, or a gap.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000440 // Make sure it's not a gap
441 for (; MMI != MME; ++MMI)
442 if (*MMI != nullptr)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000443 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000444
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000445 Context.UsePush = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000446}
447
448bool X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000449 const CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000450 // Ok, we can in fact do the transformation for this call.
451 // Do not remove the FrameSetup instruction, but adjust the parameters.
452 // PEI will end up finalizing the handling of this.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000453 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
454 MachineBasicBlock &MBB = *(FrameSetup->getParent());
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000455 FrameSetup->getOperand(1).setImm(Context.ExpectedDist);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000456
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000457 DebugLoc DL = FrameSetup->getDebugLoc();
David L Kreitzer0fe46322016-05-02 13:45:25 +0000458 bool Is64Bit = STI->is64Bit();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000459 // Now, iterate through the vector in reverse order, and replace the movs
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000460 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000461 // replace uses.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000462 for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000463 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000464 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000465 MachineBasicBlock::iterator Push = nullptr;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000466 unsigned PushOpcode;
467 switch (MOV->getOpcode()) {
468 default:
469 llvm_unreachable("Unexpected Opcode!");
470 case X86::MOV32mi:
David L Kreitzer0fe46322016-05-02 13:45:25 +0000471 case X86::MOV64mi32:
472 PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSHi32;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000473 // If the operand is a small (8-bit) immediate, we can use a
474 // PUSH instruction with a shorter encoding.
475 // Note that isImm() may fail even though this is a MOVmi, because
476 // the operand can also be a symbol.
477 if (PushOp.isImm()) {
478 int64_t Val = PushOp.getImm();
479 if (isInt<8>(Val))
David L Kreitzer0fe46322016-05-02 13:45:25 +0000480 PushOpcode = Is64Bit ? X86::PUSH64i8 : X86::PUSH32i8;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000481 }
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000482 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
David L Kreitzer99775c12016-04-12 21:45:09 +0000483 .addOperand(PushOp);
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000484 break;
485 case X86::MOV32mr:
David L Kreitzer0fe46322016-05-02 13:45:25 +0000486 case X86::MOV64mr:
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000487 unsigned int Reg = PushOp.getReg();
488
David L Kreitzer0fe46322016-05-02 13:45:25 +0000489 // If storing a 32-bit vreg on 64-bit targets, extend to a 64-bit vreg
490 // in preparation for the PUSH64. The upper 32 bits can be undef.
491 if (Is64Bit && MOV->getOpcode() == X86::MOV32mr) {
492 unsigned UndefReg = MRI->createVirtualRegister(&X86::GR64RegClass);
493 Reg = MRI->createVirtualRegister(&X86::GR64RegClass);
494 BuildMI(MBB, Context.Call, DL, TII->get(X86::IMPLICIT_DEF), UndefReg);
495 BuildMI(MBB, Context.Call, DL, TII->get(X86::INSERT_SUBREG), Reg)
496 .addReg(UndefReg)
497 .addOperand(PushOp)
498 .addImm(X86::sub_32bit);
499 }
500
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000501 // If PUSHrmm is not slow on this target, try to fold the source of the
502 // push into the instruction.
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000503 bool SlowPUSHrmm = STI->isAtom() || STI->isSLM();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000504
505 // Check that this is legal to fold. Right now, we're extremely
506 // conservative about that.
507 MachineInstr *DefMov = nullptr;
508 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000509 PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000510 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000511
512 unsigned NumOps = DefMov->getDesc().getNumOperands();
513 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
514 Push->addOperand(DefMov->getOperand(i));
515
516 DefMov->eraseFromParent();
517 } else {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000518 PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000519 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
David L Kreitzer99775c12016-04-12 21:45:09 +0000520 .addReg(Reg)
521 .getInstr();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000522 }
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000523 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000524 }
525
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000526 // For debugging, when using SP-based CFA, we need to adjust the CFA
527 // offset after each push.
Michael Kuperstein77ce9d32015-12-06 13:06:20 +0000528 // TODO: This is needed only if we require precise CFA.
529 if (!TFL->hasFP(MF))
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000530 TFL->BuildCFI(
531 MBB, std::next(Push), DL,
532 MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000533
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000534 MBB.erase(MOV);
535 }
536
537 // The stack-pointer copy is no longer used in the call sequences.
538 // There should not be any other users, but we can't commit to that, so:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000539 if (MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
540 Context.SPCopy->eraseFromParent();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000541
542 // Once we've done this, we need to make sure PEI doesn't assume a reserved
543 // frame.
544 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
545 FuncInfo->setHasPushSequences(true);
546
547 return true;
548}
549
550MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
551 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
552 // Do an extremely restricted form of load folding.
553 // ISel will often create patterns like:
554 // movl 4(%edi), %eax
555 // movl 8(%edi), %ecx
556 // movl 12(%edi), %edx
557 // movl %edx, 8(%esp)
558 // movl %ecx, 4(%esp)
559 // movl %eax, (%esp)
560 // call
561 // Get rid of those with prejudice.
562 if (!TargetRegisterInfo::isVirtualRegister(Reg))
563 return nullptr;
564
565 // Make sure this is the only use of Reg.
566 if (!MRI->hasOneNonDBGUse(Reg))
567 return nullptr;
568
569 MachineBasicBlock::iterator DefMI = MRI->getVRegDef(Reg);
570
571 // Make sure the def is a MOV from memory.
572 // If the def is an another block, give up.
David L Kreitzer0fe46322016-05-02 13:45:25 +0000573 if ((DefMI->getOpcode() != X86::MOV32rm &&
574 DefMI->getOpcode() != X86::MOV64rm) ||
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000575 DefMI->getParent() != FrameSetup->getParent())
576 return nullptr;
577
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000578 // Make sure we don't have any instructions between DefMI and the
579 // push that make folding the load illegal.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000580 for (auto I = DefMI; I != FrameSetup; ++I)
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000581 if (I->isLoadFoldBarrier())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000582 return nullptr;
583
584 return DefMI;
585}