1 //===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a pass that optimizes call sequences on x86.
11 // Currently, it converts movs of function parameters onto the stack into
12 // 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
15 // the transformation is preformed pre-reg-alloc, it can help relieve
18 //===----------------------------------------------------------------------===//
23 #include "X86InstrInfo.h"
24 #include "X86Subtarget.h"
25 #include "X86MachineFunctionInfo.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
38 #define DEBUG_TYPE "x86-cf-opt"
41 NoX86CFOpt("no-x86-call-frame-opt",
42 cl::desc("Avoid optimizing x86 call frames for size"),
43 cl::init(false), cl::Hidden);
46 class X86CallFrameOptimization : public MachineFunctionPass {
48 X86CallFrameOptimization() : MachineFunctionPass(ID) {}
50 bool runOnMachineFunction(MachineFunction &MF) override;
53 // Information we know about a particular call site
56 : FrameSetup(nullptr), Call(nullptr), SPCopy(nullptr), ExpectedDist(0),
57 MovVector(4, nullptr), NoStackParams(false), UsePush(false){}
59 // Iterator referring to the frame setup instruction
60 MachineBasicBlock::iterator FrameSetup;
62 // Actual call instruction
65 // A copy of the stack pointer
68 // The total displacement of all passed parameters
71 // The sequence of movs used to pass the parameters
72 SmallVector<MachineInstr *, 4> MovVector;
74 // True if this call site has no stack parameters
77 // True of this callsite can use push instructions
81 typedef SmallVector<CallContext, 8> ContextVector;
83 bool isLegal(MachineFunction &MF);
85 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
87 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
88 MachineBasicBlock::iterator I, CallContext &Context);
90 bool adjustCallSequence(MachineFunction &MF, const CallContext &Context);
92 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
95 enum InstClassification { Convert, Skip, Exit };
97 InstClassification classifyInstruction(MachineBasicBlock &MBB,
98 MachineBasicBlock::iterator MI,
99 const X86RegisterInfo &RegInfo,
100 DenseSet<unsigned int> &UsedRegs);
102 const char *getPassName() const override { return "X86 Optimize Call Frame"; }
104 const TargetInstrInfo *TII;
105 const TargetFrameLowering *TFL;
106 const MachineRegisterInfo *MRI;
110 char X86CallFrameOptimization::ID = 0;
113 FunctionPass *llvm::createX86CallFrameOptimization() {
114 return new X86CallFrameOptimization();
117 // This checks whether the transformation is legal.
118 // Also returns false in cases where it's potentially legal, but
119 // we don't even want to try.
120 bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
121 if (NoX86CFOpt.getValue())
124 // We currently only support call sequences where *all* parameters.
125 // are passed on the stack.
126 // No point in running this in 64-bit mode, since some arguments are
127 // passed in-register in all common calling conventions, so the pattern
128 // we're looking for will never match.
129 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
133 // You would expect straight-line code between call-frame setup and
134 // call-frame destroy. You would be wrong. There are circumstances (e.g.
135 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
136 // end up with the setup and the destroy in different basic blocks.
137 // This is bad, and breaks SP adjustment.
138 // So, check that all of the frames in the function are closed inside
139 // the same block, and, for good measure, that there are no nested frames.
140 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
141 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
142 for (MachineBasicBlock &BB : MF) {
143 bool InsideFrameSequence = false;
144 for (MachineInstr &MI : BB) {
145 if (MI.getOpcode() == FrameSetupOpcode) {
146 if (InsideFrameSequence)
148 InsideFrameSequence = true;
149 } else if (MI.getOpcode() == FrameDestroyOpcode) {
150 if (!InsideFrameSequence)
152 InsideFrameSequence = false;
156 if (InsideFrameSequence)
163 // Check whether this trasnformation is profitable for a particular
164 // function - in terms of code size.
165 bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
166 ContextVector &CallSeqVector) {
167 // This transformation is always a win when we do not expect to have
168 // a reserved call frame. Under other circumstances, it may be either
169 // a win or a loss, and requires a heuristic.
170 bool CannotReserveFrame = MF.getFrameInfo()->hasVarSizedObjects();
171 if (CannotReserveFrame)
174 // Don't do this when not optimizing for size.
175 if (!MF.getFunction()->optForSize())
178 unsigned StackAlign = TFL->getStackAlignment();
180 int64_t Advantage = 0;
181 for (auto CC : CallSeqVector) {
182 // Call sites where no parameters are passed on the stack
183 // do not affect the cost, since there needs to be no
185 if (CC.NoStackParams)
189 // If we don't use pushes for a particular call site,
190 // we pay for not having a reserved call frame with an
191 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
192 // depending on the size of the constant.
193 // TODO: Callee-pop functions should have a smaller penalty, because
194 // an add is needed even with a reserved call frame.
197 // We can use pushes. First, account for the fixed costs.
198 // We'll need a add after the call.
200 // If we have to realign the stack, we'll also need and sub before
201 if (CC.ExpectedDist % StackAlign)
203 // Now, for each push, we save ~3 bytes. For small constants, we actually,
204 // save more (up to 5 bytes), but 3 should be a good approximation.
205 Advantage += (CC.ExpectedDist / 4) * 3;
209 return (Advantage >= 0);
212 bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
213 TII = MF.getSubtarget().getInstrInfo();
214 TFL = MF.getSubtarget().getFrameLowering();
215 MRI = &MF.getRegInfo();
220 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
222 bool Changed = false;
224 ContextVector CallSeqVector;
226 for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
227 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
228 if (I->getOpcode() == FrameSetupOpcode) {
230 collectCallInfo(MF, *BB, I, Context);
231 CallSeqVector.push_back(Context);
234 if (!isProfitable(MF, CallSeqVector))
237 for (auto CC : CallSeqVector)
239 Changed |= adjustCallSequence(MF, CC);
244 X86CallFrameOptimization::InstClassification
245 X86CallFrameOptimization::classifyInstruction(
246 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
247 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
251 // The instructions we actually care about are movs onto the stack
252 int Opcode = MI->getOpcode();
253 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr)
256 // Not all calling conventions have only stack MOVs between the stack
257 // adjust and the call.
259 // We want to tolerate other instructions, to cover more cases.
261 // a) PCrel calls, where we expect an additional COPY of the basereg.
262 // b) Passing frame-index addresses.
263 // c) Calling conventions that have inreg parameters. These generate
264 // both copies and movs into registers.
265 // To avoid creating lots of special cases, allow any instruction
266 // that does not write into memory, does not def or use the stack
267 // pointer, and does not def any register that was used by a preceding
269 // (Reading from memory is allowed, even if referenced through a
270 // frame index, since these will get adjusted properly in PEI)
272 // The reason for the last condition is that the pushes can't replace
273 // the movs in place, because the order must be reversed.
274 // So if we have a MOV32mr that uses EDX, then an instruction that defs
275 // EDX, and then the call, after the transformation the push will use
276 // the modified version of EDX, and not the original one.
277 // Since we are still in SSA form at this point, we only need to
278 // make sure we don't clobber any *physical* registers that were
279 // used by an earlier mov that will become a push.
281 if (MI->isCall() || MI->mayStore())
284 for (const MachineOperand &MO : MI->operands()) {
287 unsigned int Reg = MO.getReg();
288 if (!RegInfo.isPhysicalRegister(Reg))
290 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
293 for (unsigned int U : UsedRegs)
294 if (RegInfo.regsOverlap(Reg, U))
302 void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
303 MachineBasicBlock &MBB,
304 MachineBasicBlock::iterator I,
305 CallContext &Context) {
306 // Check that this particular call sequence is amenable to the
308 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
309 MF.getSubtarget().getRegisterInfo());
310 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
312 // We expect to enter this at the beginning of a call sequence
313 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
314 MachineBasicBlock::iterator FrameSetup = I++;
315 Context.FrameSetup = FrameSetup;
317 // How much do we adjust the stack? This puts an upper bound on
318 // the number of parameters actually passed on it.
319 unsigned int MaxAdjust = FrameSetup->getOperand(0).getImm() / 4;
321 // A zero adjustment means no stack parameters
323 Context.NoStackParams = true;
327 // For globals in PIC mode, we can have some LEAs here.
328 // Ignore them, they don't bother us.
329 // TODO: Extend this to something that covers more cases.
330 while (I->getOpcode() == X86::LEA32r)
333 // We expect a copy instruction here.
334 // TODO: The copy instruction is a lowering artifact.
335 // We should also support a copy-less version, where the stack
336 // pointer is used directly.
337 if (!I->isCopy() || !I->getOperand(0).isReg())
339 Context.SPCopy = I++;
341 unsigned StackPtr = Context.SPCopy->getOperand(0).getReg();
343 // Scan the call setup sequence for the pattern we're looking for.
344 // We only handle a simple case - a sequence of MOV32mi or MOV32mr
345 // instructions, that push a sequence of 32-bit values onto the stack, with
346 // no gaps between them.
348 Context.MovVector.resize(MaxAdjust, nullptr);
350 InstClassification Classification;
351 DenseSet<unsigned int> UsedRegs;
353 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) !=
355 if (Classification == Skip) {
360 // We know the instruction is a MOV32mi/MOV32mr.
361 // We only want movs of the form:
362 // movl imm/r32, k(%esp)
363 // If we run into something else, bail.
364 // Note that AddrBaseReg may, counter to its name, not be a register,
365 // but rather a frame index.
366 // TODO: Support the fi case. This should probably work now that we
367 // have the infrastructure to track the stack pointer within a call
369 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
370 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
371 !I->getOperand(X86::AddrScaleAmt).isImm() ||
372 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
373 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
374 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
375 !I->getOperand(X86::AddrDisp).isImm())
378 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
379 assert(StackDisp >= 0 &&
380 "Negative stack displacement when passing parameters");
382 // We really don't want to consider the unaligned case.
387 assert((size_t)StackDisp < Context.MovVector.size() &&
388 "Function call has more parameters than the stack is adjusted for.");
390 // If the same stack slot is being filled twice, something's fishy.
391 if (Context.MovVector[StackDisp] != nullptr)
393 Context.MovVector[StackDisp] = I;
395 for (const MachineOperand &MO : I->uses()) {
398 unsigned int Reg = MO.getReg();
399 if (RegInfo.isPhysicalRegister(Reg))
400 UsedRegs.insert(Reg);
406 // We now expect the end of the sequence. If we stopped early,
407 // or reached the end of the block without finding a call, bail.
408 if (I == MBB.end() || !I->isCall())
412 if ((++I)->getOpcode() != FrameDestroyOpcode)
415 // Now, go through the vector, and see that we don't have any gaps,
416 // but only a series of 32-bit MOVs.
417 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
418 for (; MMI != MME; ++MMI, Context.ExpectedDist += 4)
422 // If the call had no parameters, do nothing
423 if (MMI == Context.MovVector.begin())
426 // We are either at the last parameter, or a gap.
427 // Make sure it's not a gap
428 for (; MMI != MME; ++MMI)
432 Context.UsePush = true;
436 bool X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
437 const CallContext &Context) {
438 // Ok, we can in fact do the transformation for this call.
439 // Do not remove the FrameSetup instruction, but adjust the parameters.
440 // PEI will end up finalizing the handling of this.
441 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
442 MachineBasicBlock &MBB = *(FrameSetup->getParent());
443 FrameSetup->getOperand(1).setImm(Context.ExpectedDist);
445 DebugLoc DL = FrameSetup->getDebugLoc();
446 // Now, iterate through the vector in reverse order, and replace the movs
447 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
449 for (int Idx = (Context.ExpectedDist / 4) - 1; Idx >= 0; --Idx) {
450 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
451 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
452 if (MOV->getOpcode() == X86::MOV32mi) {
453 unsigned PushOpcode = X86::PUSHi32;
454 // If the operand is a small (8-bit) immediate, we can use a
455 // PUSH instruction with a shorter encoding.
456 // Note that isImm() may fail even though this is a MOVmi, because
457 // the operand can also be a symbol.
458 if (PushOp.isImm()) {
459 int64_t Val = PushOp.getImm();
461 PushOpcode = X86::PUSH32i8;
463 BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).addOperand(PushOp);
465 unsigned int Reg = PushOp.getReg();
467 // If PUSHrmm is not slow on this target, try to fold the source of the
468 // push into the instruction.
469 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
470 bool SlowPUSHrmm = ST.isAtom() || ST.isSLM();
472 // Check that this is legal to fold. Right now, we're extremely
473 // conservative about that.
474 MachineInstr *DefMov = nullptr;
475 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
477 BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32rmm));
479 unsigned NumOps = DefMov->getDesc().getNumOperands();
480 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
481 Push->addOperand(DefMov->getOperand(i));
483 DefMov->eraseFromParent();
485 BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32r))
494 // The stack-pointer copy is no longer used in the call sequences.
495 // There should not be any other users, but we can't commit to that, so:
496 if (MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
497 Context.SPCopy->eraseFromParent();
499 // Once we've done this, we need to make sure PEI doesn't assume a reserved
501 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
502 FuncInfo->setHasPushSequences(true);
507 MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
508 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
509 // Do an extremely restricted form of load folding.
510 // ISel will often create patterns like:
511 // movl 4(%edi), %eax
512 // movl 8(%edi), %ecx
513 // movl 12(%edi), %edx
514 // movl %edx, 8(%esp)
515 // movl %ecx, 4(%esp)
518 // Get rid of those with prejudice.
519 if (!TargetRegisterInfo::isVirtualRegister(Reg))
522 // Make sure this is the only use of Reg.
523 if (!MRI->hasOneNonDBGUse(Reg))
526 MachineBasicBlock::iterator DefMI = MRI->getVRegDef(Reg);
528 // Make sure the def is a MOV from memory.
529 // If the def is an another block, give up.
530 if (DefMI->getOpcode() != X86::MOV32rm ||
531 DefMI->getParent() != FrameSetup->getParent())
534 // Make sure we don't have any instructions between DefMI and the
535 // push that make folding the load illegal.
536 for (auto I = DefMI; I != FrameSetup; ++I)
537 if (I->isLoadFoldBarrier())