X86CallFrameOptimization.cpp 23 KB

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