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 "X86TargetMachine.h"
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/ADT/SmallSet.h"
33 // FIXME: completely move here.
34 extern cl::opt<bool> ForceStackAlign;
36 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
37 return !MF.getFrameInfo()->hasVarSizedObjects();
40 /// hasFP - Return true if the specified function should have a dedicated frame
41 /// pointer register. This is true if the function has variable sized allocas
42 /// or if frame pointer elimination is disabled.
43 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
44 const MachineFrameInfo *MFI = MF.getFrameInfo();
45 const MachineModuleInfo &MMI = MF.getMMI();
46 const TargetRegisterInfo *RI = TM.getRegisterInfo();
48 return (DisableFramePointerElim(MF) ||
49 RI->needsStackRealignment(MF) ||
50 MFI->hasVarSizedObjects() ||
51 MFI->isFrameAddressTaken() ||
52 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
53 MMI.callsUnwindInit());
56 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
60 return X86::SUB64ri32;
68 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
72 return X86::ADD64ri32;
80 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
81 /// when it reaches the "return" instruction. We can then pop a stack object
82 /// to this register without worry about clobbering it.
83 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
84 MachineBasicBlock::iterator &MBBI,
85 const TargetRegisterInfo &TRI,
87 const MachineFunction *MF = MBB.getParent();
88 const Function *F = MF->getFunction();
89 if (!F || MF->getMMI().callsEHReturn())
92 static const unsigned CallerSavedRegs32Bit[] = {
93 X86::EAX, X86::EDX, X86::ECX
96 static const unsigned CallerSavedRegs64Bit[] = {
97 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
98 X86::R8, X86::R9, X86::R10, X86::R11
101 unsigned Opc = MBBI->getOpcode();
106 case X86::TCRETURNdi:
107 case X86::TCRETURNri:
108 case X86::TCRETURNmi:
109 case X86::TCRETURNdi64:
110 case X86::TCRETURNri64:
111 case X86::TCRETURNmi64:
113 case X86::EH_RETURN64: {
114 SmallSet<unsigned, 8> Uses;
115 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
116 MachineOperand &MO = MBBI->getOperand(i);
117 if (!MO.isReg() || MO.isDef())
119 unsigned Reg = MO.getReg();
122 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
126 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
128 if (!Uses.count(*CS))
137 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
138 /// stack pointer by a constant value.
140 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
141 unsigned StackPtr, int64_t NumBytes,
142 bool Is64Bit, const TargetInstrInfo &TII,
143 const TargetRegisterInfo &TRI) {
144 bool isSub = NumBytes < 0;
145 uint64_t Offset = isSub ? -NumBytes : NumBytes;
146 unsigned Opc = isSub ?
147 getSUBriOpcode(Is64Bit, Offset) :
148 getADDriOpcode(Is64Bit, Offset);
149 uint64_t Chunk = (1LL << 31) - 1;
150 DebugLoc DL = MBB.findDebugLoc(MBBI);
153 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
154 if (ThisVal == (Is64Bit ? 8 : 4)) {
155 // Use push / pop instead.
157 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
158 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
161 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
162 : (Is64Bit ? X86::POP64r : X86::POP32r);
163 BuildMI(MBB, MBBI, DL, TII.get(Opc))
164 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
171 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
174 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
179 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
181 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
182 unsigned StackPtr, uint64_t *NumBytes = NULL) {
183 if (MBBI == MBB.begin()) return;
185 MachineBasicBlock::iterator PI = prior(MBBI);
186 unsigned Opc = PI->getOpcode();
187 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
188 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
189 PI->getOperand(0).getReg() == StackPtr) {
191 *NumBytes += PI->getOperand(2).getImm();
193 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
194 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
195 PI->getOperand(0).getReg() == StackPtr) {
197 *NumBytes -= PI->getOperand(2).getImm();
202 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
204 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
205 MachineBasicBlock::iterator &MBBI,
206 unsigned StackPtr, uint64_t *NumBytes = NULL) {
207 // FIXME: THIS ISN'T RUN!!!
210 if (MBBI == MBB.end()) return;
212 MachineBasicBlock::iterator NI = llvm::next(MBBI);
213 if (NI == MBB.end()) return;
215 unsigned Opc = NI->getOpcode();
216 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
217 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
218 NI->getOperand(0).getReg() == StackPtr) {
220 *NumBytes -= NI->getOperand(2).getImm();
223 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
224 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
225 NI->getOperand(0).getReg() == StackPtr) {
227 *NumBytes += NI->getOperand(2).getImm();
233 /// mergeSPUpdates - Checks the instruction before/after the passed
234 /// instruction. If it is an ADD/SUB instruction it is deleted argument and the
235 /// stack adjustment is returned as a positive value for ADD and a negative for
237 static int mergeSPUpdates(MachineBasicBlock &MBB,
238 MachineBasicBlock::iterator &MBBI,
240 bool doMergeWithPrevious) {
241 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
242 (!doMergeWithPrevious && MBBI == MBB.end()))
245 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
246 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
247 unsigned Opc = PI->getOpcode();
250 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
251 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
252 PI->getOperand(0).getReg() == StackPtr){
253 Offset += PI->getOperand(2).getImm();
255 if (!doMergeWithPrevious) MBBI = NI;
256 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
257 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
258 PI->getOperand(0).getReg() == StackPtr) {
259 Offset -= PI->getOperand(2).getImm();
261 if (!doMergeWithPrevious) MBBI = NI;
267 static bool isEAXLiveIn(MachineFunction &MF) {
268 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
269 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
270 unsigned Reg = II->first;
272 if (Reg == X86::EAX || Reg == X86::AX ||
273 Reg == X86::AH || Reg == X86::AL)
280 void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
282 unsigned FramePtr) const {
283 MachineFrameInfo *MFI = MF.getFrameInfo();
284 MachineModuleInfo &MMI = MF.getMMI();
286 // Add callee saved registers to move list.
287 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
288 if (CSI.empty()) return;
290 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
291 const TargetData *TD = TM.getTargetData();
292 bool HasFP = hasFP(MF);
294 // Calculate amount of bytes used for return address storing.
295 int stackGrowth = -TD->getPointerSize();
297 // FIXME: This is dirty hack. The code itself is pretty mess right now.
298 // It should be rewritten from scratch and generalized sometimes.
300 // Determine maximum offset (minimum due to stack growth).
301 int64_t MaxOffset = 0;
302 for (std::vector<CalleeSavedInfo>::const_iterator
303 I = CSI.begin(), E = CSI.end(); I != E; ++I)
304 MaxOffset = std::min(MaxOffset,
305 MFI->getObjectOffset(I->getFrameIdx()));
307 // Calculate offsets.
308 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
309 for (std::vector<CalleeSavedInfo>::const_iterator
310 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
311 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
312 unsigned Reg = I->getReg();
313 Offset = MaxOffset - Offset + saveAreaOffset;
315 // Don't output a new machine move if we're re-saving the frame
316 // pointer. This happens when the PrologEpilogInserter has inserted an extra
317 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
318 // generates one when frame pointers are used. If we generate a "machine
319 // move" for this extra "PUSH", the linker will lose track of the fact that
320 // the frame pointer should have the value of the first "PUSH" when it's
323 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
324 // another bug. I.e., one where we generate a prolog like this:
332 // The immediate re-push of EBP is unnecessary. At the least, it's an
333 // optimization bug. EBP can be used as a scratch register in certain
334 // cases, but probably not when we have a frame pointer.
335 if (HasFP && FramePtr == Reg)
338 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
339 MachineLocation CSSrc(Reg);
340 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
344 /// emitPrologue - Push callee-saved registers onto the stack, which
345 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
346 /// space for local variables. Also emit labels used by the exception handler to
347 /// generate the exception handling frames.
348 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
349 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
350 MachineBasicBlock::iterator MBBI = MBB.begin();
351 MachineFrameInfo *MFI = MF.getFrameInfo();
352 const Function *Fn = MF.getFunction();
353 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
354 const X86InstrInfo &TII = *TM.getInstrInfo();
355 MachineModuleInfo &MMI = MF.getMMI();
356 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
357 bool needsFrameMoves = MMI.hasDebugInfo() ||
358 !Fn->doesNotThrow() || UnwindTablesMandatory;
359 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
360 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
361 bool HasFP = hasFP(MF);
362 bool Is64Bit = STI.is64Bit();
363 bool IsWin64 = STI.isTargetWin64();
364 unsigned StackAlign = getStackAlignment();
365 unsigned SlotSize = RegInfo->getSlotSize();
366 unsigned FramePtr = RegInfo->getFrameRegister(MF);
367 unsigned StackPtr = RegInfo->getStackRegister();
371 // If we're forcing a stack realignment we can't rely on just the frame
372 // info, we need to know the ABI stack alignment as well in case we
373 // have a call out. Otherwise just make sure we have some alignment - we'll
374 // go with the minimum SlotSize.
375 if (ForceStackAlign) {
377 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
378 else if (MaxAlign < SlotSize)
382 // Add RETADDR move area to callee saved frame size.
383 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
384 if (TailCallReturnAddrDelta < 0)
385 X86FI->setCalleeSavedFrameSize(
386 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
388 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
389 // function, and use up to 128 bytes of stack space, don't have a frame
390 // pointer, calls, or dynamic alloca then we do not need to adjust the
391 // stack pointer (we fit in the Red Zone).
392 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
393 !RegInfo->needsStackRealignment(MF) &&
394 !MFI->hasVarSizedObjects() && // No dynamic alloca.
395 !MFI->adjustsStack() && // No calls.
396 !IsWin64) { // Win64 has no Red Zone
397 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
398 if (HasFP) MinSize += SlotSize;
399 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
400 MFI->setStackSize(StackSize);
403 // Insert stack pointer adjustment for later moving of return addr. Only
404 // applies to tail call optimized functions where the callee argument stack
405 // size is bigger than the callers.
406 if (TailCallReturnAddrDelta < 0) {
408 BuildMI(MBB, MBBI, DL,
409 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
412 .addImm(-TailCallReturnAddrDelta);
413 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
416 // Mapping for machine moves:
418 // DST: VirtualFP AND
419 // SRC: VirtualFP => DW_CFA_def_cfa_offset
420 // ELSE => DW_CFA_def_cfa
422 // SRC: VirtualFP AND
423 // DST: Register => DW_CFA_def_cfa_register
426 // OFFSET < 0 => DW_CFA_offset_extended_sf
427 // REG < 64 => DW_CFA_offset + Reg
428 // ELSE => DW_CFA_offset_extended
430 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
431 const TargetData *TD = MF.getTarget().getTargetData();
432 uint64_t NumBytes = 0;
433 int stackGrowth = -TD->getPointerSize();
436 // Calculate required stack adjustment.
437 uint64_t FrameSize = StackSize - SlotSize;
438 if (RegInfo->needsStackRealignment(MF))
439 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
441 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
443 // Get the offset of the stack slot for the EBP register, which is
444 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
445 // Update the frame offset adjustment.
446 MFI->setOffsetAdjustment(-NumBytes);
448 // Save EBP/RBP into the appropriate stack slot.
449 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
450 .addReg(FramePtr, RegState::Kill);
452 if (needsFrameMoves) {
453 // Mark the place where EBP/RBP was saved.
454 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
455 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
457 // Define the current CFA rule to use the provided offset.
459 MachineLocation SPDst(MachineLocation::VirtualFP);
460 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
461 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
463 MachineLocation SPDst(StackPtr);
464 MachineLocation SPSrc(StackPtr, stackGrowth);
465 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
468 // Change the rule for the FramePtr to be an "offset" rule.
469 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
470 MachineLocation FPSrc(FramePtr);
471 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
474 // Update EBP with the new base value...
475 BuildMI(MBB, MBBI, DL,
476 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
479 if (needsFrameMoves) {
480 // Mark effective beginning of when frame pointer becomes valid.
481 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
482 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
484 // Define the current CFA to use the EBP/RBP register.
485 MachineLocation FPDst(FramePtr);
486 MachineLocation FPSrc(MachineLocation::VirtualFP);
487 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
490 // Mark the FramePtr as live-in in every block except the entry.
491 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
493 I->addLiveIn(FramePtr);
496 if (RegInfo->needsStackRealignment(MF)) {
498 BuildMI(MBB, MBBI, DL,
499 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
500 StackPtr).addReg(StackPtr).addImm(-MaxAlign);
502 // The EFLAGS implicit def is dead.
503 MI->getOperand(3).setIsDead();
506 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
509 // Skip the callee-saved push instructions.
510 bool PushedRegs = false;
511 int StackOffset = 2 * stackGrowth;
513 while (MBBI != MBB.end() &&
514 (MBBI->getOpcode() == X86::PUSH32r ||
515 MBBI->getOpcode() == X86::PUSH64r)) {
519 if (!HasFP && needsFrameMoves) {
520 // Mark callee-saved push instruction.
521 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
522 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
524 // Define the current CFA rule to use the provided offset.
525 unsigned Ptr = StackSize ?
526 MachineLocation::VirtualFP : StackPtr;
527 MachineLocation SPDst(Ptr);
528 MachineLocation SPSrc(Ptr, StackOffset);
529 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
530 StackOffset += stackGrowth;
534 DL = MBB.findDebugLoc(MBBI);
536 // If there is an SUB32ri of ESP immediately before this instruction, merge
537 // the two. This can be the case when tail call elimination is enabled and
538 // the callee has more arguments then the caller.
539 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
541 // If there is an ADD32ri or SUB32ri of ESP immediately after this
542 // instruction, merge the two instructions.
543 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
545 // Adjust stack pointer: ESP -= numbytes.
547 // Windows and cygwin/mingw require a prologue helper routine when allocating
548 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
549 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
550 // stack and adjust the stack pointer in one go. The 64-bit version of
551 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
552 // responsible for adjusting the stack pointer. Touching the stack at 4K
553 // increments is necessary to ensure that the guard pages used by the OS
554 // virtual memory manager are allocated in correct sequence.
555 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
556 const char *StackProbeSymbol;
557 bool isSPUpdateNeeded = false;
560 if (STI.isTargetCygMing())
561 StackProbeSymbol = "___chkstk";
563 StackProbeSymbol = "__chkstk";
564 isSPUpdateNeeded = true;
566 } else if (STI.isTargetCygMing())
567 StackProbeSymbol = "_alloca";
569 StackProbeSymbol = "_chkstk";
571 // Check whether EAX is livein for this function.
572 bool isEAXAlive = isEAXLiveIn(MF);
575 // Sanity check that EAX is not livein for this function.
576 // It should not be, so throw an assert.
577 assert(!Is64Bit && "EAX is livein in x64 case!");
580 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
581 .addReg(X86::EAX, RegState::Kill);
585 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
586 // Function prologue is responsible for adjusting the stack pointer.
587 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
590 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
591 // We'll also use 4 already allocated bytes for EAX.
592 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
593 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes);
596 BuildMI(MBB, MBBI, DL,
597 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
598 .addExternalSymbol(StackProbeSymbol)
599 .addReg(StackPtr, RegState::Define | RegState::Implicit)
600 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
602 // MSVC x64's __chkstk needs to adjust %rsp.
603 // FIXME: %rax preserves the offset and should be available.
604 if (isSPUpdateNeeded)
605 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
610 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
612 StackPtr, false, NumBytes - 4);
613 MBB.insert(MBBI, MI);
616 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
619 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
620 // Mark end of stack pointer adjustment.
621 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
622 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
624 if (!HasFP && NumBytes) {
625 // Define the current CFA rule to use the provided offset.
627 MachineLocation SPDst(MachineLocation::VirtualFP);
628 MachineLocation SPSrc(MachineLocation::VirtualFP,
629 -StackSize + stackGrowth);
630 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
632 MachineLocation SPDst(StackPtr);
633 MachineLocation SPSrc(StackPtr, stackGrowth);
634 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
638 // Emit DWARF info specifying the offsets of the callee-saved registers.
640 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
644 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
645 MachineBasicBlock &MBB) const {
646 const MachineFrameInfo *MFI = MF.getFrameInfo();
647 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
648 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
649 const X86InstrInfo &TII = *TM.getInstrInfo();
650 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
651 assert(MBBI != MBB.end() && "Returning block has no instructions");
652 unsigned RetOpcode = MBBI->getOpcode();
653 DebugLoc DL = MBBI->getDebugLoc();
654 bool Is64Bit = STI.is64Bit();
655 unsigned StackAlign = getStackAlignment();
656 unsigned SlotSize = RegInfo->getSlotSize();
657 unsigned FramePtr = RegInfo->getFrameRegister(MF);
658 unsigned StackPtr = RegInfo->getStackRegister();
662 llvm_unreachable("Can only insert epilog into returning blocks");
665 case X86::TCRETURNdi:
666 case X86::TCRETURNri:
667 case X86::TCRETURNmi:
668 case X86::TCRETURNdi64:
669 case X86::TCRETURNri64:
670 case X86::TCRETURNmi64:
672 case X86::EH_RETURN64:
673 break; // These are ok
676 // Get the number of bytes to allocate from the FrameInfo.
677 uint64_t StackSize = MFI->getStackSize();
678 uint64_t MaxAlign = MFI->getMaxAlignment();
679 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
680 uint64_t NumBytes = 0;
682 // If we're forcing a stack realignment we can't rely on just the frame
683 // info, we need to know the ABI stack alignment as well in case we
684 // have a call out. Otherwise just make sure we have some alignment - we'll
685 // go with the minimum.
686 if (ForceStackAlign) {
688 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
690 MaxAlign = MaxAlign ? MaxAlign : 4;
694 // Calculate required stack adjustment.
695 uint64_t FrameSize = StackSize - SlotSize;
696 if (RegInfo->needsStackRealignment(MF))
697 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
699 NumBytes = FrameSize - CSSize;
702 BuildMI(MBB, MBBI, DL,
703 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
705 NumBytes = StackSize - CSSize;
708 // Skip the callee-saved pop instructions.
709 MachineBasicBlock::iterator LastCSPop = MBBI;
710 while (MBBI != MBB.begin()) {
711 MachineBasicBlock::iterator PI = prior(MBBI);
712 unsigned Opc = PI->getOpcode();
714 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
715 !PI->getDesc().isTerminator())
721 DL = MBBI->getDebugLoc();
723 // If there is an ADD32ri or SUB32ri of ESP immediately before this
724 // instruction, merge the two instructions.
725 if (NumBytes || MFI->hasVarSizedObjects())
726 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
728 // If dynamic alloca is used, then reset esp to point to the last callee-saved
729 // slot before popping them off! Same applies for the case, when stack was
731 if (RegInfo->needsStackRealignment(MF)) {
732 // We cannot use LEA here, because stack pointer was realigned. We need to
733 // deallocate local frame back.
735 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
736 MBBI = prior(LastCSPop);
739 BuildMI(MBB, MBBI, DL,
740 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
741 StackPtr).addReg(FramePtr);
742 } else if (MFI->hasVarSizedObjects()) {
744 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
746 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
747 FramePtr, false, -CSSize);
748 MBB.insert(MBBI, MI);
750 BuildMI(MBB, MBBI, DL,
751 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
754 } else if (NumBytes) {
755 // Adjust stack pointer back: ESP += numbytes.
756 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
759 // We're returning from function via eh_return.
760 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
761 MBBI = MBB.getLastNonDebugInstr();
762 MachineOperand &DestAddr = MBBI->getOperand(0);
763 assert(DestAddr.isReg() && "Offset should be in register!");
764 BuildMI(MBB, MBBI, DL,
765 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
766 StackPtr).addReg(DestAddr.getReg());
767 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
768 RetOpcode == X86::TCRETURNmi ||
769 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
770 RetOpcode == X86::TCRETURNmi64) {
771 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
772 // Tail call return: adjust the stack pointer and jump to callee.
773 MBBI = MBB.getLastNonDebugInstr();
774 MachineOperand &JumpTarget = MBBI->getOperand(0);
775 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
776 assert(StackAdjust.isImm() && "Expecting immediate value.");
778 // Adjust stack pointer.
779 int StackAdj = StackAdjust.getImm();
780 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
782 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
784 // Incoporate the retaddr area.
785 Offset = StackAdj-MaxTCDelta;
786 assert(Offset >= 0 && "Offset should never be negative");
789 // Check for possible merge with preceding ADD instruction.
790 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
791 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
794 // Jump to label or value in register.
795 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
796 MachineInstrBuilder MIB =
797 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
798 ? X86::TAILJMPd : X86::TAILJMPd64));
799 if (JumpTarget.isGlobal())
800 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
801 JumpTarget.getTargetFlags());
803 assert(JumpTarget.isSymbol());
804 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
805 JumpTarget.getTargetFlags());
807 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
808 MachineInstrBuilder MIB =
809 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
810 ? X86::TAILJMPm : X86::TAILJMPm64));
811 for (unsigned i = 0; i != 5; ++i)
812 MIB.addOperand(MBBI->getOperand(i));
813 } else if (RetOpcode == X86::TCRETURNri64) {
814 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
815 addReg(JumpTarget.getReg(), RegState::Kill);
817 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
818 addReg(JumpTarget.getReg(), RegState::Kill);
821 MachineInstr *NewMI = prior(MBBI);
822 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
823 NewMI->addOperand(MBBI->getOperand(i));
825 // Delete the pseudo instruction TCRETURN.
827 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
828 (X86FI->getTCReturnAddrDelta() < 0)) {
829 // Add the return addr area delta back since we are not tail calling.
830 int delta = -1*X86FI->getTCReturnAddrDelta();
831 MBBI = MBB.getLastNonDebugInstr();
833 // Check for possible merge with preceding ADD instruction.
834 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
835 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
840 X86FrameLowering::getInitialFrameState(std::vector<MachineMove> &Moves) const {
841 // Calculate amount of bytes used for return address storing
842 int stackGrowth = (STI.is64Bit() ? -8 : -4);
843 const X86RegisterInfo *RI = TM.getRegisterInfo();
845 // Initial state of the frame pointer is esp+stackGrowth.
846 MachineLocation Dst(MachineLocation::VirtualFP);
847 MachineLocation Src(RI->getStackRegister(), stackGrowth);
848 Moves.push_back(MachineMove(0, Dst, Src));
850 // Add return address to move list
851 MachineLocation CSDst(RI->getStackRegister(), stackGrowth);
852 MachineLocation CSSrc(RI->getRARegister());
853 Moves.push_back(MachineMove(0, CSDst, CSSrc));
856 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
857 const X86RegisterInfo *RI =
858 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
859 const MachineFrameInfo *MFI = MF.getFrameInfo();
860 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
861 uint64_t StackSize = MFI->getStackSize();
863 if (RI->needsStackRealignment(MF)) {
865 // Skip the saved EBP.
866 Offset += RI->getSlotSize();
868 unsigned Align = MFI->getObjectAlignment(FI);
869 assert((-(Offset + StackSize)) % Align == 0);
871 return Offset + StackSize;
873 // FIXME: Support tail calls
876 return Offset + StackSize;
878 // Skip the saved EBP.
879 Offset += RI->getSlotSize();
881 // Skip the RETADDR move area
882 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
883 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
884 if (TailCallReturnAddrDelta < 0)
885 Offset -= TailCallReturnAddrDelta;
891 bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
892 MachineBasicBlock::iterator MI,
893 const std::vector<CalleeSavedInfo> &CSI,
894 const TargetRegisterInfo *TRI) const {
898 DebugLoc DL = MBB.findDebugLoc(MI);
900 MachineFunction &MF = *MBB.getParent();
902 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
903 unsigned FPReg = TRI->getFrameRegister(MF);
904 unsigned CalleeFrameSize = 0;
906 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
907 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
909 // Push GPRs. It increases frame size.
910 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
911 for (unsigned i = CSI.size(); i != 0; --i) {
912 unsigned Reg = CSI[i-1].getReg();
913 if (!X86::GR64RegClass.contains(Reg) &&
914 !X86::GR32RegClass.contains(Reg))
916 // Add the callee-saved register as live-in. It's killed at the spill.
919 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
921 CalleeFrameSize += SlotSize;
922 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill);
925 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
927 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
928 // It can be done by spilling XMMs to stack frame.
929 // Note that only Win64 ABI might spill XMMs.
930 for (unsigned i = CSI.size(); i != 0; --i) {
931 unsigned Reg = CSI[i-1].getReg();
932 if (X86::GR64RegClass.contains(Reg) ||
933 X86::GR32RegClass.contains(Reg))
935 // Add the callee-saved register as live-in. It's killed at the spill.
937 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
938 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
945 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
946 MachineBasicBlock::iterator MI,
947 const std::vector<CalleeSavedInfo> &CSI,
948 const TargetRegisterInfo *TRI) const {
952 DebugLoc DL = MBB.findDebugLoc(MI);
954 MachineFunction &MF = *MBB.getParent();
955 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
957 // Reload XMMs from stack frame.
958 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
959 unsigned Reg = CSI[i].getReg();
960 if (X86::GR64RegClass.contains(Reg) ||
961 X86::GR32RegClass.contains(Reg))
963 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
964 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
969 unsigned FPReg = TRI->getFrameRegister(MF);
970 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
971 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
972 unsigned Reg = CSI[i].getReg();
973 if (!X86::GR64RegClass.contains(Reg) &&
974 !X86::GR32RegClass.contains(Reg))
977 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
979 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
985 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
986 RegScavenger *RS) const {
987 MachineFrameInfo *MFI = MF.getFrameInfo();
988 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
989 unsigned SlotSize = RegInfo->getSlotSize();
991 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
992 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
994 if (TailCallReturnAddrDelta < 0) {
995 // create RETURNADDR area
1004 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1005 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1009 assert((TailCallReturnAddrDelta <= 0) &&
1010 "The Delta should always be zero or negative");
1011 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
1013 // Create a frame entry for the EBP register that must be saved.
1014 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1016 TFI.getOffsetOfLocalArea() +
1017 TailCallReturnAddrDelta,
1019 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1020 "Slot for EBP register must be last in order to be found!");