X86CallFrameOptimization.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. //===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines a pass that optimizes call sequences on x86.
  10. // Currently, it converts movs of function parameters onto the stack into
  11. // pushes. This is beneficial for two main reasons:
  12. // 1) The push instruction encoding is much smaller than a stack-ptr-based mov.
  13. // 2) It is possible to push memory arguments directly. So, if the
  14. // the transformation is performed pre-reg-alloc, it can help relieve
  15. // register pressure.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "MCTargetDesc/X86BaseInfo.h"
  19. #include "X86.h"
  20. #include "X86FrameLowering.h"
  21. #include "X86InstrInfo.h"
  22. #include "X86MachineFunctionInfo.h"
  23. #include "X86RegisterInfo.h"
  24. #include "X86Subtarget.h"
  25. #include "llvm/ADT/DenseSet.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineFrameInfo.h"
  30. #include "llvm/CodeGen/MachineFunction.h"
  31. #include "llvm/CodeGen/MachineFunctionPass.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineOperand.h"
  35. #include "llvm/CodeGen/MachineRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetInstrInfo.h"
  37. #include "llvm/CodeGen/TargetRegisterInfo.h"
  38. #include "llvm/IR/DebugLoc.h"
  39. #include "llvm/IR/Function.h"
  40. #include "llvm/MC/MCDwarf.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/ErrorHandling.h"
  43. #include "llvm/Support/MathExtras.h"
  44. #include <cassert>
  45. #include <cstddef>
  46. #include <cstdint>
  47. #include <iterator>
  48. using namespace llvm;
  49. #define DEBUG_TYPE "x86-cf-opt"
  50. static cl::opt<bool>
  51. NoX86CFOpt("no-x86-call-frame-opt",
  52. cl::desc("Avoid optimizing x86 call frames for size"),
  53. cl::init(false), cl::Hidden);
  54. namespace {
  55. class X86CallFrameOptimization : public MachineFunctionPass {
  56. public:
  57. X86CallFrameOptimization() : MachineFunctionPass(ID) { }
  58. bool runOnMachineFunction(MachineFunction &MF) override;
  59. static char ID;
  60. private:
  61. // Information we know about a particular call site
  62. struct CallContext {
  63. CallContext() : FrameSetup(nullptr), ArgStoreVector(4, nullptr) {}
  64. // Iterator referring to the frame setup instruction
  65. MachineBasicBlock::iterator FrameSetup;
  66. // Actual call instruction
  67. MachineInstr *Call = nullptr;
  68. // A copy of the stack pointer
  69. MachineInstr *SPCopy = nullptr;
  70. // The total displacement of all passed parameters
  71. int64_t ExpectedDist = 0;
  72. // The sequence of storing instructions used to pass the parameters
  73. SmallVector<MachineInstr *, 4> ArgStoreVector;
  74. // True if this call site has no stack parameters
  75. bool NoStackParams = false;
  76. // True if this call site can use push instructions
  77. bool UsePush = false;
  78. };
  79. typedef SmallVector<CallContext, 8> ContextVector;
  80. bool isLegal(MachineFunction &MF);
  81. bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
  82. void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
  83. MachineBasicBlock::iterator I, CallContext &Context);
  84. void adjustCallSequence(MachineFunction &MF, const CallContext &Context);
  85. MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
  86. Register Reg);
  87. enum InstClassification { Convert, Skip, Exit };
  88. InstClassification classifyInstruction(MachineBasicBlock &MBB,
  89. MachineBasicBlock::iterator MI,
  90. const X86RegisterInfo &RegInfo,
  91. DenseSet<unsigned int> &UsedRegs);
  92. StringRef getPassName() const override { return "X86 Optimize Call Frame"; }
  93. const X86InstrInfo *TII = nullptr;
  94. const X86FrameLowering *TFL = nullptr;
  95. const X86Subtarget *STI = nullptr;
  96. MachineRegisterInfo *MRI = nullptr;
  97. unsigned SlotSize = 0;
  98. unsigned Log2SlotSize = 0;
  99. };
  100. } // end anonymous namespace
  101. char X86CallFrameOptimization::ID = 0;
  102. INITIALIZE_PASS(X86CallFrameOptimization, DEBUG_TYPE,
  103. "X86 Call Frame Optimization", false, false)
  104. // This checks whether the transformation is legal.
  105. // Also returns false in cases where it's potentially legal, but
  106. // we don't even want to try.
  107. bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
  108. if (NoX86CFOpt.getValue())
  109. return false;
  110. // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
  111. // in the compact unwind encoding that Darwin uses. So, bail if there
  112. // is a danger of that being generated.
  113. if (STI->isTargetDarwin() &&
  114. (!MF.getLandingPads().empty() ||
  115. (MF.getFunction().needsUnwindTableEntry() && !TFL->hasFP(MF))))
  116. return false;
  117. // It is not valid to change the stack pointer outside the prolog/epilog
  118. // on 64-bit Windows.
  119. if (STI->isTargetWin64())
  120. return false;
  121. // You would expect straight-line code between call-frame setup and
  122. // call-frame destroy. You would be wrong. There are circumstances (e.g.
  123. // CMOV_GR8 expansion of a select that feeds a function call!) where we can
  124. // end up with the setup and the destroy in different basic blocks.
  125. // This is bad, and breaks SP adjustment.
  126. // So, check that all of the frames in the function are closed inside
  127. // the same block, and, for good measure, that there are no nested frames.
  128. //
  129. // If any call allocates more argument stack memory than the stack
  130. // probe size, don't do this optimization. Otherwise, this pass
  131. // would need to synthesize additional stack probe calls to allocate
  132. // memory for arguments.
  133. unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
  134. unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
  135. bool EmitStackProbeCall = STI->getTargetLowering()->hasStackProbeSymbol(MF);
  136. unsigned StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);
  137. for (MachineBasicBlock &BB : MF) {
  138. bool InsideFrameSequence = false;
  139. for (MachineInstr &MI : BB) {
  140. if (MI.getOpcode() == FrameSetupOpcode) {
  141. if (TII->getFrameSize(MI) >= StackProbeSize && EmitStackProbeCall)
  142. return false;
  143. if (InsideFrameSequence)
  144. return false;
  145. InsideFrameSequence = true;
  146. } else if (MI.getOpcode() == FrameDestroyOpcode) {
  147. if (!InsideFrameSequence)
  148. return false;
  149. InsideFrameSequence = false;
  150. }
  151. }
  152. if (InsideFrameSequence)
  153. return false;
  154. }
  155. return true;
  156. }
  157. // Check whether this transformation is profitable for a particular
  158. // function - in terms of code size.
  159. bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
  160. ContextVector &CallSeqVector) {
  161. // This transformation is always a win when we do not expect to have
  162. // a reserved call frame. Under other circumstances, it may be either
  163. // a win or a loss, and requires a heuristic.
  164. bool CannotReserveFrame = MF.getFrameInfo().hasVarSizedObjects();
  165. if (CannotReserveFrame)
  166. return true;
  167. Align StackAlign = TFL->getStackAlign();
  168. int64_t Advantage = 0;
  169. for (const auto &CC : CallSeqVector) {
  170. // Call sites where no parameters are passed on the stack
  171. // do not affect the cost, since there needs to be no
  172. // stack adjustment.
  173. if (CC.NoStackParams)
  174. continue;
  175. if (!CC.UsePush) {
  176. // If we don't use pushes for a particular call site,
  177. // we pay for not having a reserved call frame with an
  178. // additional sub/add esp pair. The cost is ~3 bytes per instruction,
  179. // depending on the size of the constant.
  180. // TODO: Callee-pop functions should have a smaller penalty, because
  181. // an add is needed even with a reserved call frame.
  182. Advantage -= 6;
  183. } else {
  184. // We can use pushes. First, account for the fixed costs.
  185. // We'll need a add after the call.
  186. Advantage -= 3;
  187. // If we have to realign the stack, we'll also need a sub before
  188. if (!isAligned(StackAlign, CC.ExpectedDist))
  189. Advantage -= 3;
  190. // Now, for each push, we save ~3 bytes. For small constants, we actually,
  191. // save more (up to 5 bytes), but 3 should be a good approximation.
  192. Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
  193. }
  194. }
  195. return Advantage >= 0;
  196. }
  197. bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
  198. STI = &MF.getSubtarget<X86Subtarget>();
  199. TII = STI->getInstrInfo();
  200. TFL = STI->getFrameLowering();
  201. MRI = &MF.getRegInfo();
  202. const X86RegisterInfo &RegInfo =
  203. *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
  204. SlotSize = RegInfo.getSlotSize();
  205. assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
  206. Log2SlotSize = Log2_32(SlotSize);
  207. if (skipFunction(MF.getFunction()) || !isLegal(MF))
  208. return false;
  209. unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
  210. bool Changed = false;
  211. ContextVector CallSeqVector;
  212. for (auto &MBB : MF)
  213. for (auto &MI : MBB)
  214. if (MI.getOpcode() == FrameSetupOpcode) {
  215. CallContext Context;
  216. collectCallInfo(MF, MBB, MI, Context);
  217. CallSeqVector.push_back(Context);
  218. }
  219. if (!isProfitable(MF, CallSeqVector))
  220. return false;
  221. for (const auto &CC : CallSeqVector) {
  222. if (CC.UsePush) {
  223. adjustCallSequence(MF, CC);
  224. Changed = true;
  225. }
  226. }
  227. return Changed;
  228. }
  229. X86CallFrameOptimization::InstClassification
  230. X86CallFrameOptimization::classifyInstruction(
  231. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  232. const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
  233. if (MI == MBB.end())
  234. return Exit;
  235. // The instructions we actually care about are movs onto the stack or special
  236. // cases of constant-stores to stack
  237. switch (MI->getOpcode()) {
  238. case X86::AND16mi8:
  239. case X86::AND32mi8:
  240. case X86::AND64mi8: {
  241. const MachineOperand &ImmOp = MI->getOperand(X86::AddrNumOperands);
  242. return ImmOp.getImm() == 0 ? Convert : Exit;
  243. }
  244. case X86::OR16mi8:
  245. case X86::OR32mi8:
  246. case X86::OR64mi8: {
  247. const MachineOperand &ImmOp = MI->getOperand(X86::AddrNumOperands);
  248. return ImmOp.getImm() == -1 ? Convert : Exit;
  249. }
  250. case X86::MOV32mi:
  251. case X86::MOV32mr:
  252. case X86::MOV64mi32:
  253. case X86::MOV64mr:
  254. return Convert;
  255. }
  256. // Not all calling conventions have only stack MOVs between the stack
  257. // adjust and the call.
  258. // We want to tolerate other instructions, to cover more cases.
  259. // In particular:
  260. // a) PCrel calls, where we expect an additional COPY of the basereg.
  261. // b) Passing frame-index addresses.
  262. // c) Calling conventions that have inreg parameters. These generate
  263. // both copies and movs into registers.
  264. // To avoid creating lots of special cases, allow any instruction
  265. // that does not write into memory, does not def or use the stack
  266. // pointer, and does not def any register that was used by a preceding
  267. // push.
  268. // (Reading from memory is allowed, even if referenced through a
  269. // frame index, since these will get adjusted properly in PEI)
  270. // The reason for the last condition is that the pushes can't replace
  271. // the movs in place, because the order must be reversed.
  272. // So if we have a MOV32mr that uses EDX, then an instruction that defs
  273. // EDX, and then the call, after the transformation the push will use
  274. // the modified version of EDX, and not the original one.
  275. // Since we are still in SSA form at this point, we only need to
  276. // make sure we don't clobber any *physical* registers that were
  277. // used by an earlier mov that will become a push.
  278. if (MI->isCall() || MI->mayStore())
  279. return Exit;
  280. for (const MachineOperand &MO : MI->operands()) {
  281. if (!MO.isReg())
  282. continue;
  283. Register Reg = MO.getReg();
  284. if (!Reg.isPhysical())
  285. continue;
  286. if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
  287. return Exit;
  288. if (MO.isDef()) {
  289. for (unsigned int U : UsedRegs)
  290. if (RegInfo.regsOverlap(Reg, U))
  291. return Exit;
  292. }
  293. }
  294. return Skip;
  295. }
  296. void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
  297. MachineBasicBlock &MBB,
  298. MachineBasicBlock::iterator I,
  299. CallContext &Context) {
  300. // Check that this particular call sequence is amenable to the
  301. // transformation.
  302. const X86RegisterInfo &RegInfo =
  303. *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
  304. // We expect to enter this at the beginning of a call sequence
  305. assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
  306. MachineBasicBlock::iterator FrameSetup = I++;
  307. Context.FrameSetup = FrameSetup;
  308. // How much do we adjust the stack? This puts an upper bound on
  309. // the number of parameters actually passed on it.
  310. unsigned int MaxAdjust = TII->getFrameSize(*FrameSetup) >> Log2SlotSize;
  311. // A zero adjustment means no stack parameters
  312. if (!MaxAdjust) {
  313. Context.NoStackParams = true;
  314. return;
  315. }
  316. // Skip over DEBUG_VALUE.
  317. // For globals in PIC mode, we can have some LEAs here. Skip them as well.
  318. // TODO: Extend this to something that covers more cases.
  319. while (I->getOpcode() == X86::LEA32r || I->isDebugInstr())
  320. ++I;
  321. Register StackPtr = RegInfo.getStackRegister();
  322. auto StackPtrCopyInst = MBB.end();
  323. // SelectionDAG (but not FastISel) inserts a copy of ESP into a virtual
  324. // register. If it's there, use that virtual register as stack pointer
  325. // instead. Also, we need to locate this instruction so that we can later
  326. // safely ignore it while doing the conservative processing of the call chain.
  327. // The COPY can be located anywhere between the call-frame setup
  328. // instruction and its first use. We use the call instruction as a boundary
  329. // because it is usually cheaper to check if an instruction is a call than
  330. // checking if an instruction uses a register.
  331. for (auto J = I; !J->isCall(); ++J)
  332. if (J->isCopy() && J->getOperand(0).isReg() && J->getOperand(1).isReg() &&
  333. J->getOperand(1).getReg() == StackPtr) {
  334. StackPtrCopyInst = J;
  335. Context.SPCopy = &*J++;
  336. StackPtr = Context.SPCopy->getOperand(0).getReg();
  337. break;
  338. }
  339. // Scan the call setup sequence for the pattern we're looking for.
  340. // We only handle a simple case - a sequence of store instructions that
  341. // push a sequence of stack-slot-aligned values onto the stack, with
  342. // no gaps between them.
  343. if (MaxAdjust > 4)
  344. Context.ArgStoreVector.resize(MaxAdjust, nullptr);
  345. DenseSet<unsigned int> UsedRegs;
  346. for (InstClassification Classification = Skip; Classification != Exit; ++I) {
  347. // If this is the COPY of the stack pointer, it's ok to ignore.
  348. if (I == StackPtrCopyInst)
  349. continue;
  350. Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs);
  351. if (Classification != Convert)
  352. continue;
  353. // We know the instruction has a supported store opcode.
  354. // We only want movs of the form:
  355. // mov imm/reg, k(%StackPtr)
  356. // If we run into something else, bail.
  357. // Note that AddrBaseReg may, counter to its name, not be a register,
  358. // but rather a frame index.
  359. // TODO: Support the fi case. This should probably work now that we
  360. // have the infrastructure to track the stack pointer within a call
  361. // sequence.
  362. if (!I->getOperand(X86::AddrBaseReg).isReg() ||
  363. (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
  364. !I->getOperand(X86::AddrScaleAmt).isImm() ||
  365. (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
  366. (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
  367. (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
  368. !I->getOperand(X86::AddrDisp).isImm())
  369. return;
  370. int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
  371. assert(StackDisp >= 0 &&
  372. "Negative stack displacement when passing parameters");
  373. // We really don't want to consider the unaligned case.
  374. if (StackDisp & (SlotSize - 1))
  375. return;
  376. StackDisp >>= Log2SlotSize;
  377. assert((size_t)StackDisp < Context.ArgStoreVector.size() &&
  378. "Function call has more parameters than the stack is adjusted for.");
  379. // If the same stack slot is being filled twice, something's fishy.
  380. if (Context.ArgStoreVector[StackDisp] != nullptr)
  381. return;
  382. Context.ArgStoreVector[StackDisp] = &*I;
  383. for (const MachineOperand &MO : I->uses()) {
  384. if (!MO.isReg())
  385. continue;
  386. Register Reg = MO.getReg();
  387. if (Reg.isPhysical())
  388. UsedRegs.insert(Reg);
  389. }
  390. }
  391. --I;
  392. // We now expect the end of the sequence. If we stopped early,
  393. // or reached the end of the block without finding a call, bail.
  394. if (I == MBB.end() || !I->isCall())
  395. return;
  396. Context.Call = &*I;
  397. if ((++I)->getOpcode() != TII->getCallFrameDestroyOpcode())
  398. return;
  399. // Now, go through the vector, and see that we don't have any gaps,
  400. // but only a series of storing instructions.
  401. auto MMI = Context.ArgStoreVector.begin(), MME = Context.ArgStoreVector.end();
  402. for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
  403. if (*MMI == nullptr)
  404. break;
  405. // If the call had no parameters, do nothing
  406. if (MMI == Context.ArgStoreVector.begin())
  407. return;
  408. // We are either at the last parameter, or a gap.
  409. // Make sure it's not a gap
  410. for (; MMI != MME; ++MMI)
  411. if (*MMI != nullptr)
  412. return;
  413. Context.UsePush = true;
  414. }
  415. void X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
  416. const CallContext &Context) {
  417. // Ok, we can in fact do the transformation for this call.
  418. // Do not remove the FrameSetup instruction, but adjust the parameters.
  419. // PEI will end up finalizing the handling of this.
  420. MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
  421. MachineBasicBlock &MBB = *(FrameSetup->getParent());
  422. TII->setFrameAdjustment(*FrameSetup, Context.ExpectedDist);
  423. const DebugLoc &DL = FrameSetup->getDebugLoc();
  424. bool Is64Bit = STI->is64Bit();
  425. // Now, iterate through the vector in reverse order, and replace the store to
  426. // stack with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
  427. // replace uses.
  428. for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
  429. MachineBasicBlock::iterator Store = *Context.ArgStoreVector[Idx];
  430. const MachineOperand &PushOp = Store->getOperand(X86::AddrNumOperands);
  431. MachineBasicBlock::iterator Push = nullptr;
  432. unsigned PushOpcode;
  433. switch (Store->getOpcode()) {
  434. default:
  435. llvm_unreachable("Unexpected Opcode!");
  436. case X86::AND16mi8:
  437. case X86::AND32mi8:
  438. case X86::AND64mi8:
  439. case X86::OR16mi8:
  440. case X86::OR32mi8:
  441. case X86::OR64mi8:
  442. case X86::MOV32mi:
  443. case X86::MOV64mi32:
  444. PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSHi32;
  445. // If the operand is a small (8-bit) immediate, we can use a
  446. // PUSH instruction with a shorter encoding.
  447. // Note that isImm() may fail even though this is a MOVmi, because
  448. // the operand can also be a symbol.
  449. if (PushOp.isImm()) {
  450. int64_t Val = PushOp.getImm();
  451. if (isInt<8>(Val))
  452. PushOpcode = Is64Bit ? X86::PUSH64i8 : X86::PUSH32i8;
  453. }
  454. Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).add(PushOp);
  455. Push->cloneMemRefs(MF, *Store);
  456. break;
  457. case X86::MOV32mr:
  458. case X86::MOV64mr: {
  459. Register Reg = PushOp.getReg();
  460. // If storing a 32-bit vreg on 64-bit targets, extend to a 64-bit vreg
  461. // in preparation for the PUSH64. The upper 32 bits can be undef.
  462. if (Is64Bit && Store->getOpcode() == X86::MOV32mr) {
  463. Register UndefReg = MRI->createVirtualRegister(&X86::GR64RegClass);
  464. Reg = MRI->createVirtualRegister(&X86::GR64RegClass);
  465. BuildMI(MBB, Context.Call, DL, TII->get(X86::IMPLICIT_DEF), UndefReg);
  466. BuildMI(MBB, Context.Call, DL, TII->get(X86::INSERT_SUBREG), Reg)
  467. .addReg(UndefReg)
  468. .add(PushOp)
  469. .addImm(X86::sub_32bit);
  470. }
  471. // If PUSHrmm is not slow on this target, try to fold the source of the
  472. // push into the instruction.
  473. bool SlowPUSHrmm = STI->slowTwoMemOps();
  474. // Check that this is legal to fold. Right now, we're extremely
  475. // conservative about that.
  476. MachineInstr *DefMov = nullptr;
  477. if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
  478. PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
  479. Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
  480. unsigned NumOps = DefMov->getDesc().getNumOperands();
  481. for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
  482. Push->addOperand(DefMov->getOperand(i));
  483. Push->cloneMergedMemRefs(MF, {DefMov, &*Store});
  484. DefMov->eraseFromParent();
  485. } else {
  486. PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
  487. Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
  488. .addReg(Reg)
  489. .getInstr();
  490. Push->cloneMemRefs(MF, *Store);
  491. }
  492. break;
  493. }
  494. }
  495. // For debugging, when using SP-based CFA, we need to adjust the CFA
  496. // offset after each push.
  497. // TODO: This is needed only if we require precise CFA.
  498. if (!TFL->hasFP(MF))
  499. TFL->BuildCFI(
  500. MBB, std::next(Push), DL,
  501. MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
  502. MBB.erase(Store);
  503. }
  504. // The stack-pointer copy is no longer used in the call sequences.
  505. // There should not be any other users, but we can't commit to that, so:
  506. if (Context.SPCopy && MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
  507. Context.SPCopy->eraseFromParent();
  508. // Once we've done this, we need to make sure PEI doesn't assume a reserved
  509. // frame.
  510. X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
  511. FuncInfo->setHasPushSequences(true);
  512. }
  513. MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
  514. MachineBasicBlock::iterator FrameSetup, Register Reg) {
  515. // Do an extremely restricted form of load folding.
  516. // ISel will often create patterns like:
  517. // movl 4(%edi), %eax
  518. // movl 8(%edi), %ecx
  519. // movl 12(%edi), %edx
  520. // movl %edx, 8(%esp)
  521. // movl %ecx, 4(%esp)
  522. // movl %eax, (%esp)
  523. // call
  524. // Get rid of those with prejudice.
  525. if (!Reg.isVirtual())
  526. return nullptr;
  527. // Make sure this is the only use of Reg.
  528. if (!MRI->hasOneNonDBGUse(Reg))
  529. return nullptr;
  530. MachineInstr &DefMI = *MRI->getVRegDef(Reg);
  531. // Make sure the def is a MOV from memory.
  532. // If the def is in another block, give up.
  533. if ((DefMI.getOpcode() != X86::MOV32rm &&
  534. DefMI.getOpcode() != X86::MOV64rm) ||
  535. DefMI.getParent() != FrameSetup->getParent())
  536. return nullptr;
  537. // Make sure we don't have any instructions between DefMI and the
  538. // push that make folding the load illegal.
  539. for (MachineBasicBlock::iterator I = DefMI; I != FrameSetup; ++I)
  540. if (I->isLoadFoldBarrier())
  541. return nullptr;
  542. return &DefMI;
  543. }
  544. FunctionPass *llvm::createX86CallFrameOptimization() {
  545. return new X86CallFrameOptimization();
  546. }