1 //=======- X86FrameLowering.cpp - X86 Frame Information --------*- C++ -*-====//
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/Function.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/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/ADT/SmallSet.h"
35 // FIXME: completely move here.
36 extern cl::opt<bool> ForceStackAlign;
38 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
39 return !MF.getFrameInfo()->hasVarSizedObjects();
42 /// hasFP - Return true if the specified function should have a dedicated frame
43 /// pointer register. This is true if the function has variable sized allocas
44 /// or if frame pointer elimination is disabled.
45 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
46 const MachineFrameInfo *MFI = MF.getFrameInfo();
47 const MachineModuleInfo &MMI = MF.getMMI();
48 const TargetRegisterInfo *RI = TM.getRegisterInfo();
50 return (DisableFramePointerElim(MF) ||
51 RI->needsStackRealignment(MF) ||
52 MFI->hasVarSizedObjects() ||
53 MFI->isFrameAddressTaken() ||
54 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
55 MMI.callsUnwindInit());
58 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
62 return X86::SUB64ri32;
70 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
74 return X86::ADD64ri32;
82 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
83 /// when it reaches the "return" instruction. We can then pop a stack object
84 /// to this register without worry about clobbering it.
85 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
86 MachineBasicBlock::iterator &MBBI,
87 const TargetRegisterInfo &TRI,
89 const MachineFunction *MF = MBB.getParent();
90 const Function *F = MF->getFunction();
91 if (!F || MF->getMMI().callsEHReturn())
94 static const unsigned CallerSavedRegs32Bit[] = {
95 X86::EAX, X86::EDX, X86::ECX, 0
98 static const unsigned CallerSavedRegs64Bit[] = {
99 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
100 X86::R8, X86::R9, X86::R10, X86::R11, 0
103 unsigned Opc = MBBI->getOpcode();
108 case X86::TCRETURNdi:
109 case X86::TCRETURNri:
110 case X86::TCRETURNmi:
111 case X86::TCRETURNdi64:
112 case X86::TCRETURNri64:
113 case X86::TCRETURNmi64:
115 case X86::EH_RETURN64: {
116 SmallSet<unsigned, 8> Uses;
117 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
118 MachineOperand &MO = MBBI->getOperand(i);
119 if (!MO.isReg() || MO.isDef())
121 unsigned Reg = MO.getReg();
124 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
128 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
130 if (!Uses.count(*CS))
139 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
140 /// stack pointer by a constant value.
142 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
143 unsigned StackPtr, int64_t NumBytes,
144 bool Is64Bit, const TargetInstrInfo &TII,
145 const TargetRegisterInfo &TRI) {
146 bool isSub = NumBytes < 0;
147 uint64_t Offset = isSub ? -NumBytes : NumBytes;
148 unsigned Opc = isSub ?
149 getSUBriOpcode(Is64Bit, Offset) :
150 getADDriOpcode(Is64Bit, Offset);
151 uint64_t Chunk = (1LL << 31) - 1;
152 DebugLoc DL = MBB.findDebugLoc(MBBI);
155 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
156 if (ThisVal == (Is64Bit ? 8 : 4)) {
157 // Use push / pop instead.
159 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
160 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
163 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
164 : (Is64Bit ? X86::POP64r : X86::POP32r);
165 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
166 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
168 MI->setFlag(MachineInstr::FrameSetup);
175 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
179 MI->setFlag(MachineInstr::FrameSetup);
180 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
185 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
187 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
188 unsigned StackPtr, uint64_t *NumBytes = NULL) {
189 if (MBBI == MBB.begin()) return;
191 MachineBasicBlock::iterator PI = prior(MBBI);
192 unsigned Opc = PI->getOpcode();
193 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
194 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
195 PI->getOperand(0).getReg() == StackPtr) {
197 *NumBytes += PI->getOperand(2).getImm();
199 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
200 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
201 PI->getOperand(0).getReg() == StackPtr) {
203 *NumBytes -= PI->getOperand(2).getImm();
208 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
210 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
211 MachineBasicBlock::iterator &MBBI,
212 unsigned StackPtr, uint64_t *NumBytes = NULL) {
213 // FIXME: THIS ISN'T RUN!!!
216 if (MBBI == MBB.end()) return;
218 MachineBasicBlock::iterator NI = llvm::next(MBBI);
219 if (NI == MBB.end()) return;
221 unsigned Opc = NI->getOpcode();
222 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
223 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
224 NI->getOperand(0).getReg() == StackPtr) {
226 *NumBytes -= NI->getOperand(2).getImm();
229 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
230 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
231 NI->getOperand(0).getReg() == StackPtr) {
233 *NumBytes += NI->getOperand(2).getImm();
239 /// mergeSPUpdates - Checks the instruction before/after the passed
240 /// instruction. If it is an ADD/SUB instruction it is deleted argument and the
241 /// stack adjustment is returned as a positive value for ADD and a negative for
243 static int mergeSPUpdates(MachineBasicBlock &MBB,
244 MachineBasicBlock::iterator &MBBI,
246 bool doMergeWithPrevious) {
247 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
248 (!doMergeWithPrevious && MBBI == MBB.end()))
251 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
252 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
253 unsigned Opc = PI->getOpcode();
256 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
257 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
258 PI->getOperand(0).getReg() == StackPtr){
259 Offset += PI->getOperand(2).getImm();
261 if (!doMergeWithPrevious) MBBI = NI;
262 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
263 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
264 PI->getOperand(0).getReg() == StackPtr) {
265 Offset -= PI->getOperand(2).getImm();
267 if (!doMergeWithPrevious) MBBI = NI;
273 static bool isEAXLiveIn(MachineFunction &MF) {
274 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
275 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
276 unsigned Reg = II->first;
278 if (Reg == X86::EAX || Reg == X86::AX ||
279 Reg == X86::AH || Reg == X86::AL)
286 void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
288 unsigned FramePtr) const {
289 MachineFrameInfo *MFI = MF.getFrameInfo();
290 MachineModuleInfo &MMI = MF.getMMI();
292 // Add callee saved registers to move list.
293 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
294 if (CSI.empty()) return;
296 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
297 const TargetData *TD = TM.getTargetData();
298 bool HasFP = hasFP(MF);
300 // Calculate amount of bytes used for return address storing.
301 int stackGrowth = -TD->getPointerSize();
303 // FIXME: This is dirty hack. The code itself is pretty mess right now.
304 // It should be rewritten from scratch and generalized sometimes.
306 // Determine maximum offset (minimum due to stack growth).
307 int64_t MaxOffset = 0;
308 for (std::vector<CalleeSavedInfo>::const_iterator
309 I = CSI.begin(), E = CSI.end(); I != E; ++I)
310 MaxOffset = std::min(MaxOffset,
311 MFI->getObjectOffset(I->getFrameIdx()));
313 // Calculate offsets.
314 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
315 for (std::vector<CalleeSavedInfo>::const_iterator
316 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
317 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
318 unsigned Reg = I->getReg();
319 Offset = MaxOffset - Offset + saveAreaOffset;
321 // Don't output a new machine move if we're re-saving the frame
322 // pointer. This happens when the PrologEpilogInserter has inserted an extra
323 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
324 // generates one when frame pointers are used. If we generate a "machine
325 // move" for this extra "PUSH", the linker will lose track of the fact that
326 // the frame pointer should have the value of the first "PUSH" when it's
329 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
330 // another bug. I.e., one where we generate a prolog like this:
338 // The immediate re-push of EBP is unnecessary. At the least, it's an
339 // optimization bug. EBP can be used as a scratch register in certain
340 // cases, but probably not when we have a frame pointer.
341 if (HasFP && FramePtr == Reg)
344 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
345 MachineLocation CSSrc(Reg);
346 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
350 /// getCompactUnwindRegNum - Get the compact unwind number for a given
351 /// register. The number corresponds to the enum lists in
352 /// compact_unwind_encoding.h.
353 static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
355 for (; *CURegs; ++CURegs, ++Idx)
362 /// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
363 /// used with frameless stacks. It is passed the number of registers to be saved
364 /// and an array of the registers saved.
365 static uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[6],
368 // The saved registers are numbered from 1 to 6. In order to encode the order
369 // in which they were saved, we re-number them according to their place in the
370 // register order. The re-numbering is relative to the last re-numbered
371 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
380 static const unsigned CU32BitRegs[] = {
381 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
383 static const unsigned CU64BitRegs[] = {
384 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
386 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
388 uint32_t RenumRegs[6];
389 for (unsigned i = 6 - RegCount; i < 6; ++i) {
390 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
391 if (CUReg == -1) return ~0U;
392 SavedRegs[i] = CUReg;
394 unsigned Countless = 0;
395 for (unsigned j = 6 - RegCount; j < i; ++j)
396 if (SavedRegs[j] < SavedRegs[i])
399 RenumRegs[i] = SavedRegs[i] - Countless - 1;
402 // Take the renumbered values and encode them into a 10-bit number.
403 uint32_t permutationEncoding = 0;
406 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
407 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
411 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
412 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
416 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
417 + 3 * RenumRegs[4] + RenumRegs[5];
420 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
424 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
427 permutationEncoding |= RenumRegs[5];
431 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
432 "Invalid compact register encoding!");
433 return permutationEncoding;
436 /// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
437 /// compact encoding with a frame pointer.
438 static uint32_t encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[6],
440 static const unsigned CU32BitRegs[] = {
441 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
443 static const unsigned CU64BitRegs[] = {
444 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
446 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
448 // Encode the registers in the order they were saved, 3-bits per register. The
449 // registers are numbered from 1 to 6.
451 for (int I = 5; I >= 0; --I) {
452 unsigned Reg = SavedRegs[I];
454 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
457 RegEnc |= (CURegNum & 0x7) << (5 - I);
460 assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
464 uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
465 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
466 unsigned FramePtr = RegInfo->getFrameRegister(MF);
467 unsigned StackPtr = RegInfo->getStackRegister();
469 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
470 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
472 bool Is64Bit = STI.is64Bit();
473 bool HasFP = hasFP(MF);
475 unsigned SavedRegs[6] = { 0, 0, 0, 0, 0, 0 };
478 unsigned OffsetSize = (Is64Bit ? 8 : 4);
480 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
481 unsigned PushInstrSize = 1;
482 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
483 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
484 unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
485 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
487 unsigned StackDivide = (Is64Bit ? 8 : 4);
489 unsigned InstrOffset = 0;
490 unsigned CFAOffset = 0;
491 unsigned StackAdjust = 0;
493 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
494 bool ExpectEnd = false;
495 for (MachineBasicBlock::iterator
496 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
497 MachineInstr &MI = *MBBI;
498 unsigned Opc = MI.getOpcode();
499 if (Opc == X86::PROLOG_LABEL) continue;
500 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
502 // We don't exect any more prolog instructions.
503 if (ExpectEnd) return 0;
505 if (Opc == PushInstr) {
506 // If there are too many saved registers, we cannot use compact encoding.
507 if (--SavedRegIdx < 0) return 0;
509 SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
510 CFAOffset += OffsetSize;
511 InstrOffset += PushInstrSize;
512 } else if (Opc == MoveInstr) {
513 unsigned SrcReg = MI.getOperand(1).getReg();
514 unsigned DstReg = MI.getOperand(0).getReg();
516 if (DstReg != FramePtr || SrcReg != StackPtr)
520 memset(SavedRegs, 0, sizeof(SavedRegs));
522 InstrOffset += MoveInstrSize;
523 } else if (Opc == SubtractInstr) {
525 // We all ready have a stack pointer adjustment.
528 if (!MI.getOperand(0).isReg() ||
529 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
530 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
531 // We need this to be a stack adjustment pointer. Something like:
533 // %RSP<def> = SUB64ri8 %RSP, 48
536 StackAdjust = MI.getOperand(2).getImm() / StackDivide;
537 SubtractInstrIdx += InstrOffset;
542 // Encode that we are using EBP/RBP as the frame pointer.
543 uint32_t CompactUnwindEncoding = 0;
544 CFAOffset /= StackDivide;
546 if ((CFAOffset & 0xFF) != CFAOffset)
547 // Offset was too big for compact encoding.
550 // Get the encoding of the saved registers when we have a frame pointer.
551 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
555 CompactUnwindEncoding |= 0x01000000;
556 CompactUnwindEncoding |= (CFAOffset & 0xFF) << 16;
557 CompactUnwindEncoding |= RegEnc & 0x7FFF;
559 unsigned FullOffset = CFAOffset + StackAdjust;
560 if ((FullOffset & 0xFF) == FullOffset) {
562 CompactUnwindEncoding |= 0x02000000;
563 CompactUnwindEncoding |= (FullOffset & 0xFF) << 16;
565 if ((CFAOffset & 0x7) != CFAOffset)
566 // The extra stack adjustments are too big for us to handle.
569 // Frameless stack with an offset too large for us to encode compactly.
570 CompactUnwindEncoding |= 0x03000000;
572 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
574 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
576 // Encode any extra stack stack changes (done via push instructions).
577 CompactUnwindEncoding |= (CFAOffset & 0x7) << 13;
580 // Get the encoding of the saved registers when we don't have a frame
582 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
585 if (RegEnc == ~0U) return 0;
586 CompactUnwindEncoding |= RegEnc & 0x3FF;
589 return CompactUnwindEncoding;
592 /// emitPrologue - Push callee-saved registers onto the stack, which
593 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
594 /// space for local variables. Also emit labels used by the exception handler to
595 /// generate the exception handling frames.
596 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
597 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
598 MachineBasicBlock::iterator MBBI = MBB.begin();
599 MachineFrameInfo *MFI = MF.getFrameInfo();
600 const Function *Fn = MF.getFunction();
601 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
602 const X86InstrInfo &TII = *TM.getInstrInfo();
603 MachineModuleInfo &MMI = MF.getMMI();
604 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
605 bool needsFrameMoves = MMI.hasDebugInfo() ||
606 Fn->needsUnwindTableEntry();
607 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
608 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
609 bool HasFP = hasFP(MF);
610 bool Is64Bit = STI.is64Bit();
611 bool IsWin64 = STI.isTargetWin64();
612 unsigned StackAlign = getStackAlignment();
613 unsigned SlotSize = RegInfo->getSlotSize();
614 unsigned FramePtr = RegInfo->getFrameRegister(MF);
615 unsigned StackPtr = RegInfo->getStackRegister();
618 // If we're forcing a stack realignment we can't rely on just the frame
619 // info, we need to know the ABI stack alignment as well in case we
620 // have a call out. Otherwise just make sure we have some alignment - we'll
621 // go with the minimum SlotSize.
622 if (ForceStackAlign) {
624 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
625 else if (MaxAlign < SlotSize)
629 // Add RETADDR move area to callee saved frame size.
630 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
631 if (TailCallReturnAddrDelta < 0)
632 X86FI->setCalleeSavedFrameSize(
633 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
635 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
636 // function, and use up to 128 bytes of stack space, don't have a frame
637 // pointer, calls, or dynamic alloca then we do not need to adjust the
638 // stack pointer (we fit in the Red Zone).
639 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
640 !RegInfo->needsStackRealignment(MF) &&
641 !MFI->hasVarSizedObjects() && // No dynamic alloca.
642 !MFI->adjustsStack() && // No calls.
643 !IsWin64 && // Win64 has no Red Zone
644 !EnableSegmentedStacks) { // Regular stack
645 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
646 if (HasFP) MinSize += SlotSize;
647 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
648 MFI->setStackSize(StackSize);
651 // Insert stack pointer adjustment for later moving of return addr. Only
652 // applies to tail call optimized functions where the callee argument stack
653 // size is bigger than the callers.
654 if (TailCallReturnAddrDelta < 0) {
656 BuildMI(MBB, MBBI, DL,
657 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
660 .addImm(-TailCallReturnAddrDelta)
661 .setMIFlag(MachineInstr::FrameSetup);
662 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
665 // Mapping for machine moves:
667 // DST: VirtualFP AND
668 // SRC: VirtualFP => DW_CFA_def_cfa_offset
669 // ELSE => DW_CFA_def_cfa
671 // SRC: VirtualFP AND
672 // DST: Register => DW_CFA_def_cfa_register
675 // OFFSET < 0 => DW_CFA_offset_extended_sf
676 // REG < 64 => DW_CFA_offset + Reg
677 // ELSE => DW_CFA_offset_extended
679 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
680 const TargetData *TD = MF.getTarget().getTargetData();
681 uint64_t NumBytes = 0;
682 int stackGrowth = -TD->getPointerSize();
685 // Calculate required stack adjustment.
686 uint64_t FrameSize = StackSize - SlotSize;
687 if (RegInfo->needsStackRealignment(MF))
688 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
690 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
692 // Get the offset of the stack slot for the EBP register, which is
693 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
694 // Update the frame offset adjustment.
695 MFI->setOffsetAdjustment(-NumBytes);
697 // Save EBP/RBP into the appropriate stack slot.
698 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
699 .addReg(FramePtr, RegState::Kill)
700 .setMIFlag(MachineInstr::FrameSetup);
702 if (needsFrameMoves) {
703 // Mark the place where EBP/RBP was saved.
704 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
705 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
708 // Define the current CFA rule to use the provided offset.
710 MachineLocation SPDst(MachineLocation::VirtualFP);
711 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
712 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
714 MachineLocation SPDst(StackPtr);
715 MachineLocation SPSrc(StackPtr, stackGrowth);
716 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
719 // Change the rule for the FramePtr to be an "offset" rule.
720 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
721 MachineLocation FPSrc(FramePtr);
722 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
725 // Update EBP with the new base value.
726 BuildMI(MBB, MBBI, DL,
727 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
729 .setMIFlag(MachineInstr::FrameSetup);
731 if (needsFrameMoves) {
732 // Mark effective beginning of when frame pointer becomes valid.
733 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
734 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
737 // Define the current CFA to use the EBP/RBP register.
738 MachineLocation FPDst(FramePtr);
739 MachineLocation FPSrc(MachineLocation::VirtualFP);
740 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
743 // Mark the FramePtr as live-in in every block except the entry.
744 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
746 I->addLiveIn(FramePtr);
749 if (RegInfo->needsStackRealignment(MF)) {
751 BuildMI(MBB, MBBI, DL,
752 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
755 .setMIFlag(MachineInstr::FrameSetup);
757 // The EFLAGS implicit def is dead.
758 MI->getOperand(3).setIsDead();
761 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
764 // Skip the callee-saved push instructions.
765 bool PushedRegs = false;
766 int StackOffset = 2 * stackGrowth;
768 while (MBBI != MBB.end() &&
769 (MBBI->getOpcode() == X86::PUSH32r ||
770 MBBI->getOpcode() == X86::PUSH64r)) {
772 MBBI->setFlag(MachineInstr::FrameSetup);
775 if (!HasFP && needsFrameMoves) {
776 // Mark callee-saved push instruction.
777 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
778 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
780 // Define the current CFA rule to use the provided offset.
781 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
782 MachineLocation SPDst(Ptr);
783 MachineLocation SPSrc(Ptr, StackOffset);
784 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
785 StackOffset += stackGrowth;
789 DL = MBB.findDebugLoc(MBBI);
791 // If there is an SUB32ri of ESP immediately before this instruction, merge
792 // the two. This can be the case when tail call elimination is enabled and
793 // the callee has more arguments then the caller.
794 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
796 // If there is an ADD32ri or SUB32ri of ESP immediately after this
797 // instruction, merge the two instructions.
798 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
800 // Adjust stack pointer: ESP -= numbytes.
802 // Windows and cygwin/mingw require a prologue helper routine when allocating
803 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
804 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
805 // stack and adjust the stack pointer in one go. The 64-bit version of
806 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
807 // responsible for adjusting the stack pointer. Touching the stack at 4K
808 // increments is necessary to ensure that the guard pages used by the OS
809 // virtual memory manager are allocated in correct sequence.
810 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
811 const char *StackProbeSymbol;
812 bool isSPUpdateNeeded = false;
815 if (STI.isTargetCygMing())
816 StackProbeSymbol = "___chkstk";
818 StackProbeSymbol = "__chkstk";
819 isSPUpdateNeeded = true;
821 } else if (STI.isTargetCygMing())
822 StackProbeSymbol = "_alloca";
824 StackProbeSymbol = "_chkstk";
826 // Check whether EAX is livein for this function.
827 bool isEAXAlive = isEAXLiveIn(MF);
830 // Sanity check that EAX is not livein for this function.
831 // It should not be, so throw an assert.
832 assert(!Is64Bit && "EAX is livein in x64 case!");
835 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
836 .addReg(X86::EAX, RegState::Kill)
837 .setMIFlag(MachineInstr::FrameSetup);
841 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
842 // Function prologue is responsible for adjusting the stack pointer.
843 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
845 .setMIFlag(MachineInstr::FrameSetup);
847 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
848 // We'll also use 4 already allocated bytes for EAX.
849 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
850 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
851 .setMIFlag(MachineInstr::FrameSetup);
854 BuildMI(MBB, MBBI, DL,
855 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
856 .addExternalSymbol(StackProbeSymbol)
857 .addReg(StackPtr, RegState::Define | RegState::Implicit)
858 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
859 .setMIFlag(MachineInstr::FrameSetup);
861 // MSVC x64's __chkstk needs to adjust %rsp.
862 // FIXME: %rax preserves the offset and should be available.
863 if (isSPUpdateNeeded)
864 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
869 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
871 StackPtr, false, NumBytes - 4);
872 MI->setFlag(MachineInstr::FrameSetup);
873 MBB.insert(MBBI, MI);
876 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
879 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
880 // Mark end of stack pointer adjustment.
881 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
882 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
885 if (!HasFP && NumBytes) {
886 // Define the current CFA rule to use the provided offset.
888 MachineLocation SPDst(MachineLocation::VirtualFP);
889 MachineLocation SPSrc(MachineLocation::VirtualFP,
890 -StackSize + stackGrowth);
891 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
893 MachineLocation SPDst(StackPtr);
894 MachineLocation SPSrc(StackPtr, stackGrowth);
895 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
899 // Emit DWARF info specifying the offsets of the callee-saved registers.
901 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
904 // Darwin 10.7 and greater has support for compact unwind encoding.
905 if (STI.getTargetTriple().isMacOSX() &&
906 !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
907 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
910 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
911 MachineBasicBlock &MBB) const {
912 const MachineFrameInfo *MFI = MF.getFrameInfo();
913 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
914 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
915 const X86InstrInfo &TII = *TM.getInstrInfo();
916 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
917 assert(MBBI != MBB.end() && "Returning block has no instructions");
918 unsigned RetOpcode = MBBI->getOpcode();
919 DebugLoc DL = MBBI->getDebugLoc();
920 bool Is64Bit = STI.is64Bit();
921 unsigned StackAlign = getStackAlignment();
922 unsigned SlotSize = RegInfo->getSlotSize();
923 unsigned FramePtr = RegInfo->getFrameRegister(MF);
924 unsigned StackPtr = RegInfo->getStackRegister();
928 llvm_unreachable("Can only insert epilog into returning blocks");
931 case X86::TCRETURNdi:
932 case X86::TCRETURNri:
933 case X86::TCRETURNmi:
934 case X86::TCRETURNdi64:
935 case X86::TCRETURNri64:
936 case X86::TCRETURNmi64:
938 case X86::EH_RETURN64:
939 break; // These are ok
942 // Get the number of bytes to allocate from the FrameInfo.
943 uint64_t StackSize = MFI->getStackSize();
944 uint64_t MaxAlign = MFI->getMaxAlignment();
945 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
946 uint64_t NumBytes = 0;
948 // If we're forcing a stack realignment we can't rely on just the frame
949 // info, we need to know the ABI stack alignment as well in case we
950 // have a call out. Otherwise just make sure we have some alignment - we'll
951 // go with the minimum.
952 if (ForceStackAlign) {
954 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
956 MaxAlign = MaxAlign ? MaxAlign : 4;
960 // Calculate required stack adjustment.
961 uint64_t FrameSize = StackSize - SlotSize;
962 if (RegInfo->needsStackRealignment(MF))
963 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
965 NumBytes = FrameSize - CSSize;
968 BuildMI(MBB, MBBI, DL,
969 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
971 NumBytes = StackSize - CSSize;
974 // Skip the callee-saved pop instructions.
975 MachineBasicBlock::iterator LastCSPop = MBBI;
976 while (MBBI != MBB.begin()) {
977 MachineBasicBlock::iterator PI = prior(MBBI);
978 unsigned Opc = PI->getOpcode();
980 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
981 !PI->getDesc().isTerminator())
987 DL = MBBI->getDebugLoc();
989 // If there is an ADD32ri or SUB32ri of ESP immediately before this
990 // instruction, merge the two instructions.
991 if (NumBytes || MFI->hasVarSizedObjects())
992 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
994 // If dynamic alloca is used, then reset esp to point to the last callee-saved
995 // slot before popping them off! Same applies for the case, when stack was
997 if (RegInfo->needsStackRealignment(MF)) {
998 // We cannot use LEA here, because stack pointer was realigned. We need to
999 // deallocate local frame back.
1001 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1002 MBBI = prior(LastCSPop);
1005 BuildMI(MBB, MBBI, DL,
1006 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1007 StackPtr).addReg(FramePtr);
1008 } else if (MFI->hasVarSizedObjects()) {
1010 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1012 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1013 FramePtr, false, -CSSize);
1014 MBB.insert(MBBI, MI);
1016 BuildMI(MBB, MBBI, DL,
1017 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1020 } else if (NumBytes) {
1021 // Adjust stack pointer back: ESP += numbytes.
1022 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1025 // We're returning from function via eh_return.
1026 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1027 MBBI = MBB.getLastNonDebugInstr();
1028 MachineOperand &DestAddr = MBBI->getOperand(0);
1029 assert(DestAddr.isReg() && "Offset should be in register!");
1030 BuildMI(MBB, MBBI, DL,
1031 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1032 StackPtr).addReg(DestAddr.getReg());
1033 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1034 RetOpcode == X86::TCRETURNmi ||
1035 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1036 RetOpcode == X86::TCRETURNmi64) {
1037 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1038 // Tail call return: adjust the stack pointer and jump to callee.
1039 MBBI = MBB.getLastNonDebugInstr();
1040 MachineOperand &JumpTarget = MBBI->getOperand(0);
1041 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1042 assert(StackAdjust.isImm() && "Expecting immediate value.");
1044 // Adjust stack pointer.
1045 int StackAdj = StackAdjust.getImm();
1046 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1048 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1050 // Incoporate the retaddr area.
1051 Offset = StackAdj-MaxTCDelta;
1052 assert(Offset >= 0 && "Offset should never be negative");
1055 // Check for possible merge with preceding ADD instruction.
1056 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1057 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
1060 // Jump to label or value in register.
1061 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1062 MachineInstrBuilder MIB =
1063 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1064 ? X86::TAILJMPd : X86::TAILJMPd64));
1065 if (JumpTarget.isGlobal())
1066 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1067 JumpTarget.getTargetFlags());
1069 assert(JumpTarget.isSymbol());
1070 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1071 JumpTarget.getTargetFlags());
1073 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1074 MachineInstrBuilder MIB =
1075 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1076 ? X86::TAILJMPm : X86::TAILJMPm64));
1077 for (unsigned i = 0; i != 5; ++i)
1078 MIB.addOperand(MBBI->getOperand(i));
1079 } else if (RetOpcode == X86::TCRETURNri64) {
1080 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1081 addReg(JumpTarget.getReg(), RegState::Kill);
1083 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1084 addReg(JumpTarget.getReg(), RegState::Kill);
1087 MachineInstr *NewMI = prior(MBBI);
1088 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1089 NewMI->addOperand(MBBI->getOperand(i));
1091 // Delete the pseudo instruction TCRETURN.
1093 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1094 (X86FI->getTCReturnAddrDelta() < 0)) {
1095 // Add the return addr area delta back since we are not tail calling.
1096 int delta = -1*X86FI->getTCReturnAddrDelta();
1097 MBBI = MBB.getLastNonDebugInstr();
1099 // Check for possible merge with preceding ADD instruction.
1100 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1101 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
1105 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
1106 const X86RegisterInfo *RI =
1107 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1108 const MachineFrameInfo *MFI = MF.getFrameInfo();
1109 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1110 uint64_t StackSize = MFI->getStackSize();
1112 if (RI->needsStackRealignment(MF)) {
1114 // Skip the saved EBP.
1115 Offset += RI->getSlotSize();
1117 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1118 return Offset + StackSize;
1120 // FIXME: Support tail calls
1123 return Offset + StackSize;
1125 // Skip the saved EBP.
1126 Offset += RI->getSlotSize();
1128 // Skip the RETADDR move area
1129 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1130 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1131 if (TailCallReturnAddrDelta < 0)
1132 Offset -= TailCallReturnAddrDelta;
1138 bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1139 MachineBasicBlock::iterator MI,
1140 const std::vector<CalleeSavedInfo> &CSI,
1141 const TargetRegisterInfo *TRI) const {
1145 DebugLoc DL = MBB.findDebugLoc(MI);
1147 MachineFunction &MF = *MBB.getParent();
1149 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1150 unsigned FPReg = TRI->getFrameRegister(MF);
1151 unsigned CalleeFrameSize = 0;
1153 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1154 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1156 // Push GPRs. It increases frame size.
1157 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1158 for (unsigned i = CSI.size(); i != 0; --i) {
1159 unsigned Reg = CSI[i-1].getReg();
1160 if (!X86::GR64RegClass.contains(Reg) &&
1161 !X86::GR32RegClass.contains(Reg))
1163 // Add the callee-saved register as live-in. It's killed at the spill.
1166 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1168 CalleeFrameSize += SlotSize;
1169 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1170 .setMIFlag(MachineInstr::FrameSetup);
1173 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
1175 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1176 // It can be done by spilling XMMs to stack frame.
1177 // Note that only Win64 ABI might spill XMMs.
1178 for (unsigned i = CSI.size(); i != 0; --i) {
1179 unsigned Reg = CSI[i-1].getReg();
1180 if (X86::GR64RegClass.contains(Reg) ||
1181 X86::GR32RegClass.contains(Reg))
1183 // Add the callee-saved register as live-in. It's killed at the spill.
1185 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1186 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1193 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1194 MachineBasicBlock::iterator MI,
1195 const std::vector<CalleeSavedInfo> &CSI,
1196 const TargetRegisterInfo *TRI) const {
1200 DebugLoc DL = MBB.findDebugLoc(MI);
1202 MachineFunction &MF = *MBB.getParent();
1203 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1205 // Reload XMMs from stack frame.
1206 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1207 unsigned Reg = CSI[i].getReg();
1208 if (X86::GR64RegClass.contains(Reg) ||
1209 X86::GR32RegClass.contains(Reg))
1211 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1212 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1217 unsigned FPReg = TRI->getFrameRegister(MF);
1218 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1219 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1220 unsigned Reg = CSI[i].getReg();
1221 if (!X86::GR64RegClass.contains(Reg) &&
1222 !X86::GR32RegClass.contains(Reg))
1225 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1227 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1233 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1234 RegScavenger *RS) const {
1235 MachineFrameInfo *MFI = MF.getFrameInfo();
1236 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1237 unsigned SlotSize = RegInfo->getSlotSize();
1239 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1240 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1242 if (TailCallReturnAddrDelta < 0) {
1243 // create RETURNADDR area
1252 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1253 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1257 assert((TailCallReturnAddrDelta <= 0) &&
1258 "The Delta should always be zero or negative");
1259 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
1261 // Create a frame entry for the EBP register that must be saved.
1262 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1264 TFI.getOffsetOfLocalArea() +
1265 TailCallReturnAddrDelta,
1267 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1268 "Slot for EBP register must be last in order to be found!");
1274 HasNestArgument(const MachineFunction *MF) {
1275 const Function *F = MF->getFunction();
1276 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1278 if (I->hasNestAttr())
1285 GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
1289 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1290 bool IsNested = HasNestArgument(&MF);
1292 if (CallingConvention == CallingConv::X86_FastCall) {
1294 report_fatal_error("Segmented stacks does not support fastcall with "
1295 "nested function.");
1310 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1311 MachineBasicBlock &prologueMBB = MF.front();
1312 MachineFrameInfo *MFI = MF.getFrameInfo();
1313 const X86InstrInfo &TII = *TM.getInstrInfo();
1315 bool Is64Bit = STI.is64Bit();
1316 unsigned TlsReg, TlsOffset;
1318 const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1320 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF);
1321 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1322 "Scratch register is live-in");
1324 if (MF.getFunction()->isVarArg())
1325 report_fatal_error("Segmented stacks do not support vararg functions.");
1326 if (!ST->isTargetLinux())
1327 report_fatal_error("Segmented stacks supported only on linux.");
1329 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1330 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1331 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1332 bool IsNested = false;
1334 // We need to know if the function has a nest argument only in 64 bit mode.
1336 IsNested = HasNestArgument(&MF);
1338 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1339 // allocMBB needs to be last (terminating) instruction.
1341 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1342 e = prologueMBB.livein_end(); i != e; i++) {
1343 allocMBB->addLiveIn(*i);
1344 checkMBB->addLiveIn(*i);
1348 allocMBB->addLiveIn(X86::R10);
1350 MF.push_front(allocMBB);
1351 MF.push_front(checkMBB);
1353 // Eventually StackSize will be calculated by a link-time pass; which will
1354 // also decide whether checking code needs to be injected into this particular
1356 StackSize = MFI->getStackSize();
1358 // Read the limit off the current stacklet off the stack_guard location.
1363 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1364 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1365 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1366 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1371 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1372 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1373 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1374 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1377 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1378 // It jumps to normal execution of the function body.
1379 BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
1381 // On 32 bit we first push the arguments size and then the frame size. On 64
1382 // bit, we pass the stack frame size in r10 and the argument size in r11.
1384 // Functions with nested arguments use R10, so it needs to be saved across
1385 // the call to _morestack
1388 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1390 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1392 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1393 .addImm(X86FI->getArgumentStackSize());
1394 MF.getRegInfo().setPhysRegUsed(X86::R10);
1395 MF.getRegInfo().setPhysRegUsed(X86::R11);
1397 // Since we'll call __morestack, stack alignment needs to be preserved.
1398 BuildMI(allocMBB, DL, TII.get(X86::SUB32ri), X86::ESP).addReg(X86::ESP)
1400 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1401 .addImm(X86FI->getArgumentStackSize());
1402 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1406 // __morestack is in libgcc
1408 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1409 .addExternalSymbol("__morestack");
1411 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1412 .addExternalSymbol("__morestack");
1414 // __morestack only seems to remove 8 bytes off the stack. Add back the
1415 // additional 8 bytes we added before pushing the arguments.
1417 BuildMI(allocMBB, DL, TII.get(X86::ADD32ri), X86::ESP).addReg(X86::ESP)
1420 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1422 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1424 allocMBB->addSuccessor(&prologueMBB);
1426 checkMBB->addSuccessor(allocMBB);
1427 checkMBB->addSuccessor(&prologueMBB);