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.
208 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
209 MachineBasicBlock::iterator &MBBI,
210 unsigned StackPtr, int64_t NumBytes,
211 bool Is64BitTarget, bool Is64BitStackPtr,
212 bool UseLEA, const TargetInstrInfo &TII,
213 const TargetRegisterInfo &TRI) {
214 bool isSub = NumBytes < 0;
215 uint64_t Offset = isSub ? -NumBytes : NumBytes;
218 Opc = getLEArOpcode(Is64BitStackPtr);
221 ? getSUBriOpcode(Is64BitStackPtr, Offset)
222 : getADDriOpcode(Is64BitStackPtr, Offset);
224 uint64_t Chunk = (1LL << 31) - 1;
225 DebugLoc DL = MBB.findDebugLoc(MBBI);
228 if (Offset > Chunk) {
229 // Rather than emit a long series of instructions for large offsets,
230 // load the offset into a register and do one sub/add
233 if (isSub && !isEAXLiveIn(*MBB.getParent()))
234 Reg = (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX);
236 Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
239 Opc = Is64BitTarget ? X86::MOV64ri : X86::MOV32ri;
240 BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
243 ? getSUBrrOpcode(Is64BitTarget)
244 : getADDrrOpcode(Is64BitTarget);
245 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
248 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
254 uint64_t ThisVal = std::min(Offset, Chunk);
255 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
256 // Use push / pop instead.
258 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
259 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
262 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
263 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
264 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
265 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
267 MI->setFlag(MachineInstr::FrameSetup);
273 MachineInstr *MI = nullptr;
276 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
277 StackPtr, false, isSub ? -ThisVal : ThisVal);
279 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
282 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
286 MI->setFlag(MachineInstr::FrameSetup);
292 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
294 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
295 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
296 if (MBBI == MBB.begin()) return;
298 MachineBasicBlock::iterator PI = std::prev(MBBI);
299 unsigned Opc = PI->getOpcode();
300 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
301 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
302 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
303 PI->getOperand(0).getReg() == StackPtr) {
305 *NumBytes += PI->getOperand(2).getImm();
307 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
308 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
309 PI->getOperand(0).getReg() == StackPtr) {
311 *NumBytes -= PI->getOperand(2).getImm();
316 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
317 MachineBasicBlock::iterator &MBBI,
319 bool doMergeWithPrevious) {
320 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
321 (!doMergeWithPrevious && MBBI == MBB.end()))
324 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
325 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
327 unsigned Opc = PI->getOpcode();
330 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
331 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
332 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
333 PI->getOperand(0).getReg() == StackPtr){
334 Offset += PI->getOperand(2).getImm();
336 if (!doMergeWithPrevious) MBBI = NI;
337 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
338 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
339 PI->getOperand(0).getReg() == StackPtr) {
340 Offset -= PI->getOperand(2).getImm();
342 if (!doMergeWithPrevious) MBBI = NI;
349 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
350 MachineBasicBlock::iterator MBBI,
352 MachineFunction &MF = *MBB.getParent();
353 MachineFrameInfo *MFI = MF.getFrameInfo();
354 MachineModuleInfo &MMI = MF.getMMI();
355 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
356 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
358 // Add callee saved registers to move list.
359 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
360 if (CSI.empty()) return;
362 // Calculate offsets.
363 for (std::vector<CalleeSavedInfo>::const_iterator
364 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
365 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
366 unsigned Reg = I->getReg();
368 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
370 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
372 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
373 .addCFIIndex(CFIIndex);
377 /// usesTheStack - This function checks if any of the users of EFLAGS
378 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
379 /// to use the stack, and if we don't adjust the stack we clobber the first
381 /// See X86InstrInfo::copyPhysReg.
382 static bool usesTheStack(const MachineFunction &MF) {
383 const MachineRegisterInfo &MRI = MF.getRegInfo();
385 for (MachineRegisterInfo::reg_instr_iterator
386 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
394 void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
395 MachineBasicBlock &MBB,
396 MachineBasicBlock::iterator MBBI,
398 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
399 const TargetInstrInfo &TII = *STI.getInstrInfo();
400 bool Is64Bit = STI.is64Bit();
401 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
405 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
407 CallOp = X86::CALLpcrel32;
411 if (STI.isTargetCygMing()) {
412 Symbol = "___chkstk_ms";
416 } else if (STI.isTargetCygMing())
421 MachineInstrBuilder CI;
423 // All current stack probes take AX and SP as input, clobber flags, and
424 // preserve all registers. x86_64 probes leave RSP unmodified.
425 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
426 // For the large code model, we have to call through a register. Use R11,
427 // as it is scratch in all supported calling conventions.
428 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
429 .addExternalSymbol(Symbol);
430 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
432 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
435 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
436 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
437 CI.addReg(AX, RegState::Implicit)
438 .addReg(SP, RegState::Implicit)
439 .addReg(AX, RegState::Define | RegState::Implicit)
440 .addReg(SP, RegState::Define | RegState::Implicit)
441 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
444 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
445 // themselves. It also does not clobber %rax so we can reuse it when
447 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
453 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
454 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
455 // and might require smaller successive adjustments.
456 const uint64_t Win64MaxSEHOffset = 128;
457 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
458 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
459 return SEHFrameOffset & -16;
462 // If we're forcing a stack realignment we can't rely on just the frame
463 // info, we need to know the ABI stack alignment as well in case we
464 // have a call out. Otherwise just make sure we have some alignment - we'll
465 // go with the minimum SlotSize.
466 static uint64_t calculateMaxStackAlign(const MachineFunction &MF) {
467 const MachineFrameInfo *MFI = MF.getFrameInfo();
468 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
469 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
470 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
471 unsigned SlotSize = RegInfo->getSlotSize();
472 unsigned StackAlign = STI.getFrameLowering()->getStackAlignment();
473 if (ForceStackAlign) {
475 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
476 else if (MaxAlign < SlotSize)
482 /// emitPrologue - Push callee-saved registers onto the stack, which
483 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
484 /// space for local variables. Also emit labels used by the exception handler to
485 /// generate the exception handling frames.
488 Here's a gist of what gets emitted:
490 ; Establish frame pointer, if needed
493 .cfi_def_cfa_offset 16
494 .cfi_offset %rbp, -16
497 .cfi_def_cfa_register %rbp
499 ; Spill general-purpose registers
500 [for all callee-saved GPRs]
503 .cfi_def_cfa_offset (offset from RETADDR)
506 ; If the required stack alignment > default stack alignment
507 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
508 ; of unknown size in the stack frame.
509 [if stack needs re-alignment]
512 ; Allocate space for locals
513 [if target is Windows and allocated space > 4096 bytes]
514 ; Windows needs special care for allocations larger
517 call ___chkstk_ms/___chkstk
523 .seh_stackalloc (size of XMM spill slots)
524 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
529 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
530 ; they may get spilled on any platform, if the current function
531 ; calls @llvm.eh.unwind.init
533 [for all callee-saved XMM registers]
534 movaps %<xmm reg>, -MMM(%rbp)
535 [for all callee-saved XMM registers]
536 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
537 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
539 [for all callee-saved XMM registers]
540 movaps %<xmm reg>, KKK(%rsp)
541 [for all callee-saved XMM registers]
542 .seh_savexmm %<xmm reg>, KKK
546 [if needs base pointer]
548 [if needs to restore base pointer]
553 [for all callee-saved registers]
554 .cfi_offset %<reg>, (offset from %rbp)
556 .cfi_def_cfa_offset (offset from RETADDR)
557 [for all callee-saved registers]
558 .cfi_offset %<reg>, (offset from %rsp)
561 - .seh directives are emitted only for Windows 64 ABI
562 - .cfi directives are emitted for all other ABIs
563 - for 32-bit code, substitute %e?? registers for %r??
566 void X86FrameLowering::emitPrologue(MachineFunction &MF,
567 MachineBasicBlock &MBB) const {
568 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
569 MachineBasicBlock::iterator MBBI = MBB.begin();
570 MachineFrameInfo *MFI = MF.getFrameInfo();
571 const Function *Fn = MF.getFunction();
572 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
573 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
574 const TargetInstrInfo &TII = *STI.getInstrInfo();
575 MachineModuleInfo &MMI = MF.getMMI();
576 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
577 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
578 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
579 bool HasFP = hasFP(MF);
580 bool Is64Bit = STI.is64Bit();
581 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
582 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
583 bool IsWin64 = STI.isCallingConvWin64(Fn->getCallingConv());
584 // Not necessarily synonymous with IsWin64.
585 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
586 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
588 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
589 bool UseLEA = STI.useLeaForSP();
590 unsigned SlotSize = RegInfo->getSlotSize();
591 unsigned FramePtr = RegInfo->getFrameRegister(MF);
592 const unsigned MachineFramePtr =
593 STI.isTarget64BitILP32()
594 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
596 unsigned StackPtr = RegInfo->getStackRegister();
597 unsigned BasePtr = RegInfo->getBaseRegister();
600 // Add RETADDR move area to callee saved frame size.
601 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
602 if (TailCallReturnAddrDelta && IsWinEH)
603 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
605 if (TailCallReturnAddrDelta < 0)
606 X86FI->setCalleeSavedFrameSize(
607 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
609 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
611 // The default stack probe size is 4096 if the function has no stackprobesize
613 unsigned StackProbeSize = 4096;
614 if (Fn->hasFnAttribute("stack-probe-size"))
615 Fn->getFnAttribute("stack-probe-size")
617 .getAsInteger(0, StackProbeSize);
619 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
620 // function, and use up to 128 bytes of stack space, don't have a frame
621 // pointer, calls, or dynamic alloca then we do not need to adjust the
622 // stack pointer (we fit in the Red Zone). We also check that we don't
623 // push and pop from the stack.
624 if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
625 !RegInfo->needsStackRealignment(MF) &&
626 !MFI->hasVarSizedObjects() && // No dynamic alloca.
627 !MFI->adjustsStack() && // No calls.
628 !IsWin64 && // Win64 has no Red Zone
629 !usesTheStack(MF) && // Don't push and pop.
630 !MF.shouldSplitStack()) { // Regular stack
631 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
632 if (HasFP) MinSize += SlotSize;
633 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
634 MFI->setStackSize(StackSize);
637 // Insert stack pointer adjustment for later moving of return addr. Only
638 // applies to tail call optimized functions where the callee argument stack
639 // size is bigger than the callers.
640 if (TailCallReturnAddrDelta < 0) {
642 BuildMI(MBB, MBBI, DL,
643 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
646 .addImm(-TailCallReturnAddrDelta)
647 .setMIFlag(MachineInstr::FrameSetup);
648 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
651 // Mapping for machine moves:
653 // DST: VirtualFP AND
654 // SRC: VirtualFP => DW_CFA_def_cfa_offset
655 // ELSE => DW_CFA_def_cfa
657 // SRC: VirtualFP AND
658 // DST: Register => DW_CFA_def_cfa_register
661 // OFFSET < 0 => DW_CFA_offset_extended_sf
662 // REG < 64 => DW_CFA_offset + Reg
663 // ELSE => DW_CFA_offset_extended
665 uint64_t NumBytes = 0;
666 int stackGrowth = -SlotSize;
669 // Calculate required stack adjustment.
670 uint64_t FrameSize = StackSize - SlotSize;
671 // If required, include space for extra hidden slot for stashing base pointer.
672 if (X86FI->getRestoreBasePointer())
673 FrameSize += SlotSize;
675 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
677 // Callee-saved registers are pushed on stack before the stack is realigned.
678 if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
679 NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
681 // Get the offset of the stack slot for the EBP register, which is
682 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
683 // Update the frame offset adjustment.
684 MFI->setOffsetAdjustment(-NumBytes);
686 // Save EBP/RBP into the appropriate stack slot.
687 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
688 .addReg(MachineFramePtr, RegState::Kill)
689 .setMIFlag(MachineInstr::FrameSetup);
692 // Mark the place where EBP/RBP was saved.
693 // Define the current CFA rule to use the provided offset.
695 unsigned CFIIndex = MMI.addFrameInst(
696 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
697 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
698 .addCFIIndex(CFIIndex);
700 // Change the rule for the FramePtr to be an "offset" rule.
701 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
702 CFIIndex = MMI.addFrameInst(
703 MCCFIInstruction::createOffset(nullptr,
704 DwarfFramePtr, 2 * stackGrowth));
705 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
706 .addCFIIndex(CFIIndex);
710 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
712 .setMIFlag(MachineInstr::FrameSetup);
716 // Update EBP with the new base value.
717 BuildMI(MBB, MBBI, DL,
718 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
721 .setMIFlag(MachineInstr::FrameSetup);
725 // Mark effective beginning of when frame pointer becomes valid.
726 // Define the current CFA to use the EBP/RBP register.
727 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
728 unsigned CFIIndex = MMI.addFrameInst(
729 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
730 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
731 .addCFIIndex(CFIIndex);
734 // Mark the FramePtr as live-in in every block.
735 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
736 I->addLiveIn(MachineFramePtr);
738 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
741 // Skip the callee-saved push instructions.
742 bool PushedRegs = false;
743 int StackOffset = 2 * stackGrowth;
745 while (MBBI != MBB.end() &&
746 (MBBI->getOpcode() == X86::PUSH32r ||
747 MBBI->getOpcode() == X86::PUSH64r)) {
749 unsigned Reg = MBBI->getOperand(0).getReg();
752 if (!HasFP && NeedsDwarfCFI) {
753 // Mark callee-saved push instruction.
754 // Define the current CFA rule to use the provided offset.
756 unsigned CFIIndex = MMI.addFrameInst(
757 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
758 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
759 .addCFIIndex(CFIIndex);
760 StackOffset += stackGrowth;
764 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
765 MachineInstr::FrameSetup);
769 // Realign stack after we pushed callee-saved registers (so that we'll be
770 // able to calculate their offsets from the frame pointer).
771 // Don't do this for Win64, it needs to realign the stack after the prologue.
772 if (!IsWinEH && RegInfo->needsStackRealignment(MF)) {
773 assert(HasFP && "There should be a frame pointer if stack is realigned.");
774 uint64_t Val = -MaxAlign;
776 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
780 .setMIFlag(MachineInstr::FrameSetup);
782 // The EFLAGS implicit def is dead.
783 MI->getOperand(3).setIsDead();
786 // If there is an SUB32ri of ESP immediately before this instruction, merge
787 // the two. This can be the case when tail call elimination is enabled and
788 // the callee has more arguments then the caller.
789 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
791 // Adjust stack pointer: ESP -= numbytes.
793 // Windows and cygwin/mingw require a prologue helper routine when allocating
794 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
795 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
796 // stack and adjust the stack pointer in one go. The 64-bit version of
797 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
798 // responsible for adjusting the stack pointer. Touching the stack at 4K
799 // increments is necessary to ensure that the guard pages used by the OS
800 // virtual memory manager are allocated in correct sequence.
801 uint64_t AlignedNumBytes = NumBytes;
802 if (IsWinEH && RegInfo->needsStackRealignment(MF))
803 AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
804 if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
805 // Check whether EAX is livein for this function.
806 bool isEAXAlive = isEAXLiveIn(MF);
809 // Sanity check that EAX is not livein for this function.
810 // It should not be, so throw an assert.
811 assert(!Is64Bit && "EAX is livein in x64 case!");
814 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
815 .addReg(X86::EAX, RegState::Kill)
816 .setMIFlag(MachineInstr::FrameSetup);
820 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
821 // Function prologue is responsible for adjusting the stack pointer.
822 if (isUInt<32>(NumBytes)) {
823 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
825 .setMIFlag(MachineInstr::FrameSetup);
826 } else if (isInt<32>(NumBytes)) {
827 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
829 .setMIFlag(MachineInstr::FrameSetup);
831 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
833 .setMIFlag(MachineInstr::FrameSetup);
836 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
837 // We'll also use 4 already allocated bytes for EAX.
838 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
839 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
840 .setMIFlag(MachineInstr::FrameSetup);
843 // Save a pointer to the MI where we set AX.
844 MachineBasicBlock::iterator SetRAX = MBBI;
847 // Call __chkstk, __chkstk_ms, or __alloca.
848 emitStackProbeCall(MF, MBB, MBBI, DL);
850 // Apply the frame setup flag to all inserted instrs.
851 for (; SetRAX != MBBI; ++SetRAX)
852 SetRAX->setFlag(MachineInstr::FrameSetup);
856 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
858 StackPtr, false, NumBytes - 4);
859 MI->setFlag(MachineInstr::FrameSetup);
860 MBB.insert(MBBI, MI);
862 } else if (NumBytes) {
863 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
864 UseLEA, TII, *RegInfo);
867 if (NeedsWinEH && NumBytes)
868 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
870 .setMIFlag(MachineInstr::FrameSetup);
872 int SEHFrameOffset = 0;
873 if (IsWinEH && HasFP) {
874 SEHFrameOffset = calculateSetFPREG(NumBytes);
876 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
877 StackPtr, false, SEHFrameOffset);
879 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr).addReg(StackPtr);
882 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
884 .addImm(SEHFrameOffset)
885 .setMIFlag(MachineInstr::FrameSetup);
888 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
889 const MachineInstr *FrameInstr = &*MBBI;
894 if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
895 if (X86::FR64RegClass.contains(Reg)) {
896 int Offset = getFrameIndexOffset(MF, FI);
897 Offset += SEHFrameOffset;
899 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
902 .setMIFlag(MachineInstr::FrameSetup);
909 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
910 .setMIFlag(MachineInstr::FrameSetup);
912 // Realign stack after we spilled callee-saved registers (so that we'll be
913 // able to calculate their offsets from the frame pointer).
914 // Win64 requires aligning the stack after the prologue.
915 if (IsWinEH && RegInfo->needsStackRealignment(MF)) {
916 assert(HasFP && "There should be a frame pointer if stack is realigned.");
917 uint64_t Val = -MaxAlign;
919 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
923 .setMIFlag(MachineInstr::FrameSetup);
925 // The EFLAGS implicit def is dead.
926 MI->getOperand(3).setIsDead();
929 // If we need a base pointer, set it up here. It's whatever the value
930 // of the stack pointer is at this point. Any variable size objects
931 // will be allocated after this, so we can still use the base pointer
932 // to reference locals.
933 if (RegInfo->hasBasePointer(MF)) {
934 // Update the base pointer with the current stack pointer.
935 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
936 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
938 .setMIFlag(MachineInstr::FrameSetup);
939 if (X86FI->getRestoreBasePointer()) {
940 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
941 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
942 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
943 FramePtr, true, X86FI->getRestoreBasePointerOffset())
945 .setMIFlag(MachineInstr::FrameSetup);
949 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
950 // Mark end of stack pointer adjustment.
951 if (!HasFP && NumBytes) {
952 // Define the current CFA rule to use the provided offset.
954 unsigned CFIIndex = MMI.addFrameInst(
955 MCCFIInstruction::createDefCfaOffset(nullptr,
956 -StackSize + stackGrowth));
958 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
959 .addCFIIndex(CFIIndex);
962 // Emit DWARF info specifying the offsets of the callee-saved registers.
964 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
968 bool X86FrameLowering::useLEAForSPInProlog(const MachineFunction &MF) const {
969 // We can't use LEA instructions for adjusting the stack pointer if this is a
970 // leaf function in the Win64 ABI. Only ADD instructions may be used to
971 // deallocate the stack.
972 // This means that we can use LEA for SP in two situations:
973 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
974 // 2. We *have* a frame pointer which means we are permitted to use LEA.
975 return MF.getSubtarget<X86Subtarget>().useLeaForSP() &&
976 (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF));
979 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
980 MachineBasicBlock &MBB) const {
981 const MachineFrameInfo *MFI = MF.getFrameInfo();
982 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
983 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
984 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
985 const TargetInstrInfo &TII = *STI.getInstrInfo();
986 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
987 assert(MBBI != MBB.end() && "Returning block has no instructions");
988 DebugLoc DL = MBBI->getDebugLoc();
989 bool Is64Bit = STI.is64Bit();
990 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
991 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
992 const bool Is64BitILP32 = STI.isTarget64BitILP32();
993 unsigned SlotSize = RegInfo->getSlotSize();
994 unsigned FramePtr = RegInfo->getFrameRegister(MF);
995 unsigned MachineFramePtr =
996 Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
998 unsigned StackPtr = RegInfo->getStackRegister();
1000 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1001 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
1002 bool UseLEAForSP = useLEAForSPInProlog(MF);
1004 switch (MBBI->getOpcode()) {
1006 llvm_unreachable("Can only insert epilogue into returning blocks");
1011 case X86::TCRETURNdi:
1012 case X86::TCRETURNri:
1013 case X86::TCRETURNmi:
1014 case X86::TCRETURNdi64:
1015 case X86::TCRETURNri64:
1016 case X86::TCRETURNmi64:
1017 case X86::EH_RETURN:
1018 case X86::EH_RETURN64:
1019 break; // These are ok
1022 // Get the number of bytes to allocate from the FrameInfo.
1023 uint64_t StackSize = MFI->getStackSize();
1024 uint64_t MaxAlign = calculateMaxStackAlign(MF);
1025 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1026 uint64_t NumBytes = 0;
1029 // Calculate required stack adjustment.
1030 uint64_t FrameSize = StackSize - SlotSize;
1031 NumBytes = FrameSize - CSSize;
1033 // Callee-saved registers were pushed on stack before the stack was
1035 if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
1036 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1039 BuildMI(MBB, MBBI, DL,
1040 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1042 NumBytes = StackSize - CSSize;
1044 uint64_t SEHStackAllocAmt = NumBytes;
1046 // Skip the callee-saved pop instructions.
1047 while (MBBI != MBB.begin()) {
1048 MachineBasicBlock::iterator PI = std::prev(MBBI);
1049 unsigned Opc = PI->getOpcode();
1051 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1052 !PI->isTerminator())
1057 MachineBasicBlock::iterator FirstCSPop = MBBI;
1059 DL = MBBI->getDebugLoc();
1061 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1062 // instruction, merge the two instructions.
1063 if (NumBytes || MFI->hasVarSizedObjects())
1064 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1066 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1067 // slot before popping them off! Same applies for the case, when stack was
1069 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1070 if (RegInfo->needsStackRealignment(MF))
1072 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1073 uint64_t LEAAmount = IsWinEH ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1075 // There are only two legal forms of epilogue:
1076 // - add SEHAllocationSize, %rsp
1077 // - lea SEHAllocationSize(%FramePtr), %rsp
1079 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1080 // However, we may use this sequence if we have a frame pointer because the
1081 // effects of the prologue can safely be undone.
1082 if (LEAAmount != 0) {
1083 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1084 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1085 FramePtr, false, LEAAmount);
1088 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1089 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1093 } else if (NumBytes) {
1094 // Adjust stack pointer back: ESP += numbytes.
1095 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr,
1096 UseLEAForSP, TII, *RegInfo);
1100 // Windows unwinder will not invoke function's exception handler if IP is
1101 // either in prologue or in epilogue. This behavior causes a problem when a
1102 // call immediately precedes an epilogue, because the return address points
1103 // into the epilogue. To cope with that, we insert an epilogue marker here,
1104 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1105 // final emitted code.
1107 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1109 // Add the return addr area delta back since we are not tail calling.
1110 int Offset = -1 * X86FI->getTCReturnAddrDelta();
1111 assert(Offset >= 0 && "TCDelta should never be positive");
1113 MBBI = MBB.getFirstTerminator();
1115 // Check for possible merge with preceding ADD instruction.
1116 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1117 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1118 UseLEAForSP, TII, *RegInfo);
1122 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1124 const X86RegisterInfo *RegInfo =
1125 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1126 const MachineFrameInfo *MFI = MF.getFrameInfo();
1127 // Offset will hold the offset from the stack pointer at function entry to the
1129 // We need to factor in additional offsets applied during the prologue to the
1130 // frame, base, and stack pointer depending on which is used.
1131 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1132 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1133 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1134 uint64_t StackSize = MFI->getStackSize();
1135 unsigned SlotSize = RegInfo->getSlotSize();
1136 bool HasFP = hasFP(MF);
1137 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1138 int64_t FPDelta = 0;
1141 assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1143 // Calculate required stack adjustment.
1144 uint64_t FrameSize = StackSize - SlotSize;
1145 // If required, include space for extra hidden slot for stashing base pointer.
1146 if (X86FI->getRestoreBasePointer())
1147 FrameSize += SlotSize;
1148 uint64_t NumBytes = FrameSize - CSSize;
1150 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1151 if (FI && FI == X86FI->getFAIndex())
1152 return -SEHFrameOffset;
1154 // FPDelta is the offset from the "traditional" FP location of the old base
1155 // pointer followed by return address and the location required by the
1156 // restricted Win64 prologue.
1157 // Add FPDelta to all offsets below that go through the frame pointer.
1158 FPDelta = FrameSize - SEHFrameOffset;
1159 assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1160 "FPDelta isn't aligned per the Win64 ABI!");
1164 if (RegInfo->hasBasePointer(MF)) {
1165 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1167 // Skip the saved EBP.
1168 return Offset + SlotSize + FPDelta;
1170 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1171 return Offset + StackSize;
1173 } else if (RegInfo->needsStackRealignment(MF)) {
1175 // Skip the saved EBP.
1176 return Offset + SlotSize + FPDelta;
1178 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1179 return Offset + StackSize;
1181 // FIXME: Support tail calls
1184 return Offset + StackSize;
1186 // Skip the saved EBP.
1189 // Skip the RETADDR move area
1190 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1191 if (TailCallReturnAddrDelta < 0)
1192 Offset -= TailCallReturnAddrDelta;
1195 return Offset + FPDelta;
1198 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1199 unsigned &FrameReg) const {
1200 const X86RegisterInfo *RegInfo =
1201 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1202 // We can't calculate offset from frame pointer if the stack is realigned,
1203 // so enforce usage of stack/base pointer. The base pointer is used when we
1204 // have dynamic allocas in addition to dynamic realignment.
1205 if (RegInfo->hasBasePointer(MF))
1206 FrameReg = RegInfo->getBaseRegister();
1207 else if (RegInfo->needsStackRealignment(MF))
1208 FrameReg = RegInfo->getStackRegister();
1210 FrameReg = RegInfo->getFrameRegister(MF);
1211 return getFrameIndexOffset(MF, FI);
1214 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1215 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1216 const MachineFrameInfo *MFI = MF.getFrameInfo();
1217 // Does not include any dynamic realign.
1218 const uint64_t StackSize = MFI->getStackSize();
1221 const X86RegisterInfo *RegInfo =
1222 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1223 // Note: LLVM arranges the stack as:
1224 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1225 // > "Stack Slots" (<--SP)
1226 // We can always address StackSlots from RSP. We can usually (unless
1227 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1228 // address them from RBP. FixedObjects can be placed anywhere in the stack
1229 // frame depending on their specific requirements (i.e. we can actually
1230 // refer to arguments to the function which are stored in the *callers*
1231 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1232 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1234 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1236 // We don't handle tail calls, and shouldn't be seeing them
1238 int TailCallReturnAddrDelta =
1239 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1240 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1244 // This is how the math works out:
1246 // %rsp grows (i.e. gets lower) left to right. Each box below is
1247 // one word (eight bytes). Obj0 is the stack slot we're trying to
1250 // ----------------------------------
1251 // | BP | Obj0 | Obj1 | ... | ObjN |
1252 // ----------------------------------
1256 // A is the incoming stack pointer.
1257 // (B - A) is the local area offset (-8 for x86-64) [1]
1258 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1260 // |(E - B)| is the StackSize (absolute value, positive). For a
1261 // stack that grown down, this works out to be (B - E). [3]
1263 // E is also the value of %rsp after stack has been set up, and we
1264 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1265 // (C - E) == (C - A) - (B - A) + (B - E)
1266 // { Using [1], [2] and [3] above }
1267 // == getObjectOffset - LocalAreaOffset + StackSize
1270 // Get the Offset from the StackPointer
1271 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1273 return Offset + StackSize;
1275 // Simplified from getFrameIndexReference keeping only StackPointer cases
1276 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1278 unsigned &FrameReg) const {
1279 const X86RegisterInfo *RegInfo =
1280 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1281 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1283 FrameReg = RegInfo->getStackRegister();
1284 return getFrameIndexOffsetFromSP(MF, FI);
1287 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1288 MachineFunction &MF, const TargetRegisterInfo *TRI,
1289 std::vector<CalleeSavedInfo> &CSI) const {
1290 MachineFrameInfo *MFI = MF.getFrameInfo();
1291 const X86RegisterInfo *RegInfo =
1292 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1293 unsigned SlotSize = RegInfo->getSlotSize();
1294 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1296 unsigned CalleeSavedFrameSize = 0;
1297 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1300 // emitPrologue always spills frame register the first thing.
1301 SpillSlotOffset -= SlotSize;
1302 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1304 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1305 // the frame register, we can delete it from CSI list and not have to worry
1306 // about avoiding it later.
1307 unsigned FPReg = RegInfo->getFrameRegister(MF);
1308 for (unsigned i = 0; i < CSI.size(); ++i) {
1309 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1310 CSI.erase(CSI.begin() + i);
1316 // Assign slots for GPRs. It increases frame size.
1317 for (unsigned i = CSI.size(); i != 0; --i) {
1318 unsigned Reg = CSI[i - 1].getReg();
1320 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1323 SpillSlotOffset -= SlotSize;
1324 CalleeSavedFrameSize += SlotSize;
1326 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1327 CSI[i - 1].setFrameIdx(SlotIndex);
1330 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1332 // Assign slots for XMMs.
1333 for (unsigned i = CSI.size(); i != 0; --i) {
1334 unsigned Reg = CSI[i - 1].getReg();
1335 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1338 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1340 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1342 SpillSlotOffset -= RC->getSize();
1344 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1345 CSI[i - 1].setFrameIdx(SlotIndex);
1346 MFI->ensureMaxAlignment(RC->getAlignment());
1352 bool X86FrameLowering::spillCalleeSavedRegisters(
1353 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1354 const std::vector<CalleeSavedInfo> &CSI,
1355 const TargetRegisterInfo *TRI) const {
1356 DebugLoc DL = MBB.findDebugLoc(MI);
1358 MachineFunction &MF = *MBB.getParent();
1359 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1360 const TargetInstrInfo &TII = *STI.getInstrInfo();
1362 // Push GPRs. It increases frame size.
1363 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1364 for (unsigned i = CSI.size(); i != 0; --i) {
1365 unsigned Reg = CSI[i - 1].getReg();
1367 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1369 // Add the callee-saved register as live-in. It's killed at the spill.
1372 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1373 .setMIFlag(MachineInstr::FrameSetup);
1376 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1377 // It can be done by spilling XMMs to stack frame.
1378 for (unsigned i = CSI.size(); i != 0; --i) {
1379 unsigned Reg = CSI[i-1].getReg();
1380 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1382 // Add the callee-saved register as live-in. It's killed at the spill.
1384 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1386 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1389 MI->setFlag(MachineInstr::FrameSetup);
1396 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1397 MachineBasicBlock::iterator MI,
1398 const std::vector<CalleeSavedInfo> &CSI,
1399 const TargetRegisterInfo *TRI) const {
1403 DebugLoc DL = MBB.findDebugLoc(MI);
1405 MachineFunction &MF = *MBB.getParent();
1406 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1407 const TargetInstrInfo &TII = *STI.getInstrInfo();
1409 // Reload XMMs from stack frame.
1410 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1411 unsigned Reg = CSI[i].getReg();
1412 if (X86::GR64RegClass.contains(Reg) ||
1413 X86::GR32RegClass.contains(Reg))
1416 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1417 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1421 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1422 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1423 unsigned Reg = CSI[i].getReg();
1424 if (!X86::GR64RegClass.contains(Reg) &&
1425 !X86::GR32RegClass.contains(Reg))
1428 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1434 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1435 RegScavenger *RS) const {
1436 MachineFrameInfo *MFI = MF.getFrameInfo();
1437 const X86RegisterInfo *RegInfo =
1438 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1439 unsigned SlotSize = RegInfo->getSlotSize();
1441 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1442 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1444 if (TailCallReturnAddrDelta < 0) {
1445 // create RETURNADDR area
1454 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1455 TailCallReturnAddrDelta - SlotSize, true);
1458 // Spill the BasePtr if it's used.
1459 if (RegInfo->hasBasePointer(MF))
1460 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1464 HasNestArgument(const MachineFunction *MF) {
1465 const Function *F = MF->getFunction();
1466 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1468 if (I->hasNestAttr())
1474 /// GetScratchRegister - Get a temp register for performing work in the
1475 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1476 /// and the properties of the function either one or two registers will be
1477 /// needed. Set primary to true for the first register, false for the second.
1479 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1480 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1483 if (CallingConvention == CallingConv::HiPE) {
1485 return Primary ? X86::R14 : X86::R13;
1487 return Primary ? X86::EBX : X86::EDI;
1492 return Primary ? X86::R11 : X86::R12;
1494 return Primary ? X86::R11D : X86::R12D;
1497 bool IsNested = HasNestArgument(&MF);
1499 if (CallingConvention == CallingConv::X86_FastCall ||
1500 CallingConvention == CallingConv::Fast) {
1502 report_fatal_error("Segmented stacks does not support fastcall with "
1503 "nested function.");
1504 return Primary ? X86::EAX : X86::ECX;
1507 return Primary ? X86::EDX : X86::EAX;
1508 return Primary ? X86::ECX : X86::EAX;
1511 // The stack limit in the TCB is set to this many bytes above the actual stack
1513 static const uint64_t kSplitStackAvailable = 256;
1515 void X86FrameLowering::adjustForSegmentedStacks(
1516 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1517 assert(&PrologueMBB == &MF.front() &&
1518 "Shrink-wrapping is not implemented yet");
1519 MachineFrameInfo *MFI = MF.getFrameInfo();
1520 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1521 const TargetInstrInfo &TII = *STI.getInstrInfo();
1523 bool Is64Bit = STI.is64Bit();
1524 const bool IsLP64 = STI.isTarget64BitLP64();
1525 unsigned TlsReg, TlsOffset;
1528 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1529 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1530 "Scratch register is live-in");
1532 if (MF.getFunction()->isVarArg())
1533 report_fatal_error("Segmented stacks do not support vararg functions.");
1534 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1535 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1536 !STI.isTargetDragonFly())
1537 report_fatal_error("Segmented stacks not supported on this platform.");
1539 // Eventually StackSize will be calculated by a link-time pass; which will
1540 // also decide whether checking code needs to be injected into this particular
1542 StackSize = MFI->getStackSize();
1544 // Do not generate a prologue for functions with a stack of size zero
1548 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1549 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1550 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1551 bool IsNested = false;
1553 // We need to know if the function has a nest argument only in 64 bit mode.
1555 IsNested = HasNestArgument(&MF);
1557 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1558 // allocMBB needs to be last (terminating) instruction.
1560 for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1561 e = PrologueMBB.livein_end();
1563 allocMBB->addLiveIn(*i);
1564 checkMBB->addLiveIn(*i);
1568 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1570 MF.push_front(allocMBB);
1571 MF.push_front(checkMBB);
1573 // When the frame size is less than 256 we just compare the stack
1574 // boundary directly to the value of the stack pointer, per gcc.
1575 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1577 // Read the limit off the current stacklet off the stack_guard location.
1579 if (STI.isTargetLinux()) {
1581 TlsOffset = IsLP64 ? 0x70 : 0x40;
1582 } else if (STI.isTargetDarwin()) {
1584 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1585 } else if (STI.isTargetWin64()) {
1587 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1588 } else if (STI.isTargetFreeBSD()) {
1591 } else if (STI.isTargetDragonFly()) {
1593 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1595 report_fatal_error("Segmented stacks not supported on this platform.");
1598 if (CompareStackPointer)
1599 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1601 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1602 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1604 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1605 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1607 if (STI.isTargetLinux()) {
1610 } else if (STI.isTargetDarwin()) {
1612 TlsOffset = 0x48 + 90*4;
1613 } else if (STI.isTargetWin32()) {
1615 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1616 } else if (STI.isTargetDragonFly()) {
1618 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1619 } else if (STI.isTargetFreeBSD()) {
1620 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1622 report_fatal_error("Segmented stacks not supported on this platform.");
1625 if (CompareStackPointer)
1626 ScratchReg = X86::ESP;
1628 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1629 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1631 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1632 STI.isTargetDragonFly()) {
1633 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1634 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1635 } else if (STI.isTargetDarwin()) {
1637 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1638 unsigned ScratchReg2;
1640 if (CompareStackPointer) {
1641 // The primary scratch register is available for holding the TLS offset.
1642 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1643 SaveScratch2 = false;
1645 // Need to use a second register to hold the TLS offset
1646 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1648 // Unfortunately, with fastcc the second scratch register may hold an
1650 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1653 // If Scratch2 is live-in then it needs to be saved.
1654 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1655 "Scratch register is live-in and not saved");
1658 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1659 .addReg(ScratchReg2, RegState::Kill);
1661 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1663 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1665 .addReg(ScratchReg2).addImm(1).addReg(0)
1670 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1674 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1675 // It jumps to normal execution of the function body.
1676 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
1678 // On 32 bit we first push the arguments size and then the frame size. On 64
1679 // bit, we pass the stack frame size in r10 and the argument size in r11.
1681 // Functions with nested arguments use R10, so it needs to be saved across
1682 // the call to _morestack
1684 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1685 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1686 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1687 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1688 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1691 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1693 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1695 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1696 .addImm(X86FI->getArgumentStackSize());
1697 MF.getRegInfo().setPhysRegUsed(Reg10);
1698 MF.getRegInfo().setPhysRegUsed(Reg11);
1700 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1701 .addImm(X86FI->getArgumentStackSize());
1702 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1706 // __morestack is in libgcc
1707 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1708 // Under the large code model, we cannot assume that __morestack lives
1709 // within 2^31 bytes of the call site, so we cannot use pc-relative
1710 // addressing. We cannot perform the call via a temporary register,
1711 // as the rax register may be used to store the static chain, and all
1712 // other suitable registers may be either callee-save or used for
1713 // parameter passing. We cannot use the stack at this point either
1714 // because __morestack manipulates the stack directly.
1716 // To avoid these issues, perform an indirect call via a read-only memory
1717 // location containing the address.
1719 // This solution is not perfect, as it assumes that the .rodata section
1720 // is laid out within 2^31 bytes of each function body, but this seems
1721 // to be sufficient for JIT.
1722 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1726 .addExternalSymbol("__morestack_addr")
1728 MF.getMMI().setUsesMorestackAddr(true);
1731 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1732 .addExternalSymbol("__morestack");
1734 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1735 .addExternalSymbol("__morestack");
1739 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1741 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1743 allocMBB->addSuccessor(&PrologueMBB);
1745 checkMBB->addSuccessor(allocMBB);
1746 checkMBB->addSuccessor(&PrologueMBB);
1753 /// Erlang programs may need a special prologue to handle the stack size they
1754 /// might need at runtime. That is because Erlang/OTP does not implement a C
1755 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1756 /// (for more information see Eric Stenman's Ph.D. thesis:
1757 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1760 /// temp0 = sp - MaxStack
1761 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1765 /// call inc_stack # doubles the stack space
1766 /// temp0 = sp - MaxStack
1767 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1768 void X86FrameLowering::adjustForHiPEPrologue(
1769 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1770 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1771 const TargetInstrInfo &TII = *STI.getInstrInfo();
1772 MachineFrameInfo *MFI = MF.getFrameInfo();
1773 const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
1774 const bool Is64Bit = STI.is64Bit();
1775 const bool IsLP64 = STI.isTarget64BitLP64();
1777 // HiPE-specific values
1778 const unsigned HipeLeafWords = 24;
1779 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1780 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1781 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1782 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1783 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1785 assert(STI.isTargetLinux() &&
1786 "HiPE prologue is only supported on Linux operating systems.");
1788 // Compute the largest caller's frame that is needed to fit the callees'
1789 // frames. This 'MaxStack' is computed from:
1791 // a) the fixed frame size, which is the space needed for all spilled temps,
1792 // b) outgoing on-stack parameter areas, and
1793 // c) the minimum stack space this function needs to make available for the
1794 // functions it calls (a tunable ABI property).
1795 if (MFI->hasCalls()) {
1796 unsigned MoreStackForCalls = 0;
1798 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1799 MBBI != MBBE; ++MBBI)
1800 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1805 // Get callee operand.
1806 const MachineOperand &MO = MI->getOperand(0);
1808 // Only take account of global function calls (no closures etc.).
1812 const Function *F = dyn_cast<Function>(MO.getGlobal());
1816 // Do not update 'MaxStack' for primitive and built-in functions
1817 // (encoded with names either starting with "erlang."/"bif_" or not
1818 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1819 // "_", such as the BIF "suspend_0") as they are executed on another
1821 if (F->getName().find("erlang.") != StringRef::npos ||
1822 F->getName().find("bif_") != StringRef::npos ||
1823 F->getName().find_first_of("._") == StringRef::npos)
1826 unsigned CalleeStkArity =
1827 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1828 if (HipeLeafWords - 1 > CalleeStkArity)
1829 MoreStackForCalls = std::max(MoreStackForCalls,
1830 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1832 MaxStack += MoreStackForCalls;
1835 // If the stack frame needed is larger than the guaranteed then runtime checks
1836 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1837 if (MaxStack > Guaranteed) {
1838 assert(&PrologueMBB == &MF.front() &&
1839 "Shrink-wrapping is not implemented yet");
1840 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1841 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1843 for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1844 E = PrologueMBB.livein_end();
1846 stackCheckMBB->addLiveIn(*I);
1847 incStackMBB->addLiveIn(*I);
1850 MF.push_front(incStackMBB);
1851 MF.push_front(stackCheckMBB);
1853 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1854 unsigned LEAop, CMPop, CALLop;
1858 LEAop = X86::LEA64r;
1859 CMPop = X86::CMP64rm;
1860 CALLop = X86::CALL64pcrel32;
1861 SPLimitOffset = 0x90;
1865 LEAop = X86::LEA32r;
1866 CMPop = X86::CMP32rm;
1867 CALLop = X86::CALLpcrel32;
1868 SPLimitOffset = 0x4c;
1871 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1872 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1873 "HiPE prologue scratch register is live-in");
1875 // Create new MBB for StackCheck:
1876 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1877 SPReg, false, -MaxStack);
1878 // SPLimitOffset is in a fixed heap location (pointed by BP).
1879 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1880 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1881 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
1883 // Create new MBB for IncStack:
1884 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1885 addExternalSymbol("inc_stack_0");
1886 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1887 SPReg, false, -MaxStack);
1888 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1889 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1890 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1892 stackCheckMBB->addSuccessor(&PrologueMBB, 99);
1893 stackCheckMBB->addSuccessor(incStackMBB, 1);
1894 incStackMBB->addSuccessor(&PrologueMBB, 99);
1895 incStackMBB->addSuccessor(incStackMBB, 1);
1902 void X86FrameLowering::
1903 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1904 MachineBasicBlock::iterator I) const {
1905 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1906 const TargetInstrInfo &TII = *STI.getInstrInfo();
1907 const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
1908 unsigned StackPtr = RegInfo.getStackRegister();
1909 bool reserveCallFrame = hasReservedCallFrame(MF);
1910 unsigned Opcode = I->getOpcode();
1911 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1912 bool IsLP64 = STI.isTarget64BitLP64();
1913 DebugLoc DL = I->getDebugLoc();
1914 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1915 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
1918 if (!reserveCallFrame) {
1919 // If the stack pointer can be changed after prologue, turn the
1920 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1921 // adjcallstackdown instruction into 'add ESP, <amt>'
1925 // We need to keep the stack aligned properly. To do this, we round the
1926 // amount of space needed for the outgoing arguments up to the next
1927 // alignment boundary.
1928 unsigned StackAlign = getStackAlignment();
1929 Amount = RoundUpToAlignment(Amount, StackAlign);
1931 MachineInstr *New = nullptr;
1933 // Factor out the amount that gets handled inside the sequence
1934 // (Pushes of argument for frame setup, callee pops for frame destroy)
1935 Amount -= InternalAmt;
1938 if (Opcode == TII.getCallFrameSetupOpcode()) {
1939 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1940 .addReg(StackPtr).addImm(Amount);
1942 assert(Opcode == TII.getCallFrameDestroyOpcode());
1944 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1945 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1946 .addReg(StackPtr).addImm(Amount);
1951 // The EFLAGS implicit def is dead.
1952 New->getOperand(3).setIsDead();
1954 // Replace the pseudo instruction with a new instruction.
1961 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
1962 // If we are performing frame pointer elimination and if the callee pops
1963 // something off the stack pointer, add it back. We do this until we have
1964 // more advanced stack pointer tracking ability.
1965 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
1966 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1967 .addReg(StackPtr).addImm(InternalAmt);
1969 // The EFLAGS implicit def is dead.
1970 New->getOperand(3).setIsDead();
1972 // We are not tracking the stack pointer adjustment by the callee, so make
1973 // sure we restore the stack pointer immediately after the call, there may
1974 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1975 MachineBasicBlock::iterator B = MBB.begin();
1976 while (I != B && !std::prev(I)->isCall())