1 //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
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 contains the X86 implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "X86FrameLowering.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Support/Debug.h"
37 // FIXME: completely move here.
38 extern cl::opt<bool> ForceStackAlign;
40 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
41 return !MF.getFrameInfo()->hasVarSizedObjects() &&
42 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
45 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
46 /// call frame pseudos can be simplified. Having a FP, as in the default
47 /// implementation, is not sufficient here since we can't always use it.
48 /// Use a more nuanced condition.
50 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
51 const X86RegisterInfo *TRI = static_cast<const X86RegisterInfo *>
52 (MF.getSubtarget().getRegisterInfo());
53 return hasReservedCallFrame(MF) ||
54 (hasFP(MF) && !TRI->needsStackRealignment(MF))
55 || TRI->hasBasePointer(MF);
58 // needsFrameIndexResolution - Do we need to perform FI resolution for
59 // this function. Normally, this is required only when the function
60 // has any stack objects. However, FI resolution actually has another job,
61 // not apparent from the title - it resolves callframesetup/destroy
62 // that were not simplified earlier.
63 // So, this is required for x86 functions that have push sequences even
64 // when there are no stack objects.
66 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
67 return MF.getFrameInfo()->hasStackObjects() ||
68 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
71 /// hasFP - Return true if the specified function should have a dedicated frame
72 /// pointer register. This is true if the function has variable sized allocas
73 /// or if frame pointer elimination is disabled.
74 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
75 const MachineFrameInfo *MFI = MF.getFrameInfo();
76 const MachineModuleInfo &MMI = MF.getMMI();
77 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
79 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
80 RegInfo->needsStackRealignment(MF) ||
81 MFI->hasVarSizedObjects() ||
82 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
83 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
84 MMI.callsUnwindInit() || MMI.callsEHReturn() ||
85 MFI->hasStackMap() || MFI->hasPatchPoint());
88 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
92 return X86::SUB64ri32;
100 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
103 return X86::ADD64ri8;
104 return X86::ADD64ri32;
107 return X86::ADD32ri8;
112 static unsigned getSUBrrOpcode(unsigned isLP64) {
113 return isLP64 ? X86::SUB64rr : X86::SUB32rr;
116 static unsigned getADDrrOpcode(unsigned isLP64) {
117 return isLP64 ? X86::ADD64rr : X86::ADD32rr;
120 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
123 return X86::AND64ri8;
124 return X86::AND64ri32;
127 return X86::AND32ri8;
131 static unsigned getLEArOpcode(unsigned IsLP64) {
132 return IsLP64 ? X86::LEA64r : X86::LEA32r;
135 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
136 /// when it reaches the "return" instruction. We can then pop a stack object
137 /// to this register without worry about clobbering it.
138 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
139 MachineBasicBlock::iterator &MBBI,
140 const TargetRegisterInfo &TRI,
142 const MachineFunction *MF = MBB.getParent();
143 const Function *F = MF->getFunction();
144 if (!F || MF->getMMI().callsEHReturn())
147 static const uint16_t CallerSavedRegs32Bit[] = {
148 X86::EAX, X86::EDX, X86::ECX, 0
151 static const uint16_t CallerSavedRegs64Bit[] = {
152 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
153 X86::R8, X86::R9, X86::R10, X86::R11, 0
156 unsigned Opc = MBBI->getOpcode();
163 case X86::TCRETURNdi:
164 case X86::TCRETURNri:
165 case X86::TCRETURNmi:
166 case X86::TCRETURNdi64:
167 case X86::TCRETURNri64:
168 case X86::TCRETURNmi64:
170 case X86::EH_RETURN64: {
171 SmallSet<uint16_t, 8> Uses;
172 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
173 MachineOperand &MO = MBBI->getOperand(i);
174 if (!MO.isReg() || MO.isDef())
176 unsigned Reg = MO.getReg();
179 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
183 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
185 if (!Uses.count(*CS))
193 static bool isEAXLiveIn(MachineFunction &MF) {
194 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
195 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
196 unsigned Reg = II->first;
198 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
199 Reg == X86::AH || Reg == X86::AL)
206 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
207 /// stack pointer by a constant value.
209 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
210 unsigned StackPtr, int64_t NumBytes,
211 bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
212 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
213 bool isSub = NumBytes < 0;
214 uint64_t Offset = isSub ? -NumBytes : NumBytes;
217 Opc = getLEArOpcode(Is64BitStackPtr);
220 ? getSUBriOpcode(Is64BitStackPtr, Offset)
221 : getADDriOpcode(Is64BitStackPtr, Offset);
223 uint64_t Chunk = (1LL << 31) - 1;
224 DebugLoc DL = MBB.findDebugLoc(MBBI);
227 if (Offset > Chunk) {
228 // Rather than emit a long series of instructions for large offsets,
229 // load the offset into a register and do one sub/add
232 if (isSub && !isEAXLiveIn(*MBB.getParent()))
233 Reg = (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX);
235 Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
238 Opc = Is64BitTarget ? X86::MOV64ri : X86::MOV32ri;
239 BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
242 ? getSUBrrOpcode(Is64BitTarget)
243 : getADDrrOpcode(Is64BitTarget);
244 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
247 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
253 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
254 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
255 // Use push / pop instead.
257 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
258 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
261 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
262 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
263 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
264 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
266 MI->setFlag(MachineInstr::FrameSetup);
272 MachineInstr *MI = nullptr;
275 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
276 StackPtr, false, isSub ? -ThisVal : ThisVal);
278 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
281 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
285 MI->setFlag(MachineInstr::FrameSetup);
291 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
293 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
294 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
295 if (MBBI == MBB.begin()) return;
297 MachineBasicBlock::iterator PI = std::prev(MBBI);
298 unsigned Opc = PI->getOpcode();
299 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
300 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
301 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
302 PI->getOperand(0).getReg() == StackPtr) {
304 *NumBytes += PI->getOperand(2).getImm();
306 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
307 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
308 PI->getOperand(0).getReg() == StackPtr) {
310 *NumBytes -= PI->getOperand(2).getImm();
315 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
318 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
319 MachineBasicBlock::iterator &MBBI,
320 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
321 // FIXME: THIS ISN'T RUN!!!
324 if (MBBI == MBB.end()) return;
326 MachineBasicBlock::iterator NI = std::next(MBBI);
327 if (NI == MBB.end()) return;
329 unsigned Opc = NI->getOpcode();
330 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
331 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
332 NI->getOperand(0).getReg() == StackPtr) {
334 *NumBytes -= NI->getOperand(2).getImm();
337 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
338 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
339 NI->getOperand(0).getReg() == StackPtr) {
341 *NumBytes += NI->getOperand(2).getImm();
347 /// mergeSPUpdates - Checks the instruction before/after the passed
348 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
349 /// the stack adjustment is returned as a positive value for ADD/LEA and a
350 /// negative for SUB.
351 static int mergeSPUpdates(MachineBasicBlock &MBB,
352 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
353 bool doMergeWithPrevious) {
354 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
355 (!doMergeWithPrevious && MBBI == MBB.end()))
358 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
359 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
361 unsigned Opc = PI->getOpcode();
364 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
365 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
366 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
367 PI->getOperand(0).getReg() == StackPtr){
368 Offset += PI->getOperand(2).getImm();
370 if (!doMergeWithPrevious) MBBI = NI;
371 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
372 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
373 PI->getOperand(0).getReg() == StackPtr) {
374 Offset -= PI->getOperand(2).getImm();
376 if (!doMergeWithPrevious) MBBI = NI;
383 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
384 MachineBasicBlock::iterator MBBI,
386 MachineFunction &MF = *MBB.getParent();
387 MachineFrameInfo *MFI = MF.getFrameInfo();
388 MachineModuleInfo &MMI = MF.getMMI();
389 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
390 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
392 // Add callee saved registers to move list.
393 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
394 if (CSI.empty()) return;
396 // Calculate offsets.
397 for (std::vector<CalleeSavedInfo>::const_iterator
398 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
399 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
400 unsigned Reg = I->getReg();
402 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
404 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
406 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
407 .addCFIIndex(CFIIndex);
411 /// usesTheStack - This function checks if any of the users of EFLAGS
412 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
413 /// to use the stack, and if we don't adjust the stack we clobber the first
415 /// See X86InstrInfo::copyPhysReg.
416 static bool usesTheStack(const MachineFunction &MF) {
417 const MachineRegisterInfo &MRI = MF.getRegInfo();
419 for (MachineRegisterInfo::reg_instr_iterator
420 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
428 void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
429 MachineBasicBlock &MBB,
430 MachineBasicBlock::iterator MBBI,
432 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
433 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
434 bool Is64Bit = STI.is64Bit();
435 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
439 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
441 CallOp = X86::CALLpcrel32;
445 if (STI.isTargetCygMing()) {
446 Symbol = "___chkstk_ms";
450 } else if (STI.isTargetCygMing())
455 MachineInstrBuilder CI;
457 // All current stack probes take AX and SP as input, clobber flags, and
458 // preserve all registers. x86_64 probes leave RSP unmodified.
459 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
460 // For the large code model, we have to call through a register. Use R11,
461 // as it is scratch in all supported calling conventions.
462 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
463 .addExternalSymbol(Symbol);
464 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
466 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
469 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
470 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
471 CI.addReg(AX, RegState::Implicit)
472 .addReg(SP, RegState::Implicit)
473 .addReg(AX, RegState::Define | RegState::Implicit)
474 .addReg(SP, RegState::Define | RegState::Implicit)
475 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
478 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
479 // themselves. It also does not clobber %rax so we can reuse it when
481 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
487 /// emitPrologue - Push callee-saved registers onto the stack, which
488 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
489 /// space for local variables. Also emit labels used by the exception handler to
490 /// generate the exception handling frames.
493 Here's a gist of what gets emitted:
495 ; Establish frame pointer, if needed
498 .cfi_def_cfa_offset 16
499 .cfi_offset %rbp, -16
502 .cfi_def_cfa_register %rbp
504 ; Spill general-purpose registers
505 [for all callee-saved GPRs]
508 .cfi_def_cfa_offset (offset from RETADDR)
511 ; If the required stack alignment > default stack alignment
512 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
513 ; of unknown size in the stack frame.
514 [if stack needs re-alignment]
517 ; Allocate space for locals
518 [if target is Windows and allocated space > 4096 bytes]
519 ; Windows needs special care for allocations larger
522 call ___chkstk_ms/___chkstk
528 .seh_stackalloc (size of XMM spill slots)
529 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
534 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
535 ; they may get spilled on any platform, if the current function
536 ; calls @llvm.eh.unwind.init
538 [for all callee-saved XMM registers]
539 movaps %<xmm reg>, -MMM(%rbp)
540 [for all callee-saved XMM registers]
541 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
542 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
544 [for all callee-saved XMM registers]
545 movaps %<xmm reg>, KKK(%rsp)
546 [for all callee-saved XMM registers]
547 .seh_savexmm %<xmm reg>, KKK
551 [if needs base pointer]
553 [if needs to restore base pointer]
558 [for all callee-saved registers]
559 .cfi_offset %<reg>, (offset from %rbp)
561 .cfi_def_cfa_offset (offset from RETADDR)
562 [for all callee-saved registers]
563 .cfi_offset %<reg>, (offset from %rsp)
566 - .seh directives are emitted only for Windows 64 ABI
567 - .cfi directives are emitted for all other ABIs
568 - for 32-bit code, substitute %e?? registers for %r??
571 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
572 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
573 MachineBasicBlock::iterator MBBI = MBB.begin();
574 MachineFrameInfo *MFI = MF.getFrameInfo();
575 const Function *Fn = MF.getFunction();
576 const X86RegisterInfo *RegInfo =
577 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
578 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
579 MachineModuleInfo &MMI = MF.getMMI();
580 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
581 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
582 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
583 bool HasFP = hasFP(MF);
584 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
585 bool Is64Bit = STI.is64Bit();
586 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
587 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
588 bool IsWin64 = STI.isTargetWin64();
589 // Not necessarily synonymous with IsWin64.
590 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
591 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
593 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
594 bool UseLEA = STI.useLeaForSP();
595 unsigned StackAlign = getStackAlignment();
596 unsigned SlotSize = RegInfo->getSlotSize();
597 unsigned FramePtr = RegInfo->getFrameRegister(MF);
598 const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
599 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
600 unsigned StackPtr = RegInfo->getStackRegister();
601 unsigned BasePtr = RegInfo->getBaseRegister();
604 // If we're forcing a stack realignment we can't rely on just the frame
605 // info, we need to know the ABI stack alignment as well in case we
606 // have a call out. Otherwise just make sure we have some alignment - we'll
607 // go with the minimum SlotSize.
608 if (ForceStackAlign) {
610 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
611 else if (MaxAlign < SlotSize)
615 // Add RETADDR move area to callee saved frame size.
616 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
617 if (TailCallReturnAddrDelta < 0)
618 X86FI->setCalleeSavedFrameSize(
619 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
621 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
623 // The default stack probe size is 4096 if the function has no stackprobesize
625 unsigned StackProbeSize = 4096;
626 if (Fn->hasFnAttribute("stack-probe-size"))
627 Fn->getFnAttribute("stack-probe-size")
629 .getAsInteger(0, StackProbeSize);
631 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
632 // function, and use up to 128 bytes of stack space, don't have a frame
633 // pointer, calls, or dynamic alloca then we do not need to adjust the
634 // stack pointer (we fit in the Red Zone). We also check that we don't
635 // push and pop from the stack.
636 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
637 Attribute::NoRedZone) &&
638 !RegInfo->needsStackRealignment(MF) &&
639 !MFI->hasVarSizedObjects() && // No dynamic alloca.
640 !MFI->adjustsStack() && // No calls.
641 !IsWin64 && // Win64 has no Red Zone
642 !usesTheStack(MF) && // Don't push and pop.
643 !MF.shouldSplitStack()) { // Regular stack
644 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
645 if (HasFP) MinSize += SlotSize;
646 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
647 MFI->setStackSize(StackSize);
650 // Insert stack pointer adjustment for later moving of return addr. Only
651 // applies to tail call optimized functions where the callee argument stack
652 // size is bigger than the callers.
653 if (TailCallReturnAddrDelta < 0) {
655 BuildMI(MBB, MBBI, DL,
656 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
659 .addImm(-TailCallReturnAddrDelta)
660 .setMIFlag(MachineInstr::FrameSetup);
661 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
664 // Mapping for machine moves:
666 // DST: VirtualFP AND
667 // SRC: VirtualFP => DW_CFA_def_cfa_offset
668 // ELSE => DW_CFA_def_cfa
670 // SRC: VirtualFP AND
671 // DST: Register => DW_CFA_def_cfa_register
674 // OFFSET < 0 => DW_CFA_offset_extended_sf
675 // REG < 64 => DW_CFA_offset + Reg
676 // ELSE => DW_CFA_offset_extended
678 uint64_t NumBytes = 0;
679 int stackGrowth = -SlotSize;
682 // Calculate required stack adjustment.
683 uint64_t FrameSize = StackSize - SlotSize;
684 // If required, include space for extra hidden slot for stashing base pointer.
685 if (X86FI->getRestoreBasePointer())
686 FrameSize += SlotSize;
687 if (RegInfo->needsStackRealignment(MF)) {
688 // Callee-saved registers are pushed on stack before the stack
690 FrameSize -= X86FI->getCalleeSavedFrameSize();
691 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
693 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
696 // Get the offset of the stack slot for the EBP register, which is
697 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
698 // Update the frame offset adjustment.
699 MFI->setOffsetAdjustment(-NumBytes);
701 // Save EBP/RBP into the appropriate stack slot.
702 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
703 .addReg(MachineFramePtr, RegState::Kill)
704 .setMIFlag(MachineInstr::FrameSetup);
707 // Mark the place where EBP/RBP was saved.
708 // Define the current CFA rule to use the provided offset.
710 unsigned CFIIndex = MMI.addFrameInst(
711 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
712 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
713 .addCFIIndex(CFIIndex);
715 // Change the rule for the FramePtr to be an "offset" rule.
716 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
717 CFIIndex = MMI.addFrameInst(
718 MCCFIInstruction::createOffset(nullptr,
719 DwarfFramePtr, 2 * stackGrowth));
720 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
721 .addCFIIndex(CFIIndex);
725 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
727 .setMIFlag(MachineInstr::FrameSetup);
730 // Update EBP with the new base value.
731 BuildMI(MBB, MBBI, DL,
732 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
734 .setMIFlag(MachineInstr::FrameSetup);
737 // Mark effective beginning of when frame pointer becomes valid.
738 // Define the current CFA to use the EBP/RBP register.
739 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
740 unsigned CFIIndex = MMI.addFrameInst(
741 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
742 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
743 .addCFIIndex(CFIIndex);
746 // Mark the FramePtr as live-in in every block.
747 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
748 I->addLiveIn(MachineFramePtr);
750 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
753 // Skip the callee-saved push instructions.
754 bool PushedRegs = false;
755 int StackOffset = 2 * stackGrowth;
757 while (MBBI != MBB.end() &&
758 (MBBI->getOpcode() == X86::PUSH32r ||
759 MBBI->getOpcode() == X86::PUSH64r)) {
761 unsigned Reg = MBBI->getOperand(0).getReg();
764 if (!HasFP && NeedsDwarfCFI) {
765 // Mark callee-saved push instruction.
766 // Define the current CFA rule to use the provided offset.
768 unsigned CFIIndex = MMI.addFrameInst(
769 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
770 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
771 .addCFIIndex(CFIIndex);
772 StackOffset += stackGrowth;
776 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
777 MachineInstr::FrameSetup);
781 // Realign stack after we pushed callee-saved registers (so that we'll be
782 // able to calculate their offsets from the frame pointer).
783 if (RegInfo->needsStackRealignment(MF)) {
784 assert(HasFP && "There should be a frame pointer if stack is realigned.");
785 uint64_t Val = -MaxAlign;
787 BuildMI(MBB, MBBI, DL,
788 TII.get(getANDriOpcode(Uses64BitFramePtr, Val)), StackPtr)
791 .setMIFlag(MachineInstr::FrameSetup);
793 // The EFLAGS implicit def is dead.
794 MI->getOperand(3).setIsDead();
797 // If there is an SUB32ri of ESP immediately before this instruction, merge
798 // the two. This can be the case when tail call elimination is enabled and
799 // the callee has more arguments then the caller.
800 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
802 // If there is an ADD32ri or SUB32ri of ESP immediately after this
803 // instruction, merge the two instructions.
804 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
806 // Adjust stack pointer: ESP -= numbytes.
808 // Windows and cygwin/mingw require a prologue helper routine when allocating
809 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
810 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
811 // stack and adjust the stack pointer in one go. The 64-bit version of
812 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
813 // responsible for adjusting the stack pointer. Touching the stack at 4K
814 // increments is necessary to ensure that the guard pages used by the OS
815 // virtual memory manager are allocated in correct sequence.
816 if (NumBytes >= StackProbeSize && UseStackProbe) {
817 // Check whether EAX is livein for this function.
818 bool isEAXAlive = isEAXLiveIn(MF);
821 // Sanity check that EAX is not livein for this function.
822 // It should not be, so throw an assert.
823 assert(!Is64Bit && "EAX is livein in x64 case!");
826 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
827 .addReg(X86::EAX, RegState::Kill)
828 .setMIFlag(MachineInstr::FrameSetup);
832 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
833 // Function prologue is responsible for adjusting the stack pointer.
834 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
836 .setMIFlag(MachineInstr::FrameSetup);
838 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
839 // We'll also use 4 already allocated bytes for EAX.
840 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
841 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
842 .setMIFlag(MachineInstr::FrameSetup);
845 // Save a pointer to the MI where we set AX.
846 MachineBasicBlock::iterator SetRAX = MBBI;
849 // Call __chkstk, __chkstk_ms, or __alloca.
850 emitStackProbeCall(MF, MBB, MBBI, DL);
852 // Apply the frame setup flag to all inserted instrs.
853 for (; SetRAX != MBBI; ++SetRAX)
854 SetRAX->setFlag(MachineInstr::FrameSetup);
858 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
860 StackPtr, false, NumBytes - 4);
861 MI->setFlag(MachineInstr::FrameSetup);
862 MBB.insert(MBBI, MI);
864 } else if (NumBytes) {
865 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
866 UseLEA, TII, *RegInfo);
869 int SEHFrameOffset = 0;
872 // We need to set frame base offset low enough such that all saved
873 // register offsets would be positive relative to it, but we can't
874 // just use NumBytes, because .seh_setframe offset must be <=240.
875 // So we pretend to have only allocated enough space to spill the
876 // non-volatile registers.
877 // We don't care about the rest of stack allocation, because unwinder
878 // will restore SP to (BP - SEHFrameOffset)
879 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
880 int offset = MFI->getObjectOffset(Info.getFrameIdx());
881 SEHFrameOffset = std::max(SEHFrameOffset, std::abs(offset));
883 SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
885 // This only needs to account for XMM spill slots, GPR slots
886 // are covered by the .seh_pushreg's emitted above.
887 unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
889 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
891 .setMIFlag(MachineInstr::FrameSetup);
894 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
896 .addImm(SEHFrameOffset)
897 .setMIFlag(MachineInstr::FrameSetup);
899 // SP will be the base register for restoring XMMs
901 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
903 .setMIFlag(MachineInstr::FrameSetup);
908 // Skip the rest of register spilling code
909 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
912 // Emit SEH info for non-GPRs
914 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
915 unsigned Reg = Info.getReg();
916 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
918 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
920 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
921 Offset += SEHFrameOffset;
923 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
926 .setMIFlag(MachineInstr::FrameSetup);
929 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
930 .setMIFlag(MachineInstr::FrameSetup);
933 // If we need a base pointer, set it up here. It's whatever the value
934 // of the stack pointer is at this point. Any variable size objects
935 // will be allocated after this, so we can still use the base pointer
936 // to reference locals.
937 if (RegInfo->hasBasePointer(MF)) {
938 // Update the base pointer with the current stack pointer.
939 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
940 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
942 .setMIFlag(MachineInstr::FrameSetup);
943 if (X86FI->getRestoreBasePointer()) {
944 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
945 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
946 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
947 FramePtr, true, X86FI->getRestoreBasePointerOffset())
949 .setMIFlag(MachineInstr::FrameSetup);
953 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
954 // Mark end of stack pointer adjustment.
955 if (!HasFP && NumBytes) {
956 // Define the current CFA rule to use the provided offset.
958 unsigned CFIIndex = MMI.addFrameInst(
959 MCCFIInstruction::createDefCfaOffset(nullptr,
960 -StackSize + stackGrowth));
962 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
963 .addCFIIndex(CFIIndex);
966 // Emit DWARF info specifying the offsets of the callee-saved registers.
968 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
972 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
973 MachineBasicBlock &MBB) const {
974 const MachineFrameInfo *MFI = MF.getFrameInfo();
975 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
976 const X86RegisterInfo *RegInfo =
977 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
978 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
979 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
980 assert(MBBI != MBB.end() && "Returning block has no instructions");
981 unsigned RetOpcode = MBBI->getOpcode();
982 DebugLoc DL = MBBI->getDebugLoc();
983 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
984 bool Is64Bit = STI.is64Bit();
985 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
986 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
987 const bool Is64BitILP32 = STI.isTarget64BitILP32();
988 bool UseLEA = STI.useLeaForSP();
989 unsigned StackAlign = getStackAlignment();
990 unsigned SlotSize = RegInfo->getSlotSize();
991 unsigned FramePtr = RegInfo->getFrameRegister(MF);
992 unsigned MachineFramePtr = Is64BitILP32 ?
993 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
994 unsigned StackPtr = RegInfo->getStackRegister();
996 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
997 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
1001 llvm_unreachable("Can only insert epilog into returning blocks");
1006 case X86::TCRETURNdi:
1007 case X86::TCRETURNri:
1008 case X86::TCRETURNmi:
1009 case X86::TCRETURNdi64:
1010 case X86::TCRETURNri64:
1011 case X86::TCRETURNmi64:
1012 case X86::EH_RETURN:
1013 case X86::EH_RETURN64:
1014 break; // These are ok
1017 // Get the number of bytes to allocate from the FrameInfo.
1018 uint64_t StackSize = MFI->getStackSize();
1019 uint64_t MaxAlign = MFI->getMaxAlignment();
1020 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1021 uint64_t NumBytes = 0;
1023 // If we're forcing a stack realignment we can't rely on just the frame
1024 // info, we need to know the ABI stack alignment as well in case we
1025 // have a call out. Otherwise just make sure we have some alignment - we'll
1026 // go with the minimum.
1027 if (ForceStackAlign) {
1028 if (MFI->hasCalls())
1029 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
1031 MaxAlign = MaxAlign ? MaxAlign : 4;
1035 // Calculate required stack adjustment.
1036 uint64_t FrameSize = StackSize - SlotSize;
1037 if (RegInfo->needsStackRealignment(MF)) {
1038 // Callee-saved registers were pushed on stack before the stack
1040 FrameSize -= CSSize;
1041 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
1043 NumBytes = FrameSize - CSSize;
1047 BuildMI(MBB, MBBI, DL,
1048 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1050 NumBytes = StackSize - CSSize;
1053 // Skip the callee-saved pop instructions.
1054 while (MBBI != MBB.begin()) {
1055 MachineBasicBlock::iterator PI = std::prev(MBBI);
1056 unsigned Opc = PI->getOpcode();
1058 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1059 !PI->isTerminator())
1064 MachineBasicBlock::iterator FirstCSPop = MBBI;
1066 DL = MBBI->getDebugLoc();
1068 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1069 // instruction, merge the two instructions.
1070 if (NumBytes || MFI->hasVarSizedObjects())
1071 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1073 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1074 // slot before popping them off! Same applies for the case, when stack was
1076 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1077 if (RegInfo->needsStackRealignment(MF))
1080 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1081 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1082 FramePtr, false, -CSSize);
1085 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1086 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1090 } else if (NumBytes) {
1091 // Adjust stack pointer back: ESP += numbytes.
1092 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
1097 // Windows unwinder will not invoke function's exception handler if IP is
1098 // either in prologue or in epilogue. This behavior causes a problem when a
1099 // call immediately precedes an epilogue, because the return address points
1100 // into the epilogue. To cope with that, we insert an epilogue marker here,
1101 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1102 // final emitted code.
1104 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1106 // We're returning from function via eh_return.
1107 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1108 MBBI = MBB.getLastNonDebugInstr();
1109 MachineOperand &DestAddr = MBBI->getOperand(0);
1110 assert(DestAddr.isReg() && "Offset should be in register!");
1111 BuildMI(MBB, MBBI, DL,
1112 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1113 StackPtr).addReg(DestAddr.getReg());
1114 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1115 RetOpcode == X86::TCRETURNmi ||
1116 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1117 RetOpcode == X86::TCRETURNmi64) {
1118 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1119 // Tail call return: adjust the stack pointer and jump to callee.
1120 MBBI = MBB.getLastNonDebugInstr();
1121 MachineOperand &JumpTarget = MBBI->getOperand(0);
1122 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1123 assert(StackAdjust.isImm() && "Expecting immediate value.");
1125 // Adjust stack pointer.
1126 int StackAdj = StackAdjust.getImm();
1127 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1129 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1131 // Incoporate the retaddr area.
1132 Offset = StackAdj-MaxTCDelta;
1133 assert(Offset >= 0 && "Offset should never be negative");
1136 // Check for possible merge with preceding ADD instruction.
1137 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1138 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1139 UseLEA, TII, *RegInfo);
1142 // Jump to label or value in register.
1143 bool IsWin64 = STI.isTargetWin64();
1144 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1145 unsigned Op = (RetOpcode == X86::TCRETURNdi)
1147 : (IsWin64 ? X86::TAILJMPd64_REX : X86::TAILJMPd64);
1148 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(Op));
1149 if (JumpTarget.isGlobal())
1150 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1151 JumpTarget.getTargetFlags());
1153 assert(JumpTarget.isSymbol());
1154 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1155 JumpTarget.getTargetFlags());
1157 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1158 unsigned Op = (RetOpcode == X86::TCRETURNmi)
1160 : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64);
1161 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(Op));
1162 for (unsigned i = 0; i != 5; ++i)
1163 MIB.addOperand(MBBI->getOperand(i));
1164 } else if (RetOpcode == X86::TCRETURNri64) {
1165 BuildMI(MBB, MBBI, DL,
1166 TII.get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64))
1167 .addReg(JumpTarget.getReg(), RegState::Kill);
1169 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1170 addReg(JumpTarget.getReg(), RegState::Kill);
1173 MachineInstr *NewMI = std::prev(MBBI);
1174 NewMI->copyImplicitOps(MF, MBBI);
1176 // Delete the pseudo instruction TCRETURN.
1178 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1179 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1180 (X86FI->getTCReturnAddrDelta() < 0)) {
1181 // Add the return addr area delta back since we are not tail calling.
1182 int delta = -1*X86FI->getTCReturnAddrDelta();
1183 MBBI = MBB.getLastNonDebugInstr();
1185 // Check for possible merge with preceding ADD instruction.
1186 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1187 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1192 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1194 const X86RegisterInfo *RegInfo =
1195 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1196 const MachineFrameInfo *MFI = MF.getFrameInfo();
1197 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1198 uint64_t StackSize = MFI->getStackSize();
1200 if (RegInfo->hasBasePointer(MF)) {
1201 assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1203 // Skip the saved EBP.
1204 return Offset + RegInfo->getSlotSize();
1206 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1207 return Offset + StackSize;
1209 } else if (RegInfo->needsStackRealignment(MF)) {
1211 // Skip the saved EBP.
1212 return Offset + RegInfo->getSlotSize();
1214 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1215 return Offset + StackSize;
1217 // FIXME: Support tail calls
1220 return Offset + StackSize;
1222 // Skip the saved EBP.
1223 Offset += RegInfo->getSlotSize();
1225 // Skip the RETADDR move area
1226 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1227 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1228 if (TailCallReturnAddrDelta < 0)
1229 Offset -= TailCallReturnAddrDelta;
1235 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1236 unsigned &FrameReg) const {
1237 const X86RegisterInfo *RegInfo =
1238 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1239 // We can't calculate offset from frame pointer if the stack is realigned,
1240 // so enforce usage of stack/base pointer. The base pointer is used when we
1241 // have dynamic allocas in addition to dynamic realignment.
1242 if (RegInfo->hasBasePointer(MF))
1243 FrameReg = RegInfo->getBaseRegister();
1244 else if (RegInfo->needsStackRealignment(MF))
1245 FrameReg = RegInfo->getStackRegister();
1247 FrameReg = RegInfo->getFrameRegister(MF);
1248 return getFrameIndexOffset(MF, FI);
1251 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1252 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1253 const MachineFrameInfo *MFI = MF.getFrameInfo();
1254 // Does not include any dynamic realign.
1255 const uint64_t StackSize = MFI->getStackSize();
1258 const X86RegisterInfo *RegInfo =
1259 static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
1260 // Note: LLVM arranges the stack as:
1261 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1262 // > "Stack Slots" (<--SP)
1263 // We can always address StackSlots from RSP. We can usually (unless
1264 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1265 // address them from RBP. FixedObjects can be placed anywhere in the stack
1266 // frame depending on their specific requirements (i.e. we can actually
1267 // refer to arguments to the function which are stored in the *callers*
1268 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1269 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1271 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1273 // We don't handle tail calls, and shouldn't be seeing them
1275 int TailCallReturnAddrDelta =
1276 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1277 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1281 // This is how the math works out:
1283 // %rsp grows (i.e. gets lower) left to right. Each box below is
1284 // one word (eight bytes). Obj0 is the stack slot we're trying to
1287 // ----------------------------------
1288 // | BP | Obj0 | Obj1 | ... | ObjN |
1289 // ----------------------------------
1293 // A is the incoming stack pointer.
1294 // (B - A) is the local area offset (-8 for x86-64) [1]
1295 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1297 // |(E - B)| is the StackSize (absolute value, positive). For a
1298 // stack that grown down, this works out to be (B - E). [3]
1300 // E is also the value of %rsp after stack has been set up, and we
1301 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1302 // (C - E) == (C - A) - (B - A) + (B - E)
1303 // { Using [1], [2] and [3] above }
1304 // == getObjectOffset - LocalAreaOffset + StackSize
1307 // Get the Offset from the StackPointer
1308 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1310 return Offset + StackSize;
1312 // Simplified from getFrameIndexReference keeping only StackPointer cases
1313 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF, int FI,
1314 unsigned &FrameReg) const {
1315 const X86RegisterInfo *RegInfo =
1316 static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
1318 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1320 FrameReg = RegInfo->getStackRegister();
1321 return getFrameIndexOffsetFromSP(MF, FI);
1324 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1325 MachineFunction &MF, const TargetRegisterInfo *TRI,
1326 std::vector<CalleeSavedInfo> &CSI) const {
1327 MachineFrameInfo *MFI = MF.getFrameInfo();
1328 const X86RegisterInfo *RegInfo =
1329 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1330 unsigned SlotSize = RegInfo->getSlotSize();
1331 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1333 unsigned CalleeSavedFrameSize = 0;
1334 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1337 // emitPrologue always spills frame register the first thing.
1338 SpillSlotOffset -= SlotSize;
1339 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1341 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1342 // the frame register, we can delete it from CSI list and not have to worry
1343 // about avoiding it later.
1344 unsigned FPReg = RegInfo->getFrameRegister(MF);
1345 for (unsigned i = 0; i < CSI.size(); ++i) {
1346 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1347 CSI.erase(CSI.begin() + i);
1353 // Assign slots for GPRs. It increases frame size.
1354 for (unsigned i = CSI.size(); i != 0; --i) {
1355 unsigned Reg = CSI[i - 1].getReg();
1357 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1360 SpillSlotOffset -= SlotSize;
1361 CalleeSavedFrameSize += SlotSize;
1363 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1364 CSI[i - 1].setFrameIdx(SlotIndex);
1367 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1369 // Assign slots for XMMs.
1370 for (unsigned i = CSI.size(); i != 0; --i) {
1371 unsigned Reg = CSI[i - 1].getReg();
1372 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1375 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1377 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1379 SpillSlotOffset -= RC->getSize();
1381 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1382 CSI[i - 1].setFrameIdx(SlotIndex);
1383 MFI->ensureMaxAlignment(RC->getAlignment());
1389 bool X86FrameLowering::spillCalleeSavedRegisters(
1390 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1391 const std::vector<CalleeSavedInfo> &CSI,
1392 const TargetRegisterInfo *TRI) const {
1393 DebugLoc DL = MBB.findDebugLoc(MI);
1395 MachineFunction &MF = *MBB.getParent();
1396 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1397 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1399 // Push GPRs. It increases frame size.
1400 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1401 for (unsigned i = CSI.size(); i != 0; --i) {
1402 unsigned Reg = CSI[i - 1].getReg();
1404 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1406 // Add the callee-saved register as live-in. It's killed at the spill.
1409 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1410 .setMIFlag(MachineInstr::FrameSetup);
1413 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1414 // It can be done by spilling XMMs to stack frame.
1415 for (unsigned i = CSI.size(); i != 0; --i) {
1416 unsigned Reg = CSI[i-1].getReg();
1417 if (X86::GR64RegClass.contains(Reg) ||
1418 X86::GR32RegClass.contains(Reg))
1420 // Add the callee-saved register as live-in. It's killed at the spill.
1422 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1424 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1427 MI->setFlag(MachineInstr::FrameSetup);
1434 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1435 MachineBasicBlock::iterator MI,
1436 const std::vector<CalleeSavedInfo> &CSI,
1437 const TargetRegisterInfo *TRI) const {
1441 DebugLoc DL = MBB.findDebugLoc(MI);
1443 MachineFunction &MF = *MBB.getParent();
1444 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1445 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1447 // Reload XMMs from stack frame.
1448 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1449 unsigned Reg = CSI[i].getReg();
1450 if (X86::GR64RegClass.contains(Reg) ||
1451 X86::GR32RegClass.contains(Reg))
1454 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1455 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1459 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1460 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1461 unsigned Reg = CSI[i].getReg();
1462 if (!X86::GR64RegClass.contains(Reg) &&
1463 !X86::GR32RegClass.contains(Reg))
1466 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1472 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1473 RegScavenger *RS) const {
1474 MachineFrameInfo *MFI = MF.getFrameInfo();
1475 const X86RegisterInfo *RegInfo =
1476 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1477 unsigned SlotSize = RegInfo->getSlotSize();
1479 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1480 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1482 if (TailCallReturnAddrDelta < 0) {
1483 // create RETURNADDR area
1492 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1493 TailCallReturnAddrDelta - SlotSize, true);
1496 // Spill the BasePtr if it's used.
1497 if (RegInfo->hasBasePointer(MF))
1498 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1502 HasNestArgument(const MachineFunction *MF) {
1503 const Function *F = MF->getFunction();
1504 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1506 if (I->hasNestAttr())
1512 /// GetScratchRegister - Get a temp register for performing work in the
1513 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1514 /// and the properties of the function either one or two registers will be
1515 /// needed. Set primary to true for the first register, false for the second.
1517 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1518 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1521 if (CallingConvention == CallingConv::HiPE) {
1523 return Primary ? X86::R14 : X86::R13;
1525 return Primary ? X86::EBX : X86::EDI;
1530 return Primary ? X86::R11 : X86::R12;
1532 return Primary ? X86::R11D : X86::R12D;
1535 bool IsNested = HasNestArgument(&MF);
1537 if (CallingConvention == CallingConv::X86_FastCall ||
1538 CallingConvention == CallingConv::Fast) {
1540 report_fatal_error("Segmented stacks does not support fastcall with "
1541 "nested function.");
1542 return Primary ? X86::EAX : X86::ECX;
1545 return Primary ? X86::EDX : X86::EAX;
1546 return Primary ? X86::ECX : X86::EAX;
1549 // The stack limit in the TCB is set to this many bytes above the actual stack
1551 static const uint64_t kSplitStackAvailable = 256;
1554 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1555 MachineBasicBlock &prologueMBB = MF.front();
1556 MachineFrameInfo *MFI = MF.getFrameInfo();
1557 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1559 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1560 bool Is64Bit = STI.is64Bit();
1561 const bool IsLP64 = STI.isTarget64BitLP64();
1562 unsigned TlsReg, TlsOffset;
1565 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1566 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1567 "Scratch register is live-in");
1569 if (MF.getFunction()->isVarArg())
1570 report_fatal_error("Segmented stacks do not support vararg functions.");
1571 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1572 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1573 !STI.isTargetDragonFly())
1574 report_fatal_error("Segmented stacks not supported on this platform.");
1576 // Eventually StackSize will be calculated by a link-time pass; which will
1577 // also decide whether checking code needs to be injected into this particular
1579 StackSize = MFI->getStackSize();
1581 // Do not generate a prologue for functions with a stack of size zero
1585 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1586 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1587 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1588 bool IsNested = false;
1590 // We need to know if the function has a nest argument only in 64 bit mode.
1592 IsNested = HasNestArgument(&MF);
1594 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1595 // allocMBB needs to be last (terminating) instruction.
1597 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1598 e = prologueMBB.livein_end(); i != e; i++) {
1599 allocMBB->addLiveIn(*i);
1600 checkMBB->addLiveIn(*i);
1604 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1606 MF.push_front(allocMBB);
1607 MF.push_front(checkMBB);
1609 // When the frame size is less than 256 we just compare the stack
1610 // boundary directly to the value of the stack pointer, per gcc.
1611 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1613 // Read the limit off the current stacklet off the stack_guard location.
1615 if (STI.isTargetLinux()) {
1617 TlsOffset = IsLP64 ? 0x70 : 0x40;
1618 } else if (STI.isTargetDarwin()) {
1620 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1621 } else if (STI.isTargetWin64()) {
1623 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1624 } else if (STI.isTargetFreeBSD()) {
1627 } else if (STI.isTargetDragonFly()) {
1629 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1631 report_fatal_error("Segmented stacks not supported on this platform.");
1634 if (CompareStackPointer)
1635 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1637 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1638 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1640 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1641 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1643 if (STI.isTargetLinux()) {
1646 } else if (STI.isTargetDarwin()) {
1648 TlsOffset = 0x48 + 90*4;
1649 } else if (STI.isTargetWin32()) {
1651 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1652 } else if (STI.isTargetDragonFly()) {
1654 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1655 } else if (STI.isTargetFreeBSD()) {
1656 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1658 report_fatal_error("Segmented stacks not supported on this platform.");
1661 if (CompareStackPointer)
1662 ScratchReg = X86::ESP;
1664 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1665 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1667 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1668 STI.isTargetDragonFly()) {
1669 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1670 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1671 } else if (STI.isTargetDarwin()) {
1673 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1674 unsigned ScratchReg2;
1676 if (CompareStackPointer) {
1677 // The primary scratch register is available for holding the TLS offset.
1678 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1679 SaveScratch2 = false;
1681 // Need to use a second register to hold the TLS offset
1682 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1684 // Unfortunately, with fastcc the second scratch register may hold an
1686 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1689 // If Scratch2 is live-in then it needs to be saved.
1690 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1691 "Scratch register is live-in and not saved");
1694 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1695 .addReg(ScratchReg2, RegState::Kill);
1697 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1699 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1701 .addReg(ScratchReg2).addImm(1).addReg(0)
1706 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1710 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1711 // It jumps to normal execution of the function body.
1712 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&prologueMBB);
1714 // On 32 bit we first push the arguments size and then the frame size. On 64
1715 // bit, we pass the stack frame size in r10 and the argument size in r11.
1717 // Functions with nested arguments use R10, so it needs to be saved across
1718 // the call to _morestack
1720 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1721 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1722 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1723 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1724 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1727 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1729 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1731 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1732 .addImm(X86FI->getArgumentStackSize());
1733 MF.getRegInfo().setPhysRegUsed(Reg10);
1734 MF.getRegInfo().setPhysRegUsed(Reg11);
1736 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1737 .addImm(X86FI->getArgumentStackSize());
1738 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1742 // __morestack is in libgcc
1743 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1744 // Under the large code model, we cannot assume that __morestack lives
1745 // within 2^31 bytes of the call site, so we cannot use pc-relative
1746 // addressing. We cannot perform the call via a temporary register,
1747 // as the rax register may be used to store the static chain, and all
1748 // other suitable registers may be either callee-save or used for
1749 // parameter passing. We cannot use the stack at this point either
1750 // because __morestack manipulates the stack directly.
1752 // To avoid these issues, perform an indirect call via a read-only memory
1753 // location containing the address.
1755 // This solution is not perfect, as it assumes that the .rodata section
1756 // is laid out within 2^31 bytes of each function body, but this seems
1757 // to be sufficient for JIT.
1758 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1762 .addExternalSymbol("__morestack_addr")
1764 MF.getMMI().setUsesMorestackAddr(true);
1767 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1768 .addExternalSymbol("__morestack");
1770 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1771 .addExternalSymbol("__morestack");
1775 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1777 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1779 allocMBB->addSuccessor(&prologueMBB);
1781 checkMBB->addSuccessor(allocMBB);
1782 checkMBB->addSuccessor(&prologueMBB);
1789 /// Erlang programs may need a special prologue to handle the stack size they
1790 /// might need at runtime. That is because Erlang/OTP does not implement a C
1791 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1792 /// (for more information see Eric Stenman's Ph.D. thesis:
1793 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1796 /// temp0 = sp - MaxStack
1797 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1801 /// call inc_stack # doubles the stack space
1802 /// temp0 = sp - MaxStack
1803 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1804 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
1805 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1806 MachineFrameInfo *MFI = MF.getFrameInfo();
1807 const unsigned SlotSize =
1808 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1810 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1811 const bool Is64Bit = STI.is64Bit();
1812 const bool IsLP64 = STI.isTarget64BitLP64();
1814 // HiPE-specific values
1815 const unsigned HipeLeafWords = 24;
1816 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1817 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1818 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1819 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1820 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1822 assert(STI.isTargetLinux() &&
1823 "HiPE prologue is only supported on Linux operating systems.");
1825 // Compute the largest caller's frame that is needed to fit the callees'
1826 // frames. This 'MaxStack' is computed from:
1828 // a) the fixed frame size, which is the space needed for all spilled temps,
1829 // b) outgoing on-stack parameter areas, and
1830 // c) the minimum stack space this function needs to make available for the
1831 // functions it calls (a tunable ABI property).
1832 if (MFI->hasCalls()) {
1833 unsigned MoreStackForCalls = 0;
1835 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1836 MBBI != MBBE; ++MBBI)
1837 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1842 // Get callee operand.
1843 const MachineOperand &MO = MI->getOperand(0);
1845 // Only take account of global function calls (no closures etc.).
1849 const Function *F = dyn_cast<Function>(MO.getGlobal());
1853 // Do not update 'MaxStack' for primitive and built-in functions
1854 // (encoded with names either starting with "erlang."/"bif_" or not
1855 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1856 // "_", such as the BIF "suspend_0") as they are executed on another
1858 if (F->getName().find("erlang.") != StringRef::npos ||
1859 F->getName().find("bif_") != StringRef::npos ||
1860 F->getName().find_first_of("._") == StringRef::npos)
1863 unsigned CalleeStkArity =
1864 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1865 if (HipeLeafWords - 1 > CalleeStkArity)
1866 MoreStackForCalls = std::max(MoreStackForCalls,
1867 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1869 MaxStack += MoreStackForCalls;
1872 // If the stack frame needed is larger than the guaranteed then runtime checks
1873 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1874 if (MaxStack > Guaranteed) {
1875 MachineBasicBlock &prologueMBB = MF.front();
1876 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1877 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1879 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1880 E = prologueMBB.livein_end(); I != E; I++) {
1881 stackCheckMBB->addLiveIn(*I);
1882 incStackMBB->addLiveIn(*I);
1885 MF.push_front(incStackMBB);
1886 MF.push_front(stackCheckMBB);
1888 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1889 unsigned LEAop, CMPop, CALLop;
1893 LEAop = X86::LEA64r;
1894 CMPop = X86::CMP64rm;
1895 CALLop = X86::CALL64pcrel32;
1896 SPLimitOffset = 0x90;
1900 LEAop = X86::LEA32r;
1901 CMPop = X86::CMP32rm;
1902 CALLop = X86::CALLpcrel32;
1903 SPLimitOffset = 0x4c;
1906 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1907 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1908 "HiPE prologue scratch register is live-in");
1910 // Create new MBB for StackCheck:
1911 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1912 SPReg, false, -MaxStack);
1913 // SPLimitOffset is in a fixed heap location (pointed by BP).
1914 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1915 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1916 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&prologueMBB);
1918 // Create new MBB for IncStack:
1919 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1920 addExternalSymbol("inc_stack_0");
1921 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1922 SPReg, false, -MaxStack);
1923 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1924 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1925 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1927 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1928 stackCheckMBB->addSuccessor(incStackMBB, 1);
1929 incStackMBB->addSuccessor(&prologueMBB, 99);
1930 incStackMBB->addSuccessor(incStackMBB, 1);
1937 void X86FrameLowering::
1938 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1939 MachineBasicBlock::iterator I) const {
1940 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1941 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1942 MF.getSubtarget().getRegisterInfo());
1943 unsigned StackPtr = RegInfo.getStackRegister();
1944 bool reserveCallFrame = hasReservedCallFrame(MF);
1945 int Opcode = I->getOpcode();
1946 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1947 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1948 bool IsLP64 = STI.isTarget64BitLP64();
1949 DebugLoc DL = I->getDebugLoc();
1950 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1951 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
1954 if (!reserveCallFrame) {
1955 // If the stack pointer can be changed after prologue, turn the
1956 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1957 // adjcallstackdown instruction into 'add ESP, <amt>'
1961 // We need to keep the stack aligned properly. To do this, we round the
1962 // amount of space needed for the outgoing arguments up to the next
1963 // alignment boundary.
1964 unsigned StackAlign = MF.getTarget()
1966 ->getFrameLowering()
1967 ->getStackAlignment();
1968 Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
1970 MachineInstr *New = nullptr;
1972 // Factor out the amount that gets handled inside the sequence
1973 // (Pushes of argument for frame setup, callee pops for frame destroy)
1974 Amount -= InternalAmt;
1977 if (Opcode == TII.getCallFrameSetupOpcode()) {
1978 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1979 .addReg(StackPtr).addImm(Amount);
1981 assert(Opcode == TII.getCallFrameDestroyOpcode());
1983 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1984 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1985 .addReg(StackPtr).addImm(Amount);
1990 // The EFLAGS implicit def is dead.
1991 New->getOperand(3).setIsDead();
1993 // Replace the pseudo instruction with a new instruction.
2000 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
2001 // If we are performing frame pointer elimination and if the callee pops
2002 // something off the stack pointer, add it back. We do this until we have
2003 // more advanced stack pointer tracking ability.
2004 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
2005 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
2006 .addReg(StackPtr).addImm(InternalAmt);
2008 // The EFLAGS implicit def is dead.
2009 New->getOperand(3).setIsDead();
2011 // We are not tracking the stack pointer adjustment by the callee, so make
2012 // sure we restore the stack pointer immediately after the call, there may
2013 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2014 MachineBasicBlock::iterator B = MBB.begin();
2015 while (I != B && !std::prev(I)->isCall())