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 getANDriOpcode(bool IsLP64, int64_t Imm) {
89 return X86::AND64ri32;
96 static unsigned getLEArOpcode(unsigned IsLP64) {
97 return IsLP64 ? X86::LEA64r : X86::LEA32r;
100 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
101 /// when it reaches the "return" instruction. We can then pop a stack object
102 /// to this register without worry about clobbering it.
103 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
104 MachineBasicBlock::iterator &MBBI,
105 const TargetRegisterInfo &TRI,
107 const MachineFunction *MF = MBB.getParent();
108 const Function *F = MF->getFunction();
109 if (!F || MF->getMMI().callsEHReturn())
112 static const uint16_t CallerSavedRegs32Bit[] = {
113 X86::EAX, X86::EDX, X86::ECX, 0
116 static const uint16_t CallerSavedRegs64Bit[] = {
117 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
118 X86::R8, X86::R9, X86::R10, X86::R11, 0
121 unsigned Opc = MBBI->getOpcode();
128 case X86::TCRETURNdi:
129 case X86::TCRETURNri:
130 case X86::TCRETURNmi:
131 case X86::TCRETURNdi64:
132 case X86::TCRETURNri64:
133 case X86::TCRETURNmi64:
135 case X86::EH_RETURN64: {
136 SmallSet<uint16_t, 8> Uses;
137 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
138 MachineOperand &MO = MBBI->getOperand(i);
139 if (!MO.isReg() || MO.isDef())
141 unsigned Reg = MO.getReg();
144 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
148 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
150 if (!Uses.count(*CS))
159 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
160 /// stack pointer by a constant value.
162 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
163 unsigned StackPtr, int64_t NumBytes,
164 bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
165 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
166 bool isSub = NumBytes < 0;
167 uint64_t Offset = isSub ? -NumBytes : NumBytes;
170 Opc = getLEArOpcode(Is64BitStackPtr);
173 ? getSUBriOpcode(Is64BitStackPtr, Offset)
174 : getADDriOpcode(Is64BitStackPtr, Offset);
176 uint64_t Chunk = (1LL << 31) - 1;
177 DebugLoc DL = MBB.findDebugLoc(MBBI);
180 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
181 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
182 // Use push / pop instead.
184 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
185 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
188 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
189 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
190 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
191 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
193 MI->setFlag(MachineInstr::FrameSetup);
199 MachineInstr *MI = nullptr;
202 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
203 StackPtr, false, isSub ? -ThisVal : ThisVal);
205 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
208 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
212 MI->setFlag(MachineInstr::FrameSetup);
218 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
220 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
221 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
222 if (MBBI == MBB.begin()) return;
224 MachineBasicBlock::iterator PI = std::prev(MBBI);
225 unsigned Opc = PI->getOpcode();
226 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
227 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
228 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
229 PI->getOperand(0).getReg() == StackPtr) {
231 *NumBytes += PI->getOperand(2).getImm();
233 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
234 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
235 PI->getOperand(0).getReg() == StackPtr) {
237 *NumBytes -= PI->getOperand(2).getImm();
242 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
245 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
246 MachineBasicBlock::iterator &MBBI,
247 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
248 // FIXME: THIS ISN'T RUN!!!
251 if (MBBI == MBB.end()) return;
253 MachineBasicBlock::iterator NI = std::next(MBBI);
254 if (NI == MBB.end()) return;
256 unsigned Opc = NI->getOpcode();
257 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
258 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
259 NI->getOperand(0).getReg() == StackPtr) {
261 *NumBytes -= NI->getOperand(2).getImm();
264 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
265 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
266 NI->getOperand(0).getReg() == StackPtr) {
268 *NumBytes += NI->getOperand(2).getImm();
274 /// mergeSPUpdates - Checks the instruction before/after the passed
275 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
276 /// the stack adjustment is returned as a positive value for ADD/LEA and a
277 /// negative for SUB.
278 static int mergeSPUpdates(MachineBasicBlock &MBB,
279 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
280 bool doMergeWithPrevious) {
281 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
282 (!doMergeWithPrevious && MBBI == MBB.end()))
285 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
286 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
288 unsigned Opc = PI->getOpcode();
291 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
292 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
293 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
294 PI->getOperand(0).getReg() == StackPtr){
295 Offset += PI->getOperand(2).getImm();
297 if (!doMergeWithPrevious) MBBI = NI;
298 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
299 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
300 PI->getOperand(0).getReg() == StackPtr) {
301 Offset -= PI->getOperand(2).getImm();
303 if (!doMergeWithPrevious) MBBI = NI;
309 static bool isEAXLiveIn(MachineFunction &MF) {
310 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
311 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
312 unsigned Reg = II->first;
314 if (Reg == X86::EAX || Reg == X86::AX ||
315 Reg == X86::AH || Reg == X86::AL)
323 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
324 MachineBasicBlock::iterator MBBI,
326 MachineFunction &MF = *MBB.getParent();
327 MachineFrameInfo *MFI = MF.getFrameInfo();
328 MachineModuleInfo &MMI = MF.getMMI();
329 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
330 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
332 // Add callee saved registers to move list.
333 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
334 if (CSI.empty()) return;
336 // Calculate offsets.
337 for (std::vector<CalleeSavedInfo>::const_iterator
338 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
339 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
340 unsigned Reg = I->getReg();
342 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
344 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
346 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
347 .addCFIIndex(CFIIndex);
351 /// usesTheStack - This function checks if any of the users of EFLAGS
352 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
353 /// to use the stack, and if we don't adjust the stack we clobber the first
355 /// See X86InstrInfo::copyPhysReg.
356 static bool usesTheStack(const MachineFunction &MF) {
357 const MachineRegisterInfo &MRI = MF.getRegInfo();
359 for (MachineRegisterInfo::reg_instr_iterator
360 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
368 void X86FrameLowering::getStackProbeFunction(const X86Subtarget &STI,
370 const char *&Symbol) {
371 CallOp = STI.is64Bit() ? X86::W64ALLOCA : X86::CALLpcrel32;
374 if (STI.isTargetCygMing()) {
375 Symbol = "___chkstk_ms";
379 } else if (STI.isTargetCygMing())
385 /// emitPrologue - Push callee-saved registers onto the stack, which
386 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
387 /// space for local variables. Also emit labels used by the exception handler to
388 /// generate the exception handling frames.
391 Here's a gist of what gets emitted:
393 ; Establish frame pointer, if needed
396 .cfi_def_cfa_offset 16
397 .cfi_offset %rbp, -16
400 .cfi_def_cfa_register %rbp
402 ; Spill general-purpose registers
403 [for all callee-saved GPRs]
406 .cfi_def_cfa_offset (offset from RETADDR)
409 ; If the required stack alignment > default stack alignment
410 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
411 ; of unknown size in the stack frame.
412 [if stack needs re-alignment]
415 ; Allocate space for locals
416 [if target is Windows and allocated space > 4096 bytes]
417 ; Windows needs special care for allocations larger
420 call ___chkstk_ms/___chkstk
426 .seh_stackalloc (size of XMM spill slots)
427 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
432 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
433 ; they may get spilled on any platform, if the current function
434 ; calls @llvm.eh.unwind.init
436 [for all callee-saved XMM registers]
437 movaps %<xmm reg>, -MMM(%rbp)
438 [for all callee-saved XMM registers]
439 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
440 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
442 [for all callee-saved XMM registers]
443 movaps %<xmm reg>, KKK(%rsp)
444 [for all callee-saved XMM registers]
445 .seh_savexmm %<xmm reg>, KKK
449 [if needs base pointer]
454 [for all callee-saved registers]
455 .cfi_offset %<reg>, (offset from %rbp)
457 .cfi_def_cfa_offset (offset from RETADDR)
458 [for all callee-saved registers]
459 .cfi_offset %<reg>, (offset from %rsp)
462 - .seh directives are emitted only for Windows 64 ABI
463 - .cfi directives are emitted for all other ABIs
464 - for 32-bit code, substitute %e?? registers for %r??
467 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
468 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
469 MachineBasicBlock::iterator MBBI = MBB.begin();
470 MachineFrameInfo *MFI = MF.getFrameInfo();
471 const Function *Fn = MF.getFunction();
472 const X86RegisterInfo *RegInfo =
473 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
474 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
475 MachineModuleInfo &MMI = MF.getMMI();
476 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
477 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
478 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
479 bool HasFP = hasFP(MF);
480 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
481 bool Is64Bit = STI.is64Bit();
482 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
483 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
484 bool IsWin64 = STI.isTargetWin64();
486 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
487 ExceptionHandling::WinEH; // Not necessarily synonymous with IsWin64.
488 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
490 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
491 bool UseLEA = STI.useLeaForSP();
492 unsigned StackAlign = getStackAlignment();
493 unsigned SlotSize = RegInfo->getSlotSize();
494 unsigned FramePtr = RegInfo->getFrameRegister(MF);
495 const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
496 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
497 unsigned StackPtr = RegInfo->getStackRegister();
498 unsigned BasePtr = RegInfo->getBaseRegister();
501 // If we're forcing a stack realignment we can't rely on just the frame
502 // info, we need to know the ABI stack alignment as well in case we
503 // have a call out. Otherwise just make sure we have some alignment - we'll
504 // go with the minimum SlotSize.
505 if (ForceStackAlign) {
507 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
508 else if (MaxAlign < SlotSize)
512 // Add RETADDR move area to callee saved frame size.
513 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
514 if (TailCallReturnAddrDelta < 0)
515 X86FI->setCalleeSavedFrameSize(
516 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
518 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMacho());
520 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
521 // function, and use up to 128 bytes of stack space, don't have a frame
522 // pointer, calls, or dynamic alloca then we do not need to adjust the
523 // stack pointer (we fit in the Red Zone). We also check that we don't
524 // push and pop from the stack.
525 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
526 Attribute::NoRedZone) &&
527 !RegInfo->needsStackRealignment(MF) &&
528 !MFI->hasVarSizedObjects() && // No dynamic alloca.
529 !MFI->adjustsStack() && // No calls.
530 !IsWin64 && // Win64 has no Red Zone
531 !usesTheStack(MF) && // Don't push and pop.
532 !MF.shouldSplitStack()) { // Regular stack
533 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
534 if (HasFP) MinSize += SlotSize;
535 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
536 MFI->setStackSize(StackSize);
539 // Insert stack pointer adjustment for later moving of return addr. Only
540 // applies to tail call optimized functions where the callee argument stack
541 // size is bigger than the callers.
542 if (TailCallReturnAddrDelta < 0) {
544 BuildMI(MBB, MBBI, DL,
545 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
548 .addImm(-TailCallReturnAddrDelta)
549 .setMIFlag(MachineInstr::FrameSetup);
550 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
553 // Mapping for machine moves:
555 // DST: VirtualFP AND
556 // SRC: VirtualFP => DW_CFA_def_cfa_offset
557 // ELSE => DW_CFA_def_cfa
559 // SRC: VirtualFP AND
560 // DST: Register => DW_CFA_def_cfa_register
563 // OFFSET < 0 => DW_CFA_offset_extended_sf
564 // REG < 64 => DW_CFA_offset + Reg
565 // ELSE => DW_CFA_offset_extended
567 uint64_t NumBytes = 0;
568 int stackGrowth = -SlotSize;
571 // Calculate required stack adjustment.
572 uint64_t FrameSize = StackSize - SlotSize;
573 if (RegInfo->needsStackRealignment(MF)) {
574 // Callee-saved registers are pushed on stack before the stack
576 FrameSize -= X86FI->getCalleeSavedFrameSize();
577 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
579 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
582 // Get the offset of the stack slot for the EBP register, which is
583 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
584 // Update the frame offset adjustment.
585 MFI->setOffsetAdjustment(-NumBytes);
587 // Save EBP/RBP into the appropriate stack slot.
588 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
589 .addReg(MachineFramePtr, RegState::Kill)
590 .setMIFlag(MachineInstr::FrameSetup);
593 // Mark the place where EBP/RBP was saved.
594 // Define the current CFA rule to use the provided offset.
596 unsigned CFIIndex = MMI.addFrameInst(
597 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
598 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
599 .addCFIIndex(CFIIndex);
601 // Change the rule for the FramePtr to be an "offset" rule.
602 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
603 CFIIndex = MMI.addFrameInst(
604 MCCFIInstruction::createOffset(nullptr,
605 DwarfFramePtr, 2 * stackGrowth));
606 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
607 .addCFIIndex(CFIIndex);
611 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
613 .setMIFlag(MachineInstr::FrameSetup);
616 // Update EBP with the new base value.
617 BuildMI(MBB, MBBI, DL,
618 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
620 .setMIFlag(MachineInstr::FrameSetup);
623 // Mark effective beginning of when frame pointer becomes valid.
624 // Define the current CFA to use the EBP/RBP register.
625 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
626 unsigned CFIIndex = MMI.addFrameInst(
627 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
628 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
629 .addCFIIndex(CFIIndex);
632 // Mark the FramePtr as live-in in every block.
633 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
634 I->addLiveIn(MachineFramePtr);
636 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
639 // Skip the callee-saved push instructions.
640 bool PushedRegs = false;
641 int StackOffset = 2 * stackGrowth;
643 while (MBBI != MBB.end() &&
644 (MBBI->getOpcode() == X86::PUSH32r ||
645 MBBI->getOpcode() == X86::PUSH64r)) {
647 unsigned Reg = MBBI->getOperand(0).getReg();
650 if (!HasFP && NeedsDwarfCFI) {
651 // Mark callee-saved push instruction.
652 // Define the current CFA rule to use the provided offset.
654 unsigned CFIIndex = MMI.addFrameInst(
655 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
656 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
657 .addCFIIndex(CFIIndex);
658 StackOffset += stackGrowth;
662 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
663 MachineInstr::FrameSetup);
667 // Realign stack after we pushed callee-saved registers (so that we'll be
668 // able to calculate their offsets from the frame pointer).
669 if (RegInfo->needsStackRealignment(MF)) {
670 assert(HasFP && "There should be a frame pointer if stack is realigned.");
671 uint64_t Val = -MaxAlign;
673 BuildMI(MBB, MBBI, DL,
674 TII.get(getANDriOpcode(Uses64BitFramePtr, Val)), StackPtr)
677 .setMIFlag(MachineInstr::FrameSetup);
679 // The EFLAGS implicit def is dead.
680 MI->getOperand(3).setIsDead();
683 // If there is an SUB32ri of ESP immediately before this instruction, merge
684 // the two. This can be the case when tail call elimination is enabled and
685 // the callee has more arguments then the caller.
686 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
688 // If there is an ADD32ri or SUB32ri of ESP immediately after this
689 // instruction, merge the two instructions.
690 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
692 // Adjust stack pointer: ESP -= numbytes.
694 static const size_t PageSize = 4096;
696 // Windows and cygwin/mingw require a prologue helper routine when allocating
697 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
698 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
699 // stack and adjust the stack pointer in one go. The 64-bit version of
700 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
701 // responsible for adjusting the stack pointer. Touching the stack at 4K
702 // increments is necessary to ensure that the guard pages used by the OS
703 // virtual memory manager are allocated in correct sequence.
704 if (NumBytes >= PageSize && UseStackProbe) {
705 const char *StackProbeSymbol;
708 getStackProbeFunction(STI, CallOp, StackProbeSymbol);
710 // Check whether EAX is livein for this function.
711 bool isEAXAlive = isEAXLiveIn(MF);
714 // Sanity check that EAX is not livein for this function.
715 // It should not be, so throw an assert.
716 assert(!Is64Bit && "EAX is livein in x64 case!");
719 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
720 .addReg(X86::EAX, RegState::Kill)
721 .setMIFlag(MachineInstr::FrameSetup);
725 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
726 // Function prologue is responsible for adjusting the stack pointer.
727 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
729 .setMIFlag(MachineInstr::FrameSetup);
731 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
732 // We'll also use 4 already allocated bytes for EAX.
733 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
734 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
735 .setMIFlag(MachineInstr::FrameSetup);
738 BuildMI(MBB, MBBI, DL,
740 .addExternalSymbol(StackProbeSymbol)
741 .addReg(StackPtr, RegState::Define | RegState::Implicit)
742 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
743 .setMIFlag(MachineInstr::FrameSetup);
746 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
747 // themself. It also does not clobber %rax so we can reuse it when
749 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
752 .setMIFlag(MachineInstr::FrameSetup);
756 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
758 StackPtr, false, NumBytes - 4);
759 MI->setFlag(MachineInstr::FrameSetup);
760 MBB.insert(MBBI, MI);
762 } else if (NumBytes) {
763 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
764 UseLEA, TII, *RegInfo);
767 int SEHFrameOffset = 0;
770 // We need to set frame base offset low enough such that all saved
771 // register offsets would be positive relative to it, but we can't
772 // just use NumBytes, because .seh_setframe offset must be <=240.
773 // So we pretend to have only allocated enough space to spill the
774 // non-volatile registers.
775 // We don't care about the rest of stack allocation, because unwinder
776 // will restore SP to (BP - SEHFrameOffset)
777 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
778 int offset = MFI->getObjectOffset(Info.getFrameIdx());
779 SEHFrameOffset = std::max(SEHFrameOffset, std::abs(offset));
781 SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
783 // This only needs to account for XMM spill slots, GPR slots
784 // are covered by the .seh_pushreg's emitted above.
785 unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
787 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
789 .setMIFlag(MachineInstr::FrameSetup);
792 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
794 .addImm(SEHFrameOffset)
795 .setMIFlag(MachineInstr::FrameSetup);
797 // SP will be the base register for restoring XMMs
799 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
801 .setMIFlag(MachineInstr::FrameSetup);
806 // Skip the rest of register spilling code
807 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
810 // Emit SEH info for non-GPRs
812 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
813 unsigned Reg = Info.getReg();
814 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
816 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
818 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
819 Offset += SEHFrameOffset;
821 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
824 .setMIFlag(MachineInstr::FrameSetup);
827 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
828 .setMIFlag(MachineInstr::FrameSetup);
831 // If we need a base pointer, set it up here. It's whatever the value
832 // of the stack pointer is at this point. Any variable size objects
833 // will be allocated after this, so we can still use the base pointer
834 // to reference locals.
835 if (RegInfo->hasBasePointer(MF)) {
836 // Update the base pointer with the current stack pointer.
837 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
838 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
840 .setMIFlag(MachineInstr::FrameSetup);
843 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
844 // Mark end of stack pointer adjustment.
845 if (!HasFP && NumBytes) {
846 // Define the current CFA rule to use the provided offset.
848 unsigned CFIIndex = MMI.addFrameInst(
849 MCCFIInstruction::createDefCfaOffset(nullptr,
850 -StackSize + stackGrowth));
852 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
853 .addCFIIndex(CFIIndex);
856 // Emit DWARF info specifying the offsets of the callee-saved registers.
858 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
862 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
863 MachineBasicBlock &MBB) const {
864 const MachineFrameInfo *MFI = MF.getFrameInfo();
865 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
866 const X86RegisterInfo *RegInfo =
867 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
868 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
869 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
870 assert(MBBI != MBB.end() && "Returning block has no instructions");
871 unsigned RetOpcode = MBBI->getOpcode();
872 DebugLoc DL = MBBI->getDebugLoc();
873 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
874 bool Is64Bit = STI.is64Bit();
875 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
876 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
877 const bool Is64BitILP32 = STI.isTarget64BitILP32();
878 bool UseLEA = STI.useLeaForSP();
879 unsigned StackAlign = getStackAlignment();
880 unsigned SlotSize = RegInfo->getSlotSize();
881 unsigned FramePtr = RegInfo->getFrameRegister(MF);
882 unsigned MachineFramePtr = Is64BitILP32 ?
883 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
884 unsigned StackPtr = RegInfo->getStackRegister();
887 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
888 ExceptionHandling::WinEH;
889 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
893 llvm_unreachable("Can only insert epilog into returning blocks");
898 case X86::TCRETURNdi:
899 case X86::TCRETURNri:
900 case X86::TCRETURNmi:
901 case X86::TCRETURNdi64:
902 case X86::TCRETURNri64:
903 case X86::TCRETURNmi64:
905 case X86::EH_RETURN64:
906 break; // These are ok
909 // Get the number of bytes to allocate from the FrameInfo.
910 uint64_t StackSize = MFI->getStackSize();
911 uint64_t MaxAlign = MFI->getMaxAlignment();
912 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
913 uint64_t NumBytes = 0;
915 // If we're forcing a stack realignment we can't rely on just the frame
916 // info, we need to know the ABI stack alignment as well in case we
917 // have a call out. Otherwise just make sure we have some alignment - we'll
918 // go with the minimum.
919 if (ForceStackAlign) {
921 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
923 MaxAlign = MaxAlign ? MaxAlign : 4;
927 // Calculate required stack adjustment.
928 uint64_t FrameSize = StackSize - SlotSize;
929 if (RegInfo->needsStackRealignment(MF)) {
930 // Callee-saved registers were pushed on stack before the stack
933 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
935 NumBytes = FrameSize - CSSize;
939 BuildMI(MBB, MBBI, DL,
940 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
942 NumBytes = StackSize - CSSize;
945 // Skip the callee-saved pop instructions.
946 while (MBBI != MBB.begin()) {
947 MachineBasicBlock::iterator PI = std::prev(MBBI);
948 unsigned Opc = PI->getOpcode();
950 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
956 MachineBasicBlock::iterator FirstCSPop = MBBI;
958 DL = MBBI->getDebugLoc();
960 // If there is an ADD32ri or SUB32ri of ESP immediately before this
961 // instruction, merge the two instructions.
962 if (NumBytes || MFI->hasVarSizedObjects())
963 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
965 // If dynamic alloca is used, then reset esp to point to the last callee-saved
966 // slot before popping them off! Same applies for the case, when stack was
968 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
969 if (RegInfo->needsStackRealignment(MF))
972 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
973 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
974 FramePtr, false, -CSSize);
977 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
978 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
982 } else if (NumBytes) {
983 // Adjust stack pointer back: ESP += numbytes.
984 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
989 // Windows unwinder will not invoke function's exception handler if IP is
990 // either in prologue or in epilogue. This behavior causes a problem when a
991 // call immediately precedes an epilogue, because the return address points
992 // into the epilogue. To cope with that, we insert an epilogue marker here,
993 // then replace it with a 'nop' if it ends up immediately after a CALL in the
994 // final emitted code.
996 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
998 // We're returning from function via eh_return.
999 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1000 MBBI = MBB.getLastNonDebugInstr();
1001 MachineOperand &DestAddr = MBBI->getOperand(0);
1002 assert(DestAddr.isReg() && "Offset should be in register!");
1003 BuildMI(MBB, MBBI, DL,
1004 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1005 StackPtr).addReg(DestAddr.getReg());
1006 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1007 RetOpcode == X86::TCRETURNmi ||
1008 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1009 RetOpcode == X86::TCRETURNmi64) {
1010 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1011 // Tail call return: adjust the stack pointer and jump to callee.
1012 MBBI = MBB.getLastNonDebugInstr();
1013 MachineOperand &JumpTarget = MBBI->getOperand(0);
1014 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1015 assert(StackAdjust.isImm() && "Expecting immediate value.");
1017 // Adjust stack pointer.
1018 int StackAdj = StackAdjust.getImm();
1019 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1021 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1023 // Incoporate the retaddr area.
1024 Offset = StackAdj-MaxTCDelta;
1025 assert(Offset >= 0 && "Offset should never be negative");
1028 // Check for possible merge with preceding ADD instruction.
1029 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1030 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1031 UseLEA, TII, *RegInfo);
1034 // Jump to label or value in register.
1035 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1036 MachineInstrBuilder MIB =
1037 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1038 ? X86::TAILJMPd : X86::TAILJMPd64));
1039 if (JumpTarget.isGlobal())
1040 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1041 JumpTarget.getTargetFlags());
1043 assert(JumpTarget.isSymbol());
1044 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1045 JumpTarget.getTargetFlags());
1047 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1048 MachineInstrBuilder MIB =
1049 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1050 ? X86::TAILJMPm : X86::TAILJMPm64));
1051 for (unsigned i = 0; i != 5; ++i)
1052 MIB.addOperand(MBBI->getOperand(i));
1053 } else if (RetOpcode == X86::TCRETURNri64) {
1054 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1055 addReg(JumpTarget.getReg(), RegState::Kill);
1057 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1058 addReg(JumpTarget.getReg(), RegState::Kill);
1061 MachineInstr *NewMI = std::prev(MBBI);
1062 NewMI->copyImplicitOps(MF, MBBI);
1064 // Delete the pseudo instruction TCRETURN.
1066 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1067 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1068 (X86FI->getTCReturnAddrDelta() < 0)) {
1069 // Add the return addr area delta back since we are not tail calling.
1070 int delta = -1*X86FI->getTCReturnAddrDelta();
1071 MBBI = MBB.getLastNonDebugInstr();
1073 // Check for possible merge with preceding ADD instruction.
1074 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1075 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1080 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1082 const X86RegisterInfo *RegInfo =
1083 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1084 const MachineFrameInfo *MFI = MF.getFrameInfo();
1085 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1086 uint64_t StackSize = MFI->getStackSize();
1088 if (RegInfo->hasBasePointer(MF)) {
1089 assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1091 // Skip the saved EBP.
1092 return Offset + RegInfo->getSlotSize();
1094 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1095 return Offset + StackSize;
1097 } else if (RegInfo->needsStackRealignment(MF)) {
1099 // Skip the saved EBP.
1100 return Offset + RegInfo->getSlotSize();
1102 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1103 return Offset + StackSize;
1105 // FIXME: Support tail calls
1108 return Offset + StackSize;
1110 // Skip the saved EBP.
1111 Offset += RegInfo->getSlotSize();
1113 // Skip the RETADDR move area
1114 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1115 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1116 if (TailCallReturnAddrDelta < 0)
1117 Offset -= TailCallReturnAddrDelta;
1123 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1124 unsigned &FrameReg) const {
1125 const X86RegisterInfo *RegInfo =
1126 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1127 // We can't calculate offset from frame pointer if the stack is realigned,
1128 // so enforce usage of stack/base pointer. The base pointer is used when we
1129 // have dynamic allocas in addition to dynamic realignment.
1130 if (RegInfo->hasBasePointer(MF))
1131 FrameReg = RegInfo->getBaseRegister();
1132 else if (RegInfo->needsStackRealignment(MF))
1133 FrameReg = RegInfo->getStackRegister();
1135 FrameReg = RegInfo->getFrameRegister(MF);
1136 return getFrameIndexOffset(MF, FI);
1139 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1140 MachineFunction &MF, const TargetRegisterInfo *TRI,
1141 std::vector<CalleeSavedInfo> &CSI) const {
1142 MachineFrameInfo *MFI = MF.getFrameInfo();
1143 const X86RegisterInfo *RegInfo =
1144 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1145 unsigned SlotSize = RegInfo->getSlotSize();
1146 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1148 unsigned CalleeSavedFrameSize = 0;
1149 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1152 // emitPrologue always spills frame register the first thing.
1153 SpillSlotOffset -= SlotSize;
1154 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1156 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1157 // the frame register, we can delete it from CSI list and not have to worry
1158 // about avoiding it later.
1159 unsigned FPReg = RegInfo->getFrameRegister(MF);
1160 for (unsigned i = 0; i < CSI.size(); ++i) {
1161 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1162 CSI.erase(CSI.begin() + i);
1168 // Assign slots for GPRs. It increases frame size.
1169 for (unsigned i = CSI.size(); i != 0; --i) {
1170 unsigned Reg = CSI[i - 1].getReg();
1172 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1175 SpillSlotOffset -= SlotSize;
1176 CalleeSavedFrameSize += SlotSize;
1178 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1179 CSI[i - 1].setFrameIdx(SlotIndex);
1182 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1184 // Assign slots for XMMs.
1185 for (unsigned i = CSI.size(); i != 0; --i) {
1186 unsigned Reg = CSI[i - 1].getReg();
1187 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1190 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1192 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1194 SpillSlotOffset -= RC->getSize();
1196 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1197 CSI[i - 1].setFrameIdx(SlotIndex);
1198 MFI->ensureMaxAlignment(RC->getAlignment());
1204 bool X86FrameLowering::spillCalleeSavedRegisters(
1205 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1206 const std::vector<CalleeSavedInfo> &CSI,
1207 const TargetRegisterInfo *TRI) const {
1208 DebugLoc DL = MBB.findDebugLoc(MI);
1210 MachineFunction &MF = *MBB.getParent();
1211 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1212 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1214 // Push GPRs. It increases frame size.
1215 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1216 for (unsigned i = CSI.size(); i != 0; --i) {
1217 unsigned Reg = CSI[i - 1].getReg();
1219 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1221 // Add the callee-saved register as live-in. It's killed at the spill.
1224 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1225 .setMIFlag(MachineInstr::FrameSetup);
1228 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1229 // It can be done by spilling XMMs to stack frame.
1230 for (unsigned i = CSI.size(); i != 0; --i) {
1231 unsigned Reg = CSI[i-1].getReg();
1232 if (X86::GR64RegClass.contains(Reg) ||
1233 X86::GR32RegClass.contains(Reg))
1235 // Add the callee-saved register as live-in. It's killed at the spill.
1237 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1239 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1242 MI->setFlag(MachineInstr::FrameSetup);
1249 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1250 MachineBasicBlock::iterator MI,
1251 const std::vector<CalleeSavedInfo> &CSI,
1252 const TargetRegisterInfo *TRI) const {
1256 DebugLoc DL = MBB.findDebugLoc(MI);
1258 MachineFunction &MF = *MBB.getParent();
1259 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1260 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1262 // Reload XMMs from stack frame.
1263 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1264 unsigned Reg = CSI[i].getReg();
1265 if (X86::GR64RegClass.contains(Reg) ||
1266 X86::GR32RegClass.contains(Reg))
1269 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1270 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1274 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1275 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1276 unsigned Reg = CSI[i].getReg();
1277 if (!X86::GR64RegClass.contains(Reg) &&
1278 !X86::GR32RegClass.contains(Reg))
1281 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1287 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1288 RegScavenger *RS) const {
1289 MachineFrameInfo *MFI = MF.getFrameInfo();
1290 const X86RegisterInfo *RegInfo =
1291 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1292 unsigned SlotSize = RegInfo->getSlotSize();
1294 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1295 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1297 if (TailCallReturnAddrDelta < 0) {
1298 // create RETURNADDR area
1307 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1308 TailCallReturnAddrDelta - SlotSize, true);
1311 // Spill the BasePtr if it's used.
1312 if (RegInfo->hasBasePointer(MF))
1313 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1317 HasNestArgument(const MachineFunction *MF) {
1318 const Function *F = MF->getFunction();
1319 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1321 if (I->hasNestAttr())
1327 /// GetScratchRegister - Get a temp register for performing work in the
1328 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1329 /// and the properties of the function either one or two registers will be
1330 /// needed. Set primary to true for the first register, false for the second.
1332 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1333 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1336 if (CallingConvention == CallingConv::HiPE) {
1338 return Primary ? X86::R14 : X86::R13;
1340 return Primary ? X86::EBX : X86::EDI;
1345 return Primary ? X86::R11 : X86::R12;
1347 return Primary ? X86::R11D : X86::R12D;
1350 bool IsNested = HasNestArgument(&MF);
1352 if (CallingConvention == CallingConv::X86_FastCall ||
1353 CallingConvention == CallingConv::Fast) {
1355 report_fatal_error("Segmented stacks does not support fastcall with "
1356 "nested function.");
1357 return Primary ? X86::EAX : X86::ECX;
1360 return Primary ? X86::EDX : X86::EAX;
1361 return Primary ? X86::ECX : X86::EAX;
1364 // The stack limit in the TCB is set to this many bytes above the actual stack
1366 static const uint64_t kSplitStackAvailable = 256;
1369 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1370 MachineBasicBlock &prologueMBB = MF.front();
1371 MachineFrameInfo *MFI = MF.getFrameInfo();
1372 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1374 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1375 bool Is64Bit = STI.is64Bit();
1376 const bool IsLP64 = STI.isTarget64BitLP64();
1377 unsigned TlsReg, TlsOffset;
1380 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1381 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1382 "Scratch register is live-in");
1384 if (MF.getFunction()->isVarArg())
1385 report_fatal_error("Segmented stacks do not support vararg functions.");
1386 if (!STI.isTargetLinux() && !STI.isTargetDarwin() &&
1387 !STI.isTargetWin32() && !STI.isTargetWin64() && !STI.isTargetFreeBSD())
1388 report_fatal_error("Segmented stacks not supported on this platform.");
1390 // Eventually StackSize will be calculated by a link-time pass; which will
1391 // also decide whether checking code needs to be injected into this particular
1393 StackSize = MFI->getStackSize();
1395 // Do not generate a prologue for functions with a stack of size zero
1399 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1400 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1401 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1402 bool IsNested = false;
1404 // We need to know if the function has a nest argument only in 64 bit mode.
1406 IsNested = HasNestArgument(&MF);
1408 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1409 // allocMBB needs to be last (terminating) instruction.
1411 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1412 e = prologueMBB.livein_end(); i != e; i++) {
1413 allocMBB->addLiveIn(*i);
1414 checkMBB->addLiveIn(*i);
1418 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1420 MF.push_front(allocMBB);
1421 MF.push_front(checkMBB);
1423 // When the frame size is less than 256 we just compare the stack
1424 // boundary directly to the value of the stack pointer, per gcc.
1425 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1427 // Read the limit off the current stacklet off the stack_guard location.
1429 if (STI.isTargetLinux()) {
1431 TlsOffset = IsLP64 ? 0x70 : 0x40;
1432 } else if (STI.isTargetDarwin()) {
1434 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1435 } else if (STI.isTargetWin64()) {
1437 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1438 } else if (STI.isTargetFreeBSD()) {
1442 report_fatal_error("Segmented stacks not supported on this platform.");
1445 if (CompareStackPointer)
1446 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1448 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1449 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1451 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1452 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1454 if (STI.isTargetLinux()) {
1457 } else if (STI.isTargetDarwin()) {
1459 TlsOffset = 0x48 + 90*4;
1460 } else if (STI.isTargetWin32()) {
1462 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1463 } else if (STI.isTargetFreeBSD()) {
1464 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1466 report_fatal_error("Segmented stacks not supported on this platform.");
1469 if (CompareStackPointer)
1470 ScratchReg = X86::ESP;
1472 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1473 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1475 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64()) {
1476 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1477 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1478 } else if (STI.isTargetDarwin()) {
1480 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1481 unsigned ScratchReg2;
1483 if (CompareStackPointer) {
1484 // The primary scratch register is available for holding the TLS offset.
1485 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1486 SaveScratch2 = false;
1488 // Need to use a second register to hold the TLS offset
1489 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1491 // Unfortunately, with fastcc the second scratch register may hold an
1493 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1496 // If Scratch2 is live-in then it needs to be saved.
1497 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1498 "Scratch register is live-in and not saved");
1501 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1502 .addReg(ScratchReg2, RegState::Kill);
1504 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1506 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1508 .addReg(ScratchReg2).addImm(1).addReg(0)
1513 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1517 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1518 // It jumps to normal execution of the function body.
1519 BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
1521 // On 32 bit we first push the arguments size and then the frame size. On 64
1522 // bit, we pass the stack frame size in r10 and the argument size in r11.
1524 // Functions with nested arguments use R10, so it needs to be saved across
1525 // the call to _morestack
1527 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1528 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1529 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1530 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1531 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1534 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1536 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1538 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1539 .addImm(X86FI->getArgumentStackSize());
1540 MF.getRegInfo().setPhysRegUsed(Reg10);
1541 MF.getRegInfo().setPhysRegUsed(Reg11);
1543 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1544 .addImm(X86FI->getArgumentStackSize());
1545 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1549 // __morestack is in libgcc
1551 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1552 .addExternalSymbol("__morestack");
1554 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1555 .addExternalSymbol("__morestack");
1558 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1560 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1562 allocMBB->addSuccessor(&prologueMBB);
1564 checkMBB->addSuccessor(allocMBB);
1565 checkMBB->addSuccessor(&prologueMBB);
1572 /// Erlang programs may need a special prologue to handle the stack size they
1573 /// might need at runtime. That is because Erlang/OTP does not implement a C
1574 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1575 /// (for more information see Eric Stenman's Ph.D. thesis:
1576 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1579 /// temp0 = sp - MaxStack
1580 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1584 /// call inc_stack # doubles the stack space
1585 /// temp0 = sp - MaxStack
1586 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1587 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
1588 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1589 MachineFrameInfo *MFI = MF.getFrameInfo();
1590 const unsigned SlotSize =
1591 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1593 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1594 const bool Is64Bit = STI.is64Bit();
1595 const bool IsLP64 = STI.isTarget64BitLP64();
1597 // HiPE-specific values
1598 const unsigned HipeLeafWords = 24;
1599 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1600 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1601 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1602 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1603 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1605 assert(STI.isTargetLinux() &&
1606 "HiPE prologue is only supported on Linux operating systems.");
1608 // Compute the largest caller's frame that is needed to fit the callees'
1609 // frames. This 'MaxStack' is computed from:
1611 // a) the fixed frame size, which is the space needed for all spilled temps,
1612 // b) outgoing on-stack parameter areas, and
1613 // c) the minimum stack space this function needs to make available for the
1614 // functions it calls (a tunable ABI property).
1615 if (MFI->hasCalls()) {
1616 unsigned MoreStackForCalls = 0;
1618 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1619 MBBI != MBBE; ++MBBI)
1620 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1625 // Get callee operand.
1626 const MachineOperand &MO = MI->getOperand(0);
1628 // Only take account of global function calls (no closures etc.).
1632 const Function *F = dyn_cast<Function>(MO.getGlobal());
1636 // Do not update 'MaxStack' for primitive and built-in functions
1637 // (encoded with names either starting with "erlang."/"bif_" or not
1638 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1639 // "_", such as the BIF "suspend_0") as they are executed on another
1641 if (F->getName().find("erlang.") != StringRef::npos ||
1642 F->getName().find("bif_") != StringRef::npos ||
1643 F->getName().find_first_of("._") == StringRef::npos)
1646 unsigned CalleeStkArity =
1647 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1648 if (HipeLeafWords - 1 > CalleeStkArity)
1649 MoreStackForCalls = std::max(MoreStackForCalls,
1650 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1652 MaxStack += MoreStackForCalls;
1655 // If the stack frame needed is larger than the guaranteed then runtime checks
1656 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1657 if (MaxStack > Guaranteed) {
1658 MachineBasicBlock &prologueMBB = MF.front();
1659 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1660 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1662 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1663 E = prologueMBB.livein_end(); I != E; I++) {
1664 stackCheckMBB->addLiveIn(*I);
1665 incStackMBB->addLiveIn(*I);
1668 MF.push_front(incStackMBB);
1669 MF.push_front(stackCheckMBB);
1671 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1672 unsigned LEAop, CMPop, CALLop;
1676 LEAop = X86::LEA64r;
1677 CMPop = X86::CMP64rm;
1678 CALLop = X86::CALL64pcrel32;
1679 SPLimitOffset = 0x90;
1683 LEAop = X86::LEA32r;
1684 CMPop = X86::CMP32rm;
1685 CALLop = X86::CALLpcrel32;
1686 SPLimitOffset = 0x4c;
1689 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1690 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1691 "HiPE prologue scratch register is live-in");
1693 // Create new MBB for StackCheck:
1694 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1695 SPReg, false, -MaxStack);
1696 // SPLimitOffset is in a fixed heap location (pointed by BP).
1697 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1698 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1699 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_4)).addMBB(&prologueMBB);
1701 // Create new MBB for IncStack:
1702 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1703 addExternalSymbol("inc_stack_0");
1704 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1705 SPReg, false, -MaxStack);
1706 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1707 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1708 BuildMI(incStackMBB, DL, TII.get(X86::JLE_4)).addMBB(incStackMBB);
1710 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1711 stackCheckMBB->addSuccessor(incStackMBB, 1);
1712 incStackMBB->addSuccessor(&prologueMBB, 99);
1713 incStackMBB->addSuccessor(incStackMBB, 1);
1720 void X86FrameLowering::
1721 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1722 MachineBasicBlock::iterator I) const {
1723 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1724 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1725 MF.getSubtarget().getRegisterInfo());
1726 unsigned StackPtr = RegInfo.getStackRegister();
1727 bool reseveCallFrame = hasReservedCallFrame(MF);
1728 int Opcode = I->getOpcode();
1729 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1730 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1731 bool IsLP64 = STI.isTarget64BitLP64();
1732 DebugLoc DL = I->getDebugLoc();
1733 uint64_t Amount = !reseveCallFrame ? I->getOperand(0).getImm() : 0;
1734 uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
1737 if (!reseveCallFrame) {
1738 // If the stack pointer can be changed after prologue, turn the
1739 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1740 // adjcallstackdown instruction into 'add ESP, <amt>'
1741 // TODO: consider using push / pop instead of sub + store / add
1745 // We need to keep the stack aligned properly. To do this, we round the
1746 // amount of space needed for the outgoing arguments up to the next
1747 // alignment boundary.
1748 unsigned StackAlign = MF.getTarget()
1750 ->getFrameLowering()
1751 ->getStackAlignment();
1752 Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
1754 MachineInstr *New = nullptr;
1755 if (Opcode == TII.getCallFrameSetupOpcode()) {
1756 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
1761 assert(Opcode == TII.getCallFrameDestroyOpcode());
1763 // Factor out the amount the callee already popped.
1764 Amount -= CalleeAmt;
1767 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1768 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1769 .addReg(StackPtr).addImm(Amount);
1774 // The EFLAGS implicit def is dead.
1775 New->getOperand(3).setIsDead();
1777 // Replace the pseudo instruction with a new instruction.
1784 if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
1785 // If we are performing frame pointer elimination and if the callee pops
1786 // something off the stack pointer, add it back. We do this until we have
1787 // more advanced stack pointer tracking ability.
1788 unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
1789 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1790 .addReg(StackPtr).addImm(CalleeAmt);
1792 // The EFLAGS implicit def is dead.
1793 New->getOperand(3).setIsDead();
1795 // We are not tracking the stack pointer adjustment by the callee, so make
1796 // sure we restore the stack pointer immediately after the call, there may
1797 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1798 MachineBasicBlock::iterator B = MBB.begin();
1799 while (I != B && !std::prev(I)->isCall())