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 const MCAsmInfo &MAI = MMI.getContext().getAsmInfo();
481 if (MAI.getExceptionHandlingType() == ExceptionHandling::DwarfCFI) {
482 MCSymbol *FrameLabel0 = MMI.getContext().CreateTempSymbol();
483 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel0);
484 MachineLocation FPSrc0(FramePtr);
485 MachineLocation FPDst0(FramePtr, -2 * stackGrowth);
486 Moves.push_back(MachineMove(FrameLabel0, FPDst0, FPSrc0));
489 // Mark effective beginning of when frame pointer becomes valid.
490 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
491 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
493 // Define the current CFA to use the EBP/RBP register.
494 MachineLocation FPDst(FramePtr);
495 MachineLocation FPSrc(MachineLocation::VirtualFP);
496 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
499 // Mark the FramePtr as live-in in every block except the entry.
500 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
502 I->addLiveIn(FramePtr);
505 if (RegInfo->needsStackRealignment(MF)) {
507 BuildMI(MBB, MBBI, DL,
508 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
509 StackPtr).addReg(StackPtr).addImm(-MaxAlign);
511 // The EFLAGS implicit def is dead.
512 MI->getOperand(3).setIsDead();
515 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
518 // Skip the callee-saved push instructions.
519 bool PushedRegs = false;
520 int StackOffset = 2 * stackGrowth;
522 while (MBBI != MBB.end() &&
523 (MBBI->getOpcode() == X86::PUSH32r ||
524 MBBI->getOpcode() == X86::PUSH64r)) {
528 if (!HasFP && needsFrameMoves) {
529 // Mark callee-saved push instruction.
530 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
531 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
533 // Define the current CFA rule to use the provided offset.
534 unsigned Ptr = StackSize ?
535 MachineLocation::VirtualFP : StackPtr;
536 MachineLocation SPDst(Ptr);
537 MachineLocation SPSrc(Ptr, StackOffset);
538 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
539 StackOffset += stackGrowth;
543 DL = MBB.findDebugLoc(MBBI);
545 // If there is an SUB32ri of ESP immediately before this instruction, merge
546 // the two. This can be the case when tail call elimination is enabled and
547 // the callee has more arguments then the caller.
548 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
550 // If there is an ADD32ri or SUB32ri of ESP immediately after this
551 // instruction, merge the two instructions.
552 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
554 // Adjust stack pointer: ESP -= numbytes.
556 // Windows and cygwin/mingw require a prologue helper routine when allocating
557 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
558 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
559 // stack and adjust the stack pointer in one go. The 64-bit version of
560 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
561 // responsible for adjusting the stack pointer. Touching the stack at 4K
562 // increments is necessary to ensure that the guard pages used by the OS
563 // virtual memory manager are allocated in correct sequence.
564 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
565 const char *StackProbeSymbol;
566 bool isSPUpdateNeeded = false;
569 if (STI.isTargetCygMing())
570 StackProbeSymbol = "___chkstk";
572 StackProbeSymbol = "__chkstk";
573 isSPUpdateNeeded = true;
575 } else if (STI.isTargetCygMing())
576 StackProbeSymbol = "_alloca";
578 StackProbeSymbol = "_chkstk";
580 // Check whether EAX is livein for this function.
581 bool isEAXAlive = isEAXLiveIn(MF);
584 // Sanity check that EAX is not livein for this function.
585 // It should not be, so throw an assert.
586 assert(!Is64Bit && "EAX is livein in x64 case!");
589 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
590 .addReg(X86::EAX, RegState::Kill);
594 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
595 // Function prologue is responsible for adjusting the stack pointer.
596 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
599 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
600 // We'll also use 4 already allocated bytes for EAX.
601 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
602 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes);
605 BuildMI(MBB, MBBI, DL,
606 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
607 .addExternalSymbol(StackProbeSymbol)
608 .addReg(StackPtr, RegState::Define | RegState::Implicit)
609 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
611 // MSVC x64's __chkstk needs to adjust %rsp.
612 // FIXME: %rax preserves the offset and should be available.
613 if (isSPUpdateNeeded)
614 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
619 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
621 StackPtr, false, NumBytes - 4);
622 MBB.insert(MBBI, MI);
625 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
628 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
629 // Mark end of stack pointer adjustment.
630 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
631 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
633 if (!HasFP && NumBytes) {
634 // Define the current CFA rule to use the provided offset.
636 MachineLocation SPDst(MachineLocation::VirtualFP);
637 MachineLocation SPSrc(MachineLocation::VirtualFP,
638 -StackSize + stackGrowth);
639 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
641 MachineLocation SPDst(StackPtr);
642 MachineLocation SPSrc(StackPtr, stackGrowth);
643 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
647 // Emit DWARF info specifying the offsets of the callee-saved registers.
649 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
653 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
654 MachineBasicBlock &MBB) const {
655 const MachineFrameInfo *MFI = MF.getFrameInfo();
656 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
657 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
658 const X86InstrInfo &TII = *TM.getInstrInfo();
659 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
660 assert(MBBI != MBB.end() && "Returning block has no instructions");
661 unsigned RetOpcode = MBBI->getOpcode();
662 DebugLoc DL = MBBI->getDebugLoc();
663 bool Is64Bit = STI.is64Bit();
664 unsigned StackAlign = getStackAlignment();
665 unsigned SlotSize = RegInfo->getSlotSize();
666 unsigned FramePtr = RegInfo->getFrameRegister(MF);
667 unsigned StackPtr = RegInfo->getStackRegister();
671 llvm_unreachable("Can only insert epilog into returning blocks");
674 case X86::TCRETURNdi:
675 case X86::TCRETURNri:
676 case X86::TCRETURNmi:
677 case X86::TCRETURNdi64:
678 case X86::TCRETURNri64:
679 case X86::TCRETURNmi64:
681 case X86::EH_RETURN64:
682 break; // These are ok
685 // Get the number of bytes to allocate from the FrameInfo.
686 uint64_t StackSize = MFI->getStackSize();
687 uint64_t MaxAlign = MFI->getMaxAlignment();
688 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
689 uint64_t NumBytes = 0;
691 // If we're forcing a stack realignment we can't rely on just the frame
692 // info, we need to know the ABI stack alignment as well in case we
693 // have a call out. Otherwise just make sure we have some alignment - we'll
694 // go with the minimum.
695 if (ForceStackAlign) {
697 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
699 MaxAlign = MaxAlign ? MaxAlign : 4;
703 // Calculate required stack adjustment.
704 uint64_t FrameSize = StackSize - SlotSize;
705 if (RegInfo->needsStackRealignment(MF))
706 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
708 NumBytes = FrameSize - CSSize;
711 BuildMI(MBB, MBBI, DL,
712 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
714 NumBytes = StackSize - CSSize;
717 // Skip the callee-saved pop instructions.
718 MachineBasicBlock::iterator LastCSPop = MBBI;
719 while (MBBI != MBB.begin()) {
720 MachineBasicBlock::iterator PI = prior(MBBI);
721 unsigned Opc = PI->getOpcode();
723 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
724 !PI->getDesc().isTerminator())
730 DL = MBBI->getDebugLoc();
732 // If there is an ADD32ri or SUB32ri of ESP immediately before this
733 // instruction, merge the two instructions.
734 if (NumBytes || MFI->hasVarSizedObjects())
735 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
737 // If dynamic alloca is used, then reset esp to point to the last callee-saved
738 // slot before popping them off! Same applies for the case, when stack was
740 if (RegInfo->needsStackRealignment(MF)) {
741 // We cannot use LEA here, because stack pointer was realigned. We need to
742 // deallocate local frame back.
744 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
745 MBBI = prior(LastCSPop);
748 BuildMI(MBB, MBBI, DL,
749 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
750 StackPtr).addReg(FramePtr);
751 } else if (MFI->hasVarSizedObjects()) {
753 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
755 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
756 FramePtr, false, -CSSize);
757 MBB.insert(MBBI, MI);
759 BuildMI(MBB, MBBI, DL,
760 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
763 } else if (NumBytes) {
764 // Adjust stack pointer back: ESP += numbytes.
765 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
768 // We're returning from function via eh_return.
769 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
770 MBBI = MBB.getLastNonDebugInstr();
771 MachineOperand &DestAddr = MBBI->getOperand(0);
772 assert(DestAddr.isReg() && "Offset should be in register!");
773 BuildMI(MBB, MBBI, DL,
774 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
775 StackPtr).addReg(DestAddr.getReg());
776 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
777 RetOpcode == X86::TCRETURNmi ||
778 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
779 RetOpcode == X86::TCRETURNmi64) {
780 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
781 // Tail call return: adjust the stack pointer and jump to callee.
782 MBBI = MBB.getLastNonDebugInstr();
783 MachineOperand &JumpTarget = MBBI->getOperand(0);
784 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
785 assert(StackAdjust.isImm() && "Expecting immediate value.");
787 // Adjust stack pointer.
788 int StackAdj = StackAdjust.getImm();
789 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
791 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
793 // Incoporate the retaddr area.
794 Offset = StackAdj-MaxTCDelta;
795 assert(Offset >= 0 && "Offset should never be negative");
798 // Check for possible merge with preceding ADD instruction.
799 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
800 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
803 // Jump to label or value in register.
804 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
805 MachineInstrBuilder MIB =
806 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
807 ? X86::TAILJMPd : X86::TAILJMPd64));
808 if (JumpTarget.isGlobal())
809 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
810 JumpTarget.getTargetFlags());
812 assert(JumpTarget.isSymbol());
813 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
814 JumpTarget.getTargetFlags());
816 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
817 MachineInstrBuilder MIB =
818 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
819 ? X86::TAILJMPm : X86::TAILJMPm64));
820 for (unsigned i = 0; i != 5; ++i)
821 MIB.addOperand(MBBI->getOperand(i));
822 } else if (RetOpcode == X86::TCRETURNri64) {
823 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
824 addReg(JumpTarget.getReg(), RegState::Kill);
826 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
827 addReg(JumpTarget.getReg(), RegState::Kill);
830 MachineInstr *NewMI = prior(MBBI);
831 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
832 NewMI->addOperand(MBBI->getOperand(i));
834 // Delete the pseudo instruction TCRETURN.
836 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
837 (X86FI->getTCReturnAddrDelta() < 0)) {
838 // Add the return addr area delta back since we are not tail calling.
839 int delta = -1*X86FI->getTCReturnAddrDelta();
840 MBBI = MBB.getLastNonDebugInstr();
842 // Check for possible merge with preceding ADD instruction.
843 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
844 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
849 X86FrameLowering::getInitialFrameState(std::vector<MachineMove> &Moves) const {
850 // Calculate amount of bytes used for return address storing
851 int stackGrowth = (STI.is64Bit() ? -8 : -4);
852 const X86RegisterInfo *RI = TM.getRegisterInfo();
854 // Initial state of the frame pointer is esp+stackGrowth.
855 MachineLocation Dst(MachineLocation::VirtualFP);
856 MachineLocation Src(RI->getStackRegister(), stackGrowth);
857 Moves.push_back(MachineMove(0, Dst, Src));
859 // Add return address to move list
860 MachineLocation CSDst(RI->getStackRegister(), stackGrowth);
861 MachineLocation CSSrc(RI->getRARegister());
862 Moves.push_back(MachineMove(0, CSDst, CSSrc));
865 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
866 const X86RegisterInfo *RI =
867 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
868 const MachineFrameInfo *MFI = MF.getFrameInfo();
869 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
870 uint64_t StackSize = MFI->getStackSize();
872 if (RI->needsStackRealignment(MF)) {
874 // Skip the saved EBP.
875 Offset += RI->getSlotSize();
877 unsigned Align = MFI->getObjectAlignment(FI);
878 assert((-(Offset + StackSize)) % Align == 0);
880 return Offset + StackSize;
882 // FIXME: Support tail calls
885 return Offset + StackSize;
887 // Skip the saved EBP.
888 Offset += RI->getSlotSize();
890 // Skip the RETADDR move area
891 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
892 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
893 if (TailCallReturnAddrDelta < 0)
894 Offset -= TailCallReturnAddrDelta;
900 bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
901 MachineBasicBlock::iterator MI,
902 const std::vector<CalleeSavedInfo> &CSI,
903 const TargetRegisterInfo *TRI) const {
907 DebugLoc DL = MBB.findDebugLoc(MI);
909 MachineFunction &MF = *MBB.getParent();
911 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
912 unsigned FPReg = TRI->getFrameRegister(MF);
913 unsigned CalleeFrameSize = 0;
915 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
916 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
918 // Push GPRs. It increases frame size.
919 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
920 for (unsigned i = CSI.size(); i != 0; --i) {
921 unsigned Reg = CSI[i-1].getReg();
922 if (!X86::GR64RegClass.contains(Reg) &&
923 !X86::GR32RegClass.contains(Reg))
925 // Add the callee-saved register as live-in. It's killed at the spill.
928 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
930 CalleeFrameSize += SlotSize;
931 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill);
934 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
936 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
937 // It can be done by spilling XMMs to stack frame.
938 // Note that only Win64 ABI might spill XMMs.
939 for (unsigned i = CSI.size(); i != 0; --i) {
940 unsigned Reg = CSI[i-1].getReg();
941 if (X86::GR64RegClass.contains(Reg) ||
942 X86::GR32RegClass.contains(Reg))
944 // Add the callee-saved register as live-in. It's killed at the spill.
946 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
947 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
954 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
955 MachineBasicBlock::iterator MI,
956 const std::vector<CalleeSavedInfo> &CSI,
957 const TargetRegisterInfo *TRI) const {
961 DebugLoc DL = MBB.findDebugLoc(MI);
963 MachineFunction &MF = *MBB.getParent();
964 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
966 // Reload XMMs from stack frame.
967 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
968 unsigned Reg = CSI[i].getReg();
969 if (X86::GR64RegClass.contains(Reg) ||
970 X86::GR32RegClass.contains(Reg))
972 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
973 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
978 unsigned FPReg = TRI->getFrameRegister(MF);
979 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
980 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
981 unsigned Reg = CSI[i].getReg();
982 if (!X86::GR64RegClass.contains(Reg) &&
983 !X86::GR32RegClass.contains(Reg))
986 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
988 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
994 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
995 RegScavenger *RS) const {
996 MachineFrameInfo *MFI = MF.getFrameInfo();
997 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
998 unsigned SlotSize = RegInfo->getSlotSize();
1000 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1001 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1003 if (TailCallReturnAddrDelta < 0) {
1004 // create RETURNADDR area
1013 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1014 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1018 assert((TailCallReturnAddrDelta <= 0) &&
1019 "The Delta should always be zero or negative");
1020 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
1022 // Create a frame entry for the EBP register that must be saved.
1023 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1025 TFI.getOffsetOfLocalArea() +
1026 TailCallReturnAddrDelta,
1028 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1029 "Slot for EBP register must be last in order to be found!");