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/Target/TargetData.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/ADT/SmallSet.h"
32 // FIXME: completely move here.
33 extern cl::opt<bool> ForceStackAlign;
35 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
36 return !MF.getFrameInfo()->hasVarSizedObjects();
39 /// hasFP - Return true if the specified function should have a dedicated frame
40 /// pointer register. This is true if the function has variable sized allocas
41 /// or if frame pointer elimination is disabled.
42 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
43 const MachineFrameInfo *MFI = MF.getFrameInfo();
44 const MachineModuleInfo &MMI = MF.getMMI();
45 const TargetRegisterInfo *RI = TM.getRegisterInfo();
47 return (DisableFramePointerElim(MF) ||
48 RI->needsStackRealignment(MF) ||
49 MFI->hasVarSizedObjects() ||
50 MFI->isFrameAddressTaken() ||
51 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
52 MMI.callsUnwindInit());
55 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
59 return X86::SUB64ri32;
67 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
71 return X86::ADD64ri32;
79 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
80 /// when it reaches the "return" instruction. We can then pop a stack object
81 /// to this register without worry about clobbering it.
82 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
83 MachineBasicBlock::iterator &MBBI,
84 const TargetRegisterInfo &TRI,
86 const MachineFunction *MF = MBB.getParent();
87 const Function *F = MF->getFunction();
88 if (!F || MF->getMMI().callsEHReturn())
91 static const unsigned CallerSavedRegs32Bit[] = {
92 X86::EAX, X86::EDX, X86::ECX
95 static const unsigned CallerSavedRegs64Bit[] = {
96 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
97 X86::R8, X86::R9, X86::R10, X86::R11
100 unsigned Opc = MBBI->getOpcode();
105 case X86::TCRETURNdi:
106 case X86::TCRETURNri:
107 case X86::TCRETURNmi:
108 case X86::TCRETURNdi64:
109 case X86::TCRETURNri64:
110 case X86::TCRETURNmi64:
112 case X86::EH_RETURN64: {
113 SmallSet<unsigned, 8> Uses;
114 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
115 MachineOperand &MO = MBBI->getOperand(i);
116 if (!MO.isReg() || MO.isDef())
118 unsigned Reg = MO.getReg();
121 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
125 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
127 if (!Uses.count(*CS))
136 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
137 /// stack pointer by a constant value.
139 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
140 unsigned StackPtr, int64_t NumBytes,
141 bool Is64Bit, const TargetInstrInfo &TII,
142 const TargetRegisterInfo &TRI) {
143 bool isSub = NumBytes < 0;
144 uint64_t Offset = isSub ? -NumBytes : NumBytes;
145 unsigned Opc = isSub ?
146 getSUBriOpcode(Is64Bit, Offset) :
147 getADDriOpcode(Is64Bit, Offset);
148 uint64_t Chunk = (1LL << 31) - 1;
149 DebugLoc DL = MBB.findDebugLoc(MBBI);
152 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
153 if (ThisVal == (Is64Bit ? 8 : 4)) {
154 // Use push / pop instead.
156 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
157 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
160 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
161 : (Is64Bit ? X86::POP64r : X86::POP32r);
162 BuildMI(MBB, MBBI, DL, TII.get(Opc))
163 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
170 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
173 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
178 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
180 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
181 unsigned StackPtr, uint64_t *NumBytes = NULL) {
182 if (MBBI == MBB.begin()) return;
184 MachineBasicBlock::iterator PI = prior(MBBI);
185 unsigned Opc = PI->getOpcode();
186 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
187 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
188 PI->getOperand(0).getReg() == StackPtr) {
190 *NumBytes += PI->getOperand(2).getImm();
192 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
193 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
194 PI->getOperand(0).getReg() == StackPtr) {
196 *NumBytes -= PI->getOperand(2).getImm();
201 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
203 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
204 MachineBasicBlock::iterator &MBBI,
205 unsigned StackPtr, uint64_t *NumBytes = NULL) {
206 // FIXME: THIS ISN'T RUN!!!
209 if (MBBI == MBB.end()) return;
211 MachineBasicBlock::iterator NI = llvm::next(MBBI);
212 if (NI == MBB.end()) return;
214 unsigned Opc = NI->getOpcode();
215 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
216 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
217 NI->getOperand(0).getReg() == StackPtr) {
219 *NumBytes -= NI->getOperand(2).getImm();
222 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
223 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
224 NI->getOperand(0).getReg() == StackPtr) {
226 *NumBytes += NI->getOperand(2).getImm();
232 /// mergeSPUpdates - Checks the instruction before/after the passed
233 /// instruction. If it is an ADD/SUB instruction it is deleted argument and the
234 /// stack adjustment is returned as a positive value for ADD and a negative for
236 static int mergeSPUpdates(MachineBasicBlock &MBB,
237 MachineBasicBlock::iterator &MBBI,
239 bool doMergeWithPrevious) {
240 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
241 (!doMergeWithPrevious && MBBI == MBB.end()))
244 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
245 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
246 unsigned Opc = PI->getOpcode();
249 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
250 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
251 PI->getOperand(0).getReg() == StackPtr){
252 Offset += PI->getOperand(2).getImm();
254 if (!doMergeWithPrevious) MBBI = NI;
255 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
256 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
257 PI->getOperand(0).getReg() == StackPtr) {
258 Offset -= PI->getOperand(2).getImm();
260 if (!doMergeWithPrevious) MBBI = NI;
266 static bool isEAXLiveIn(MachineFunction &MF) {
267 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
268 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
269 unsigned Reg = II->first;
271 if (Reg == X86::EAX || Reg == X86::AX ||
272 Reg == X86::AH || Reg == X86::AL)
279 void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
281 unsigned FramePtr) const {
282 MachineFrameInfo *MFI = MF.getFrameInfo();
283 MachineModuleInfo &MMI = MF.getMMI();
285 // Add callee saved registers to move list.
286 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
287 if (CSI.empty()) return;
289 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
290 const TargetData *TD = TM.getTargetData();
291 bool HasFP = hasFP(MF);
293 // Calculate amount of bytes used for return address storing.
294 int stackGrowth = -TD->getPointerSize();
296 // FIXME: This is dirty hack. The code itself is pretty mess right now.
297 // It should be rewritten from scratch and generalized sometimes.
299 // Determine maximum offset (minumum due to stack growth).
300 int64_t MaxOffset = 0;
301 for (std::vector<CalleeSavedInfo>::const_iterator
302 I = CSI.begin(), E = CSI.end(); I != E; ++I)
303 MaxOffset = std::min(MaxOffset,
304 MFI->getObjectOffset(I->getFrameIdx()));
306 // Calculate offsets.
307 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
308 for (std::vector<CalleeSavedInfo>::const_iterator
309 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
310 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
311 unsigned Reg = I->getReg();
312 Offset = MaxOffset - Offset + saveAreaOffset;
314 // Don't output a new machine move if we're re-saving the frame
315 // pointer. This happens when the PrologEpilogInserter has inserted an extra
316 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
317 // generates one when frame pointers are used. If we generate a "machine
318 // move" for this extra "PUSH", the linker will lose track of the fact that
319 // the frame pointer should have the value of the first "PUSH" when it's
322 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
323 // another bug. I.e., one where we generate a prolog like this:
331 // The immediate re-push of EBP is unnecessary. At the least, it's an
332 // optimization bug. EBP can be used as a scratch register in certain
333 // cases, but probably not when we have a frame pointer.
334 if (HasFP && FramePtr == Reg)
337 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
338 MachineLocation CSSrc(Reg);
339 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
343 /// emitPrologue - Push callee-saved registers onto the stack, which
344 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
345 /// space for local variables. Also emit labels used by the exception handler to
346 /// generate the exception handling frames.
347 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
348 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
349 MachineBasicBlock::iterator MBBI = MBB.begin();
350 MachineFrameInfo *MFI = MF.getFrameInfo();
351 const Function *Fn = MF.getFunction();
352 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
353 const X86InstrInfo &TII = *TM.getInstrInfo();
354 MachineModuleInfo &MMI = MF.getMMI();
355 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
356 bool needsFrameMoves = MMI.hasDebugInfo() ||
357 !Fn->doesNotThrow() || UnwindTablesMandatory;
358 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
359 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
360 bool HasFP = hasFP(MF);
361 bool Is64Bit = STI.is64Bit();
362 bool IsWin64 = STI.isTargetWin64();
363 unsigned StackAlign = getStackAlignment();
364 unsigned SlotSize = RegInfo->getSlotSize();
365 unsigned FramePtr = RegInfo->getFrameRegister(MF);
366 unsigned StackPtr = RegInfo->getStackRegister();
370 // If we're forcing a stack realignment we can't rely on just the frame
371 // info, we need to know the ABI stack alignment as well in case we
372 // have a call out. Otherwise just make sure we have some alignment - we'll
373 // go with the minimum SlotSize.
374 if (ForceStackAlign) {
376 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
377 else if (MaxAlign < SlotSize)
381 // Add RETADDR move area to callee saved frame size.
382 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
383 if (TailCallReturnAddrDelta < 0)
384 X86FI->setCalleeSavedFrameSize(
385 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
387 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
388 // function, and use up to 128 bytes of stack space, don't have a frame
389 // pointer, calls, or dynamic alloca then we do not need to adjust the
390 // stack pointer (we fit in the Red Zone).
391 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
392 !RegInfo->needsStackRealignment(MF) &&
393 !MFI->hasVarSizedObjects() && // No dynamic alloca.
394 !MFI->adjustsStack() && // No calls.
395 !IsWin64) { // Win64 has no Red Zone
396 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
397 if (HasFP) MinSize += SlotSize;
398 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
399 MFI->setStackSize(StackSize);
400 } else if (IsWin64) {
401 // We need to always allocate 32 bytes as register spill area.
402 // FIXME: We might reuse these 32 bytes for leaf functions.
404 MFI->setStackSize(StackSize);
407 // Insert stack pointer adjustment for later moving of return addr. Only
408 // applies to tail call optimized functions where the callee argument stack
409 // size is bigger than the callers.
410 if (TailCallReturnAddrDelta < 0) {
412 BuildMI(MBB, MBBI, DL,
413 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
416 .addImm(-TailCallReturnAddrDelta);
417 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
420 // Mapping for machine moves:
422 // DST: VirtualFP AND
423 // SRC: VirtualFP => DW_CFA_def_cfa_offset
424 // ELSE => DW_CFA_def_cfa
426 // SRC: VirtualFP AND
427 // DST: Register => DW_CFA_def_cfa_register
430 // OFFSET < 0 => DW_CFA_offset_extended_sf
431 // REG < 64 => DW_CFA_offset + Reg
432 // ELSE => DW_CFA_offset_extended
434 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
435 const TargetData *TD = MF.getTarget().getTargetData();
436 uint64_t NumBytes = 0;
437 int stackGrowth = -TD->getPointerSize();
440 // Calculate required stack adjustment.
441 uint64_t FrameSize = StackSize - SlotSize;
442 if (RegInfo->needsStackRealignment(MF))
443 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
445 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
447 // Get the offset of the stack slot for the EBP register, which is
448 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
449 // Update the frame offset adjustment.
450 MFI->setOffsetAdjustment(-NumBytes);
452 // Save EBP/RBP into the appropriate stack slot.
453 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
454 .addReg(FramePtr, RegState::Kill);
456 if (needsFrameMoves) {
457 // Mark the place where EBP/RBP was saved.
458 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
459 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
461 // Define the current CFA rule to use the provided offset.
463 MachineLocation SPDst(MachineLocation::VirtualFP);
464 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
465 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
467 MachineLocation SPDst(StackPtr);
468 MachineLocation SPSrc(StackPtr, stackGrowth);
469 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
472 // Change the rule for the FramePtr to be an "offset" rule.
473 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
474 MachineLocation FPSrc(FramePtr);
475 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
478 // Update EBP with the new base value...
479 BuildMI(MBB, MBBI, DL,
480 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
483 if (needsFrameMoves) {
484 // Mark effective beginning of when frame pointer becomes valid.
485 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
486 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
488 // Define the current CFA to use the EBP/RBP register.
489 MachineLocation FPDst(FramePtr);
490 MachineLocation FPSrc(MachineLocation::VirtualFP);
491 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
494 // Mark the FramePtr as live-in in every block except the entry.
495 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
497 I->addLiveIn(FramePtr);
500 if (RegInfo->needsStackRealignment(MF)) {
502 BuildMI(MBB, MBBI, DL,
503 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
504 StackPtr).addReg(StackPtr).addImm(-MaxAlign);
506 // The EFLAGS implicit def is dead.
507 MI->getOperand(3).setIsDead();
510 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
513 // Skip the callee-saved push instructions.
514 bool PushedRegs = false;
515 int StackOffset = 2 * stackGrowth;
517 while (MBBI != MBB.end() &&
518 (MBBI->getOpcode() == X86::PUSH32r ||
519 MBBI->getOpcode() == X86::PUSH64r)) {
523 if (!HasFP && needsFrameMoves) {
524 // Mark callee-saved push instruction.
525 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
526 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
528 // Define the current CFA rule to use the provided offset.
529 unsigned Ptr = StackSize ?
530 MachineLocation::VirtualFP : StackPtr;
531 MachineLocation SPDst(Ptr);
532 MachineLocation SPSrc(Ptr, StackOffset);
533 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
534 StackOffset += stackGrowth;
538 DL = MBB.findDebugLoc(MBBI);
540 // If there is an SUB32ri of ESP immediately before this instruction, merge
541 // the two. This can be the case when tail call elimination is enabled and
542 // the callee has more arguments then the caller.
543 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
545 // If there is an ADD32ri or SUB32ri of ESP immediately after this
546 // instruction, merge the two instructions.
547 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
549 // Adjust stack pointer: ESP -= numbytes.
551 // Windows and cygwin/mingw require a prologue helper routine when allocating
552 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
553 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
554 // stack and adjust the stack pointer in one go. The 64-bit version of
555 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
556 // responsible for adjusting the stack pointer. Touching the stack at 4K
557 // increments is necessary to ensure that the guard pages used by the OS
558 // virtual memory manager are allocated in correct sequence.
559 if (NumBytes >= 4096 && (STI.isTargetCygMing() || STI.isTargetWin32())) {
560 // Check whether EAX is livein for this function.
561 bool isEAXAlive = isEAXLiveIn(MF);
563 const char *StackProbeSymbol =
564 STI.isTargetWindows() ? "_chkstk" : "_alloca";
565 if (Is64Bit && STI.isTargetCygMing())
566 StackProbeSymbol = "__chkstk";
567 unsigned CallOp = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
569 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
571 BuildMI(MBB, MBBI, DL, TII.get(CallOp))
572 .addExternalSymbol(StackProbeSymbol)
573 .addReg(StackPtr, RegState::Define | RegState::Implicit)
574 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
577 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
578 .addReg(X86::EAX, RegState::Kill);
580 // Allocate NumBytes-4 bytes on stack. We'll also use 4 already
581 // allocated bytes for EAX.
582 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
583 .addImm(NumBytes - 4);
584 BuildMI(MBB, MBBI, DL, TII.get(CallOp))
585 .addExternalSymbol(StackProbeSymbol)
586 .addReg(StackPtr, RegState::Define | RegState::Implicit)
587 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
590 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
592 StackPtr, false, NumBytes - 4);
593 MBB.insert(MBBI, MI);
595 } else if (NumBytes >= 4096 && STI.isTargetWin64()) {
596 // Sanity check that EAX is not livein for this function. It should
597 // should not be, so throw an assert.
598 assert(!isEAXLiveIn(MF) && "EAX is livein in the Win64 case!");
600 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
601 // Function prologue is responsible for adjusting the stack pointer.
602 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
604 BuildMI(MBB, MBBI, DL, TII.get(X86::WINCALL64pcrel32))
605 .addExternalSymbol("__chkstk")
606 .addReg(StackPtr, RegState::Define | RegState::Implicit);
607 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
610 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
613 if ((NumBytes || PushedRegs) && needsFrameMoves) {
614 // Mark end of stack pointer adjustment.
615 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
616 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
618 if (!HasFP && NumBytes) {
619 // Define the current CFA rule to use the provided offset.
621 MachineLocation SPDst(MachineLocation::VirtualFP);
622 MachineLocation SPSrc(MachineLocation::VirtualFP,
623 -StackSize + stackGrowth);
624 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
626 MachineLocation SPDst(StackPtr);
627 MachineLocation SPSrc(StackPtr, stackGrowth);
628 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
632 // Emit DWARF info specifying the offsets of the callee-saved registers.
634 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
638 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
639 MachineBasicBlock &MBB) const {
640 const MachineFrameInfo *MFI = MF.getFrameInfo();
641 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
642 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
643 const X86InstrInfo &TII = *TM.getInstrInfo();
644 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
645 assert(MBBI != MBB.end() && "Returning block has no instructions");
646 unsigned RetOpcode = MBBI->getOpcode();
647 DebugLoc DL = MBBI->getDebugLoc();
648 bool Is64Bit = STI.is64Bit();
649 unsigned StackAlign = getStackAlignment();
650 unsigned SlotSize = RegInfo->getSlotSize();
651 unsigned FramePtr = RegInfo->getFrameRegister(MF);
652 unsigned StackPtr = RegInfo->getStackRegister();
656 llvm_unreachable("Can only insert epilog into returning blocks");
659 case X86::TCRETURNdi:
660 case X86::TCRETURNri:
661 case X86::TCRETURNmi:
662 case X86::TCRETURNdi64:
663 case X86::TCRETURNri64:
664 case X86::TCRETURNmi64:
666 case X86::EH_RETURN64:
667 break; // These are ok
670 // Get the number of bytes to allocate from the FrameInfo.
671 uint64_t StackSize = MFI->getStackSize();
672 uint64_t MaxAlign = MFI->getMaxAlignment();
673 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
674 uint64_t NumBytes = 0;
676 // If we're forcing a stack realignment we can't rely on just the frame
677 // info, we need to know the ABI stack alignment as well in case we
678 // have a call out. Otherwise just make sure we have some alignment - we'll
679 // go with the minimum.
680 if (ForceStackAlign) {
682 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
684 MaxAlign = MaxAlign ? MaxAlign : 4;
688 // Calculate required stack adjustment.
689 uint64_t FrameSize = StackSize - SlotSize;
690 if (RegInfo->needsStackRealignment(MF))
691 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
693 NumBytes = FrameSize - CSSize;
696 BuildMI(MBB, MBBI, DL,
697 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
699 NumBytes = StackSize - CSSize;
702 // Skip the callee-saved pop instructions.
703 MachineBasicBlock::iterator LastCSPop = MBBI;
704 while (MBBI != MBB.begin()) {
705 MachineBasicBlock::iterator PI = prior(MBBI);
706 unsigned Opc = PI->getOpcode();
708 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
709 !PI->getDesc().isTerminator())
715 DL = MBBI->getDebugLoc();
717 // If there is an ADD32ri or SUB32ri of ESP immediately before this
718 // instruction, merge the two instructions.
719 if (NumBytes || MFI->hasVarSizedObjects())
720 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
722 // If dynamic alloca is used, then reset esp to point to the last callee-saved
723 // slot before popping them off! Same applies for the case, when stack was
725 if (RegInfo->needsStackRealignment(MF)) {
726 // We cannot use LEA here, because stack pointer was realigned. We need to
727 // deallocate local frame back.
729 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
730 MBBI = prior(LastCSPop);
733 BuildMI(MBB, MBBI, DL,
734 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
735 StackPtr).addReg(FramePtr);
736 } else if (MFI->hasVarSizedObjects()) {
738 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
740 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
741 FramePtr, false, -CSSize);
742 MBB.insert(MBBI, MI);
744 BuildMI(MBB, MBBI, DL,
745 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
748 } else if (NumBytes) {
749 // Adjust stack pointer back: ESP += numbytes.
750 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
753 // We're returning from function via eh_return.
754 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
755 MBBI = MBB.getLastNonDebugInstr();
756 MachineOperand &DestAddr = MBBI->getOperand(0);
757 assert(DestAddr.isReg() && "Offset should be in register!");
758 BuildMI(MBB, MBBI, DL,
759 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
760 StackPtr).addReg(DestAddr.getReg());
761 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
762 RetOpcode == X86::TCRETURNmi ||
763 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
764 RetOpcode == X86::TCRETURNmi64) {
765 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
766 // Tail call return: adjust the stack pointer and jump to callee.
767 MBBI = MBB.getLastNonDebugInstr();
768 MachineOperand &JumpTarget = MBBI->getOperand(0);
769 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
770 assert(StackAdjust.isImm() && "Expecting immediate value.");
772 // Adjust stack pointer.
773 int StackAdj = StackAdjust.getImm();
774 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
776 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
778 // Incoporate the retaddr area.
779 Offset = StackAdj-MaxTCDelta;
780 assert(Offset >= 0 && "Offset should never be negative");
783 // Check for possible merge with preceeding ADD instruction.
784 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
785 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
788 // Jump to label or value in register.
789 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
790 MachineInstrBuilder MIB =
791 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
792 ? X86::TAILJMPd : X86::TAILJMPd64));
793 if (JumpTarget.isGlobal())
794 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
795 JumpTarget.getTargetFlags());
797 assert(JumpTarget.isSymbol());
798 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
799 JumpTarget.getTargetFlags());
801 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
802 MachineInstrBuilder MIB =
803 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
804 ? X86::TAILJMPm : X86::TAILJMPm64));
805 for (unsigned i = 0; i != 5; ++i)
806 MIB.addOperand(MBBI->getOperand(i));
807 } else if (RetOpcode == X86::TCRETURNri64) {
808 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
809 addReg(JumpTarget.getReg(), RegState::Kill);
811 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
812 addReg(JumpTarget.getReg(), RegState::Kill);
815 MachineInstr *NewMI = prior(MBBI);
816 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
817 NewMI->addOperand(MBBI->getOperand(i));
819 // Delete the pseudo instruction TCRETURN.
821 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
822 (X86FI->getTCReturnAddrDelta() < 0)) {
823 // Add the return addr area delta back since we are not tail calling.
824 int delta = -1*X86FI->getTCReturnAddrDelta();
825 MBBI = MBB.getLastNonDebugInstr();
827 // Check for possible merge with preceeding ADD instruction.
828 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
829 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
834 X86FrameLowering::getInitialFrameState(std::vector<MachineMove> &Moves) const {
835 // Calculate amount of bytes used for return address storing
836 int stackGrowth = (STI.is64Bit() ? -8 : -4);
837 const X86RegisterInfo *RI = TM.getRegisterInfo();
839 // Initial state of the frame pointer is esp+stackGrowth.
840 MachineLocation Dst(MachineLocation::VirtualFP);
841 MachineLocation Src(RI->getStackRegister(), stackGrowth);
842 Moves.push_back(MachineMove(0, Dst, Src));
844 // Add return address to move list
845 MachineLocation CSDst(RI->getStackRegister(), stackGrowth);
846 MachineLocation CSSrc(RI->getRARegister());
847 Moves.push_back(MachineMove(0, CSDst, CSSrc));
850 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
851 const X86RegisterInfo *RI =
852 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
853 const MachineFrameInfo *MFI = MF.getFrameInfo();
854 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
855 uint64_t StackSize = MFI->getStackSize();
857 if (RI->needsStackRealignment(MF)) {
859 // Skip the saved EBP.
860 Offset += RI->getSlotSize();
862 unsigned Align = MFI->getObjectAlignment(FI);
863 assert((-(Offset + StackSize)) % Align == 0);
865 return Offset + StackSize;
867 // FIXME: Support tail calls
870 return Offset + StackSize;
872 // Skip the saved EBP.
873 Offset += RI->getSlotSize();
875 // Skip the RETADDR move area
876 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
877 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
878 if (TailCallReturnAddrDelta < 0)
879 Offset -= TailCallReturnAddrDelta;
885 bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
886 MachineBasicBlock::iterator MI,
887 const std::vector<CalleeSavedInfo> &CSI,
888 const TargetRegisterInfo *TRI) const {
892 DebugLoc DL = MBB.findDebugLoc(MI);
894 MachineFunction &MF = *MBB.getParent();
896 bool isWin64 = STI.isTargetWin64();
897 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
898 unsigned FPReg = TRI->getFrameRegister(MF);
899 unsigned CalleeFrameSize = 0;
901 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
902 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
904 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
905 for (unsigned i = CSI.size(); i != 0; --i) {
906 unsigned Reg = CSI[i-1].getReg();
907 // Add the callee-saved register as live-in. It's killed at the spill.
910 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
912 if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
913 CalleeFrameSize += SlotSize;
914 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill);
916 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
917 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
922 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
926 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
927 MachineBasicBlock::iterator MI,
928 const std::vector<CalleeSavedInfo> &CSI,
929 const TargetRegisterInfo *TRI) const {
933 DebugLoc DL = MBB.findDebugLoc(MI);
935 MachineFunction &MF = *MBB.getParent();
936 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
937 unsigned FPReg = TRI->getFrameRegister(MF);
938 bool isWin64 = STI.isTargetWin64();
939 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
940 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
941 unsigned Reg = CSI[i].getReg();
943 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
945 if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
946 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
948 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
949 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
957 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
958 RegScavenger *RS) const {
959 MachineFrameInfo *MFI = MF.getFrameInfo();
960 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
961 unsigned SlotSize = RegInfo->getSlotSize();
963 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
964 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
966 if (TailCallReturnAddrDelta < 0) {
967 // create RETURNADDR area
976 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
977 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
981 assert((TailCallReturnAddrDelta <= 0) &&
982 "The Delta should always be zero or negative");
983 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
985 // Create a frame entry for the EBP register that must be saved.
986 int FrameIdx = MFI->CreateFixedObject(SlotSize,
988 TFI.getOffsetOfLocalArea() +
989 TailCallReturnAddrDelta,
991 assert(FrameIdx == MFI->getObjectIndexBegin() &&
992 "Slot for EBP register must be last in order to be found!");