LLVM 24.0.0git
X86CallFrameOptimization.cpp
Go to the documentation of this file.
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
20#include "X86.h"
21#include "X86FrameLowering.h"
22#include "X86InstrInfo.h"
24#include "X86RegisterInfo.h"
25#include "X86Subtarget.h"
26#include "llvm/ADT/DenseSet.h"
28#include "llvm/ADT/StringRef.h"
40#include "llvm/IR/DebugLoc.h"
41#include "llvm/IR/Function.h"
42#include "llvm/MC/MCDwarf.h"
46#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <iterator>
50
51using namespace llvm;
52
53#define DEBUG_TYPE "x86-cf-opt"
54
55static cl::opt<bool>
56 NoX86CFOpt("no-x86-call-frame-opt",
57 cl::desc("Avoid optimizing x86 call frames for size"),
58 cl::init(false), cl::Hidden);
59
60namespace {
61
62class X86CallFrameOptimizationImpl {
63public:
64 bool runOnMachineFunction(MachineFunction &MF);
65
66private:
67 // Information we know about a particular call site
68 struct CallContext {
69 CallContext() : FrameSetup(nullptr), ArgStoreVector(4, nullptr) {}
70
71 // Iterator referring to the frame setup instruction
73
74 // Actual call instruction
75 MachineInstr *Call = nullptr;
76
77 // A copy of the stack pointer
78 MachineInstr *SPCopy = nullptr;
79
80 // The total displacement of all passed parameters
81 int64_t ExpectedDist = 0;
82
83 // The sequence of storing instructions used to pass the parameters
84 SmallVector<MachineInstr *, 4> ArgStoreVector;
85
86 // True if this call site has no stack parameters
87 bool NoStackParams = false;
88
89 // True if this call site can use push instructions
90 bool UsePush = false;
91 };
92
93 typedef SmallVector<CallContext, 8> ContextVector;
94
95 bool isLegal(MachineFunction &MF);
96
97 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
98
99 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
101
102 void adjustCallSequence(MachineFunction &MF, const CallContext &Context);
103
104 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
105 Register Reg);
106
107 enum InstClassification { Convert, Skip, Exit };
108
109 InstClassification classifyInstruction(MachineBasicBlock &MBB,
111 const X86RegisterInfo &RegInfo,
112 const DenseSet<MCRegister> &UsedRegs);
113
114 const X86InstrInfo *TII = nullptr;
115 const X86FrameLowering *TFL = nullptr;
116 const X86Subtarget *STI = nullptr;
117 MachineRegisterInfo *MRI = nullptr;
118 unsigned SlotSize = 0;
119 unsigned Log2SlotSize = 0;
120};
121
122class X86CallFrameOptimizationLegacy : public MachineFunctionPass {
123public:
124 X86CallFrameOptimizationLegacy() : MachineFunctionPass(ID) {}
125
126 bool runOnMachineFunction(MachineFunction &MF) override;
127
128 void getAnalysisUsage(AnalysisUsage &AU) const override {
129 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
131 }
132
133 static char ID;
134
135private:
136 StringRef getPassName() const override { return "X86 Optimize Call Frame"; }
137};
138
139} // end anonymous namespace
140char X86CallFrameOptimizationLegacy::ID = 0;
141INITIALIZE_PASS(X86CallFrameOptimizationLegacy, DEBUG_TYPE,
142 "X86 Call Frame Optimization", false, false)
143
144// This checks whether the transformation is legal.
145// Also returns false in cases where it's potentially legal, but
146// we don't even want to try.
147bool X86CallFrameOptimizationImpl::isLegal(MachineFunction &MF) {
148 if (NoX86CFOpt.getValue())
149 return false;
150
151 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
152 // in the compact unwind encoding that Darwin uses. So, bail if there
153 // is a danger of that being generated.
154 if (STI->isTargetDarwin() &&
155 (!MF.getLandingPads().empty() ||
156 (MF.getFunction().needsUnwindTableEntry() && !TFL->hasFP(MF))))
157 return false;
158
159 // It is not valid to change the stack pointer outside the prolog/epilog
160 // on 64-bit Windows.
161 if (STI->isTargetWin64())
162 return false;
163
164 // You would expect straight-line code between call-frame setup and
165 // call-frame destroy. You would be wrong. There are circumstances (e.g.
166 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
167 // end up with the setup and the destroy in different basic blocks.
168 // This is bad, and breaks SP adjustment.
169 // So, check that all of the frames in the function are closed inside
170 // the same block, and, for good measure, that there are no nested frames.
171 //
172 // If any call allocates more argument stack memory than the stack
173 // probe size, don't do this optimization. Otherwise, this pass
174 // would need to synthesize additional stack probe calls to allocate
175 // memory for arguments.
176 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
177 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
178 bool EmitStackProbeCall = STI->getTargetLowering()->hasStackProbeSymbol(MF);
179 unsigned StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);
180 for (MachineBasicBlock &BB : MF) {
181 bool InsideFrameSequence = false;
182 for (MachineInstr &MI : BB) {
183 if (MI.getOpcode() == FrameSetupOpcode) {
184 if (TII->getFrameSize(MI) >= StackProbeSize && EmitStackProbeCall)
185 return false;
186 if (InsideFrameSequence)
187 return false;
188 InsideFrameSequence = true;
189 } else if (MI.getOpcode() == FrameDestroyOpcode) {
190 if (!InsideFrameSequence)
191 return false;
192 InsideFrameSequence = false;
193 }
194 }
195
196 if (InsideFrameSequence)
197 return false;
198 }
199
200 return true;
201}
202
203// Check whether this transformation is profitable for a particular
204// function - in terms of code size.
205bool X86CallFrameOptimizationImpl::isProfitable(MachineFunction &MF,
206 ContextVector &CallSeqVector) {
207 // This transformation is always a win when we do not expect to have
208 // a reserved call frame. Under other circumstances, it may be either
209 // a win or a loss, and requires a heuristic.
210 bool CannotReserveFrame = MF.getFrameInfo().hasVarSizedObjects();
211 if (CannotReserveFrame)
212 return true;
213
214 Align StackAlign = TFL->getStackAlign();
215
216 int64_t Advantage = 0;
217 for (const auto &CC : CallSeqVector) {
218 // Call sites where no parameters are passed on the stack
219 // do not affect the cost, since there needs to be no
220 // stack adjustment.
221 if (CC.NoStackParams)
222 continue;
223
224 if (!CC.UsePush) {
225 // If we don't use pushes for a particular call site,
226 // we pay for not having a reserved call frame with an
227 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
228 // depending on the size of the constant.
229 // TODO: Callee-pop functions should have a smaller penalty, because
230 // an add is needed even with a reserved call frame.
231 Advantage -= 6;
232 } else {
233 // We can use pushes. First, account for the fixed costs.
234 // We'll need a add after the call.
235 Advantage -= 3;
236 // If we have to realign the stack, we'll also need a sub before
237 if (!isAligned(StackAlign, CC.ExpectedDist))
238 Advantage -= 3;
239 // Now, for each push, we save ~3 bytes. For small constants, we actually,
240 // save more (up to 5 bytes), but 3 should be a good approximation.
241 Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
242 }
243 }
244
245 return Advantage >= 0;
246}
247
248bool X86CallFrameOptimizationImpl::runOnMachineFunction(MachineFunction &MF) {
249 STI = &MF.getSubtarget<X86Subtarget>();
250 TII = STI->getInstrInfo();
251 TFL = STI->getFrameLowering();
252 MRI = &MF.getRegInfo();
253
254 const X86RegisterInfo &RegInfo = *STI->getRegisterInfo();
255 SlotSize = RegInfo.getSlotSize();
256 assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
257 Log2SlotSize = Log2_32(SlotSize);
258
259 if (!isLegal(MF))
260 return false;
261
262 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
263
264 bool Changed = false;
265
266 ContextVector CallSeqVector;
267
268 for (auto &MBB : MF)
269 for (auto &MI : MBB)
270 if (MI.getOpcode() == FrameSetupOpcode) {
271 CallContext Context;
272 collectCallInfo(MF, MBB, MI, Context);
273 CallSeqVector.push_back(Context);
274 }
275
276 if (!isProfitable(MF, CallSeqVector))
277 return false;
278
279 for (const auto &CC : CallSeqVector) {
280 if (CC.UsePush) {
281 adjustCallSequence(MF, CC);
282 Changed = true;
283 }
284 }
285
286 return Changed;
287}
288
289X86CallFrameOptimizationImpl::InstClassification
290X86CallFrameOptimizationImpl::classifyInstruction(
291 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
292 const X86RegisterInfo &RegInfo, const DenseSet<MCRegister> &UsedRegs) {
293 if (MI == MBB.end())
294 return Exit;
295
296 // The instructions we actually care about are movs onto the stack or special
297 // cases of constant-stores to stack
298 switch (MI->getOpcode()) {
299 case X86::AND16mi:
300 case X86::AND32mi:
301 case X86::AND64mi32: {
302 const MachineOperand &ImmOp = MI->getOperand(X86::AddrNumOperands);
303 return ImmOp.getImm() == 0 ? Convert : Exit;
304 }
305 case X86::OR16mi:
306 case X86::OR32mi:
307 case X86::OR64mi32: {
308 const MachineOperand &ImmOp = MI->getOperand(X86::AddrNumOperands);
309 return ImmOp.getImm() == -1 ? Convert : Exit;
310 }
311 case X86::MOV32mi:
312 case X86::MOV32mr:
313 case X86::MOV64mi32:
314 case X86::MOV64mr:
315 return Convert;
316 }
317
318 // Not all calling conventions have only stack MOVs between the stack
319 // adjust and the call.
320
321 // We want to tolerate other instructions, to cover more cases.
322 // In particular:
323 // a) PCrel calls, where we expect an additional COPY of the basereg.
324 // b) Passing frame-index addresses.
325 // c) Calling conventions that have inreg parameters. These generate
326 // both copies and movs into registers.
327 // To avoid creating lots of special cases, allow any instruction
328 // that does not write into memory, does not def or use the stack
329 // pointer, and does not def any register that was used by a preceding
330 // push.
331 // (Reading from memory is allowed, even if referenced through a
332 // frame index, since these will get adjusted properly in PEI)
333
334 // The reason for the last condition is that the pushes can't replace
335 // the movs in place, because the order must be reversed.
336 // So if we have a MOV32mr that uses EDX, then an instruction that defs
337 // EDX, and then the call, after the transformation the push will use
338 // the modified version of EDX, and not the original one.
339 // Since we are still in SSA form at this point, we only need to
340 // make sure we don't clobber any *physical* registers that were
341 // used by an earlier mov that will become a push.
342
343 if (MI->isCall() || MI->mayStore())
344 return Exit;
345
346 for (const MachineOperand &MO : MI->operands()) {
347 if (!MO.isReg())
348 continue;
349 Register Reg = MO.getReg();
350 if (!Reg.isPhysical())
351 continue;
352 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
353 return Exit;
354 if (MO.isDef()) {
355 for (MCRegister U : UsedRegs)
356 if (RegInfo.regsOverlap(Reg, U))
357 return Exit;
358 }
359 }
360
361 return Skip;
362}
363
364void X86CallFrameOptimizationImpl::collectCallInfo(
365 MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
366 CallContext &Context) {
367 // Check that this particular call sequence is amenable to the
368 // transformation.
369 const X86RegisterInfo &RegInfo = *STI->getRegisterInfo();
370
371 // We expect to enter this at the beginning of a call sequence
372 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
373 MachineBasicBlock::iterator FrameSetup = I++;
374 Context.FrameSetup = FrameSetup;
375
376 // How much do we adjust the stack? This puts an upper bound on
377 // the number of parameters actually passed on it.
378 unsigned int MaxAdjust = TII->getFrameSize(*FrameSetup) >> Log2SlotSize;
379
380 // A zero adjustment means no stack parameters
381 if (!MaxAdjust) {
382 Context.NoStackParams = true;
383 return;
384 }
385
386 // Skip over DEBUG_VALUE.
387 // For globals in PIC mode, we can have some LEAs here. Skip them as well.
388 // TODO: Extend this to something that covers more cases.
389 while (I->getOpcode() == X86::LEA32r || I->isDebugInstr())
390 ++I;
391
393 auto StackPtrCopyInst = MBB.end();
394 // SelectionDAG (but not FastISel) inserts a copy of ESP into a virtual
395 // register. If it's there, use that virtual register as stack pointer
396 // instead. Also, we need to locate this instruction so that we can later
397 // safely ignore it while doing the conservative processing of the call chain.
398 // The COPY can be located anywhere between the call-frame setup
399 // instruction and its first use. We use the call instruction as a boundary
400 // because it is usually cheaper to check if an instruction is a call than
401 // checking if an instruction uses a register.
402 for (auto J = I; !J->isCall(); ++J)
403 if (J->isCopy() && J->getOperand(0).isReg() && J->getOperand(1).isReg() &&
404 J->getOperand(1).getReg() == StackPtr) {
405 StackPtrCopyInst = J;
406 Context.SPCopy = &*J++;
407 StackPtr = Context.SPCopy->getOperand(0).getReg();
408 break;
409 }
410
411 // Scan the call setup sequence for the pattern we're looking for.
412 // We only handle a simple case - a sequence of store instructions that
413 // push a sequence of stack-slot-aligned values onto the stack, with
414 // no gaps between them.
415 if (MaxAdjust > 4)
416 Context.ArgStoreVector.resize(MaxAdjust, nullptr);
417
418 DenseSet<MCRegister> UsedRegs;
419
420 for (InstClassification Classification = Skip; Classification != Exit; ++I) {
421 // If this is the COPY of the stack pointer, it's ok to ignore.
422 if (I == StackPtrCopyInst)
423 continue;
424 Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs);
425 if (Classification != Convert)
426 continue;
427 // We know the instruction has a supported store opcode.
428 // We only want movs of the form:
429 // mov imm/reg, k(%StackPtr)
430 // If we run into something else, bail.
431 // Note that AddrBaseReg may, counter to its name, not be a register,
432 // but rather a frame index.
433 // TODO: Support the fi case. This should probably work now that we
434 // have the infrastructure to track the stack pointer within a call
435 // sequence.
436 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
437 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
438 !I->getOperand(X86::AddrScaleAmt).isImm() ||
439 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
440 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
441 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
442 !I->getOperand(X86::AddrDisp).isImm())
443 return;
444
445 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
446 assert(StackDisp >= 0 &&
447 "Negative stack displacement when passing parameters");
448
449 // We really don't want to consider the unaligned case.
450 if (StackDisp & (SlotSize - 1))
451 return;
452 StackDisp >>= Log2SlotSize;
453
454 assert((size_t)StackDisp < Context.ArgStoreVector.size() &&
455 "Function call has more parameters than the stack is adjusted for.");
456
457 // If the same stack slot is being filled twice, something's fishy.
458 if (Context.ArgStoreVector[StackDisp] != nullptr)
459 return;
460 Context.ArgStoreVector[StackDisp] = &*I;
461
462 for (const MachineOperand &MO : I->uses()) {
463 if (!MO.isReg())
464 continue;
465 Register Reg = MO.getReg();
466 if (Reg.isPhysical())
467 UsedRegs.insert(Reg.asMCReg());
468 }
469 }
470
471 --I;
472
473 // We now expect the end of the sequence. If we stopped early,
474 // or reached the end of the block without finding a call, bail.
475 if (I == MBB.end() || !I->isCall())
476 return;
477
478 Context.Call = &*I;
479 if ((++I)->getOpcode() != TII->getCallFrameDestroyOpcode())
480 return;
481
482 // Now, go through the vector, and see that we don't have any gaps,
483 // but only a series of storing instructions.
484 auto MMI = Context.ArgStoreVector.begin(), MME = Context.ArgStoreVector.end();
485 for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
486 if (*MMI == nullptr)
487 break;
488
489 // If the call had no parameters, do nothing
490 if (MMI == Context.ArgStoreVector.begin())
491 return;
492
493 // We are either at the last parameter, or a gap.
494 // Make sure it's not a gap
495 for (; MMI != MME; ++MMI)
496 if (*MMI != nullptr)
497 return;
498
499 Context.UsePush = true;
500}
501
502void X86CallFrameOptimizationImpl::adjustCallSequence(
503 MachineFunction &MF, const CallContext &Context) {
504 // Ok, we can in fact do the transformation for this call.
505 // Do not remove the FrameSetup instruction, but adjust the parameters.
506 // PEI will end up finalizing the handling of this.
507 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
508 MachineBasicBlock &MBB = *(FrameSetup->getParent());
509 TII->setFrameAdjustment(*FrameSetup, Context.ExpectedDist);
510
511 const DebugLoc &DL = FrameSetup->getDebugLoc();
512 bool Is64Bit = STI->is64Bit();
513 // Now, iterate through the vector in reverse order, and replace the store to
514 // stack with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
515 // replace uses.
516 for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
517 MachineBasicBlock::iterator Store = *Context.ArgStoreVector[Idx];
518 const MachineOperand &PushOp = Store->getOperand(X86::AddrNumOperands);
519 MachineBasicBlock::iterator Push = nullptr;
520 unsigned PushOpcode;
521 switch (Store->getOpcode()) {
522 default:
523 llvm_unreachable("Unexpected Opcode!");
524 case X86::AND16mi:
525 case X86::AND32mi:
526 case X86::AND64mi32:
527 case X86::OR16mi:
528 case X86::OR32mi:
529 case X86::OR64mi32:
530 case X86::MOV32mi:
531 case X86::MOV64mi32:
532 PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSH32i;
533 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).add(PushOp);
534 Push->cloneMemRefs(MF, *Store);
535 break;
536 case X86::MOV32mr:
537 case X86::MOV64mr: {
538 Register Reg = PushOp.getReg();
539
540 // If storing a 32-bit vreg on 64-bit targets, extend to a 64-bit vreg
541 // in preparation for the PUSH64. The upper 32 bits can be undef.
542 if (Is64Bit && Store->getOpcode() == X86::MOV32mr) {
543 Register UndefReg = MRI->createVirtualRegister(&X86::GR64RegClass);
544 Reg = MRI->createVirtualRegister(&X86::GR64RegClass);
545 BuildMI(MBB, Context.Call, DL, TII->get(X86::IMPLICIT_DEF), UndefReg);
546 BuildMI(MBB, Context.Call, DL, TII->get(X86::INSERT_SUBREG), Reg)
547 .addReg(UndefReg)
548 .add(PushOp)
549 .addImm(X86::sub_32bit);
550 }
551
552 // If PUSHrmm is not slow on this target, try to fold the source of the
553 // push into the instruction.
554 bool SlowPUSHrmm = STI->slowTwoMemOps();
555
556 // Check that this is legal to fold. Right now, we're extremely
557 // conservative about that.
558 MachineInstr *DefMov = nullptr;
559 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
560 PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
561 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
562
563 unsigned NumOps = DefMov->getDesc().getNumOperands();
564 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
565 Push->addOperand(DefMov->getOperand(i));
566 Push->cloneMergedMemRefs(MF, {DefMov, &*Store});
567 DefMov->eraseFromParent();
568 } else {
569 PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
570 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
571 .addReg(Reg)
572 .getInstr();
573 Push->cloneMemRefs(MF, *Store);
574 }
575 break;
576 }
577 }
578
579 // For debugging, when using SP-based CFA, we need to adjust the CFA
580 // offset after each push.
581 // TODO: This is needed only if we require precise CFA.
582 if (!TFL->hasFP(MF))
583 TFL->BuildCFI(
584 MBB, std::next(Push), DL,
585 MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
586
587 MBB.erase(Store);
588 }
589
590 // The stack-pointer copy is no longer used in the call sequences.
591 // There should not be any other users, but we can't commit to that, so:
592 if (Context.SPCopy && MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
593 Context.SPCopy->eraseFromParent();
594
595 // Once we've done this, we need to make sure PEI doesn't assume a reserved
596 // frame.
597 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
598 FuncInfo->setHasPushSequences(true);
599}
600
601MachineInstr *X86CallFrameOptimizationImpl::canFoldIntoRegPush(
603 // Do an extremely restricted form of load folding.
604 // ISel will often create patterns like:
605 // movl 4(%edi), %eax
606 // movl 8(%edi), %ecx
607 // movl 12(%edi), %edx
608 // movl %edx, 8(%esp)
609 // movl %ecx, 4(%esp)
610 // movl %eax, (%esp)
611 // call
612 // Get rid of those with prejudice.
613 if (!Reg.isVirtual())
614 return nullptr;
615
616 // Make sure this is the only use of Reg.
617 if (!MRI->hasOneNonDBGUse(Reg))
618 return nullptr;
619
620 MachineInstr &DefMI = *MRI->getVRegDef(Reg);
621
622 // Make sure the def is a MOV from memory.
623 // If the def is in another block, give up.
624 if ((DefMI.getOpcode() != X86::MOV32rm &&
625 DefMI.getOpcode() != X86::MOV64rm) ||
626 DefMI.getParent() != FrameSetup->getParent())
627 return nullptr;
628
629 // Make sure we don't have any instructions between DefMI and the
630 // push that make folding the load illegal.
631 for (MachineBasicBlock::iterator I = DefMI; I != FrameSetup; ++I)
632 if (I->isLoadFoldBarrier())
633 return nullptr;
634
635 return &DefMI;
636}
637
639 return new X86CallFrameOptimizationLegacy();
640}
641
642bool X86CallFrameOptimizationLegacy::runOnMachineFunction(MachineFunction &MF) {
643 if (skipFunction(MF.getFunction()))
644 return false;
645 X86CallFrameOptimizationImpl Impl;
646 return Impl.runOnMachineFunction(MF);
647}
648
649PreservedAnalyses
652 X86CallFrameOptimizationImpl Impl;
653 bool Changed = Impl.runOnMachineFunction(MF);
656}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the DenseSet and SmallDenseSet classes.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the SmallVector class.
static bool isProfitable(const StableFunctionMap::StableFunctionEntries &SFS)
static cl::opt< bool > NoX86CFOpt("no-x86-call-frame-opt", cl::desc("Avoid optimizing x86 call frames for size"), cl::init(false), cl::Hidden)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
static MCCFIInstruction createAdjustCfaOffset(MCSymbol *L, int64_t Adjustment, SMLoc Loc={})
.cfi_adjust_cfa_offset Same as .cfi_def_cfa_offset, but Offset is a relative value that is added/subt...
Definition MCDwarf.h:651
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineInstrBundleIterator< MachineInstr > iterator
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
int64_t getImm() const
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void BuildCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCCFIInstruction &CFIInst, MachineInstr::MIFlag Flag=MachineInstr::NoFlags) const
Wraps up getting a CFI index and building a MachineInstr for it.
Register getStackRegister() const
unsigned getSlotSize() const
const X86InstrInfo * getInstrInfo() const override
const X86RegisterInfo * getRegisterInfo() const override
const X86FrameLowering * getFrameLowering() const override
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ AddrNumOperands
Definition X86BaseInfo.h:36
initializer< Ty > init(const Ty &Val)
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:134
@ Store
The extracted value is stored (ExtractElement only).
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
FunctionPass * createX86CallFrameOptimizationLegacyPass()