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();
44 /// hasFP - Return true if the specified function should have a dedicated frame
45 /// pointer register. This is true if the function has variable sized allocas
46 /// or if frame pointer elimination is disabled.
47 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
48 const MachineFrameInfo *MFI = MF.getFrameInfo();
49 const MachineModuleInfo &MMI = MF.getMMI();
50 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
52 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
53 RegInfo->needsStackRealignment(MF) ||
54 MFI->hasVarSizedObjects() ||
55 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
56 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
57 MMI.callsUnwindInit() || MMI.callsEHReturn() ||
58 MFI->hasStackMap() || MFI->hasPatchPoint());
61 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
65 return X86::SUB64ri32;
73 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
77 return X86::ADD64ri32;
85 static unsigned getSUBrrOpcode(unsigned isLP64) {
86 return isLP64 ? X86::SUB64rr : X86::SUB32rr;
89 static unsigned getADDrrOpcode(unsigned isLP64) {
90 return isLP64 ? X86::ADD64rr : X86::ADD32rr;
93 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
97 return X86::AND64ri32;
100 return X86::AND32ri8;
104 static unsigned getPUSHiOpcode(bool IsLP64, MachineOperand MO) {
105 // We don't support LP64 for now.
108 if (MO.isImm() && isInt<8>(MO.getImm()))
109 return X86::PUSH32i8;
111 return X86::PUSHi32;;
114 static unsigned getLEArOpcode(unsigned IsLP64) {
115 return IsLP64 ? X86::LEA64r : X86::LEA32r;
118 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
119 /// when it reaches the "return" instruction. We can then pop a stack object
120 /// to this register without worry about clobbering it.
121 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
122 MachineBasicBlock::iterator &MBBI,
123 const TargetRegisterInfo &TRI,
125 const MachineFunction *MF = MBB.getParent();
126 const Function *F = MF->getFunction();
127 if (!F || MF->getMMI().callsEHReturn())
130 static const uint16_t CallerSavedRegs32Bit[] = {
131 X86::EAX, X86::EDX, X86::ECX, 0
134 static const uint16_t CallerSavedRegs64Bit[] = {
135 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
136 X86::R8, X86::R9, X86::R10, X86::R11, 0
139 unsigned Opc = MBBI->getOpcode();
146 case X86::TCRETURNdi:
147 case X86::TCRETURNri:
148 case X86::TCRETURNmi:
149 case X86::TCRETURNdi64:
150 case X86::TCRETURNri64:
151 case X86::TCRETURNmi64:
153 case X86::EH_RETURN64: {
154 SmallSet<uint16_t, 8> Uses;
155 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
156 MachineOperand &MO = MBBI->getOperand(i);
157 if (!MO.isReg() || MO.isDef())
159 unsigned Reg = MO.getReg();
162 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
166 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
168 if (!Uses.count(*CS))
176 static bool isEAXLiveIn(MachineFunction &MF) {
177 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
178 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
179 unsigned Reg = II->first;
181 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
182 Reg == X86::AH || Reg == X86::AL)
189 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
190 /// stack pointer by a constant value.
192 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
193 unsigned StackPtr, int64_t NumBytes,
194 bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
195 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
196 bool isSub = NumBytes < 0;
197 uint64_t Offset = isSub ? -NumBytes : NumBytes;
200 Opc = getLEArOpcode(Is64BitStackPtr);
203 ? getSUBriOpcode(Is64BitStackPtr, Offset)
204 : getADDriOpcode(Is64BitStackPtr, Offset);
206 uint64_t Chunk = (1LL << 31) - 1;
207 DebugLoc DL = MBB.findDebugLoc(MBBI);
210 if (Offset > Chunk) {
211 // Rather than emit a long series of instructions for large offsets,
212 // load the offset into a register and do one sub/add
215 if (isSub && !isEAXLiveIn(*MBB.getParent()))
216 Reg = (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX);
218 Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
221 Opc = Is64BitTarget ? X86::MOV64ri : X86::MOV32ri;
222 BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
225 ? getSUBrrOpcode(Is64BitTarget)
226 : getADDrrOpcode(Is64BitTarget);
227 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
230 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
236 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
237 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
238 // Use push / pop instead.
240 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
241 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
244 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
245 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
246 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
247 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
249 MI->setFlag(MachineInstr::FrameSetup);
255 MachineInstr *MI = nullptr;
258 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
259 StackPtr, false, isSub ? -ThisVal : ThisVal);
261 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
264 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
268 MI->setFlag(MachineInstr::FrameSetup);
274 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
276 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
277 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
278 if (MBBI == MBB.begin()) return;
280 MachineBasicBlock::iterator PI = std::prev(MBBI);
281 unsigned Opc = PI->getOpcode();
282 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
283 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
284 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
285 PI->getOperand(0).getReg() == StackPtr) {
287 *NumBytes += PI->getOperand(2).getImm();
289 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
290 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
291 PI->getOperand(0).getReg() == StackPtr) {
293 *NumBytes -= PI->getOperand(2).getImm();
298 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
301 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
302 MachineBasicBlock::iterator &MBBI,
303 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
304 // FIXME: THIS ISN'T RUN!!!
307 if (MBBI == MBB.end()) return;
309 MachineBasicBlock::iterator NI = std::next(MBBI);
310 if (NI == MBB.end()) return;
312 unsigned Opc = NI->getOpcode();
313 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
314 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
315 NI->getOperand(0).getReg() == StackPtr) {
317 *NumBytes -= NI->getOperand(2).getImm();
320 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
321 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
322 NI->getOperand(0).getReg() == StackPtr) {
324 *NumBytes += NI->getOperand(2).getImm();
330 /// mergeSPUpdates - Checks the instruction before/after the passed
331 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
332 /// the stack adjustment is returned as a positive value for ADD/LEA and a
333 /// negative for SUB.
334 static int mergeSPUpdates(MachineBasicBlock &MBB,
335 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
336 bool doMergeWithPrevious) {
337 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
338 (!doMergeWithPrevious && MBBI == MBB.end()))
341 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
342 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
344 unsigned Opc = PI->getOpcode();
347 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
348 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
349 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
350 PI->getOperand(0).getReg() == StackPtr){
351 Offset += PI->getOperand(2).getImm();
353 if (!doMergeWithPrevious) MBBI = NI;
354 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
355 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
356 PI->getOperand(0).getReg() == StackPtr) {
357 Offset -= PI->getOperand(2).getImm();
359 if (!doMergeWithPrevious) MBBI = NI;
366 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
367 MachineBasicBlock::iterator MBBI,
369 MachineFunction &MF = *MBB.getParent();
370 MachineFrameInfo *MFI = MF.getFrameInfo();
371 MachineModuleInfo &MMI = MF.getMMI();
372 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
373 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
375 // Add callee saved registers to move list.
376 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
377 if (CSI.empty()) return;
379 // Calculate offsets.
380 for (std::vector<CalleeSavedInfo>::const_iterator
381 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
382 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
383 unsigned Reg = I->getReg();
385 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
387 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
389 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
390 .addCFIIndex(CFIIndex);
394 /// usesTheStack - This function checks if any of the users of EFLAGS
395 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
396 /// to use the stack, and if we don't adjust the stack we clobber the first
398 /// See X86InstrInfo::copyPhysReg.
399 static bool usesTheStack(const MachineFunction &MF) {
400 const MachineRegisterInfo &MRI = MF.getRegInfo();
402 for (MachineRegisterInfo::reg_instr_iterator
403 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
411 void X86FrameLowering::getStackProbeFunction(const X86Subtarget &STI,
413 const char *&Symbol) {
414 CallOp = STI.is64Bit() ? X86::W64ALLOCA : X86::CALLpcrel32;
417 if (STI.isTargetCygMing()) {
418 Symbol = "___chkstk_ms";
422 } else if (STI.isTargetCygMing())
428 /// emitPrologue - Push callee-saved registers onto the stack, which
429 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
430 /// space for local variables. Also emit labels used by the exception handler to
431 /// generate the exception handling frames.
434 Here's a gist of what gets emitted:
436 ; Establish frame pointer, if needed
439 .cfi_def_cfa_offset 16
440 .cfi_offset %rbp, -16
443 .cfi_def_cfa_register %rbp
445 ; Spill general-purpose registers
446 [for all callee-saved GPRs]
449 .cfi_def_cfa_offset (offset from RETADDR)
452 ; If the required stack alignment > default stack alignment
453 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
454 ; of unknown size in the stack frame.
455 [if stack needs re-alignment]
458 ; Allocate space for locals
459 [if target is Windows and allocated space > 4096 bytes]
460 ; Windows needs special care for allocations larger
463 call ___chkstk_ms/___chkstk
469 .seh_stackalloc (size of XMM spill slots)
470 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
475 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
476 ; they may get spilled on any platform, if the current function
477 ; calls @llvm.eh.unwind.init
479 [for all callee-saved XMM registers]
480 movaps %<xmm reg>, -MMM(%rbp)
481 [for all callee-saved XMM registers]
482 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
483 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
485 [for all callee-saved XMM registers]
486 movaps %<xmm reg>, KKK(%rsp)
487 [for all callee-saved XMM registers]
488 .seh_savexmm %<xmm reg>, KKK
492 [if needs base pointer]
494 [if needs to restore base pointer]
499 [for all callee-saved registers]
500 .cfi_offset %<reg>, (offset from %rbp)
502 .cfi_def_cfa_offset (offset from RETADDR)
503 [for all callee-saved registers]
504 .cfi_offset %<reg>, (offset from %rsp)
507 - .seh directives are emitted only for Windows 64 ABI
508 - .cfi directives are emitted for all other ABIs
509 - for 32-bit code, substitute %e?? registers for %r??
512 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
513 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
514 MachineBasicBlock::iterator MBBI = MBB.begin();
515 MachineFrameInfo *MFI = MF.getFrameInfo();
516 const Function *Fn = MF.getFunction();
517 const X86RegisterInfo *RegInfo =
518 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
519 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
520 MachineModuleInfo &MMI = MF.getMMI();
521 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
522 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
523 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
524 bool HasFP = hasFP(MF);
525 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
526 bool Is64Bit = STI.is64Bit();
527 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
528 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
529 bool IsWin64 = STI.isTargetWin64();
530 // Not necessarily synonymous with IsWin64.
531 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
532 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
534 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
535 bool UseLEA = STI.useLeaForSP();
536 unsigned StackAlign = getStackAlignment();
537 unsigned SlotSize = RegInfo->getSlotSize();
538 unsigned FramePtr = RegInfo->getFrameRegister(MF);
539 const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
540 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
541 unsigned StackPtr = RegInfo->getStackRegister();
542 unsigned BasePtr = RegInfo->getBaseRegister();
545 // If we're forcing a stack realignment we can't rely on just the frame
546 // info, we need to know the ABI stack alignment as well in case we
547 // have a call out. Otherwise just make sure we have some alignment - we'll
548 // go with the minimum SlotSize.
549 if (ForceStackAlign) {
551 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
552 else if (MaxAlign < SlotSize)
556 // Add RETADDR move area to callee saved frame size.
557 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
558 if (TailCallReturnAddrDelta < 0)
559 X86FI->setCalleeSavedFrameSize(
560 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
562 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
564 // The default stack probe size is 4096 if the function has no stackprobesize
566 unsigned StackProbeSize = 4096;
567 if (Fn->hasFnAttribute("stack-probe-size"))
568 Fn->getFnAttribute("stack-probe-size")
570 .getAsInteger(0, StackProbeSize);
572 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
573 // function, and use up to 128 bytes of stack space, don't have a frame
574 // pointer, calls, or dynamic alloca then we do not need to adjust the
575 // stack pointer (we fit in the Red Zone). We also check that we don't
576 // push and pop from the stack.
577 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
578 Attribute::NoRedZone) &&
579 !RegInfo->needsStackRealignment(MF) &&
580 !MFI->hasVarSizedObjects() && // No dynamic alloca.
581 !MFI->adjustsStack() && // No calls.
582 !IsWin64 && // Win64 has no Red Zone
583 !usesTheStack(MF) && // Don't push and pop.
584 !MF.shouldSplitStack()) { // Regular stack
585 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
586 if (HasFP) MinSize += SlotSize;
587 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
588 MFI->setStackSize(StackSize);
591 // Insert stack pointer adjustment for later moving of return addr. Only
592 // applies to tail call optimized functions where the callee argument stack
593 // size is bigger than the callers.
594 if (TailCallReturnAddrDelta < 0) {
596 BuildMI(MBB, MBBI, DL,
597 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
600 .addImm(-TailCallReturnAddrDelta)
601 .setMIFlag(MachineInstr::FrameSetup);
602 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
605 // Mapping for machine moves:
607 // DST: VirtualFP AND
608 // SRC: VirtualFP => DW_CFA_def_cfa_offset
609 // ELSE => DW_CFA_def_cfa
611 // SRC: VirtualFP AND
612 // DST: Register => DW_CFA_def_cfa_register
615 // OFFSET < 0 => DW_CFA_offset_extended_sf
616 // REG < 64 => DW_CFA_offset + Reg
617 // ELSE => DW_CFA_offset_extended
619 uint64_t NumBytes = 0;
620 int stackGrowth = -SlotSize;
623 // Calculate required stack adjustment.
624 uint64_t FrameSize = StackSize - SlotSize;
625 // If required, include space for extra hidden slot for stashing base pointer.
626 if (X86FI->getRestoreBasePointer())
627 FrameSize += SlotSize;
628 if (RegInfo->needsStackRealignment(MF)) {
629 // Callee-saved registers are pushed on stack before the stack
631 FrameSize -= X86FI->getCalleeSavedFrameSize();
632 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
634 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
637 // Get the offset of the stack slot for the EBP register, which is
638 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
639 // Update the frame offset adjustment.
640 MFI->setOffsetAdjustment(-NumBytes);
642 // Save EBP/RBP into the appropriate stack slot.
643 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
644 .addReg(MachineFramePtr, RegState::Kill)
645 .setMIFlag(MachineInstr::FrameSetup);
648 // Mark the place where EBP/RBP was saved.
649 // Define the current CFA rule to use the provided offset.
651 unsigned CFIIndex = MMI.addFrameInst(
652 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
653 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
654 .addCFIIndex(CFIIndex);
656 // Change the rule for the FramePtr to be an "offset" rule.
657 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
658 CFIIndex = MMI.addFrameInst(
659 MCCFIInstruction::createOffset(nullptr,
660 DwarfFramePtr, 2 * stackGrowth));
661 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
662 .addCFIIndex(CFIIndex);
666 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
668 .setMIFlag(MachineInstr::FrameSetup);
671 // Update EBP with the new base value.
672 BuildMI(MBB, MBBI, DL,
673 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
675 .setMIFlag(MachineInstr::FrameSetup);
678 // Mark effective beginning of when frame pointer becomes valid.
679 // Define the current CFA to use the EBP/RBP register.
680 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
681 unsigned CFIIndex = MMI.addFrameInst(
682 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
683 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
684 .addCFIIndex(CFIIndex);
687 // Mark the FramePtr as live-in in every block.
688 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
689 I->addLiveIn(MachineFramePtr);
691 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
694 // Skip the callee-saved push instructions.
695 bool PushedRegs = false;
696 int StackOffset = 2 * stackGrowth;
698 while (MBBI != MBB.end() &&
699 (MBBI->getOpcode() == X86::PUSH32r ||
700 MBBI->getOpcode() == X86::PUSH64r)) {
702 unsigned Reg = MBBI->getOperand(0).getReg();
705 if (!HasFP && NeedsDwarfCFI) {
706 // Mark callee-saved push instruction.
707 // Define the current CFA rule to use the provided offset.
709 unsigned CFIIndex = MMI.addFrameInst(
710 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
711 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
712 .addCFIIndex(CFIIndex);
713 StackOffset += stackGrowth;
717 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
718 MachineInstr::FrameSetup);
722 // Realign stack after we pushed callee-saved registers (so that we'll be
723 // able to calculate their offsets from the frame pointer).
724 if (RegInfo->needsStackRealignment(MF)) {
725 assert(HasFP && "There should be a frame pointer if stack is realigned.");
726 uint64_t Val = -MaxAlign;
728 BuildMI(MBB, MBBI, DL,
729 TII.get(getANDriOpcode(Uses64BitFramePtr, Val)), StackPtr)
732 .setMIFlag(MachineInstr::FrameSetup);
734 // The EFLAGS implicit def is dead.
735 MI->getOperand(3).setIsDead();
738 // If there is an SUB32ri of ESP immediately before this instruction, merge
739 // the two. This can be the case when tail call elimination is enabled and
740 // the callee has more arguments then the caller.
741 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
743 // If there is an ADD32ri or SUB32ri of ESP immediately after this
744 // instruction, merge the two instructions.
745 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
747 // Adjust stack pointer: ESP -= numbytes.
749 // Windows and cygwin/mingw require a prologue helper routine when allocating
750 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
751 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
752 // stack and adjust the stack pointer in one go. The 64-bit version of
753 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
754 // responsible for adjusting the stack pointer. Touching the stack at 4K
755 // increments is necessary to ensure that the guard pages used by the OS
756 // virtual memory manager are allocated in correct sequence.
757 if (NumBytes >= StackProbeSize && UseStackProbe) {
758 const char *StackProbeSymbol;
761 getStackProbeFunction(STI, CallOp, StackProbeSymbol);
763 // Check whether EAX is livein for this function.
764 bool isEAXAlive = isEAXLiveIn(MF);
767 // Sanity check that EAX is not livein for this function.
768 // It should not be, so throw an assert.
769 assert(!Is64Bit && "EAX is livein in x64 case!");
772 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
773 .addReg(X86::EAX, RegState::Kill)
774 .setMIFlag(MachineInstr::FrameSetup);
778 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
779 // Function prologue is responsible for adjusting the stack pointer.
780 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
782 .setMIFlag(MachineInstr::FrameSetup);
784 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
785 // We'll also use 4 already allocated bytes for EAX.
786 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
787 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
788 .setMIFlag(MachineInstr::FrameSetup);
791 BuildMI(MBB, MBBI, DL,
793 .addExternalSymbol(StackProbeSymbol)
794 .addReg(StackPtr, RegState::Define | RegState::Implicit)
795 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
796 .setMIFlag(MachineInstr::FrameSetup);
799 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
800 // themself. It also does not clobber %rax so we can reuse it when
802 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
805 .setMIFlag(MachineInstr::FrameSetup);
809 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
811 StackPtr, false, NumBytes - 4);
812 MI->setFlag(MachineInstr::FrameSetup);
813 MBB.insert(MBBI, MI);
815 } else if (NumBytes) {
816 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
817 UseLEA, TII, *RegInfo);
820 int SEHFrameOffset = 0;
823 // We need to set frame base offset low enough such that all saved
824 // register offsets would be positive relative to it, but we can't
825 // just use NumBytes, because .seh_setframe offset must be <=240.
826 // So we pretend to have only allocated enough space to spill the
827 // non-volatile registers.
828 // We don't care about the rest of stack allocation, because unwinder
829 // will restore SP to (BP - SEHFrameOffset)
830 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
831 int offset = MFI->getObjectOffset(Info.getFrameIdx());
832 SEHFrameOffset = std::max(SEHFrameOffset, std::abs(offset));
834 SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
836 // This only needs to account for XMM spill slots, GPR slots
837 // are covered by the .seh_pushreg's emitted above.
838 unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
840 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
842 .setMIFlag(MachineInstr::FrameSetup);
845 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
847 .addImm(SEHFrameOffset)
848 .setMIFlag(MachineInstr::FrameSetup);
850 // SP will be the base register for restoring XMMs
852 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
854 .setMIFlag(MachineInstr::FrameSetup);
859 // Skip the rest of register spilling code
860 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
863 // Emit SEH info for non-GPRs
865 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
866 unsigned Reg = Info.getReg();
867 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
869 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
871 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
872 Offset += SEHFrameOffset;
874 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
877 .setMIFlag(MachineInstr::FrameSetup);
880 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
881 .setMIFlag(MachineInstr::FrameSetup);
884 // If we need a base pointer, set it up here. It's whatever the value
885 // of the stack pointer is at this point. Any variable size objects
886 // will be allocated after this, so we can still use the base pointer
887 // to reference locals.
888 if (RegInfo->hasBasePointer(MF)) {
889 // Update the base pointer with the current stack pointer.
890 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
891 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
893 .setMIFlag(MachineInstr::FrameSetup);
894 if (X86FI->getRestoreBasePointer()) {
895 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
896 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
897 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
898 FramePtr, true, X86FI->getRestoreBasePointerOffset())
900 .setMIFlag(MachineInstr::FrameSetup);
904 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
905 // Mark end of stack pointer adjustment.
906 if (!HasFP && NumBytes) {
907 // Define the current CFA rule to use the provided offset.
909 unsigned CFIIndex = MMI.addFrameInst(
910 MCCFIInstruction::createDefCfaOffset(nullptr,
911 -StackSize + stackGrowth));
913 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
914 .addCFIIndex(CFIIndex);
917 // Emit DWARF info specifying the offsets of the callee-saved registers.
919 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
923 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
924 MachineBasicBlock &MBB) const {
925 const MachineFrameInfo *MFI = MF.getFrameInfo();
926 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
927 const X86RegisterInfo *RegInfo =
928 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
929 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
930 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
931 assert(MBBI != MBB.end() && "Returning block has no instructions");
932 unsigned RetOpcode = MBBI->getOpcode();
933 DebugLoc DL = MBBI->getDebugLoc();
934 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
935 bool Is64Bit = STI.is64Bit();
936 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
937 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
938 const bool Is64BitILP32 = STI.isTarget64BitILP32();
939 bool UseLEA = STI.useLeaForSP();
940 unsigned StackAlign = getStackAlignment();
941 unsigned SlotSize = RegInfo->getSlotSize();
942 unsigned FramePtr = RegInfo->getFrameRegister(MF);
943 unsigned MachineFramePtr = Is64BitILP32 ?
944 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
945 unsigned StackPtr = RegInfo->getStackRegister();
947 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
948 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
952 llvm_unreachable("Can only insert epilog into returning blocks");
957 case X86::TCRETURNdi:
958 case X86::TCRETURNri:
959 case X86::TCRETURNmi:
960 case X86::TCRETURNdi64:
961 case X86::TCRETURNri64:
962 case X86::TCRETURNmi64:
964 case X86::EH_RETURN64:
965 break; // These are ok
968 // Get the number of bytes to allocate from the FrameInfo.
969 uint64_t StackSize = MFI->getStackSize();
970 uint64_t MaxAlign = MFI->getMaxAlignment();
971 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
972 uint64_t NumBytes = 0;
974 // If we're forcing a stack realignment we can't rely on just the frame
975 // info, we need to know the ABI stack alignment as well in case we
976 // have a call out. Otherwise just make sure we have some alignment - we'll
977 // go with the minimum.
978 if (ForceStackAlign) {
980 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
982 MaxAlign = MaxAlign ? MaxAlign : 4;
986 // Calculate required stack adjustment.
987 uint64_t FrameSize = StackSize - SlotSize;
988 if (RegInfo->needsStackRealignment(MF)) {
989 // Callee-saved registers were pushed on stack before the stack
992 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
994 NumBytes = FrameSize - CSSize;
998 BuildMI(MBB, MBBI, DL,
999 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1001 NumBytes = StackSize - CSSize;
1004 // Skip the callee-saved pop instructions.
1005 while (MBBI != MBB.begin()) {
1006 MachineBasicBlock::iterator PI = std::prev(MBBI);
1007 unsigned Opc = PI->getOpcode();
1009 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1010 !PI->isTerminator())
1015 MachineBasicBlock::iterator FirstCSPop = MBBI;
1017 DL = MBBI->getDebugLoc();
1019 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1020 // instruction, merge the two instructions.
1021 if (NumBytes || MFI->hasVarSizedObjects())
1022 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1024 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1025 // slot before popping them off! Same applies for the case, when stack was
1027 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1028 if (RegInfo->needsStackRealignment(MF))
1031 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1032 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1033 FramePtr, false, -CSSize);
1036 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1037 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1041 } else if (NumBytes) {
1042 // Adjust stack pointer back: ESP += numbytes.
1043 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
1048 // Windows unwinder will not invoke function's exception handler if IP is
1049 // either in prologue or in epilogue. This behavior causes a problem when a
1050 // call immediately precedes an epilogue, because the return address points
1051 // into the epilogue. To cope with that, we insert an epilogue marker here,
1052 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1053 // final emitted code.
1055 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1057 // We're returning from function via eh_return.
1058 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1059 MBBI = MBB.getLastNonDebugInstr();
1060 MachineOperand &DestAddr = MBBI->getOperand(0);
1061 assert(DestAddr.isReg() && "Offset should be in register!");
1062 BuildMI(MBB, MBBI, DL,
1063 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1064 StackPtr).addReg(DestAddr.getReg());
1065 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1066 RetOpcode == X86::TCRETURNmi ||
1067 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1068 RetOpcode == X86::TCRETURNmi64) {
1069 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1070 // Tail call return: adjust the stack pointer and jump to callee.
1071 MBBI = MBB.getLastNonDebugInstr();
1072 MachineOperand &JumpTarget = MBBI->getOperand(0);
1073 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1074 assert(StackAdjust.isImm() && "Expecting immediate value.");
1076 // Adjust stack pointer.
1077 int StackAdj = StackAdjust.getImm();
1078 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1080 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1082 // Incoporate the retaddr area.
1083 Offset = StackAdj-MaxTCDelta;
1084 assert(Offset >= 0 && "Offset should never be negative");
1087 // Check for possible merge with preceding ADD instruction.
1088 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1089 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1090 UseLEA, TII, *RegInfo);
1093 // Jump to label or value in register.
1094 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1095 MachineInstrBuilder MIB =
1096 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1097 ? X86::TAILJMPd : X86::TAILJMPd64));
1098 if (JumpTarget.isGlobal())
1099 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1100 JumpTarget.getTargetFlags());
1102 assert(JumpTarget.isSymbol());
1103 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1104 JumpTarget.getTargetFlags());
1106 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1107 MachineInstrBuilder MIB =
1108 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1109 ? X86::TAILJMPm : X86::TAILJMPm64));
1110 for (unsigned i = 0; i != 5; ++i)
1111 MIB.addOperand(MBBI->getOperand(i));
1112 } else if (RetOpcode == X86::TCRETURNri64) {
1113 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1114 addReg(JumpTarget.getReg(), RegState::Kill);
1116 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1117 addReg(JumpTarget.getReg(), RegState::Kill);
1120 MachineInstr *NewMI = std::prev(MBBI);
1121 NewMI->copyImplicitOps(MF, MBBI);
1123 // Delete the pseudo instruction TCRETURN.
1125 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1126 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1127 (X86FI->getTCReturnAddrDelta() < 0)) {
1128 // Add the return addr area delta back since we are not tail calling.
1129 int delta = -1*X86FI->getTCReturnAddrDelta();
1130 MBBI = MBB.getLastNonDebugInstr();
1132 // Check for possible merge with preceding ADD instruction.
1133 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1134 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1139 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1141 const X86RegisterInfo *RegInfo =
1142 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1143 const MachineFrameInfo *MFI = MF.getFrameInfo();
1144 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1145 uint64_t StackSize = MFI->getStackSize();
1147 if (RegInfo->hasBasePointer(MF)) {
1148 assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1150 // Skip the saved EBP.
1151 return Offset + RegInfo->getSlotSize();
1153 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1154 return Offset + StackSize;
1156 } else if (RegInfo->needsStackRealignment(MF)) {
1158 // Skip the saved EBP.
1159 return Offset + RegInfo->getSlotSize();
1161 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1162 return Offset + StackSize;
1164 // FIXME: Support tail calls
1167 return Offset + StackSize;
1169 // Skip the saved EBP.
1170 Offset += RegInfo->getSlotSize();
1172 // Skip the RETADDR move area
1173 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1174 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1175 if (TailCallReturnAddrDelta < 0)
1176 Offset -= TailCallReturnAddrDelta;
1182 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1183 unsigned &FrameReg) const {
1184 const X86RegisterInfo *RegInfo =
1185 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1186 // We can't calculate offset from frame pointer if the stack is realigned,
1187 // so enforce usage of stack/base pointer. The base pointer is used when we
1188 // have dynamic allocas in addition to dynamic realignment.
1189 if (RegInfo->hasBasePointer(MF))
1190 FrameReg = RegInfo->getBaseRegister();
1191 else if (RegInfo->needsStackRealignment(MF))
1192 FrameReg = RegInfo->getStackRegister();
1194 FrameReg = RegInfo->getFrameRegister(MF);
1195 return getFrameIndexOffset(MF, FI);
1198 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1199 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1200 const MachineFrameInfo *MFI = MF.getFrameInfo();
1201 // Does not include any dynamic realign.
1202 const uint64_t StackSize = MFI->getStackSize();
1205 const X86RegisterInfo *RegInfo =
1206 static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
1207 // Note: LLVM arranges the stack as:
1208 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1209 // > "Stack Slots" (<--SP)
1210 // We can always address StackSlots from RSP. We can usually (unless
1211 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1212 // address them from RBP. FixedObjects can be placed anywhere in the stack
1213 // frame depending on their specific requirements (i.e. we can actually
1214 // refer to arguments to the function which are stored in the *callers*
1215 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1216 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1218 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1220 // We don't handle tail calls, and shouldn't be seeing them
1222 int TailCallReturnAddrDelta =
1223 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1224 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1228 // This is how the math works out:
1230 // %rsp grows (i.e. gets lower) left to right. Each box below is
1231 // one word (eight bytes). Obj0 is the stack slot we're trying to
1234 // ----------------------------------
1235 // | BP | Obj0 | Obj1 | ... | ObjN |
1236 // ----------------------------------
1240 // A is the incoming stack pointer.
1241 // (B - A) is the local area offset (-8 for x86-64) [1]
1242 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1244 // |(E - B)| is the StackSize (absolute value, positive). For a
1245 // stack that grown down, this works out to be (B - E). [3]
1247 // E is also the value of %rsp after stack has been set up, and we
1248 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1249 // (C - E) == (C - A) - (B - A) + (B - E)
1250 // { Using [1], [2] and [3] above }
1251 // == getObjectOffset - LocalAreaOffset + StackSize
1254 // Get the Offset from the StackPointer
1255 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1257 return Offset + StackSize;
1259 // Simplified from getFrameIndexReference keeping only StackPointer cases
1260 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF, int FI,
1261 unsigned &FrameReg) const {
1262 const X86RegisterInfo *RegInfo =
1263 static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
1265 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1267 FrameReg = RegInfo->getStackRegister();
1268 return getFrameIndexOffsetFromSP(MF, FI);
1271 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1272 MachineFunction &MF, const TargetRegisterInfo *TRI,
1273 std::vector<CalleeSavedInfo> &CSI) const {
1274 MachineFrameInfo *MFI = MF.getFrameInfo();
1275 const X86RegisterInfo *RegInfo =
1276 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1277 unsigned SlotSize = RegInfo->getSlotSize();
1278 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1280 unsigned CalleeSavedFrameSize = 0;
1281 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1284 // emitPrologue always spills frame register the first thing.
1285 SpillSlotOffset -= SlotSize;
1286 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1288 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1289 // the frame register, we can delete it from CSI list and not have to worry
1290 // about avoiding it later.
1291 unsigned FPReg = RegInfo->getFrameRegister(MF);
1292 for (unsigned i = 0; i < CSI.size(); ++i) {
1293 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1294 CSI.erase(CSI.begin() + i);
1300 // Assign slots for GPRs. It increases frame size.
1301 for (unsigned i = CSI.size(); i != 0; --i) {
1302 unsigned Reg = CSI[i - 1].getReg();
1304 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1307 SpillSlotOffset -= SlotSize;
1308 CalleeSavedFrameSize += SlotSize;
1310 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1311 CSI[i - 1].setFrameIdx(SlotIndex);
1314 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1316 // Assign slots for XMMs.
1317 for (unsigned i = CSI.size(); i != 0; --i) {
1318 unsigned Reg = CSI[i - 1].getReg();
1319 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1322 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1324 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1326 SpillSlotOffset -= RC->getSize();
1328 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1329 CSI[i - 1].setFrameIdx(SlotIndex);
1330 MFI->ensureMaxAlignment(RC->getAlignment());
1336 bool X86FrameLowering::spillCalleeSavedRegisters(
1337 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1338 const std::vector<CalleeSavedInfo> &CSI,
1339 const TargetRegisterInfo *TRI) const {
1340 DebugLoc DL = MBB.findDebugLoc(MI);
1342 MachineFunction &MF = *MBB.getParent();
1343 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1344 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1346 // Push GPRs. It increases frame size.
1347 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1348 for (unsigned i = CSI.size(); i != 0; --i) {
1349 unsigned Reg = CSI[i - 1].getReg();
1351 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1353 // Add the callee-saved register as live-in. It's killed at the spill.
1356 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1357 .setMIFlag(MachineInstr::FrameSetup);
1360 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1361 // It can be done by spilling XMMs to stack frame.
1362 for (unsigned i = CSI.size(); i != 0; --i) {
1363 unsigned Reg = CSI[i-1].getReg();
1364 if (X86::GR64RegClass.contains(Reg) ||
1365 X86::GR32RegClass.contains(Reg))
1367 // Add the callee-saved register as live-in. It's killed at the spill.
1369 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1371 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1374 MI->setFlag(MachineInstr::FrameSetup);
1381 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1382 MachineBasicBlock::iterator MI,
1383 const std::vector<CalleeSavedInfo> &CSI,
1384 const TargetRegisterInfo *TRI) const {
1388 DebugLoc DL = MBB.findDebugLoc(MI);
1390 MachineFunction &MF = *MBB.getParent();
1391 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1392 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1394 // Reload XMMs from stack frame.
1395 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1396 unsigned Reg = CSI[i].getReg();
1397 if (X86::GR64RegClass.contains(Reg) ||
1398 X86::GR32RegClass.contains(Reg))
1401 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1402 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1406 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1407 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1408 unsigned Reg = CSI[i].getReg();
1409 if (!X86::GR64RegClass.contains(Reg) &&
1410 !X86::GR32RegClass.contains(Reg))
1413 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1419 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1420 RegScavenger *RS) const {
1421 MachineFrameInfo *MFI = MF.getFrameInfo();
1422 const X86RegisterInfo *RegInfo =
1423 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1424 unsigned SlotSize = RegInfo->getSlotSize();
1426 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1427 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1429 if (TailCallReturnAddrDelta < 0) {
1430 // create RETURNADDR area
1439 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1440 TailCallReturnAddrDelta - SlotSize, true);
1443 // Spill the BasePtr if it's used.
1444 if (RegInfo->hasBasePointer(MF))
1445 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1449 HasNestArgument(const MachineFunction *MF) {
1450 const Function *F = MF->getFunction();
1451 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1453 if (I->hasNestAttr())
1459 /// GetScratchRegister - Get a temp register for performing work in the
1460 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1461 /// and the properties of the function either one or two registers will be
1462 /// needed. Set primary to true for the first register, false for the second.
1464 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1465 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1468 if (CallingConvention == CallingConv::HiPE) {
1470 return Primary ? X86::R14 : X86::R13;
1472 return Primary ? X86::EBX : X86::EDI;
1477 return Primary ? X86::R11 : X86::R12;
1479 return Primary ? X86::R11D : X86::R12D;
1482 bool IsNested = HasNestArgument(&MF);
1484 if (CallingConvention == CallingConv::X86_FastCall ||
1485 CallingConvention == CallingConv::Fast) {
1487 report_fatal_error("Segmented stacks does not support fastcall with "
1488 "nested function.");
1489 return Primary ? X86::EAX : X86::ECX;
1492 return Primary ? X86::EDX : X86::EAX;
1493 return Primary ? X86::ECX : X86::EAX;
1496 // The stack limit in the TCB is set to this many bytes above the actual stack
1498 static const uint64_t kSplitStackAvailable = 256;
1501 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1502 MachineBasicBlock &prologueMBB = MF.front();
1503 MachineFrameInfo *MFI = MF.getFrameInfo();
1504 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1506 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1507 bool Is64Bit = STI.is64Bit();
1508 const bool IsLP64 = STI.isTarget64BitLP64();
1509 unsigned TlsReg, TlsOffset;
1512 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1513 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1514 "Scratch register is live-in");
1516 if (MF.getFunction()->isVarArg())
1517 report_fatal_error("Segmented stacks do not support vararg functions.");
1518 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1519 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1520 !STI.isTargetDragonFly())
1521 report_fatal_error("Segmented stacks not supported on this platform.");
1523 // Eventually StackSize will be calculated by a link-time pass; which will
1524 // also decide whether checking code needs to be injected into this particular
1526 StackSize = MFI->getStackSize();
1528 // Do not generate a prologue for functions with a stack of size zero
1532 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1533 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1534 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1535 bool IsNested = false;
1537 // We need to know if the function has a nest argument only in 64 bit mode.
1539 IsNested = HasNestArgument(&MF);
1541 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1542 // allocMBB needs to be last (terminating) instruction.
1544 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1545 e = prologueMBB.livein_end(); i != e; i++) {
1546 allocMBB->addLiveIn(*i);
1547 checkMBB->addLiveIn(*i);
1551 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1553 MF.push_front(allocMBB);
1554 MF.push_front(checkMBB);
1556 // When the frame size is less than 256 we just compare the stack
1557 // boundary directly to the value of the stack pointer, per gcc.
1558 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1560 // Read the limit off the current stacklet off the stack_guard location.
1562 if (STI.isTargetLinux()) {
1564 TlsOffset = IsLP64 ? 0x70 : 0x40;
1565 } else if (STI.isTargetDarwin()) {
1567 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1568 } else if (STI.isTargetWin64()) {
1570 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1571 } else if (STI.isTargetFreeBSD()) {
1574 } else if (STI.isTargetDragonFly()) {
1576 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1578 report_fatal_error("Segmented stacks not supported on this platform.");
1581 if (CompareStackPointer)
1582 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1584 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1585 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1587 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1588 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1590 if (STI.isTargetLinux()) {
1593 } else if (STI.isTargetDarwin()) {
1595 TlsOffset = 0x48 + 90*4;
1596 } else if (STI.isTargetWin32()) {
1598 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1599 } else if (STI.isTargetDragonFly()) {
1601 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1602 } else if (STI.isTargetFreeBSD()) {
1603 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1605 report_fatal_error("Segmented stacks not supported on this platform.");
1608 if (CompareStackPointer)
1609 ScratchReg = X86::ESP;
1611 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1612 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1614 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1615 STI.isTargetDragonFly()) {
1616 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1617 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1618 } else if (STI.isTargetDarwin()) {
1620 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1621 unsigned ScratchReg2;
1623 if (CompareStackPointer) {
1624 // The primary scratch register is available for holding the TLS offset.
1625 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1626 SaveScratch2 = false;
1628 // Need to use a second register to hold the TLS offset
1629 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1631 // Unfortunately, with fastcc the second scratch register may hold an
1633 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1636 // If Scratch2 is live-in then it needs to be saved.
1637 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1638 "Scratch register is live-in and not saved");
1641 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1642 .addReg(ScratchReg2, RegState::Kill);
1644 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1646 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1648 .addReg(ScratchReg2).addImm(1).addReg(0)
1653 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1657 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1658 // It jumps to normal execution of the function body.
1659 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&prologueMBB);
1661 // On 32 bit we first push the arguments size and then the frame size. On 64
1662 // bit, we pass the stack frame size in r10 and the argument size in r11.
1664 // Functions with nested arguments use R10, so it needs to be saved across
1665 // the call to _morestack
1667 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1668 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1669 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1670 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1671 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1674 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1676 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1678 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1679 .addImm(X86FI->getArgumentStackSize());
1680 MF.getRegInfo().setPhysRegUsed(Reg10);
1681 MF.getRegInfo().setPhysRegUsed(Reg11);
1683 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1684 .addImm(X86FI->getArgumentStackSize());
1685 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1689 // __morestack is in libgcc
1690 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1691 // Under the large code model, we cannot assume that __morestack lives
1692 // within 2^31 bytes of the call site, so we cannot use pc-relative
1693 // addressing. We cannot perform the call via a temporary register,
1694 // as the rax register may be used to store the static chain, and all
1695 // other suitable registers may be either callee-save or used for
1696 // parameter passing. We cannot use the stack at this point either
1697 // because __morestack manipulates the stack directly.
1699 // To avoid these issues, perform an indirect call via a read-only memory
1700 // location containing the address.
1702 // This solution is not perfect, as it assumes that the .rodata section
1703 // is laid out within 2^31 bytes of each function body, but this seems
1704 // to be sufficient for JIT.
1705 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1709 .addExternalSymbol("__morestack_addr")
1711 MF.getMMI().setUsesMorestackAddr(true);
1714 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1715 .addExternalSymbol("__morestack");
1717 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1718 .addExternalSymbol("__morestack");
1722 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1724 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1726 allocMBB->addSuccessor(&prologueMBB);
1728 checkMBB->addSuccessor(allocMBB);
1729 checkMBB->addSuccessor(&prologueMBB);
1736 /// Erlang programs may need a special prologue to handle the stack size they
1737 /// might need at runtime. That is because Erlang/OTP does not implement a C
1738 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1739 /// (for more information see Eric Stenman's Ph.D. thesis:
1740 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1743 /// temp0 = sp - MaxStack
1744 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1748 /// call inc_stack # doubles the stack space
1749 /// temp0 = sp - MaxStack
1750 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1751 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
1752 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1753 MachineFrameInfo *MFI = MF.getFrameInfo();
1754 const unsigned SlotSize =
1755 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1757 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1758 const bool Is64Bit = STI.is64Bit();
1759 const bool IsLP64 = STI.isTarget64BitLP64();
1761 // HiPE-specific values
1762 const unsigned HipeLeafWords = 24;
1763 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1764 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1765 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1766 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1767 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1769 assert(STI.isTargetLinux() &&
1770 "HiPE prologue is only supported on Linux operating systems.");
1772 // Compute the largest caller's frame that is needed to fit the callees'
1773 // frames. This 'MaxStack' is computed from:
1775 // a) the fixed frame size, which is the space needed for all spilled temps,
1776 // b) outgoing on-stack parameter areas, and
1777 // c) the minimum stack space this function needs to make available for the
1778 // functions it calls (a tunable ABI property).
1779 if (MFI->hasCalls()) {
1780 unsigned MoreStackForCalls = 0;
1782 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1783 MBBI != MBBE; ++MBBI)
1784 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1789 // Get callee operand.
1790 const MachineOperand &MO = MI->getOperand(0);
1792 // Only take account of global function calls (no closures etc.).
1796 const Function *F = dyn_cast<Function>(MO.getGlobal());
1800 // Do not update 'MaxStack' for primitive and built-in functions
1801 // (encoded with names either starting with "erlang."/"bif_" or not
1802 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1803 // "_", such as the BIF "suspend_0") as they are executed on another
1805 if (F->getName().find("erlang.") != StringRef::npos ||
1806 F->getName().find("bif_") != StringRef::npos ||
1807 F->getName().find_first_of("._") == StringRef::npos)
1810 unsigned CalleeStkArity =
1811 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1812 if (HipeLeafWords - 1 > CalleeStkArity)
1813 MoreStackForCalls = std::max(MoreStackForCalls,
1814 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1816 MaxStack += MoreStackForCalls;
1819 // If the stack frame needed is larger than the guaranteed then runtime checks
1820 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1821 if (MaxStack > Guaranteed) {
1822 MachineBasicBlock &prologueMBB = MF.front();
1823 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1824 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1826 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1827 E = prologueMBB.livein_end(); I != E; I++) {
1828 stackCheckMBB->addLiveIn(*I);
1829 incStackMBB->addLiveIn(*I);
1832 MF.push_front(incStackMBB);
1833 MF.push_front(stackCheckMBB);
1835 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1836 unsigned LEAop, CMPop, CALLop;
1840 LEAop = X86::LEA64r;
1841 CMPop = X86::CMP64rm;
1842 CALLop = X86::CALL64pcrel32;
1843 SPLimitOffset = 0x90;
1847 LEAop = X86::LEA32r;
1848 CMPop = X86::CMP32rm;
1849 CALLop = X86::CALLpcrel32;
1850 SPLimitOffset = 0x4c;
1853 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1854 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1855 "HiPE prologue scratch register is live-in");
1857 // Create new MBB for StackCheck:
1858 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1859 SPReg, false, -MaxStack);
1860 // SPLimitOffset is in a fixed heap location (pointed by BP).
1861 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1862 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1863 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&prologueMBB);
1865 // Create new MBB for IncStack:
1866 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1867 addExternalSymbol("inc_stack_0");
1868 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1869 SPReg, false, -MaxStack);
1870 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1871 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1872 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1874 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1875 stackCheckMBB->addSuccessor(incStackMBB, 1);
1876 incStackMBB->addSuccessor(&prologueMBB, 99);
1877 incStackMBB->addSuccessor(incStackMBB, 1);
1884 bool X86FrameLowering::
1885 convertArgMovsToPushes(MachineFunction &MF, MachineBasicBlock &MBB,
1886 MachineBasicBlock::iterator I, uint64_t Amount) const {
1887 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1888 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1889 MF.getSubtarget().getRegisterInfo());
1890 unsigned StackPtr = RegInfo.getStackRegister();
1892 // Scan the call setup sequence for the pattern we're looking for.
1893 // We only handle a simple case now - a sequence of MOV32mi or MOV32mr
1894 // instructions, that push a sequence of 32-bit values onto the stack, with
1896 std::map<int64_t, MachineBasicBlock::iterator> MovMap;
1898 int Opcode = I->getOpcode();
1899 if (Opcode != X86::MOV32mi && Opcode != X86::MOV32mr)
1902 // We only want movs of the form:
1903 // movl imm/r32, k(%ecx)
1904 // If we run into something else, bail
1905 // Note that AddrBaseReg may, counterintuitively, not be a register...
1906 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
1907 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
1908 !I->getOperand(X86::AddrScaleAmt).isImm() ||
1909 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
1910 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
1911 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
1912 !I->getOperand(X86::AddrDisp).isImm())
1915 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
1917 // We don't want to consider the unaligned case.
1921 // If the same stack slot is being filled twice, something's fishy.
1922 if (!MovMap.insert(std::pair<int64_t, MachineInstr*>(StackDisp, I)).second)
1926 } while (I != MBB.end());
1928 // We now expect the end of the sequence - a call and a stack adjust.
1933 MachineBasicBlock::iterator Call = I;
1934 if ((++I)->getOpcode() != TII.getCallFrameDestroyOpcode())
1937 // Now, go through the map, and see that we don't have any gaps,
1938 // but only a series of 32-bit MOVs.
1939 // Since std::map provides ordered iteration, the original order
1940 // of the MOVs doesn't matter.
1941 int64_t ExpectedDist = 0;
1942 for (auto MMI = MovMap.begin(), MME = MovMap.end(); MMI != MME;
1943 ++MMI, ExpectedDist += 4)
1944 if (MMI->first != ExpectedDist)
1947 // Ok, everything looks fine. Do the transformation.
1948 DebugLoc DL = I->getDebugLoc();
1950 // It's possible the original stack adjustment amount was larger than
1951 // that done by the pushes. If so, we still need a SUB.
1952 Amount -= ExpectedDist;
1954 MachineInstr* Sub = BuildMI(MBB, Call, DL,
1955 TII.get(getSUBriOpcode(false, Amount)), StackPtr)
1956 .addReg(StackPtr).addImm(Amount);
1957 Sub->getOperand(3).setIsDead();
1960 // Now, iterate through the map in reverse order, and replace the movs
1961 // with pushes. MOVmi/MOVmr doesn't have any defs, so need to replace uses.
1962 for (auto MMI = MovMap.rbegin(), MME = MovMap.rend(); MMI != MME; ++MMI) {
1963 MachineBasicBlock::iterator MOV = MMI->second;
1964 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
1966 // Replace MOVmr with PUSH32r, and MOVmi with PUSHi of appropriate size
1967 int PushOpcode = X86::PUSH32r;
1968 if (MOV->getOpcode() == X86::MOV32mi)
1969 PushOpcode = getPUSHiOpcode(false, PushOp);
1971 BuildMI(MBB, Call, DL, TII.get(PushOpcode)).addOperand(PushOp);
1978 void X86FrameLowering::
1979 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1980 MachineBasicBlock::iterator I) const {
1981 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1982 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1983 MF.getSubtarget().getRegisterInfo());
1984 unsigned StackPtr = RegInfo.getStackRegister();
1985 bool reserveCallFrame = hasReservedCallFrame(MF);
1986 int Opcode = I->getOpcode();
1987 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1988 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1989 bool IsLP64 = STI.isTarget64BitLP64();
1990 DebugLoc DL = I->getDebugLoc();
1991 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1992 uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
1995 if (!reserveCallFrame) {
1996 // If the stack pointer can be changed after prologue, turn the
1997 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1998 // adjcallstackdown instruction into 'add ESP, <amt>'
2002 // We need to keep the stack aligned properly. To do this, we round the
2003 // amount of space needed for the outgoing arguments up to the next
2004 // alignment boundary.
2005 unsigned StackAlign = MF.getTarget()
2007 ->getFrameLowering()
2008 ->getStackAlignment();
2009 Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
2011 MachineInstr *New = nullptr;
2012 if (Opcode == TII.getCallFrameSetupOpcode()) {
2013 // Try to convert movs to the stack into pushes.
2014 // We currently only look for a pattern that appears in 32-bit
2015 // calling conventions.
2016 if (!IsLP64 && convertArgMovsToPushes(MF, MBB, I, Amount))
2019 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
2024 assert(Opcode == TII.getCallFrameDestroyOpcode());
2026 // Factor out the amount the callee already popped.
2027 Amount -= CalleeAmt;
2030 unsigned Opc = getADDriOpcode(IsLP64, Amount);
2031 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
2032 .addReg(StackPtr).addImm(Amount);
2037 // The EFLAGS implicit def is dead.
2038 New->getOperand(3).setIsDead();
2040 // Replace the pseudo instruction with a new instruction.
2047 if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
2048 // If we are performing frame pointer elimination and if the callee pops
2049 // something off the stack pointer, add it back. We do this until we have
2050 // more advanced stack pointer tracking ability.
2051 unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
2052 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
2053 .addReg(StackPtr).addImm(CalleeAmt);
2055 // The EFLAGS implicit def is dead.
2056 New->getOperand(3).setIsDead();
2058 // We are not tracking the stack pointer adjustment by the callee, so make
2059 // sure we restore the stack pointer immediately after the call, there may
2060 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2061 MachineBasicBlock::iterator B = MBB.begin();
2062 while (I != B && !std::prev(I)->isCall())