blob: a25643b2e2ebe74b2f337d1f32587508e4c3b606 [file] [log] [blame]
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001//===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the X86 implementation of TargetFrameLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86FrameLowering.h"
15#include "X86InstrBuilder.h"
16#include "X86InstrInfo.h"
17#include "X86MachineFunctionInfo.h"
18#include "X86Subtarget.h"
19#include "X86TargetMachine.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCSymbol.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Target/TargetOptions.h"
32#include "llvm/Support/Debug.h"
33#include <cstdlib>
34
35using namespace llvm;
36
37// FIXME: completely move here.
38extern cl::opt<bool> ForceStackAlign;
39
40bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Michael Kuperstein13fbd452015-02-01 16:56:04 +000041 return !MF.getFrameInfo()->hasVarSizedObjects() &&
42 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
43}
44
45/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
46/// call frame pseudos can be simplified. Having a FP, as in the default
47/// implementation, is not sufficient here since we can't always use it.
48/// Use a more nuanced condition.
49bool
50X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
51 const X86RegisterInfo *TRI = static_cast<const X86RegisterInfo *>
52 (MF.getSubtarget().getRegisterInfo());
53 return hasReservedCallFrame(MF) ||
54 (hasFP(MF) && !TRI->needsStackRealignment(MF))
55 || TRI->hasBasePointer(MF);
56}
57
58// needsFrameIndexResolution - Do we need to perform FI resolution for
59// this function. Normally, this is required only when the function
60// has any stack objects. However, FI resolution actually has another job,
61// not apparent from the title - it resolves callframesetup/destroy
62// that were not simplified earlier.
63// So, this is required for x86 functions that have push sequences even
64// when there are no stack objects.
65bool
66X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
67 return MF.getFrameInfo()->hasStackObjects() ||
68 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000069}
70
71/// hasFP - Return true if the specified function should have a dedicated frame
72/// pointer register. This is true if the function has variable sized allocas
73/// or if frame pointer elimination is disabled.
74bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
75 const MachineFrameInfo *MFI = MF.getFrameInfo();
76 const MachineModuleInfo &MMI = MF.getMMI();
77 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
78
79 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
80 RegInfo->needsStackRealignment(MF) ||
81 MFI->hasVarSizedObjects() ||
82 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
83 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
84 MMI.callsUnwindInit() || MMI.callsEHReturn() ||
85 MFI->hasStackMap() || MFI->hasPatchPoint());
86}
87
88static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
89 if (IsLP64) {
90 if (isInt<8>(Imm))
91 return X86::SUB64ri8;
92 return X86::SUB64ri32;
93 } else {
94 if (isInt<8>(Imm))
95 return X86::SUB32ri8;
96 return X86::SUB32ri;
97 }
98}
99
100static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
101 if (IsLP64) {
102 if (isInt<8>(Imm))
103 return X86::ADD64ri8;
104 return X86::ADD64ri32;
105 } else {
106 if (isInt<8>(Imm))
107 return X86::ADD32ri8;
108 return X86::ADD32ri;
109 }
110}
111
112static unsigned getSUBrrOpcode(unsigned isLP64) {
113 return isLP64 ? X86::SUB64rr : X86::SUB32rr;
114}
115
116static unsigned getADDrrOpcode(unsigned isLP64) {
117 return isLP64 ? X86::ADD64rr : X86::ADD32rr;
118}
119
120static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
121 if (IsLP64) {
122 if (isInt<8>(Imm))
123 return X86::AND64ri8;
124 return X86::AND64ri32;
125 }
126 if (isInt<8>(Imm))
127 return X86::AND32ri8;
128 return X86::AND32ri;
129}
130
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000131static unsigned getLEArOpcode(unsigned IsLP64) {
132 return IsLP64 ? X86::LEA64r : X86::LEA32r;
133}
134
135/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
136/// when it reaches the "return" instruction. We can then pop a stack object
137/// to this register without worry about clobbering it.
138static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
139 MachineBasicBlock::iterator &MBBI,
140 const TargetRegisterInfo &TRI,
141 bool Is64Bit) {
142 const MachineFunction *MF = MBB.getParent();
143 const Function *F = MF->getFunction();
144 if (!F || MF->getMMI().callsEHReturn())
145 return 0;
146
147 static const uint16_t CallerSavedRegs32Bit[] = {
148 X86::EAX, X86::EDX, X86::ECX, 0
149 };
150
151 static const uint16_t CallerSavedRegs64Bit[] = {
152 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
153 X86::R8, X86::R9, X86::R10, X86::R11, 0
154 };
155
156 unsigned Opc = MBBI->getOpcode();
157 switch (Opc) {
158 default: return 0;
159 case X86::RETL:
160 case X86::RETQ:
161 case X86::RETIL:
162 case X86::RETIQ:
163 case X86::TCRETURNdi:
164 case X86::TCRETURNri:
165 case X86::TCRETURNmi:
166 case X86::TCRETURNdi64:
167 case X86::TCRETURNri64:
168 case X86::TCRETURNmi64:
169 case X86::EH_RETURN:
170 case X86::EH_RETURN64: {
171 SmallSet<uint16_t, 8> Uses;
172 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
173 MachineOperand &MO = MBBI->getOperand(i);
174 if (!MO.isReg() || MO.isDef())
175 continue;
176 unsigned Reg = MO.getReg();
177 if (!Reg)
178 continue;
179 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
180 Uses.insert(*AI);
181 }
182
183 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
184 for (; *CS; ++CS)
185 if (!Uses.count(*CS))
186 return *CS;
187 }
188 }
189
190 return 0;
191}
192
193static bool isEAXLiveIn(MachineFunction &MF) {
194 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
195 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
196 unsigned Reg = II->first;
197
198 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
199 Reg == X86::AH || Reg == X86::AL)
200 return true;
201 }
202
203 return false;
204}
205
206/// emitSPUpdate - Emit a series of instructions to increment / decrement the
207/// stack pointer by a constant value.
208static
209void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
210 unsigned StackPtr, int64_t NumBytes,
211 bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
212 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
213 bool isSub = NumBytes < 0;
214 uint64_t Offset = isSub ? -NumBytes : NumBytes;
215 unsigned Opc;
216 if (UseLEA)
217 Opc = getLEArOpcode(Is64BitStackPtr);
218 else
219 Opc = isSub
220 ? getSUBriOpcode(Is64BitStackPtr, Offset)
221 : getADDriOpcode(Is64BitStackPtr, Offset);
222
223 uint64_t Chunk = (1LL << 31) - 1;
224 DebugLoc DL = MBB.findDebugLoc(MBBI);
225
226 while (Offset) {
227 if (Offset > Chunk) {
228 // Rather than emit a long series of instructions for large offsets,
229 // load the offset into a register and do one sub/add
230 unsigned Reg = 0;
231
232 if (isSub && !isEAXLiveIn(*MBB.getParent()))
233 Reg = (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX);
234 else
235 Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
236
237 if (Reg) {
238 Opc = Is64BitTarget ? X86::MOV64ri : X86::MOV32ri;
239 BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
240 .addImm(Offset);
241 Opc = isSub
242 ? getSUBrrOpcode(Is64BitTarget)
243 : getADDrrOpcode(Is64BitTarget);
244 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
245 .addReg(StackPtr)
246 .addReg(Reg);
247 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
248 Offset = 0;
249 continue;
250 }
251 }
252
David Majnemer3aa0bd82015-02-24 00:11:32 +0000253 uint64_t ThisVal = std::min(Offset, Chunk);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000254 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
255 // Use push / pop instead.
256 unsigned Reg = isSub
257 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
258 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
259 if (Reg) {
260 Opc = isSub
261 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
262 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
263 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
264 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
265 if (isSub)
266 MI->setFlag(MachineInstr::FrameSetup);
267 Offset -= ThisVal;
268 continue;
269 }
270 }
271
272 MachineInstr *MI = nullptr;
273
274 if (UseLEA) {
275 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
276 StackPtr, false, isSub ? -ThisVal : ThisVal);
277 } else {
278 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
279 .addReg(StackPtr)
280 .addImm(ThisVal);
281 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
282 }
283
284 if (isSub)
285 MI->setFlag(MachineInstr::FrameSetup);
286
287 Offset -= ThisVal;
288 }
289}
290
291/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
292static
293void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
294 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
295 if (MBBI == MBB.begin()) return;
296
297 MachineBasicBlock::iterator PI = std::prev(MBBI);
298 unsigned Opc = PI->getOpcode();
299 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
300 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
301 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
302 PI->getOperand(0).getReg() == StackPtr) {
303 if (NumBytes)
304 *NumBytes += PI->getOperand(2).getImm();
305 MBB.erase(PI);
306 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
307 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
308 PI->getOperand(0).getReg() == StackPtr) {
309 if (NumBytes)
310 *NumBytes -= PI->getOperand(2).getImm();
311 MBB.erase(PI);
312 }
313}
314
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000315/// mergeSPUpdates - Checks the instruction before/after the passed
316/// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
317/// the stack adjustment is returned as a positive value for ADD/LEA and a
318/// negative for SUB.
319static int mergeSPUpdates(MachineBasicBlock &MBB,
320 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
321 bool doMergeWithPrevious) {
322 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
323 (!doMergeWithPrevious && MBBI == MBB.end()))
324 return 0;
325
326 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
327 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
328 : std::next(MBBI);
329 unsigned Opc = PI->getOpcode();
330 int Offset = 0;
331
332 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
333 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
334 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
335 PI->getOperand(0).getReg() == StackPtr){
336 Offset += PI->getOperand(2).getImm();
337 MBB.erase(PI);
338 if (!doMergeWithPrevious) MBBI = NI;
339 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
340 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
341 PI->getOperand(0).getReg() == StackPtr) {
342 Offset -= PI->getOperand(2).getImm();
343 MBB.erase(PI);
344 if (!doMergeWithPrevious) MBBI = NI;
345 }
346
347 return Offset;
348}
349
350void
351X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
352 MachineBasicBlock::iterator MBBI,
353 DebugLoc DL) const {
354 MachineFunction &MF = *MBB.getParent();
355 MachineFrameInfo *MFI = MF.getFrameInfo();
356 MachineModuleInfo &MMI = MF.getMMI();
357 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
358 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
359
360 // Add callee saved registers to move list.
361 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
362 if (CSI.empty()) return;
363
364 // Calculate offsets.
365 for (std::vector<CalleeSavedInfo>::const_iterator
366 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
367 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
368 unsigned Reg = I->getReg();
369
370 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
371 unsigned CFIIndex =
372 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
373 Offset));
374 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
375 .addCFIIndex(CFIIndex);
376 }
377}
378
379/// usesTheStack - This function checks if any of the users of EFLAGS
380/// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
381/// to use the stack, and if we don't adjust the stack we clobber the first
382/// frame index.
383/// See X86InstrInfo::copyPhysReg.
384static bool usesTheStack(const MachineFunction &MF) {
385 const MachineRegisterInfo &MRI = MF.getRegInfo();
386
387 for (MachineRegisterInfo::reg_instr_iterator
388 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
389 ri != re; ++ri)
390 if (ri->isCopy())
391 return true;
392
393 return false;
394}
395
396void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
397 MachineBasicBlock &MBB,
398 MachineBasicBlock::iterator MBBI,
399 DebugLoc DL) {
Eric Christopher05b81972015-02-02 17:38:43 +0000400 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
401 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000402 bool Is64Bit = STI.is64Bit();
403 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
404
405 unsigned CallOp;
406 if (Is64Bit)
407 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
408 else
409 CallOp = X86::CALLpcrel32;
410
411 const char *Symbol;
412 if (Is64Bit) {
413 if (STI.isTargetCygMing()) {
414 Symbol = "___chkstk_ms";
415 } else {
416 Symbol = "__chkstk";
417 }
418 } else if (STI.isTargetCygMing())
419 Symbol = "_alloca";
420 else
421 Symbol = "_chkstk";
422
423 MachineInstrBuilder CI;
424
425 // All current stack probes take AX and SP as input, clobber flags, and
426 // preserve all registers. x86_64 probes leave RSP unmodified.
427 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
428 // For the large code model, we have to call through a register. Use R11,
429 // as it is scratch in all supported calling conventions.
430 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
431 .addExternalSymbol(Symbol);
432 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
433 } else {
434 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
435 }
436
437 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
438 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
439 CI.addReg(AX, RegState::Implicit)
440 .addReg(SP, RegState::Implicit)
441 .addReg(AX, RegState::Define | RegState::Implicit)
442 .addReg(SP, RegState::Define | RegState::Implicit)
443 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
444
445 if (Is64Bit) {
446 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
447 // themselves. It also does not clobber %rax so we can reuse it when
448 // adjusting %rsp.
449 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
450 .addReg(X86::RSP)
451 .addReg(X86::RAX);
452 }
453}
454
David Majnemer93c22a42015-02-10 00:57:42 +0000455static unsigned calculateSetFPREG(uint64_t SPAdjust) {
456 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
457 // and might require smaller successive adjustments.
458 const uint64_t Win64MaxSEHOffset = 128;
459 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
460 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
David Majnemer89d05642015-02-21 01:04:47 +0000461 return SEHFrameOffset & -16;
David Majnemer93c22a42015-02-10 00:57:42 +0000462}
463
464// If we're forcing a stack realignment we can't rely on just the frame
465// info, we need to know the ABI stack alignment as well in case we
466// have a call out. Otherwise just make sure we have some alignment - we'll
467// go with the minimum SlotSize.
468static uint64_t calculateMaxStackAlign(const MachineFunction &MF) {
469 const MachineFrameInfo *MFI = MF.getFrameInfo();
470 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
471 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
472 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
473 unsigned SlotSize = RegInfo->getSlotSize();
474 unsigned StackAlign = STI.getFrameLowering()->getStackAlignment();
475 if (ForceStackAlign) {
476 if (MFI->hasCalls())
477 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
478 else if (MaxAlign < SlotSize)
479 MaxAlign = SlotSize;
480 }
481 return MaxAlign;
482}
483
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000484/// emitPrologue - Push callee-saved registers onto the stack, which
485/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
486/// space for local variables. Also emit labels used by the exception handler to
487/// generate the exception handling frames.
488
489/*
490 Here's a gist of what gets emitted:
491
492 ; Establish frame pointer, if needed
493 [if needs FP]
494 push %rbp
495 .cfi_def_cfa_offset 16
496 .cfi_offset %rbp, -16
497 .seh_pushreg %rpb
498 mov %rsp, %rbp
499 .cfi_def_cfa_register %rbp
500
501 ; Spill general-purpose registers
502 [for all callee-saved GPRs]
503 pushq %<reg>
504 [if not needs FP]
505 .cfi_def_cfa_offset (offset from RETADDR)
506 .seh_pushreg %<reg>
507
508 ; If the required stack alignment > default stack alignment
509 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
510 ; of unknown size in the stack frame.
511 [if stack needs re-alignment]
512 and $MASK, %rsp
513
514 ; Allocate space for locals
515 [if target is Windows and allocated space > 4096 bytes]
516 ; Windows needs special care for allocations larger
517 ; than one page.
518 mov $NNN, %rax
519 call ___chkstk_ms/___chkstk
520 sub %rax, %rsp
521 [else]
522 sub $NNN, %rsp
523
524 [if needs FP]
525 .seh_stackalloc (size of XMM spill slots)
526 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
527 [else]
528 .seh_stackalloc NNN
529
530 ; Spill XMMs
531 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
532 ; they may get spilled on any platform, if the current function
533 ; calls @llvm.eh.unwind.init
534 [if needs FP]
535 [for all callee-saved XMM registers]
536 movaps %<xmm reg>, -MMM(%rbp)
537 [for all callee-saved XMM registers]
538 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
539 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
540 [else]
541 [for all callee-saved XMM registers]
542 movaps %<xmm reg>, KKK(%rsp)
543 [for all callee-saved XMM registers]
544 .seh_savexmm %<xmm reg>, KKK
545
546 .seh_endprologue
547
548 [if needs base pointer]
549 mov %rsp, %rbx
550 [if needs to restore base pointer]
551 mov %rsp, -MMM(%rbp)
552
553 ; Emit CFI info
554 [if needs FP]
555 [for all callee-saved registers]
556 .cfi_offset %<reg>, (offset from %rbp)
557 [else]
558 .cfi_def_cfa_offset (offset from RETADDR)
559 [for all callee-saved registers]
560 .cfi_offset %<reg>, (offset from %rsp)
561
562 Notes:
563 - .seh directives are emitted only for Windows 64 ABI
564 - .cfi directives are emitted for all other ABIs
565 - for 32-bit code, substitute %e?? registers for %r??
566*/
567
Quentin Colombet61b305e2015-05-05 17:38:16 +0000568void X86FrameLowering::emitPrologue(MachineFunction &MF,
569 MachineBasicBlock &MBB) const {
570 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000571 MachineBasicBlock::iterator MBBI = MBB.begin();
572 MachineFrameInfo *MFI = MF.getFrameInfo();
573 const Function *Fn = MF.getFunction();
Eric Christopher05b81972015-02-02 17:38:43 +0000574 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
575 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
576 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000577 MachineModuleInfo &MMI = MF.getMMI();
578 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
David Majnemer93c22a42015-02-10 00:57:42 +0000579 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000580 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
581 bool HasFP = hasFP(MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000582 bool Is64Bit = STI.is64Bit();
583 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
584 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
Charles Davis83687fb2015-02-27 21:11:16 +0000585 bool IsWin64 = STI.isCallingConvWin64(Fn->getCallingConv());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000586 // Not necessarily synonymous with IsWin64.
587 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
588 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
589 bool NeedsDwarfCFI =
590 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
591 bool UseLEA = STI.useLeaForSP();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000592 unsigned SlotSize = RegInfo->getSlotSize();
593 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Eric Christopher05b81972015-02-02 17:38:43 +0000594 const unsigned MachineFramePtr =
595 STI.isTarget64BitILP32()
596 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
597 : FramePtr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000598 unsigned StackPtr = RegInfo->getStackRegister();
599 unsigned BasePtr = RegInfo->getBaseRegister();
600 DebugLoc DL;
601
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000602 // Add RETADDR move area to callee saved frame size.
603 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
David Majnemer93c22a42015-02-10 00:57:42 +0000604 if (TailCallReturnAddrDelta && IsWinEH)
605 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
606
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000607 if (TailCallReturnAddrDelta < 0)
608 X86FI->setCalleeSavedFrameSize(
609 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
610
611 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
612
613 // The default stack probe size is 4096 if the function has no stackprobesize
614 // attribute.
615 unsigned StackProbeSize = 4096;
616 if (Fn->hasFnAttribute("stack-probe-size"))
617 Fn->getFnAttribute("stack-probe-size")
618 .getValueAsString()
619 .getAsInteger(0, StackProbeSize);
620
621 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
622 // function, and use up to 128 bytes of stack space, don't have a frame
623 // pointer, calls, or dynamic alloca then we do not need to adjust the
624 // stack pointer (we fit in the Red Zone). We also check that we don't
625 // push and pop from the stack.
Duncan P. N. Exon Smith5975a702015-02-14 01:59:52 +0000626 if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000627 !RegInfo->needsStackRealignment(MF) &&
Duncan P. N. Exon Smith5975a702015-02-14 01:59:52 +0000628 !MFI->hasVarSizedObjects() && // No dynamic alloca.
629 !MFI->adjustsStack() && // No calls.
630 !IsWin64 && // Win64 has no Red Zone
631 !usesTheStack(MF) && // Don't push and pop.
632 !MF.shouldSplitStack()) { // Regular stack
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000633 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
634 if (HasFP) MinSize += SlotSize;
635 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
636 MFI->setStackSize(StackSize);
637 }
638
639 // Insert stack pointer adjustment for later moving of return addr. Only
640 // applies to tail call optimized functions where the callee argument stack
641 // size is bigger than the callers.
642 if (TailCallReturnAddrDelta < 0) {
643 MachineInstr *MI =
644 BuildMI(MBB, MBBI, DL,
645 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
646 StackPtr)
647 .addReg(StackPtr)
648 .addImm(-TailCallReturnAddrDelta)
649 .setMIFlag(MachineInstr::FrameSetup);
650 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
651 }
652
653 // Mapping for machine moves:
654 //
655 // DST: VirtualFP AND
656 // SRC: VirtualFP => DW_CFA_def_cfa_offset
657 // ELSE => DW_CFA_def_cfa
658 //
659 // SRC: VirtualFP AND
660 // DST: Register => DW_CFA_def_cfa_register
661 //
662 // ELSE
663 // OFFSET < 0 => DW_CFA_offset_extended_sf
664 // REG < 64 => DW_CFA_offset + Reg
665 // ELSE => DW_CFA_offset_extended
666
667 uint64_t NumBytes = 0;
668 int stackGrowth = -SlotSize;
669
670 if (HasFP) {
671 // Calculate required stack adjustment.
672 uint64_t FrameSize = StackSize - SlotSize;
673 // If required, include space for extra hidden slot for stashing base pointer.
674 if (X86FI->getRestoreBasePointer())
675 FrameSize += SlotSize;
David Majnemer89d05642015-02-21 01:04:47 +0000676
677 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
678
679 // Callee-saved registers are pushed on stack before the stack is realigned.
680 if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
681 NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000682
683 // Get the offset of the stack slot for the EBP register, which is
684 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
685 // Update the frame offset adjustment.
686 MFI->setOffsetAdjustment(-NumBytes);
687
688 // Save EBP/RBP into the appropriate stack slot.
689 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
690 .addReg(MachineFramePtr, RegState::Kill)
691 .setMIFlag(MachineInstr::FrameSetup);
692
693 if (NeedsDwarfCFI) {
694 // Mark the place where EBP/RBP was saved.
695 // Define the current CFA rule to use the provided offset.
696 assert(StackSize);
697 unsigned CFIIndex = MMI.addFrameInst(
698 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
699 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
700 .addCFIIndex(CFIIndex);
701
702 // Change the rule for the FramePtr to be an "offset" rule.
703 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
704 CFIIndex = MMI.addFrameInst(
705 MCCFIInstruction::createOffset(nullptr,
706 DwarfFramePtr, 2 * stackGrowth));
707 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
708 .addCFIIndex(CFIIndex);
709 }
710
711 if (NeedsWinEH) {
712 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
713 .addImm(FramePtr)
714 .setMIFlag(MachineInstr::FrameSetup);
715 }
716
David Majnemer93c22a42015-02-10 00:57:42 +0000717 if (!IsWinEH) {
718 // Update EBP with the new base value.
719 BuildMI(MBB, MBBI, DL,
720 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
721 FramePtr)
722 .addReg(StackPtr)
723 .setMIFlag(MachineInstr::FrameSetup);
724 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000725
726 if (NeedsDwarfCFI) {
727 // Mark effective beginning of when frame pointer becomes valid.
728 // Define the current CFA to use the EBP/RBP register.
729 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
730 unsigned CFIIndex = MMI.addFrameInst(
731 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
732 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
733 .addCFIIndex(CFIIndex);
734 }
735
736 // Mark the FramePtr as live-in in every block.
737 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
738 I->addLiveIn(MachineFramePtr);
739 } else {
740 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
741 }
742
743 // Skip the callee-saved push instructions.
744 bool PushedRegs = false;
745 int StackOffset = 2 * stackGrowth;
746
747 while (MBBI != MBB.end() &&
748 (MBBI->getOpcode() == X86::PUSH32r ||
749 MBBI->getOpcode() == X86::PUSH64r)) {
750 PushedRegs = true;
751 unsigned Reg = MBBI->getOperand(0).getReg();
752 ++MBBI;
753
754 if (!HasFP && NeedsDwarfCFI) {
755 // Mark callee-saved push instruction.
756 // Define the current CFA rule to use the provided offset.
757 assert(StackSize);
758 unsigned CFIIndex = MMI.addFrameInst(
759 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
760 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
761 .addCFIIndex(CFIIndex);
762 StackOffset += stackGrowth;
763 }
764
765 if (NeedsWinEH) {
766 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
767 MachineInstr::FrameSetup);
768 }
769 }
770
771 // Realign stack after we pushed callee-saved registers (so that we'll be
772 // able to calculate their offsets from the frame pointer).
David Majnemer93c22a42015-02-10 00:57:42 +0000773 // Don't do this for Win64, it needs to realign the stack after the prologue.
774 if (!IsWinEH && RegInfo->needsStackRealignment(MF)) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000775 assert(HasFP && "There should be a frame pointer if stack is realigned.");
776 uint64_t Val = -MaxAlign;
777 MachineInstr *MI =
David Majnemer93c22a42015-02-10 00:57:42 +0000778 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
779 StackPtr)
780 .addReg(StackPtr)
781 .addImm(Val)
782 .setMIFlag(MachineInstr::FrameSetup);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000783
784 // The EFLAGS implicit def is dead.
785 MI->getOperand(3).setIsDead();
786 }
787
788 // If there is an SUB32ri of ESP immediately before this instruction, merge
789 // the two. This can be the case when tail call elimination is enabled and
790 // the callee has more arguments then the caller.
791 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
792
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000793 // Adjust stack pointer: ESP -= numbytes.
794
795 // Windows and cygwin/mingw require a prologue helper routine when allocating
796 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
797 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
798 // stack and adjust the stack pointer in one go. The 64-bit version of
799 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
800 // responsible for adjusting the stack pointer. Touching the stack at 4K
801 // increments is necessary to ensure that the guard pages used by the OS
802 // virtual memory manager are allocated in correct sequence.
David Majnemer89d05642015-02-21 01:04:47 +0000803 uint64_t AlignedNumBytes = NumBytes;
804 if (IsWinEH && RegInfo->needsStackRealignment(MF))
805 AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
806 if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000807 // Check whether EAX is livein for this function.
808 bool isEAXAlive = isEAXLiveIn(MF);
809
810 if (isEAXAlive) {
811 // Sanity check that EAX is not livein for this function.
812 // It should not be, so throw an assert.
813 assert(!Is64Bit && "EAX is livein in x64 case!");
814
815 // Save EAX
816 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
817 .addReg(X86::EAX, RegState::Kill)
818 .setMIFlag(MachineInstr::FrameSetup);
819 }
820
821 if (Is64Bit) {
822 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
823 // Function prologue is responsible for adjusting the stack pointer.
David Majnemer006c4902015-02-23 21:50:30 +0000824 if (isUInt<32>(NumBytes)) {
825 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
826 .addImm(NumBytes)
827 .setMIFlag(MachineInstr::FrameSetup);
828 } else if (isInt<32>(NumBytes)) {
829 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
830 .addImm(NumBytes)
831 .setMIFlag(MachineInstr::FrameSetup);
832 } else {
833 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
834 .addImm(NumBytes)
835 .setMIFlag(MachineInstr::FrameSetup);
836 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000837 } else {
838 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
839 // We'll also use 4 already allocated bytes for EAX.
840 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
841 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
842 .setMIFlag(MachineInstr::FrameSetup);
843 }
844
845 // Save a pointer to the MI where we set AX.
846 MachineBasicBlock::iterator SetRAX = MBBI;
847 --SetRAX;
848
849 // Call __chkstk, __chkstk_ms, or __alloca.
850 emitStackProbeCall(MF, MBB, MBBI, DL);
851
852 // Apply the frame setup flag to all inserted instrs.
853 for (; SetRAX != MBBI; ++SetRAX)
854 SetRAX->setFlag(MachineInstr::FrameSetup);
855
856 if (isEAXAlive) {
857 // Restore EAX
858 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
859 X86::EAX),
860 StackPtr, false, NumBytes - 4);
861 MI->setFlag(MachineInstr::FrameSetup);
862 MBB.insert(MBBI, MI);
863 }
864 } else if (NumBytes) {
865 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
866 UseLEA, TII, *RegInfo);
867 }
868
David Majnemer93c22a42015-02-10 00:57:42 +0000869 if (NeedsWinEH && NumBytes)
870 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
871 .addImm(NumBytes)
872 .setMIFlag(MachineInstr::FrameSetup);
873
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000874 int SEHFrameOffset = 0;
David Majnemer93c22a42015-02-10 00:57:42 +0000875 if (IsWinEH && HasFP) {
876 SEHFrameOffset = calculateSetFPREG(NumBytes);
David Majnemer31d868b2015-02-23 21:50:27 +0000877 if (SEHFrameOffset)
878 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
879 StackPtr, false, SEHFrameOffset);
880 else
881 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr).addReg(StackPtr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000882
David Majnemer93c22a42015-02-10 00:57:42 +0000883 if (NeedsWinEH)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000884 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
885 .addImm(FramePtr)
886 .addImm(SEHFrameOffset)
887 .setMIFlag(MachineInstr::FrameSetup);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000888 }
889
David Majnemera7d908e2015-02-10 19:01:47 +0000890 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
891 const MachineInstr *FrameInstr = &*MBBI;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000892 ++MBBI;
893
David Majnemera7d908e2015-02-10 19:01:47 +0000894 if (NeedsWinEH) {
895 int FI;
896 if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
897 if (X86::FR64RegClass.contains(Reg)) {
898 int Offset = getFrameIndexOffset(MF, FI);
899 Offset += SEHFrameOffset;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000900
David Majnemera7d908e2015-02-10 19:01:47 +0000901 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
902 .addImm(Reg)
903 .addImm(Offset)
904 .setMIFlag(MachineInstr::FrameSetup);
905 }
906 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000907 }
David Majnemera7d908e2015-02-10 19:01:47 +0000908 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000909
David Majnemera7d908e2015-02-10 19:01:47 +0000910 if (NeedsWinEH)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000911 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
912 .setMIFlag(MachineInstr::FrameSetup);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000913
David Majnemer93c22a42015-02-10 00:57:42 +0000914 // Realign stack after we spilled callee-saved registers (so that we'll be
915 // able to calculate their offsets from the frame pointer).
916 // Win64 requires aligning the stack after the prologue.
917 if (IsWinEH && RegInfo->needsStackRealignment(MF)) {
918 assert(HasFP && "There should be a frame pointer if stack is realigned.");
919 uint64_t Val = -MaxAlign;
920 MachineInstr *MI =
921 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
922 StackPtr)
923 .addReg(StackPtr)
924 .addImm(Val)
925 .setMIFlag(MachineInstr::FrameSetup);
926
927 // The EFLAGS implicit def is dead.
928 MI->getOperand(3).setIsDead();
929 }
930
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000931 // If we need a base pointer, set it up here. It's whatever the value
932 // of the stack pointer is at this point. Any variable size objects
933 // will be allocated after this, so we can still use the base pointer
934 // to reference locals.
935 if (RegInfo->hasBasePointer(MF)) {
936 // Update the base pointer with the current stack pointer.
937 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
938 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
939 .addReg(StackPtr)
940 .setMIFlag(MachineInstr::FrameSetup);
941 if (X86FI->getRestoreBasePointer()) {
942 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
943 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
944 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
945 FramePtr, true, X86FI->getRestoreBasePointerOffset())
946 .addReg(StackPtr)
947 .setMIFlag(MachineInstr::FrameSetup);
948 }
949 }
950
951 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
952 // Mark end of stack pointer adjustment.
953 if (!HasFP && NumBytes) {
954 // Define the current CFA rule to use the provided offset.
955 assert(StackSize);
956 unsigned CFIIndex = MMI.addFrameInst(
957 MCCFIInstruction::createDefCfaOffset(nullptr,
958 -StackSize + stackGrowth));
959
960 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
961 .addCFIIndex(CFIIndex);
962 }
963
964 // Emit DWARF info specifying the offsets of the callee-saved registers.
965 if (PushedRegs)
966 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
967 }
968}
969
970void X86FrameLowering::emitEpilogue(MachineFunction &MF,
971 MachineBasicBlock &MBB) const {
972 const MachineFrameInfo *MFI = MF.getFrameInfo();
973 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Eric Christopher05b81972015-02-02 17:38:43 +0000974 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
975 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
976 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000977 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
978 assert(MBBI != MBB.end() && "Returning block has no instructions");
979 unsigned RetOpcode = MBBI->getOpcode();
980 DebugLoc DL = MBBI->getDebugLoc();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000981 bool Is64Bit = STI.is64Bit();
982 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
983 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
David Majnemer3aa0bd82015-02-24 00:11:32 +0000984 bool HasFP = hasFP(MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000985 const bool Is64BitILP32 = STI.isTarget64BitILP32();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000986 unsigned SlotSize = RegInfo->getSlotSize();
987 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Eric Christopher05b81972015-02-02 17:38:43 +0000988 unsigned MachineFramePtr =
989 Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
990 : FramePtr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000991 unsigned StackPtr = RegInfo->getStackRegister();
992
993 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
994 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
David Majnemer3aa0bd82015-02-24 00:11:32 +0000995 bool UseLEAForSP = false;
996
997 // We can't use LEA instructions for adjusting the stack pointer if this is a
998 // leaf function in the Win64 ABI. Only ADD instructions may be used to
999 // deallocate the stack.
1000 if (STI.useLeaForSP()) {
1001 if (!IsWinEH) {
1002 // We *aren't* using the Win64 ABI which means we are free to use LEA.
1003 UseLEAForSP = true;
1004 } else if (HasFP) {
1005 // We *have* a frame pointer which means we are permitted to use LEA.
1006 UseLEAForSP = true;
1007 }
1008 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001009
1010 switch (RetOpcode) {
1011 default:
David Majnemer086f6a72015-02-23 21:50:18 +00001012 llvm_unreachable("Can only insert epilogue into returning blocks");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001013 case X86::RETQ:
1014 case X86::RETL:
1015 case X86::RETIL:
1016 case X86::RETIQ:
1017 case X86::TCRETURNdi:
1018 case X86::TCRETURNri:
1019 case X86::TCRETURNmi:
1020 case X86::TCRETURNdi64:
1021 case X86::TCRETURNri64:
1022 case X86::TCRETURNmi64:
1023 case X86::EH_RETURN:
1024 case X86::EH_RETURN64:
1025 break; // These are ok
1026 }
1027
1028 // Get the number of bytes to allocate from the FrameInfo.
1029 uint64_t StackSize = MFI->getStackSize();
David Majnemer93c22a42015-02-10 00:57:42 +00001030 uint64_t MaxAlign = calculateMaxStackAlign(MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001031 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1032 uint64_t NumBytes = 0;
1033
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001034 if (hasFP(MF)) {
1035 // Calculate required stack adjustment.
1036 uint64_t FrameSize = StackSize - SlotSize;
David Majnemer89d05642015-02-21 01:04:47 +00001037 NumBytes = FrameSize - CSSize;
1038
1039 // Callee-saved registers were pushed on stack before the stack was
1040 // realigned.
1041 if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
1042 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001043
1044 // Pop EBP.
1045 BuildMI(MBB, MBBI, DL,
1046 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1047 } else {
1048 NumBytes = StackSize - CSSize;
1049 }
David Majnemer93c22a42015-02-10 00:57:42 +00001050 uint64_t SEHStackAllocAmt = NumBytes;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001051
1052 // Skip the callee-saved pop instructions.
1053 while (MBBI != MBB.begin()) {
1054 MachineBasicBlock::iterator PI = std::prev(MBBI);
1055 unsigned Opc = PI->getOpcode();
1056
1057 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1058 !PI->isTerminator())
1059 break;
1060
1061 --MBBI;
1062 }
1063 MachineBasicBlock::iterator FirstCSPop = MBBI;
1064
1065 DL = MBBI->getDebugLoc();
1066
1067 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1068 // instruction, merge the two instructions.
1069 if (NumBytes || MFI->hasVarSizedObjects())
1070 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1071
1072 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1073 // slot before popping them off! Same applies for the case, when stack was
1074 // realigned.
1075 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1076 if (RegInfo->needsStackRealignment(MF))
1077 MBBI = FirstCSPop;
David Majnemere1bbad92015-02-25 21:13:37 +00001078 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1079 uint64_t LEAAmount = IsWinEH ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1080
1081 // There are only two legal forms of epilogue:
1082 // - add SEHAllocationSize, %rsp
1083 // - lea SEHAllocationSize(%FramePtr), %rsp
1084 //
1085 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1086 // However, we may use this sequence if we have a frame pointer because the
1087 // effects of the prologue can safely be undone.
1088 if (LEAAmount != 0) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001089 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1090 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
David Majnemere1bbad92015-02-25 21:13:37 +00001091 FramePtr, false, LEAAmount);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001092 --MBBI;
1093 } else {
1094 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1095 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1096 .addReg(FramePtr);
1097 --MBBI;
1098 }
1099 } else if (NumBytes) {
1100 // Adjust stack pointer back: ESP += numbytes.
David Majnemer3aa0bd82015-02-24 00:11:32 +00001101 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr,
1102 UseLEAForSP, TII, *RegInfo);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001103 --MBBI;
1104 }
1105
1106 // Windows unwinder will not invoke function's exception handler if IP is
1107 // either in prologue or in epilogue. This behavior causes a problem when a
1108 // call immediately precedes an epilogue, because the return address points
1109 // into the epilogue. To cope with that, we insert an epilogue marker here,
1110 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1111 // final emitted code.
1112 if (NeedsWinEH)
1113 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1114
1115 // We're returning from function via eh_return.
1116 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1117 MBBI = MBB.getLastNonDebugInstr();
1118 MachineOperand &DestAddr = MBBI->getOperand(0);
1119 assert(DestAddr.isReg() && "Offset should be in register!");
1120 BuildMI(MBB, MBBI, DL,
1121 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1122 StackPtr).addReg(DestAddr.getReg());
1123 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1124 RetOpcode == X86::TCRETURNmi ||
1125 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1126 RetOpcode == X86::TCRETURNmi64) {
1127 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1128 // Tail call return: adjust the stack pointer and jump to callee.
1129 MBBI = MBB.getLastNonDebugInstr();
1130 MachineOperand &JumpTarget = MBBI->getOperand(0);
1131 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1132 assert(StackAdjust.isImm() && "Expecting immediate value.");
1133
1134 // Adjust stack pointer.
1135 int StackAdj = StackAdjust.getImm();
1136 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1137 int Offset = 0;
1138 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1139
1140 // Incoporate the retaddr area.
1141 Offset = StackAdj-MaxTCDelta;
1142 assert(Offset >= 0 && "Offset should never be negative");
1143
1144 if (Offset) {
1145 // Check for possible merge with preceding ADD instruction.
1146 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1147 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
David Majnemer3aa0bd82015-02-24 00:11:32 +00001148 UseLEAForSP, TII, *RegInfo);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001149 }
1150
1151 // Jump to label or value in register.
1152 bool IsWin64 = STI.isTargetWin64();
1153 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1154 unsigned Op = (RetOpcode == X86::TCRETURNdi)
1155 ? X86::TAILJMPd
1156 : (IsWin64 ? X86::TAILJMPd64_REX : X86::TAILJMPd64);
1157 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(Op));
1158 if (JumpTarget.isGlobal())
1159 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1160 JumpTarget.getTargetFlags());
1161 else {
1162 assert(JumpTarget.isSymbol());
1163 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1164 JumpTarget.getTargetFlags());
1165 }
1166 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1167 unsigned Op = (RetOpcode == X86::TCRETURNmi)
1168 ? X86::TAILJMPm
1169 : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64);
1170 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(Op));
1171 for (unsigned i = 0; i != 5; ++i)
1172 MIB.addOperand(MBBI->getOperand(i));
1173 } else if (RetOpcode == X86::TCRETURNri64) {
1174 BuildMI(MBB, MBBI, DL,
1175 TII.get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64))
1176 .addReg(JumpTarget.getReg(), RegState::Kill);
1177 } else {
1178 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1179 addReg(JumpTarget.getReg(), RegState::Kill);
1180 }
1181
1182 MachineInstr *NewMI = std::prev(MBBI);
1183 NewMI->copyImplicitOps(MF, MBBI);
1184
1185 // Delete the pseudo instruction TCRETURN.
1186 MBB.erase(MBBI);
1187 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1188 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1189 (X86FI->getTCReturnAddrDelta() < 0)) {
1190 // Add the return addr area delta back since we are not tail calling.
1191 int delta = -1*X86FI->getTCReturnAddrDelta();
1192 MBBI = MBB.getLastNonDebugInstr();
1193
1194 // Check for possible merge with preceding ADD instruction.
1195 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
David Majnemer3aa0bd82015-02-24 00:11:32 +00001196 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr,
1197 UseLEAForSP, TII, *RegInfo);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001198 }
1199}
1200
1201int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1202 int FI) const {
1203 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001204 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001205 const MachineFrameInfo *MFI = MF.getFrameInfo();
David Majnemer93c22a42015-02-10 00:57:42 +00001206 // Offset will hold the offset from the stack pointer at function entry to the
1207 // object.
1208 // We need to factor in additional offsets applied during the prologue to the
1209 // frame, base, and stack pointer depending on which is used.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001210 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
David Majnemer93c22a42015-02-10 00:57:42 +00001211 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1212 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001213 uint64_t StackSize = MFI->getStackSize();
David Majnemer93c22a42015-02-10 00:57:42 +00001214 unsigned SlotSize = RegInfo->getSlotSize();
1215 bool HasFP = hasFP(MF);
1216 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1217 int64_t FPDelta = 0;
1218
1219 if (IsWinEH) {
David Majnemer89d05642015-02-21 01:04:47 +00001220 assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1221
David Majnemer93c22a42015-02-10 00:57:42 +00001222 // Calculate required stack adjustment.
1223 uint64_t FrameSize = StackSize - SlotSize;
1224 // If required, include space for extra hidden slot for stashing base pointer.
1225 if (X86FI->getRestoreBasePointer())
1226 FrameSize += SlotSize;
David Majnemer89d05642015-02-21 01:04:47 +00001227 uint64_t NumBytes = FrameSize - CSSize;
David Majnemer93c22a42015-02-10 00:57:42 +00001228
David Majnemer93c22a42015-02-10 00:57:42 +00001229 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
David Majnemer13d0b112015-02-10 21:22:05 +00001230 if (FI && FI == X86FI->getFAIndex())
1231 return -SEHFrameOffset;
1232
David Majnemer93c22a42015-02-10 00:57:42 +00001233 // FPDelta is the offset from the "traditional" FP location of the old base
1234 // pointer followed by return address and the location required by the
1235 // restricted Win64 prologue.
1236 // Add FPDelta to all offsets below that go through the frame pointer.
David Majnemer89d05642015-02-21 01:04:47 +00001237 FPDelta = FrameSize - SEHFrameOffset;
1238 assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1239 "FPDelta isn't aligned per the Win64 ABI!");
David Majnemer93c22a42015-02-10 00:57:42 +00001240 }
1241
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001242
1243 if (RegInfo->hasBasePointer(MF)) {
David Majnemer93c22a42015-02-10 00:57:42 +00001244 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001245 if (FI < 0) {
1246 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001247 return Offset + SlotSize + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001248 } else {
1249 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1250 return Offset + StackSize;
1251 }
1252 } else if (RegInfo->needsStackRealignment(MF)) {
1253 if (FI < 0) {
1254 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001255 return Offset + SlotSize + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001256 } else {
1257 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1258 return Offset + StackSize;
1259 }
1260 // FIXME: Support tail calls
1261 } else {
David Majnemer93c22a42015-02-10 00:57:42 +00001262 if (!HasFP)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001263 return Offset + StackSize;
1264
1265 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001266 Offset += SlotSize;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001267
1268 // Skip the RETADDR move area
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001269 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1270 if (TailCallReturnAddrDelta < 0)
1271 Offset -= TailCallReturnAddrDelta;
1272 }
1273
David Majnemer89d05642015-02-21 01:04:47 +00001274 return Offset + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001275}
1276
1277int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1278 unsigned &FrameReg) const {
1279 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001280 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001281 // We can't calculate offset from frame pointer if the stack is realigned,
1282 // so enforce usage of stack/base pointer. The base pointer is used when we
1283 // have dynamic allocas in addition to dynamic realignment.
1284 if (RegInfo->hasBasePointer(MF))
1285 FrameReg = RegInfo->getBaseRegister();
1286 else if (RegInfo->needsStackRealignment(MF))
1287 FrameReg = RegInfo->getStackRegister();
1288 else
1289 FrameReg = RegInfo->getFrameRegister(MF);
1290 return getFrameIndexOffset(MF, FI);
1291}
1292
1293// Simplified from getFrameIndexOffset keeping only StackPointer cases
1294int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1295 const MachineFrameInfo *MFI = MF.getFrameInfo();
1296 // Does not include any dynamic realign.
1297 const uint64_t StackSize = MFI->getStackSize();
1298 {
1299#ifndef NDEBUG
1300 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001301 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001302 // Note: LLVM arranges the stack as:
1303 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1304 // > "Stack Slots" (<--SP)
1305 // We can always address StackSlots from RSP. We can usually (unless
1306 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1307 // address them from RBP. FixedObjects can be placed anywhere in the stack
1308 // frame depending on their specific requirements (i.e. we can actually
1309 // refer to arguments to the function which are stored in the *callers*
1310 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1311 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1312
1313 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1314
1315 // We don't handle tail calls, and shouldn't be seeing them
1316 // either.
1317 int TailCallReturnAddrDelta =
1318 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1319 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1320#endif
1321 }
1322
1323 // This is how the math works out:
1324 //
1325 // %rsp grows (i.e. gets lower) left to right. Each box below is
1326 // one word (eight bytes). Obj0 is the stack slot we're trying to
1327 // get to.
1328 //
1329 // ----------------------------------
1330 // | BP | Obj0 | Obj1 | ... | ObjN |
1331 // ----------------------------------
1332 // ^ ^ ^ ^
1333 // A B C E
1334 //
1335 // A is the incoming stack pointer.
1336 // (B - A) is the local area offset (-8 for x86-64) [1]
1337 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1338 //
1339 // |(E - B)| is the StackSize (absolute value, positive). For a
1340 // stack that grown down, this works out to be (B - E). [3]
1341 //
1342 // E is also the value of %rsp after stack has been set up, and we
1343 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1344 // (C - E) == (C - A) - (B - A) + (B - E)
1345 // { Using [1], [2] and [3] above }
1346 // == getObjectOffset - LocalAreaOffset + StackSize
1347 //
1348
1349 // Get the Offset from the StackPointer
1350 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1351
1352 return Offset + StackSize;
1353}
1354// Simplified from getFrameIndexReference keeping only StackPointer cases
Eric Christopher05b81972015-02-02 17:38:43 +00001355int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1356 int FI,
1357 unsigned &FrameReg) const {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001358 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001359 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001360 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1361
1362 FrameReg = RegInfo->getStackRegister();
1363 return getFrameIndexOffsetFromSP(MF, FI);
1364}
1365
1366bool X86FrameLowering::assignCalleeSavedSpillSlots(
1367 MachineFunction &MF, const TargetRegisterInfo *TRI,
1368 std::vector<CalleeSavedInfo> &CSI) const {
1369 MachineFrameInfo *MFI = MF.getFrameInfo();
1370 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001371 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001372 unsigned SlotSize = RegInfo->getSlotSize();
1373 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1374
1375 unsigned CalleeSavedFrameSize = 0;
1376 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1377
1378 if (hasFP(MF)) {
1379 // emitPrologue always spills frame register the first thing.
1380 SpillSlotOffset -= SlotSize;
1381 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1382
1383 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1384 // the frame register, we can delete it from CSI list and not have to worry
1385 // about avoiding it later.
1386 unsigned FPReg = RegInfo->getFrameRegister(MF);
1387 for (unsigned i = 0; i < CSI.size(); ++i) {
1388 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1389 CSI.erase(CSI.begin() + i);
1390 break;
1391 }
1392 }
1393 }
1394
1395 // Assign slots for GPRs. It increases frame size.
1396 for (unsigned i = CSI.size(); i != 0; --i) {
1397 unsigned Reg = CSI[i - 1].getReg();
1398
1399 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1400 continue;
1401
1402 SpillSlotOffset -= SlotSize;
1403 CalleeSavedFrameSize += SlotSize;
1404
1405 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1406 CSI[i - 1].setFrameIdx(SlotIndex);
1407 }
1408
1409 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1410
1411 // Assign slots for XMMs.
1412 for (unsigned i = CSI.size(); i != 0; --i) {
1413 unsigned Reg = CSI[i - 1].getReg();
1414 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1415 continue;
1416
1417 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1418 // ensure alignment
1419 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1420 // spill into slot
1421 SpillSlotOffset -= RC->getSize();
1422 int SlotIndex =
1423 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1424 CSI[i - 1].setFrameIdx(SlotIndex);
1425 MFI->ensureMaxAlignment(RC->getAlignment());
1426 }
1427
1428 return true;
1429}
1430
1431bool X86FrameLowering::spillCalleeSavedRegisters(
1432 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1433 const std::vector<CalleeSavedInfo> &CSI,
1434 const TargetRegisterInfo *TRI) const {
1435 DebugLoc DL = MBB.findDebugLoc(MI);
1436
1437 MachineFunction &MF = *MBB.getParent();
Eric Christopher05b81972015-02-02 17:38:43 +00001438 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1439 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001440
1441 // Push GPRs. It increases frame size.
1442 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1443 for (unsigned i = CSI.size(); i != 0; --i) {
1444 unsigned Reg = CSI[i - 1].getReg();
1445
1446 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1447 continue;
1448 // Add the callee-saved register as live-in. It's killed at the spill.
1449 MBB.addLiveIn(Reg);
1450
1451 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1452 .setMIFlag(MachineInstr::FrameSetup);
1453 }
1454
1455 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1456 // It can be done by spilling XMMs to stack frame.
1457 for (unsigned i = CSI.size(); i != 0; --i) {
1458 unsigned Reg = CSI[i-1].getReg();
David Majnemera7d908e2015-02-10 19:01:47 +00001459 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001460 continue;
1461 // Add the callee-saved register as live-in. It's killed at the spill.
1462 MBB.addLiveIn(Reg);
1463 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1464
1465 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1466 TRI);
1467 --MI;
1468 MI->setFlag(MachineInstr::FrameSetup);
1469 ++MI;
1470 }
1471
1472 return true;
1473}
1474
1475bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1476 MachineBasicBlock::iterator MI,
1477 const std::vector<CalleeSavedInfo> &CSI,
1478 const TargetRegisterInfo *TRI) const {
1479 if (CSI.empty())
1480 return false;
1481
1482 DebugLoc DL = MBB.findDebugLoc(MI);
1483
1484 MachineFunction &MF = *MBB.getParent();
Eric Christopher05b81972015-02-02 17:38:43 +00001485 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1486 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001487
1488 // Reload XMMs from stack frame.
1489 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1490 unsigned Reg = CSI[i].getReg();
1491 if (X86::GR64RegClass.contains(Reg) ||
1492 X86::GR32RegClass.contains(Reg))
1493 continue;
1494
1495 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1496 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1497 }
1498
1499 // POP GPRs.
1500 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1501 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1502 unsigned Reg = CSI[i].getReg();
1503 if (!X86::GR64RegClass.contains(Reg) &&
1504 !X86::GR32RegClass.contains(Reg))
1505 continue;
1506
1507 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1508 }
1509 return true;
1510}
1511
1512void
1513X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1514 RegScavenger *RS) const {
1515 MachineFrameInfo *MFI = MF.getFrameInfo();
1516 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001517 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001518 unsigned SlotSize = RegInfo->getSlotSize();
1519
1520 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1521 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1522
1523 if (TailCallReturnAddrDelta < 0) {
1524 // create RETURNADDR area
1525 // arg
1526 // arg
1527 // RETADDR
1528 // { ...
1529 // RETADDR area
1530 // ...
1531 // }
1532 // [EBP]
1533 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1534 TailCallReturnAddrDelta - SlotSize, true);
1535 }
1536
1537 // Spill the BasePtr if it's used.
1538 if (RegInfo->hasBasePointer(MF))
1539 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1540}
1541
1542static bool
1543HasNestArgument(const MachineFunction *MF) {
1544 const Function *F = MF->getFunction();
1545 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1546 I != E; I++) {
1547 if (I->hasNestAttr())
1548 return true;
1549 }
1550 return false;
1551}
1552
1553/// GetScratchRegister - Get a temp register for performing work in the
1554/// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1555/// and the properties of the function either one or two registers will be
1556/// needed. Set primary to true for the first register, false for the second.
1557static unsigned
1558GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1559 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1560
1561 // Erlang stuff.
1562 if (CallingConvention == CallingConv::HiPE) {
1563 if (Is64Bit)
1564 return Primary ? X86::R14 : X86::R13;
1565 else
1566 return Primary ? X86::EBX : X86::EDI;
1567 }
1568
1569 if (Is64Bit) {
1570 if (IsLP64)
1571 return Primary ? X86::R11 : X86::R12;
1572 else
1573 return Primary ? X86::R11D : X86::R12D;
1574 }
1575
1576 bool IsNested = HasNestArgument(&MF);
1577
1578 if (CallingConvention == CallingConv::X86_FastCall ||
1579 CallingConvention == CallingConv::Fast) {
1580 if (IsNested)
1581 report_fatal_error("Segmented stacks does not support fastcall with "
1582 "nested function.");
1583 return Primary ? X86::EAX : X86::ECX;
1584 }
1585 if (IsNested)
1586 return Primary ? X86::EDX : X86::EAX;
1587 return Primary ? X86::ECX : X86::EAX;
1588}
1589
1590// The stack limit in the TCB is set to this many bytes above the actual stack
1591// limit.
1592static const uint64_t kSplitStackAvailable = 256;
1593
Quentin Colombet61b305e2015-05-05 17:38:16 +00001594void X86FrameLowering::adjustForSegmentedStacks(
1595 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1596 assert(&PrologueMBB == &MF.front() &&
1597 "Shrink-wrapping is not implemented yet");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001598 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopher05b81972015-02-02 17:38:43 +00001599 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1600 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001601 uint64_t StackSize;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001602 bool Is64Bit = STI.is64Bit();
1603 const bool IsLP64 = STI.isTarget64BitLP64();
1604 unsigned TlsReg, TlsOffset;
1605 DebugLoc DL;
1606
1607 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1608 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1609 "Scratch register is live-in");
1610
1611 if (MF.getFunction()->isVarArg())
1612 report_fatal_error("Segmented stacks do not support vararg functions.");
1613 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1614 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1615 !STI.isTargetDragonFly())
1616 report_fatal_error("Segmented stacks not supported on this platform.");
1617
1618 // Eventually StackSize will be calculated by a link-time pass; which will
1619 // also decide whether checking code needs to be injected into this particular
1620 // prologue.
1621 StackSize = MFI->getStackSize();
1622
1623 // Do not generate a prologue for functions with a stack of size zero
1624 if (StackSize == 0)
1625 return;
1626
1627 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1628 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1629 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1630 bool IsNested = false;
1631
1632 // We need to know if the function has a nest argument only in 64 bit mode.
1633 if (Is64Bit)
1634 IsNested = HasNestArgument(&MF);
1635
1636 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1637 // allocMBB needs to be last (terminating) instruction.
1638
Quentin Colombet61b305e2015-05-05 17:38:16 +00001639 for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1640 e = PrologueMBB.livein_end();
1641 i != e; i++) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001642 allocMBB->addLiveIn(*i);
1643 checkMBB->addLiveIn(*i);
1644 }
1645
1646 if (IsNested)
1647 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1648
1649 MF.push_front(allocMBB);
1650 MF.push_front(checkMBB);
1651
1652 // When the frame size is less than 256 we just compare the stack
1653 // boundary directly to the value of the stack pointer, per gcc.
1654 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1655
1656 // Read the limit off the current stacklet off the stack_guard location.
1657 if (Is64Bit) {
1658 if (STI.isTargetLinux()) {
1659 TlsReg = X86::FS;
1660 TlsOffset = IsLP64 ? 0x70 : 0x40;
1661 } else if (STI.isTargetDarwin()) {
1662 TlsReg = X86::GS;
1663 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1664 } else if (STI.isTargetWin64()) {
1665 TlsReg = X86::GS;
1666 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1667 } else if (STI.isTargetFreeBSD()) {
1668 TlsReg = X86::FS;
1669 TlsOffset = 0x18;
1670 } else if (STI.isTargetDragonFly()) {
1671 TlsReg = X86::FS;
1672 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1673 } else {
1674 report_fatal_error("Segmented stacks not supported on this platform.");
1675 }
1676
1677 if (CompareStackPointer)
1678 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1679 else
1680 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1681 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1682
1683 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1684 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1685 } else {
1686 if (STI.isTargetLinux()) {
1687 TlsReg = X86::GS;
1688 TlsOffset = 0x30;
1689 } else if (STI.isTargetDarwin()) {
1690 TlsReg = X86::GS;
1691 TlsOffset = 0x48 + 90*4;
1692 } else if (STI.isTargetWin32()) {
1693 TlsReg = X86::FS;
1694 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1695 } else if (STI.isTargetDragonFly()) {
1696 TlsReg = X86::FS;
1697 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1698 } else if (STI.isTargetFreeBSD()) {
1699 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1700 } else {
1701 report_fatal_error("Segmented stacks not supported on this platform.");
1702 }
1703
1704 if (CompareStackPointer)
1705 ScratchReg = X86::ESP;
1706 else
1707 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1708 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1709
1710 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1711 STI.isTargetDragonFly()) {
1712 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1713 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1714 } else if (STI.isTargetDarwin()) {
1715
1716 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1717 unsigned ScratchReg2;
1718 bool SaveScratch2;
1719 if (CompareStackPointer) {
1720 // The primary scratch register is available for holding the TLS offset.
1721 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1722 SaveScratch2 = false;
1723 } else {
1724 // Need to use a second register to hold the TLS offset
1725 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1726
1727 // Unfortunately, with fastcc the second scratch register may hold an
1728 // argument.
1729 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1730 }
1731
1732 // If Scratch2 is live-in then it needs to be saved.
1733 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1734 "Scratch register is live-in and not saved");
1735
1736 if (SaveScratch2)
1737 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1738 .addReg(ScratchReg2, RegState::Kill);
1739
1740 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1741 .addImm(TlsOffset);
1742 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1743 .addReg(ScratchReg)
1744 .addReg(ScratchReg2).addImm(1).addReg(0)
1745 .addImm(0)
1746 .addReg(TlsReg);
1747
1748 if (SaveScratch2)
1749 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1750 }
1751 }
1752
1753 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1754 // It jumps to normal execution of the function body.
Quentin Colombet61b305e2015-05-05 17:38:16 +00001755 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001756
1757 // On 32 bit we first push the arguments size and then the frame size. On 64
1758 // bit, we pass the stack frame size in r10 and the argument size in r11.
1759 if (Is64Bit) {
1760 // Functions with nested arguments use R10, so it needs to be saved across
1761 // the call to _morestack
1762
1763 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1764 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1765 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1766 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1767 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1768
1769 if (IsNested)
1770 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1771
1772 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1773 .addImm(StackSize);
1774 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1775 .addImm(X86FI->getArgumentStackSize());
1776 MF.getRegInfo().setPhysRegUsed(Reg10);
1777 MF.getRegInfo().setPhysRegUsed(Reg11);
1778 } else {
1779 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1780 .addImm(X86FI->getArgumentStackSize());
1781 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1782 .addImm(StackSize);
1783 }
1784
1785 // __morestack is in libgcc
1786 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1787 // Under the large code model, we cannot assume that __morestack lives
1788 // within 2^31 bytes of the call site, so we cannot use pc-relative
1789 // addressing. We cannot perform the call via a temporary register,
1790 // as the rax register may be used to store the static chain, and all
1791 // other suitable registers may be either callee-save or used for
1792 // parameter passing. We cannot use the stack at this point either
1793 // because __morestack manipulates the stack directly.
1794 //
1795 // To avoid these issues, perform an indirect call via a read-only memory
1796 // location containing the address.
1797 //
1798 // This solution is not perfect, as it assumes that the .rodata section
1799 // is laid out within 2^31 bytes of each function body, but this seems
1800 // to be sufficient for JIT.
1801 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1802 .addReg(X86::RIP)
1803 .addImm(0)
1804 .addReg(0)
1805 .addExternalSymbol("__morestack_addr")
1806 .addReg(0);
1807 MF.getMMI().setUsesMorestackAddr(true);
1808 } else {
1809 if (Is64Bit)
1810 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1811 .addExternalSymbol("__morestack");
1812 else
1813 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1814 .addExternalSymbol("__morestack");
1815 }
1816
1817 if (IsNested)
1818 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1819 else
1820 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1821
Quentin Colombet61b305e2015-05-05 17:38:16 +00001822 allocMBB->addSuccessor(&PrologueMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001823
1824 checkMBB->addSuccessor(allocMBB);
Quentin Colombet61b305e2015-05-05 17:38:16 +00001825 checkMBB->addSuccessor(&PrologueMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001826
1827#ifdef XDEBUG
1828 MF.verify();
1829#endif
1830}
1831
1832/// Erlang programs may need a special prologue to handle the stack size they
1833/// might need at runtime. That is because Erlang/OTP does not implement a C
1834/// stack but uses a custom implementation of hybrid stack/heap architecture.
1835/// (for more information see Eric Stenman's Ph.D. thesis:
1836/// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1837///
1838/// CheckStack:
1839/// temp0 = sp - MaxStack
1840/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1841/// OldStart:
1842/// ...
1843/// IncStack:
1844/// call inc_stack # doubles the stack space
1845/// temp0 = sp - MaxStack
1846/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
Quentin Colombet61b305e2015-05-05 17:38:16 +00001847void X86FrameLowering::adjustForHiPEPrologue(
1848 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Eric Christopher05b81972015-02-02 17:38:43 +00001849 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1850 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001851 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopher05b81972015-02-02 17:38:43 +00001852 const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001853 const bool Is64Bit = STI.is64Bit();
1854 const bool IsLP64 = STI.isTarget64BitLP64();
1855 DebugLoc DL;
1856 // HiPE-specific values
1857 const unsigned HipeLeafWords = 24;
1858 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1859 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1860 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1861 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1862 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1863
1864 assert(STI.isTargetLinux() &&
1865 "HiPE prologue is only supported on Linux operating systems.");
1866
1867 // Compute the largest caller's frame that is needed to fit the callees'
1868 // frames. This 'MaxStack' is computed from:
1869 //
1870 // a) the fixed frame size, which is the space needed for all spilled temps,
1871 // b) outgoing on-stack parameter areas, and
1872 // c) the minimum stack space this function needs to make available for the
1873 // functions it calls (a tunable ABI property).
1874 if (MFI->hasCalls()) {
1875 unsigned MoreStackForCalls = 0;
1876
1877 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1878 MBBI != MBBE; ++MBBI)
1879 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1880 MI != ME; ++MI) {
1881 if (!MI->isCall())
1882 continue;
1883
1884 // Get callee operand.
1885 const MachineOperand &MO = MI->getOperand(0);
1886
1887 // Only take account of global function calls (no closures etc.).
1888 if (!MO.isGlobal())
1889 continue;
1890
1891 const Function *F = dyn_cast<Function>(MO.getGlobal());
1892 if (!F)
1893 continue;
1894
1895 // Do not update 'MaxStack' for primitive and built-in functions
1896 // (encoded with names either starting with "erlang."/"bif_" or not
1897 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1898 // "_", such as the BIF "suspend_0") as they are executed on another
1899 // stack.
1900 if (F->getName().find("erlang.") != StringRef::npos ||
1901 F->getName().find("bif_") != StringRef::npos ||
1902 F->getName().find_first_of("._") == StringRef::npos)
1903 continue;
1904
1905 unsigned CalleeStkArity =
1906 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1907 if (HipeLeafWords - 1 > CalleeStkArity)
1908 MoreStackForCalls = std::max(MoreStackForCalls,
1909 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1910 }
1911 MaxStack += MoreStackForCalls;
1912 }
1913
1914 // If the stack frame needed is larger than the guaranteed then runtime checks
1915 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1916 if (MaxStack > Guaranteed) {
Quentin Colombet61b305e2015-05-05 17:38:16 +00001917 assert(&PrologueMBB == &MF.front() &&
1918 "Shrink-wrapping is not implemented yet");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001919 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1920 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1921
Quentin Colombet61b305e2015-05-05 17:38:16 +00001922 for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1923 E = PrologueMBB.livein_end();
1924 I != E; I++) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001925 stackCheckMBB->addLiveIn(*I);
1926 incStackMBB->addLiveIn(*I);
1927 }
1928
1929 MF.push_front(incStackMBB);
1930 MF.push_front(stackCheckMBB);
1931
1932 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1933 unsigned LEAop, CMPop, CALLop;
1934 if (Is64Bit) {
1935 SPReg = X86::RSP;
1936 PReg = X86::RBP;
1937 LEAop = X86::LEA64r;
1938 CMPop = X86::CMP64rm;
1939 CALLop = X86::CALL64pcrel32;
1940 SPLimitOffset = 0x90;
1941 } else {
1942 SPReg = X86::ESP;
1943 PReg = X86::EBP;
1944 LEAop = X86::LEA32r;
1945 CMPop = X86::CMP32rm;
1946 CALLop = X86::CALLpcrel32;
1947 SPLimitOffset = 0x4c;
1948 }
1949
1950 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1951 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1952 "HiPE prologue scratch register is live-in");
1953
1954 // Create new MBB for StackCheck:
1955 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1956 SPReg, false, -MaxStack);
1957 // SPLimitOffset is in a fixed heap location (pointed by BP).
1958 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1959 .addReg(ScratchReg), PReg, false, SPLimitOffset);
Quentin Colombet61b305e2015-05-05 17:38:16 +00001960 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001961
1962 // Create new MBB for IncStack:
1963 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1964 addExternalSymbol("inc_stack_0");
1965 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1966 SPReg, false, -MaxStack);
1967 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1968 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1969 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1970
Quentin Colombet61b305e2015-05-05 17:38:16 +00001971 stackCheckMBB->addSuccessor(&PrologueMBB, 99);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001972 stackCheckMBB->addSuccessor(incStackMBB, 1);
Quentin Colombet61b305e2015-05-05 17:38:16 +00001973 incStackMBB->addSuccessor(&PrologueMBB, 99);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001974 incStackMBB->addSuccessor(incStackMBB, 1);
1975 }
1976#ifdef XDEBUG
1977 MF.verify();
1978#endif
1979}
1980
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001981void X86FrameLowering::
1982eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1983 MachineBasicBlock::iterator I) const {
Eric Christopher05b81972015-02-02 17:38:43 +00001984 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1985 const TargetInstrInfo &TII = *STI.getInstrInfo();
1986 const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001987 unsigned StackPtr = RegInfo.getStackRegister();
1988 bool reserveCallFrame = hasReservedCallFrame(MF);
1989 int Opcode = I->getOpcode();
1990 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001991 bool IsLP64 = STI.isTarget64BitLP64();
1992 DebugLoc DL = I->getDebugLoc();
1993 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001994 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001995 I = MBB.erase(I);
1996
1997 if (!reserveCallFrame) {
1998 // If the stack pointer can be changed after prologue, turn the
1999 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
2000 // adjcallstackdown instruction into 'add ESP, <amt>'
2001 if (Amount == 0)
2002 return;
2003
2004 // We need to keep the stack aligned properly. To do this, we round the
2005 // amount of space needed for the outgoing arguments up to the next
2006 // alignment boundary.
David Majnemer93c22a42015-02-10 00:57:42 +00002007 unsigned StackAlign = getStackAlignment();
2008 Amount = RoundUpToAlignment(Amount, StackAlign);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002009
2010 MachineInstr *New = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002011
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002012 // Factor out the amount that gets handled inside the sequence
2013 // (Pushes of argument for frame setup, callee pops for frame destroy)
2014 Amount -= InternalAmt;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002015
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002016 if (Amount) {
2017 if (Opcode == TII.getCallFrameSetupOpcode()) {
2018 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
2019 .addReg(StackPtr).addImm(Amount);
2020 } else {
2021 assert(Opcode == TII.getCallFrameDestroyOpcode());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002022
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002023 unsigned Opc = getADDriOpcode(IsLP64, Amount);
2024 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
2025 .addReg(StackPtr).addImm(Amount);
2026 }
2027 }
2028
2029 if (New) {
2030 // The EFLAGS implicit def is dead.
2031 New->getOperand(3).setIsDead();
2032
2033 // Replace the pseudo instruction with a new instruction.
2034 MBB.insert(I, New);
2035 }
2036
2037 return;
2038 }
2039
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002040 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002041 // If we are performing frame pointer elimination and if the callee pops
2042 // something off the stack pointer, add it back. We do this until we have
2043 // more advanced stack pointer tracking ability.
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002044 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002045 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002046 .addReg(StackPtr).addImm(InternalAmt);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002047
2048 // The EFLAGS implicit def is dead.
2049 New->getOperand(3).setIsDead();
2050
2051 // We are not tracking the stack pointer adjustment by the callee, so make
2052 // sure we restore the stack pointer immediately after the call, there may
2053 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2054 MachineBasicBlock::iterator B = MBB.begin();
2055 while (I != B && !std::prev(I)->isCall())
2056 --I;
2057 MBB.insert(I, New);
2058 }
2059}
2060