blob: 8b79a9f1ebdd21d5e2af0fd1764fb4ecd7639ea3 [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
253 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
254 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
315/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
316/// iterator.
317static
318void mergeSPUpdatesDown(MachineBasicBlock &MBB,
319 MachineBasicBlock::iterator &MBBI,
320 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
321 // FIXME: THIS ISN'T RUN!!!
322 return;
323
324 if (MBBI == MBB.end()) return;
325
326 MachineBasicBlock::iterator NI = std::next(MBBI);
327 if (NI == MBB.end()) return;
328
329 unsigned Opc = NI->getOpcode();
330 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
331 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
332 NI->getOperand(0).getReg() == StackPtr) {
333 if (NumBytes)
334 *NumBytes -= NI->getOperand(2).getImm();
335 MBB.erase(NI);
336 MBBI = NI;
337 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
338 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
339 NI->getOperand(0).getReg() == StackPtr) {
340 if (NumBytes)
341 *NumBytes += NI->getOperand(2).getImm();
342 MBB.erase(NI);
343 MBBI = NI;
344 }
345}
346
347/// mergeSPUpdates - Checks the instruction before/after the passed
348/// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
349/// the stack adjustment is returned as a positive value for ADD/LEA and a
350/// negative for SUB.
351static int mergeSPUpdates(MachineBasicBlock &MBB,
352 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
353 bool doMergeWithPrevious) {
354 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
355 (!doMergeWithPrevious && MBBI == MBB.end()))
356 return 0;
357
358 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
359 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
360 : std::next(MBBI);
361 unsigned Opc = PI->getOpcode();
362 int Offset = 0;
363
364 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
365 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
366 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
367 PI->getOperand(0).getReg() == StackPtr){
368 Offset += PI->getOperand(2).getImm();
369 MBB.erase(PI);
370 if (!doMergeWithPrevious) MBBI = NI;
371 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
372 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
373 PI->getOperand(0).getReg() == StackPtr) {
374 Offset -= PI->getOperand(2).getImm();
375 MBB.erase(PI);
376 if (!doMergeWithPrevious) MBBI = NI;
377 }
378
379 return Offset;
380}
381
382void
383X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
384 MachineBasicBlock::iterator MBBI,
385 DebugLoc DL) const {
386 MachineFunction &MF = *MBB.getParent();
387 MachineFrameInfo *MFI = MF.getFrameInfo();
388 MachineModuleInfo &MMI = MF.getMMI();
389 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
390 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
391
392 // Add callee saved registers to move list.
393 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
394 if (CSI.empty()) return;
395
396 // Calculate offsets.
397 for (std::vector<CalleeSavedInfo>::const_iterator
398 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
399 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
400 unsigned Reg = I->getReg();
401
402 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
403 unsigned CFIIndex =
404 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
405 Offset));
406 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
407 .addCFIIndex(CFIIndex);
408 }
409}
410
411/// usesTheStack - This function checks if any of the users of EFLAGS
412/// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
413/// to use the stack, and if we don't adjust the stack we clobber the first
414/// frame index.
415/// See X86InstrInfo::copyPhysReg.
416static bool usesTheStack(const MachineFunction &MF) {
417 const MachineRegisterInfo &MRI = MF.getRegInfo();
418
419 for (MachineRegisterInfo::reg_instr_iterator
420 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
421 ri != re; ++ri)
422 if (ri->isCopy())
423 return true;
424
425 return false;
426}
427
428void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
429 MachineBasicBlock &MBB,
430 MachineBasicBlock::iterator MBBI,
431 DebugLoc DL) {
Eric Christopher05b81972015-02-02 17:38:43 +0000432 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
433 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000434 bool Is64Bit = STI.is64Bit();
435 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
436
437 unsigned CallOp;
438 if (Is64Bit)
439 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
440 else
441 CallOp = X86::CALLpcrel32;
442
443 const char *Symbol;
444 if (Is64Bit) {
445 if (STI.isTargetCygMing()) {
446 Symbol = "___chkstk_ms";
447 } else {
448 Symbol = "__chkstk";
449 }
450 } else if (STI.isTargetCygMing())
451 Symbol = "_alloca";
452 else
453 Symbol = "_chkstk";
454
455 MachineInstrBuilder CI;
456
457 // All current stack probes take AX and SP as input, clobber flags, and
458 // preserve all registers. x86_64 probes leave RSP unmodified.
459 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
460 // For the large code model, we have to call through a register. Use R11,
461 // as it is scratch in all supported calling conventions.
462 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
463 .addExternalSymbol(Symbol);
464 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
465 } else {
466 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
467 }
468
469 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
470 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
471 CI.addReg(AX, RegState::Implicit)
472 .addReg(SP, RegState::Implicit)
473 .addReg(AX, RegState::Define | RegState::Implicit)
474 .addReg(SP, RegState::Define | RegState::Implicit)
475 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
476
477 if (Is64Bit) {
478 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
479 // themselves. It also does not clobber %rax so we can reuse it when
480 // adjusting %rsp.
481 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
482 .addReg(X86::RSP)
483 .addReg(X86::RAX);
484 }
485}
486
David Majnemer93c22a42015-02-10 00:57:42 +0000487static unsigned calculateSetFPREG(uint64_t SPAdjust) {
488 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
489 // and might require smaller successive adjustments.
490 const uint64_t Win64MaxSEHOffset = 128;
491 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
492 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
493 return static_cast<unsigned>(RoundUpToAlignment(SEHFrameOffset, 16));
494}
495
496// If we're forcing a stack realignment we can't rely on just the frame
497// info, we need to know the ABI stack alignment as well in case we
498// have a call out. Otherwise just make sure we have some alignment - we'll
499// go with the minimum SlotSize.
500static uint64_t calculateMaxStackAlign(const MachineFunction &MF) {
501 const MachineFrameInfo *MFI = MF.getFrameInfo();
502 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
503 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
504 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
505 unsigned SlotSize = RegInfo->getSlotSize();
506 unsigned StackAlign = STI.getFrameLowering()->getStackAlignment();
507 if (ForceStackAlign) {
508 if (MFI->hasCalls())
509 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
510 else if (MaxAlign < SlotSize)
511 MaxAlign = SlotSize;
512 }
513 return MaxAlign;
514}
515
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000516/// emitPrologue - Push callee-saved registers onto the stack, which
517/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
518/// space for local variables. Also emit labels used by the exception handler to
519/// generate the exception handling frames.
520
521/*
522 Here's a gist of what gets emitted:
523
524 ; Establish frame pointer, if needed
525 [if needs FP]
526 push %rbp
527 .cfi_def_cfa_offset 16
528 .cfi_offset %rbp, -16
529 .seh_pushreg %rpb
530 mov %rsp, %rbp
531 .cfi_def_cfa_register %rbp
532
533 ; Spill general-purpose registers
534 [for all callee-saved GPRs]
535 pushq %<reg>
536 [if not needs FP]
537 .cfi_def_cfa_offset (offset from RETADDR)
538 .seh_pushreg %<reg>
539
540 ; If the required stack alignment > default stack alignment
541 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
542 ; of unknown size in the stack frame.
543 [if stack needs re-alignment]
544 and $MASK, %rsp
545
546 ; Allocate space for locals
547 [if target is Windows and allocated space > 4096 bytes]
548 ; Windows needs special care for allocations larger
549 ; than one page.
550 mov $NNN, %rax
551 call ___chkstk_ms/___chkstk
552 sub %rax, %rsp
553 [else]
554 sub $NNN, %rsp
555
556 [if needs FP]
557 .seh_stackalloc (size of XMM spill slots)
558 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
559 [else]
560 .seh_stackalloc NNN
561
562 ; Spill XMMs
563 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
564 ; they may get spilled on any platform, if the current function
565 ; calls @llvm.eh.unwind.init
566 [if needs FP]
567 [for all callee-saved XMM registers]
568 movaps %<xmm reg>, -MMM(%rbp)
569 [for all callee-saved XMM registers]
570 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
571 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
572 [else]
573 [for all callee-saved XMM registers]
574 movaps %<xmm reg>, KKK(%rsp)
575 [for all callee-saved XMM registers]
576 .seh_savexmm %<xmm reg>, KKK
577
578 .seh_endprologue
579
580 [if needs base pointer]
581 mov %rsp, %rbx
582 [if needs to restore base pointer]
583 mov %rsp, -MMM(%rbp)
584
585 ; Emit CFI info
586 [if needs FP]
587 [for all callee-saved registers]
588 .cfi_offset %<reg>, (offset from %rbp)
589 [else]
590 .cfi_def_cfa_offset (offset from RETADDR)
591 [for all callee-saved registers]
592 .cfi_offset %<reg>, (offset from %rsp)
593
594 Notes:
595 - .seh directives are emitted only for Windows 64 ABI
596 - .cfi directives are emitted for all other ABIs
597 - for 32-bit code, substitute %e?? registers for %r??
598*/
599
600void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
601 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
602 MachineBasicBlock::iterator MBBI = MBB.begin();
603 MachineFrameInfo *MFI = MF.getFrameInfo();
604 const Function *Fn = MF.getFunction();
Eric Christopher05b81972015-02-02 17:38:43 +0000605 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
606 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
607 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000608 MachineModuleInfo &MMI = MF.getMMI();
609 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
David Majnemer93c22a42015-02-10 00:57:42 +0000610 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000611 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
612 bool HasFP = hasFP(MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000613 bool Is64Bit = STI.is64Bit();
614 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
615 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
616 bool IsWin64 = STI.isTargetWin64();
617 // Not necessarily synonymous with IsWin64.
618 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
619 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
620 bool NeedsDwarfCFI =
621 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
622 bool UseLEA = STI.useLeaForSP();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000623 unsigned SlotSize = RegInfo->getSlotSize();
624 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Eric Christopher05b81972015-02-02 17:38:43 +0000625 const unsigned MachineFramePtr =
626 STI.isTarget64BitILP32()
627 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
628 : FramePtr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000629 unsigned StackPtr = RegInfo->getStackRegister();
630 unsigned BasePtr = RegInfo->getBaseRegister();
631 DebugLoc DL;
632
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000633 // Add RETADDR move area to callee saved frame size.
634 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
David Majnemer93c22a42015-02-10 00:57:42 +0000635 if (TailCallReturnAddrDelta && IsWinEH)
636 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
637
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000638 if (TailCallReturnAddrDelta < 0)
639 X86FI->setCalleeSavedFrameSize(
640 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
641
642 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
643
644 // The default stack probe size is 4096 if the function has no stackprobesize
645 // attribute.
646 unsigned StackProbeSize = 4096;
647 if (Fn->hasFnAttribute("stack-probe-size"))
648 Fn->getFnAttribute("stack-probe-size")
649 .getValueAsString()
650 .getAsInteger(0, StackProbeSize);
651
652 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
653 // function, and use up to 128 bytes of stack space, don't have a frame
654 // pointer, calls, or dynamic alloca then we do not need to adjust the
655 // stack pointer (we fit in the Red Zone). We also check that we don't
656 // push and pop from the stack.
657 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
658 Attribute::NoRedZone) &&
659 !RegInfo->needsStackRealignment(MF) &&
660 !MFI->hasVarSizedObjects() && // No dynamic alloca.
661 !MFI->adjustsStack() && // No calls.
662 !IsWin64 && // Win64 has no Red Zone
663 !usesTheStack(MF) && // Don't push and pop.
664 !MF.shouldSplitStack()) { // Regular stack
665 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
666 if (HasFP) MinSize += SlotSize;
667 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
668 MFI->setStackSize(StackSize);
669 }
670
671 // Insert stack pointer adjustment for later moving of return addr. Only
672 // applies to tail call optimized functions where the callee argument stack
673 // size is bigger than the callers.
674 if (TailCallReturnAddrDelta < 0) {
675 MachineInstr *MI =
676 BuildMI(MBB, MBBI, DL,
677 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
678 StackPtr)
679 .addReg(StackPtr)
680 .addImm(-TailCallReturnAddrDelta)
681 .setMIFlag(MachineInstr::FrameSetup);
682 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
683 }
684
685 // Mapping for machine moves:
686 //
687 // DST: VirtualFP AND
688 // SRC: VirtualFP => DW_CFA_def_cfa_offset
689 // ELSE => DW_CFA_def_cfa
690 //
691 // SRC: VirtualFP AND
692 // DST: Register => DW_CFA_def_cfa_register
693 //
694 // ELSE
695 // OFFSET < 0 => DW_CFA_offset_extended_sf
696 // REG < 64 => DW_CFA_offset + Reg
697 // ELSE => DW_CFA_offset_extended
698
699 uint64_t NumBytes = 0;
700 int stackGrowth = -SlotSize;
701
702 if (HasFP) {
703 // Calculate required stack adjustment.
704 uint64_t FrameSize = StackSize - SlotSize;
705 // If required, include space for extra hidden slot for stashing base pointer.
706 if (X86FI->getRestoreBasePointer())
707 FrameSize += SlotSize;
708 if (RegInfo->needsStackRealignment(MF)) {
709 // Callee-saved registers are pushed on stack before the stack
710 // is realigned.
711 FrameSize -= X86FI->getCalleeSavedFrameSize();
David Majnemer93c22a42015-02-10 00:57:42 +0000712 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000713 } else {
714 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
715 }
716
717 // Get the offset of the stack slot for the EBP register, which is
718 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
719 // Update the frame offset adjustment.
720 MFI->setOffsetAdjustment(-NumBytes);
721
722 // Save EBP/RBP into the appropriate stack slot.
723 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
724 .addReg(MachineFramePtr, RegState::Kill)
725 .setMIFlag(MachineInstr::FrameSetup);
726
727 if (NeedsDwarfCFI) {
728 // Mark the place where EBP/RBP was saved.
729 // Define the current CFA rule to use the provided offset.
730 assert(StackSize);
731 unsigned CFIIndex = MMI.addFrameInst(
732 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
733 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
734 .addCFIIndex(CFIIndex);
735
736 // Change the rule for the FramePtr to be an "offset" rule.
737 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
738 CFIIndex = MMI.addFrameInst(
739 MCCFIInstruction::createOffset(nullptr,
740 DwarfFramePtr, 2 * stackGrowth));
741 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
742 .addCFIIndex(CFIIndex);
743 }
744
745 if (NeedsWinEH) {
746 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
747 .addImm(FramePtr)
748 .setMIFlag(MachineInstr::FrameSetup);
749 }
750
David Majnemer93c22a42015-02-10 00:57:42 +0000751 if (!IsWinEH) {
752 // Update EBP with the new base value.
753 BuildMI(MBB, MBBI, DL,
754 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
755 FramePtr)
756 .addReg(StackPtr)
757 .setMIFlag(MachineInstr::FrameSetup);
758 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000759
760 if (NeedsDwarfCFI) {
761 // Mark effective beginning of when frame pointer becomes valid.
762 // Define the current CFA to use the EBP/RBP register.
763 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
764 unsigned CFIIndex = MMI.addFrameInst(
765 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
766 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
767 .addCFIIndex(CFIIndex);
768 }
769
770 // Mark the FramePtr as live-in in every block.
771 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
772 I->addLiveIn(MachineFramePtr);
773 } else {
774 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
775 }
776
777 // Skip the callee-saved push instructions.
778 bool PushedRegs = false;
779 int StackOffset = 2 * stackGrowth;
780
781 while (MBBI != MBB.end() &&
782 (MBBI->getOpcode() == X86::PUSH32r ||
783 MBBI->getOpcode() == X86::PUSH64r)) {
784 PushedRegs = true;
785 unsigned Reg = MBBI->getOperand(0).getReg();
786 ++MBBI;
787
788 if (!HasFP && NeedsDwarfCFI) {
789 // Mark callee-saved push instruction.
790 // Define the current CFA rule to use the provided offset.
791 assert(StackSize);
792 unsigned CFIIndex = MMI.addFrameInst(
793 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
794 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
795 .addCFIIndex(CFIIndex);
796 StackOffset += stackGrowth;
797 }
798
799 if (NeedsWinEH) {
800 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
801 MachineInstr::FrameSetup);
802 }
803 }
804
805 // Realign stack after we pushed callee-saved registers (so that we'll be
806 // able to calculate their offsets from the frame pointer).
David Majnemer93c22a42015-02-10 00:57:42 +0000807 // Don't do this for Win64, it needs to realign the stack after the prologue.
808 if (!IsWinEH && RegInfo->needsStackRealignment(MF)) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000809 assert(HasFP && "There should be a frame pointer if stack is realigned.");
810 uint64_t Val = -MaxAlign;
811 MachineInstr *MI =
David Majnemer93c22a42015-02-10 00:57:42 +0000812 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
813 StackPtr)
814 .addReg(StackPtr)
815 .addImm(Val)
816 .setMIFlag(MachineInstr::FrameSetup);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000817
818 // The EFLAGS implicit def is dead.
819 MI->getOperand(3).setIsDead();
820 }
821
822 // If there is an SUB32ri of ESP immediately before this instruction, merge
823 // the two. This can be the case when tail call elimination is enabled and
824 // the callee has more arguments then the caller.
825 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
826
827 // If there is an ADD32ri or SUB32ri of ESP immediately after this
828 // instruction, merge the two instructions.
829 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
830
831 // Adjust stack pointer: ESP -= numbytes.
832
833 // Windows and cygwin/mingw require a prologue helper routine when allocating
834 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
835 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
836 // stack and adjust the stack pointer in one go. The 64-bit version of
837 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
838 // responsible for adjusting the stack pointer. Touching the stack at 4K
839 // increments is necessary to ensure that the guard pages used by the OS
840 // virtual memory manager are allocated in correct sequence.
841 if (NumBytes >= StackProbeSize && UseStackProbe) {
842 // Check whether EAX is livein for this function.
843 bool isEAXAlive = isEAXLiveIn(MF);
844
845 if (isEAXAlive) {
846 // Sanity check that EAX is not livein for this function.
847 // It should not be, so throw an assert.
848 assert(!Is64Bit && "EAX is livein in x64 case!");
849
850 // Save EAX
851 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
852 .addReg(X86::EAX, RegState::Kill)
853 .setMIFlag(MachineInstr::FrameSetup);
854 }
855
856 if (Is64Bit) {
857 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
858 // Function prologue is responsible for adjusting the stack pointer.
859 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
860 .addImm(NumBytes)
861 .setMIFlag(MachineInstr::FrameSetup);
862 } else {
863 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
864 // We'll also use 4 already allocated bytes for EAX.
865 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
866 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
867 .setMIFlag(MachineInstr::FrameSetup);
868 }
869
870 // Save a pointer to the MI where we set AX.
871 MachineBasicBlock::iterator SetRAX = MBBI;
872 --SetRAX;
873
874 // Call __chkstk, __chkstk_ms, or __alloca.
875 emitStackProbeCall(MF, MBB, MBBI, DL);
876
877 // Apply the frame setup flag to all inserted instrs.
878 for (; SetRAX != MBBI; ++SetRAX)
879 SetRAX->setFlag(MachineInstr::FrameSetup);
880
881 if (isEAXAlive) {
882 // Restore EAX
883 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
884 X86::EAX),
885 StackPtr, false, NumBytes - 4);
886 MI->setFlag(MachineInstr::FrameSetup);
887 MBB.insert(MBBI, MI);
888 }
889 } else if (NumBytes) {
890 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
891 UseLEA, TII, *RegInfo);
892 }
893
David Majnemer93c22a42015-02-10 00:57:42 +0000894 if (NeedsWinEH && NumBytes)
895 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
896 .addImm(NumBytes)
897 .setMIFlag(MachineInstr::FrameSetup);
898
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000899 int SEHFrameOffset = 0;
David Majnemer93c22a42015-02-10 00:57:42 +0000900 if (IsWinEH && HasFP) {
901 SEHFrameOffset = calculateSetFPREG(NumBytes);
902 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
903 StackPtr, false, SEHFrameOffset);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000904
David Majnemer93c22a42015-02-10 00:57:42 +0000905 if (NeedsWinEH)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000906 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
907 .addImm(FramePtr)
908 .addImm(SEHFrameOffset)
909 .setMIFlag(MachineInstr::FrameSetup);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000910 }
911
912 // Skip the rest of register spilling code
913 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
914 ++MBBI;
915
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000916 if (NeedsWinEH) {
917 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
918 unsigned Reg = Info.getReg();
919 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
920 continue;
921 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
922
923 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
924 Offset += SEHFrameOffset;
925
926 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
927 .addImm(Reg)
928 .addImm(Offset)
929 .setMIFlag(MachineInstr::FrameSetup);
930 }
931
932 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
933 .setMIFlag(MachineInstr::FrameSetup);
934 }
935
David Majnemer93c22a42015-02-10 00:57:42 +0000936 // Realign stack after we spilled callee-saved registers (so that we'll be
937 // able to calculate their offsets from the frame pointer).
938 // Win64 requires aligning the stack after the prologue.
939 if (IsWinEH && RegInfo->needsStackRealignment(MF)) {
940 assert(HasFP && "There should be a frame pointer if stack is realigned.");
941 uint64_t Val = -MaxAlign;
942 MachineInstr *MI =
943 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
944 StackPtr)
945 .addReg(StackPtr)
946 .addImm(Val)
947 .setMIFlag(MachineInstr::FrameSetup);
948
949 // The EFLAGS implicit def is dead.
950 MI->getOperand(3).setIsDead();
951 }
952
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000953 // If we need a base pointer, set it up here. It's whatever the value
954 // of the stack pointer is at this point. Any variable size objects
955 // will be allocated after this, so we can still use the base pointer
956 // to reference locals.
957 if (RegInfo->hasBasePointer(MF)) {
958 // Update the base pointer with the current stack pointer.
959 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
960 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
961 .addReg(StackPtr)
962 .setMIFlag(MachineInstr::FrameSetup);
963 if (X86FI->getRestoreBasePointer()) {
964 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
965 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
966 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
967 FramePtr, true, X86FI->getRestoreBasePointerOffset())
968 .addReg(StackPtr)
969 .setMIFlag(MachineInstr::FrameSetup);
970 }
971 }
972
973 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
974 // Mark end of stack pointer adjustment.
975 if (!HasFP && NumBytes) {
976 // Define the current CFA rule to use the provided offset.
977 assert(StackSize);
978 unsigned CFIIndex = MMI.addFrameInst(
979 MCCFIInstruction::createDefCfaOffset(nullptr,
980 -StackSize + stackGrowth));
981
982 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
983 .addCFIIndex(CFIIndex);
984 }
985
986 // Emit DWARF info specifying the offsets of the callee-saved registers.
987 if (PushedRegs)
988 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
989 }
990}
991
992void X86FrameLowering::emitEpilogue(MachineFunction &MF,
993 MachineBasicBlock &MBB) const {
994 const MachineFrameInfo *MFI = MF.getFrameInfo();
995 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Eric Christopher05b81972015-02-02 17:38:43 +0000996 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
997 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
998 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000999 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1000 assert(MBBI != MBB.end() && "Returning block has no instructions");
1001 unsigned RetOpcode = MBBI->getOpcode();
1002 DebugLoc DL = MBBI->getDebugLoc();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001003 bool Is64Bit = STI.is64Bit();
1004 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
1005 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
1006 const bool Is64BitILP32 = STI.isTarget64BitILP32();
1007 bool UseLEA = STI.useLeaForSP();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001008 unsigned SlotSize = RegInfo->getSlotSize();
1009 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Eric Christopher05b81972015-02-02 17:38:43 +00001010 unsigned MachineFramePtr =
1011 Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
1012 : FramePtr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001013 unsigned StackPtr = RegInfo->getStackRegister();
1014
1015 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1016 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
1017
1018 switch (RetOpcode) {
1019 default:
1020 llvm_unreachable("Can only insert epilog into returning blocks");
1021 case X86::RETQ:
1022 case X86::RETL:
1023 case X86::RETIL:
1024 case X86::RETIQ:
1025 case X86::TCRETURNdi:
1026 case X86::TCRETURNri:
1027 case X86::TCRETURNmi:
1028 case X86::TCRETURNdi64:
1029 case X86::TCRETURNri64:
1030 case X86::TCRETURNmi64:
1031 case X86::EH_RETURN:
1032 case X86::EH_RETURN64:
1033 break; // These are ok
1034 }
1035
1036 // Get the number of bytes to allocate from the FrameInfo.
1037 uint64_t StackSize = MFI->getStackSize();
David Majnemer93c22a42015-02-10 00:57:42 +00001038 uint64_t MaxAlign = calculateMaxStackAlign(MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001039 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1040 uint64_t NumBytes = 0;
1041
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001042 if (hasFP(MF)) {
1043 // Calculate required stack adjustment.
1044 uint64_t FrameSize = StackSize - SlotSize;
1045 if (RegInfo->needsStackRealignment(MF)) {
1046 // Callee-saved registers were pushed on stack before the stack
1047 // was realigned.
1048 FrameSize -= CSSize;
1049 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
1050 } else {
1051 NumBytes = FrameSize - CSSize;
1052 }
1053
1054 // Pop EBP.
1055 BuildMI(MBB, MBBI, DL,
1056 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1057 } else {
1058 NumBytes = StackSize - CSSize;
1059 }
David Majnemer93c22a42015-02-10 00:57:42 +00001060 uint64_t SEHStackAllocAmt = NumBytes;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001061
1062 // Skip the callee-saved pop instructions.
1063 while (MBBI != MBB.begin()) {
1064 MachineBasicBlock::iterator PI = std::prev(MBBI);
1065 unsigned Opc = PI->getOpcode();
1066
1067 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1068 !PI->isTerminator())
1069 break;
1070
1071 --MBBI;
1072 }
1073 MachineBasicBlock::iterator FirstCSPop = MBBI;
1074
1075 DL = MBBI->getDebugLoc();
1076
1077 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1078 // instruction, merge the two instructions.
1079 if (NumBytes || MFI->hasVarSizedObjects())
1080 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1081
1082 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1083 // slot before popping them off! Same applies for the case, when stack was
1084 // realigned.
1085 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1086 if (RegInfo->needsStackRealignment(MF))
1087 MBBI = FirstCSPop;
David Majnemer93c22a42015-02-10 00:57:42 +00001088 if (IsWinEH) {
1089 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1090 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), StackPtr),
1091 FramePtr, false, SEHStackAllocAmt - SEHFrameOffset);
1092 --MBBI;
1093 } else if (CSSize != 0) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001094 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1095 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1096 FramePtr, false, -CSSize);
1097 --MBBI;
1098 } else {
1099 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1100 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1101 .addReg(FramePtr);
1102 --MBBI;
1103 }
1104 } else if (NumBytes) {
1105 // Adjust stack pointer back: ESP += numbytes.
1106 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
1107 TII, *RegInfo);
1108 --MBBI;
1109 }
1110
1111 // Windows unwinder will not invoke function's exception handler if IP is
1112 // either in prologue or in epilogue. This behavior causes a problem when a
1113 // call immediately precedes an epilogue, because the return address points
1114 // into the epilogue. To cope with that, we insert an epilogue marker here,
1115 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1116 // final emitted code.
1117 if (NeedsWinEH)
1118 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1119
1120 // We're returning from function via eh_return.
1121 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1122 MBBI = MBB.getLastNonDebugInstr();
1123 MachineOperand &DestAddr = MBBI->getOperand(0);
1124 assert(DestAddr.isReg() && "Offset should be in register!");
1125 BuildMI(MBB, MBBI, DL,
1126 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1127 StackPtr).addReg(DestAddr.getReg());
1128 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1129 RetOpcode == X86::TCRETURNmi ||
1130 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1131 RetOpcode == X86::TCRETURNmi64) {
1132 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1133 // Tail call return: adjust the stack pointer and jump to callee.
1134 MBBI = MBB.getLastNonDebugInstr();
1135 MachineOperand &JumpTarget = MBBI->getOperand(0);
1136 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1137 assert(StackAdjust.isImm() && "Expecting immediate value.");
1138
1139 // Adjust stack pointer.
1140 int StackAdj = StackAdjust.getImm();
1141 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1142 int Offset = 0;
1143 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1144
1145 // Incoporate the retaddr area.
1146 Offset = StackAdj-MaxTCDelta;
1147 assert(Offset >= 0 && "Offset should never be negative");
1148
1149 if (Offset) {
1150 // Check for possible merge with preceding ADD instruction.
1151 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1152 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1153 UseLEA, TII, *RegInfo);
1154 }
1155
1156 // Jump to label or value in register.
1157 bool IsWin64 = STI.isTargetWin64();
1158 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1159 unsigned Op = (RetOpcode == X86::TCRETURNdi)
1160 ? X86::TAILJMPd
1161 : (IsWin64 ? X86::TAILJMPd64_REX : X86::TAILJMPd64);
1162 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(Op));
1163 if (JumpTarget.isGlobal())
1164 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1165 JumpTarget.getTargetFlags());
1166 else {
1167 assert(JumpTarget.isSymbol());
1168 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1169 JumpTarget.getTargetFlags());
1170 }
1171 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1172 unsigned Op = (RetOpcode == X86::TCRETURNmi)
1173 ? X86::TAILJMPm
1174 : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64);
1175 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(Op));
1176 for (unsigned i = 0; i != 5; ++i)
1177 MIB.addOperand(MBBI->getOperand(i));
1178 } else if (RetOpcode == X86::TCRETURNri64) {
1179 BuildMI(MBB, MBBI, DL,
1180 TII.get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64))
1181 .addReg(JumpTarget.getReg(), RegState::Kill);
1182 } else {
1183 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1184 addReg(JumpTarget.getReg(), RegState::Kill);
1185 }
1186
1187 MachineInstr *NewMI = std::prev(MBBI);
1188 NewMI->copyImplicitOps(MF, MBBI);
1189
1190 // Delete the pseudo instruction TCRETURN.
1191 MBB.erase(MBBI);
1192 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1193 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1194 (X86FI->getTCReturnAddrDelta() < 0)) {
1195 // Add the return addr area delta back since we are not tail calling.
1196 int delta = -1*X86FI->getTCReturnAddrDelta();
1197 MBBI = MBB.getLastNonDebugInstr();
1198
1199 // Check for possible merge with preceding ADD instruction.
1200 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1201 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1202 *RegInfo);
1203 }
1204}
1205
1206int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1207 int FI) const {
1208 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001209 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001210 const MachineFrameInfo *MFI = MF.getFrameInfo();
David Majnemer93c22a42015-02-10 00:57:42 +00001211 // Offset will hold the offset from the stack pointer at function entry to the
1212 // object.
1213 // We need to factor in additional offsets applied during the prologue to the
1214 // frame, base, and stack pointer depending on which is used.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001215 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
David Majnemer93c22a42015-02-10 00:57:42 +00001216 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1217 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001218 uint64_t StackSize = MFI->getStackSize();
David Majnemer93c22a42015-02-10 00:57:42 +00001219 unsigned SlotSize = RegInfo->getSlotSize();
1220 bool HasFP = hasFP(MF);
1221 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1222 int64_t FPDelta = 0;
1223
1224 if (IsWinEH) {
1225 uint64_t NumBytes = 0;
1226 // Calculate required stack adjustment.
1227 uint64_t FrameSize = StackSize - SlotSize;
1228 // If required, include space for extra hidden slot for stashing base pointer.
1229 if (X86FI->getRestoreBasePointer())
1230 FrameSize += SlotSize;
1231 uint64_t SEHStackAllocAmt = StackSize;
1232 if (RegInfo->needsStackRealignment(MF)) {
1233 // Callee-saved registers are pushed on stack before the stack
1234 // is realigned.
1235 FrameSize -= CSSize;
1236
1237 uint64_t MaxAlign =
1238 calculateMaxStackAlign(MF); // Desired stack alignment.
1239 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1240 SEHStackAllocAmt = RoundUpToAlignment(SEHStackAllocAmt, 16);
1241 } else {
1242 NumBytes = FrameSize - CSSize;
1243 }
1244 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1245 // FPDelta is the offset from the "traditional" FP location of the old base
1246 // pointer followed by return address and the location required by the
1247 // restricted Win64 prologue.
1248 // Add FPDelta to all offsets below that go through the frame pointer.
1249 FPDelta = SEHStackAllocAmt - SEHFrameOffset;
1250 }
1251
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001252
1253 if (RegInfo->hasBasePointer(MF)) {
David Majnemer93c22a42015-02-10 00:57:42 +00001254 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001255 if (FI < 0) {
1256 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001257 return Offset + SlotSize + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001258 } else {
1259 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1260 return Offset + StackSize;
1261 }
1262 } else if (RegInfo->needsStackRealignment(MF)) {
1263 if (FI < 0) {
1264 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001265 return Offset + SlotSize + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001266 } else {
1267 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1268 return Offset + StackSize;
1269 }
1270 // FIXME: Support tail calls
1271 } else {
David Majnemer93c22a42015-02-10 00:57:42 +00001272 if (!HasFP)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001273 return Offset + StackSize;
David Majnemer93c22a42015-02-10 00:57:42 +00001274 if (IsWinEH)
1275 return Offset + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001276
1277 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001278 Offset += SlotSize;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001279
1280 // Skip the RETADDR move area
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001281 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1282 if (TailCallReturnAddrDelta < 0)
1283 Offset -= TailCallReturnAddrDelta;
1284 }
1285
1286 return Offset;
1287}
1288
1289int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1290 unsigned &FrameReg) const {
1291 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001292 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001293 // We can't calculate offset from frame pointer if the stack is realigned,
1294 // so enforce usage of stack/base pointer. The base pointer is used when we
1295 // have dynamic allocas in addition to dynamic realignment.
1296 if (RegInfo->hasBasePointer(MF))
1297 FrameReg = RegInfo->getBaseRegister();
1298 else if (RegInfo->needsStackRealignment(MF))
1299 FrameReg = RegInfo->getStackRegister();
1300 else
1301 FrameReg = RegInfo->getFrameRegister(MF);
1302 return getFrameIndexOffset(MF, FI);
1303}
1304
1305// Simplified from getFrameIndexOffset keeping only StackPointer cases
1306int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1307 const MachineFrameInfo *MFI = MF.getFrameInfo();
1308 // Does not include any dynamic realign.
1309 const uint64_t StackSize = MFI->getStackSize();
1310 {
1311#ifndef NDEBUG
1312 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001313 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001314 // Note: LLVM arranges the stack as:
1315 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1316 // > "Stack Slots" (<--SP)
1317 // We can always address StackSlots from RSP. We can usually (unless
1318 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1319 // address them from RBP. FixedObjects can be placed anywhere in the stack
1320 // frame depending on their specific requirements (i.e. we can actually
1321 // refer to arguments to the function which are stored in the *callers*
1322 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1323 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1324
1325 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1326
1327 // We don't handle tail calls, and shouldn't be seeing them
1328 // either.
1329 int TailCallReturnAddrDelta =
1330 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1331 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1332#endif
1333 }
1334
1335 // This is how the math works out:
1336 //
1337 // %rsp grows (i.e. gets lower) left to right. Each box below is
1338 // one word (eight bytes). Obj0 is the stack slot we're trying to
1339 // get to.
1340 //
1341 // ----------------------------------
1342 // | BP | Obj0 | Obj1 | ... | ObjN |
1343 // ----------------------------------
1344 // ^ ^ ^ ^
1345 // A B C E
1346 //
1347 // A is the incoming stack pointer.
1348 // (B - A) is the local area offset (-8 for x86-64) [1]
1349 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1350 //
1351 // |(E - B)| is the StackSize (absolute value, positive). For a
1352 // stack that grown down, this works out to be (B - E). [3]
1353 //
1354 // E is also the value of %rsp after stack has been set up, and we
1355 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1356 // (C - E) == (C - A) - (B - A) + (B - E)
1357 // { Using [1], [2] and [3] above }
1358 // == getObjectOffset - LocalAreaOffset + StackSize
1359 //
1360
1361 // Get the Offset from the StackPointer
1362 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1363
1364 return Offset + StackSize;
1365}
1366// Simplified from getFrameIndexReference keeping only StackPointer cases
Eric Christopher05b81972015-02-02 17:38:43 +00001367int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1368 int FI,
1369 unsigned &FrameReg) const {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001370 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001371 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001372 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1373
1374 FrameReg = RegInfo->getStackRegister();
1375 return getFrameIndexOffsetFromSP(MF, FI);
1376}
1377
1378bool X86FrameLowering::assignCalleeSavedSpillSlots(
1379 MachineFunction &MF, const TargetRegisterInfo *TRI,
1380 std::vector<CalleeSavedInfo> &CSI) const {
1381 MachineFrameInfo *MFI = MF.getFrameInfo();
1382 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001383 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001384 unsigned SlotSize = RegInfo->getSlotSize();
1385 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1386
1387 unsigned CalleeSavedFrameSize = 0;
1388 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1389
1390 if (hasFP(MF)) {
1391 // emitPrologue always spills frame register the first thing.
1392 SpillSlotOffset -= SlotSize;
1393 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1394
1395 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1396 // the frame register, we can delete it from CSI list and not have to worry
1397 // about avoiding it later.
1398 unsigned FPReg = RegInfo->getFrameRegister(MF);
1399 for (unsigned i = 0; i < CSI.size(); ++i) {
1400 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1401 CSI.erase(CSI.begin() + i);
1402 break;
1403 }
1404 }
1405 }
1406
1407 // Assign slots for GPRs. It increases frame size.
1408 for (unsigned i = CSI.size(); i != 0; --i) {
1409 unsigned Reg = CSI[i - 1].getReg();
1410
1411 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1412 continue;
1413
1414 SpillSlotOffset -= SlotSize;
1415 CalleeSavedFrameSize += SlotSize;
1416
1417 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1418 CSI[i - 1].setFrameIdx(SlotIndex);
1419 }
1420
1421 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1422
1423 // Assign slots for XMMs.
1424 for (unsigned i = CSI.size(); i != 0; --i) {
1425 unsigned Reg = CSI[i - 1].getReg();
1426 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1427 continue;
1428
1429 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1430 // ensure alignment
1431 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1432 // spill into slot
1433 SpillSlotOffset -= RC->getSize();
1434 int SlotIndex =
1435 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1436 CSI[i - 1].setFrameIdx(SlotIndex);
1437 MFI->ensureMaxAlignment(RC->getAlignment());
1438 }
1439
1440 return true;
1441}
1442
1443bool X86FrameLowering::spillCalleeSavedRegisters(
1444 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1445 const std::vector<CalleeSavedInfo> &CSI,
1446 const TargetRegisterInfo *TRI) const {
1447 DebugLoc DL = MBB.findDebugLoc(MI);
1448
1449 MachineFunction &MF = *MBB.getParent();
Eric Christopher05b81972015-02-02 17:38:43 +00001450 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1451 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001452
1453 // Push GPRs. It increases frame size.
1454 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1455 for (unsigned i = CSI.size(); i != 0; --i) {
1456 unsigned Reg = CSI[i - 1].getReg();
1457
1458 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1459 continue;
1460 // Add the callee-saved register as live-in. It's killed at the spill.
1461 MBB.addLiveIn(Reg);
1462
1463 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1464 .setMIFlag(MachineInstr::FrameSetup);
1465 }
1466
1467 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1468 // It can be done by spilling XMMs to stack frame.
1469 for (unsigned i = CSI.size(); i != 0; --i) {
1470 unsigned Reg = CSI[i-1].getReg();
1471 if (X86::GR64RegClass.contains(Reg) ||
1472 X86::GR32RegClass.contains(Reg))
1473 continue;
1474 // Add the callee-saved register as live-in. It's killed at the spill.
1475 MBB.addLiveIn(Reg);
1476 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1477
1478 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1479 TRI);
1480 --MI;
1481 MI->setFlag(MachineInstr::FrameSetup);
1482 ++MI;
1483 }
1484
1485 return true;
1486}
1487
1488bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1489 MachineBasicBlock::iterator MI,
1490 const std::vector<CalleeSavedInfo> &CSI,
1491 const TargetRegisterInfo *TRI) const {
1492 if (CSI.empty())
1493 return false;
1494
1495 DebugLoc DL = MBB.findDebugLoc(MI);
1496
1497 MachineFunction &MF = *MBB.getParent();
Eric Christopher05b81972015-02-02 17:38:43 +00001498 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1499 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001500
1501 // Reload XMMs from stack frame.
1502 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1503 unsigned Reg = CSI[i].getReg();
1504 if (X86::GR64RegClass.contains(Reg) ||
1505 X86::GR32RegClass.contains(Reg))
1506 continue;
1507
1508 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1509 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1510 }
1511
1512 // POP GPRs.
1513 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1514 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1515 unsigned Reg = CSI[i].getReg();
1516 if (!X86::GR64RegClass.contains(Reg) &&
1517 !X86::GR32RegClass.contains(Reg))
1518 continue;
1519
1520 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1521 }
1522 return true;
1523}
1524
1525void
1526X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1527 RegScavenger *RS) const {
1528 MachineFrameInfo *MFI = MF.getFrameInfo();
1529 const X86RegisterInfo *RegInfo =
Eric Christopher05b81972015-02-02 17:38:43 +00001530 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001531 unsigned SlotSize = RegInfo->getSlotSize();
1532
1533 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1534 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1535
1536 if (TailCallReturnAddrDelta < 0) {
1537 // create RETURNADDR area
1538 // arg
1539 // arg
1540 // RETADDR
1541 // { ...
1542 // RETADDR area
1543 // ...
1544 // }
1545 // [EBP]
1546 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1547 TailCallReturnAddrDelta - SlotSize, true);
1548 }
1549
1550 // Spill the BasePtr if it's used.
1551 if (RegInfo->hasBasePointer(MF))
1552 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1553}
1554
1555static bool
1556HasNestArgument(const MachineFunction *MF) {
1557 const Function *F = MF->getFunction();
1558 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1559 I != E; I++) {
1560 if (I->hasNestAttr())
1561 return true;
1562 }
1563 return false;
1564}
1565
1566/// GetScratchRegister - Get a temp register for performing work in the
1567/// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1568/// and the properties of the function either one or two registers will be
1569/// needed. Set primary to true for the first register, false for the second.
1570static unsigned
1571GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1572 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1573
1574 // Erlang stuff.
1575 if (CallingConvention == CallingConv::HiPE) {
1576 if (Is64Bit)
1577 return Primary ? X86::R14 : X86::R13;
1578 else
1579 return Primary ? X86::EBX : X86::EDI;
1580 }
1581
1582 if (Is64Bit) {
1583 if (IsLP64)
1584 return Primary ? X86::R11 : X86::R12;
1585 else
1586 return Primary ? X86::R11D : X86::R12D;
1587 }
1588
1589 bool IsNested = HasNestArgument(&MF);
1590
1591 if (CallingConvention == CallingConv::X86_FastCall ||
1592 CallingConvention == CallingConv::Fast) {
1593 if (IsNested)
1594 report_fatal_error("Segmented stacks does not support fastcall with "
1595 "nested function.");
1596 return Primary ? X86::EAX : X86::ECX;
1597 }
1598 if (IsNested)
1599 return Primary ? X86::EDX : X86::EAX;
1600 return Primary ? X86::ECX : X86::EAX;
1601}
1602
1603// The stack limit in the TCB is set to this many bytes above the actual stack
1604// limit.
1605static const uint64_t kSplitStackAvailable = 256;
1606
1607void
1608X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1609 MachineBasicBlock &prologueMBB = MF.front();
1610 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopher05b81972015-02-02 17:38:43 +00001611 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1612 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001613 uint64_t StackSize;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001614 bool Is64Bit = STI.is64Bit();
1615 const bool IsLP64 = STI.isTarget64BitLP64();
1616 unsigned TlsReg, TlsOffset;
1617 DebugLoc DL;
1618
1619 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1620 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1621 "Scratch register is live-in");
1622
1623 if (MF.getFunction()->isVarArg())
1624 report_fatal_error("Segmented stacks do not support vararg functions.");
1625 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1626 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1627 !STI.isTargetDragonFly())
1628 report_fatal_error("Segmented stacks not supported on this platform.");
1629
1630 // Eventually StackSize will be calculated by a link-time pass; which will
1631 // also decide whether checking code needs to be injected into this particular
1632 // prologue.
1633 StackSize = MFI->getStackSize();
1634
1635 // Do not generate a prologue for functions with a stack of size zero
1636 if (StackSize == 0)
1637 return;
1638
1639 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1640 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1641 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1642 bool IsNested = false;
1643
1644 // We need to know if the function has a nest argument only in 64 bit mode.
1645 if (Is64Bit)
1646 IsNested = HasNestArgument(&MF);
1647
1648 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1649 // allocMBB needs to be last (terminating) instruction.
1650
1651 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1652 e = prologueMBB.livein_end(); i != e; i++) {
1653 allocMBB->addLiveIn(*i);
1654 checkMBB->addLiveIn(*i);
1655 }
1656
1657 if (IsNested)
1658 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1659
1660 MF.push_front(allocMBB);
1661 MF.push_front(checkMBB);
1662
1663 // When the frame size is less than 256 we just compare the stack
1664 // boundary directly to the value of the stack pointer, per gcc.
1665 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1666
1667 // Read the limit off the current stacklet off the stack_guard location.
1668 if (Is64Bit) {
1669 if (STI.isTargetLinux()) {
1670 TlsReg = X86::FS;
1671 TlsOffset = IsLP64 ? 0x70 : 0x40;
1672 } else if (STI.isTargetDarwin()) {
1673 TlsReg = X86::GS;
1674 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1675 } else if (STI.isTargetWin64()) {
1676 TlsReg = X86::GS;
1677 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1678 } else if (STI.isTargetFreeBSD()) {
1679 TlsReg = X86::FS;
1680 TlsOffset = 0x18;
1681 } else if (STI.isTargetDragonFly()) {
1682 TlsReg = X86::FS;
1683 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1684 } else {
1685 report_fatal_error("Segmented stacks not supported on this platform.");
1686 }
1687
1688 if (CompareStackPointer)
1689 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1690 else
1691 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1692 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1693
1694 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1695 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1696 } else {
1697 if (STI.isTargetLinux()) {
1698 TlsReg = X86::GS;
1699 TlsOffset = 0x30;
1700 } else if (STI.isTargetDarwin()) {
1701 TlsReg = X86::GS;
1702 TlsOffset = 0x48 + 90*4;
1703 } else if (STI.isTargetWin32()) {
1704 TlsReg = X86::FS;
1705 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1706 } else if (STI.isTargetDragonFly()) {
1707 TlsReg = X86::FS;
1708 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1709 } else if (STI.isTargetFreeBSD()) {
1710 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1711 } else {
1712 report_fatal_error("Segmented stacks not supported on this platform.");
1713 }
1714
1715 if (CompareStackPointer)
1716 ScratchReg = X86::ESP;
1717 else
1718 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1719 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1720
1721 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1722 STI.isTargetDragonFly()) {
1723 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1724 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1725 } else if (STI.isTargetDarwin()) {
1726
1727 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1728 unsigned ScratchReg2;
1729 bool SaveScratch2;
1730 if (CompareStackPointer) {
1731 // The primary scratch register is available for holding the TLS offset.
1732 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1733 SaveScratch2 = false;
1734 } else {
1735 // Need to use a second register to hold the TLS offset
1736 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1737
1738 // Unfortunately, with fastcc the second scratch register may hold an
1739 // argument.
1740 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1741 }
1742
1743 // If Scratch2 is live-in then it needs to be saved.
1744 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1745 "Scratch register is live-in and not saved");
1746
1747 if (SaveScratch2)
1748 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1749 .addReg(ScratchReg2, RegState::Kill);
1750
1751 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1752 .addImm(TlsOffset);
1753 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1754 .addReg(ScratchReg)
1755 .addReg(ScratchReg2).addImm(1).addReg(0)
1756 .addImm(0)
1757 .addReg(TlsReg);
1758
1759 if (SaveScratch2)
1760 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1761 }
1762 }
1763
1764 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1765 // It jumps to normal execution of the function body.
1766 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&prologueMBB);
1767
1768 // On 32 bit we first push the arguments size and then the frame size. On 64
1769 // bit, we pass the stack frame size in r10 and the argument size in r11.
1770 if (Is64Bit) {
1771 // Functions with nested arguments use R10, so it needs to be saved across
1772 // the call to _morestack
1773
1774 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1775 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1776 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1777 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1778 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1779
1780 if (IsNested)
1781 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1782
1783 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1784 .addImm(StackSize);
1785 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1786 .addImm(X86FI->getArgumentStackSize());
1787 MF.getRegInfo().setPhysRegUsed(Reg10);
1788 MF.getRegInfo().setPhysRegUsed(Reg11);
1789 } else {
1790 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1791 .addImm(X86FI->getArgumentStackSize());
1792 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1793 .addImm(StackSize);
1794 }
1795
1796 // __morestack is in libgcc
1797 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1798 // Under the large code model, we cannot assume that __morestack lives
1799 // within 2^31 bytes of the call site, so we cannot use pc-relative
1800 // addressing. We cannot perform the call via a temporary register,
1801 // as the rax register may be used to store the static chain, and all
1802 // other suitable registers may be either callee-save or used for
1803 // parameter passing. We cannot use the stack at this point either
1804 // because __morestack manipulates the stack directly.
1805 //
1806 // To avoid these issues, perform an indirect call via a read-only memory
1807 // location containing the address.
1808 //
1809 // This solution is not perfect, as it assumes that the .rodata section
1810 // is laid out within 2^31 bytes of each function body, but this seems
1811 // to be sufficient for JIT.
1812 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1813 .addReg(X86::RIP)
1814 .addImm(0)
1815 .addReg(0)
1816 .addExternalSymbol("__morestack_addr")
1817 .addReg(0);
1818 MF.getMMI().setUsesMorestackAddr(true);
1819 } else {
1820 if (Is64Bit)
1821 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1822 .addExternalSymbol("__morestack");
1823 else
1824 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1825 .addExternalSymbol("__morestack");
1826 }
1827
1828 if (IsNested)
1829 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1830 else
1831 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1832
1833 allocMBB->addSuccessor(&prologueMBB);
1834
1835 checkMBB->addSuccessor(allocMBB);
1836 checkMBB->addSuccessor(&prologueMBB);
1837
1838#ifdef XDEBUG
1839 MF.verify();
1840#endif
1841}
1842
1843/// Erlang programs may need a special prologue to handle the stack size they
1844/// might need at runtime. That is because Erlang/OTP does not implement a C
1845/// stack but uses a custom implementation of hybrid stack/heap architecture.
1846/// (for more information see Eric Stenman's Ph.D. thesis:
1847/// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1848///
1849/// CheckStack:
1850/// temp0 = sp - MaxStack
1851/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1852/// OldStart:
1853/// ...
1854/// IncStack:
1855/// call inc_stack # doubles the stack space
1856/// temp0 = sp - MaxStack
1857/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1858void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
Eric Christopher05b81972015-02-02 17:38:43 +00001859 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1860 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001861 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopher05b81972015-02-02 17:38:43 +00001862 const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001863 const bool Is64Bit = STI.is64Bit();
1864 const bool IsLP64 = STI.isTarget64BitLP64();
1865 DebugLoc DL;
1866 // HiPE-specific values
1867 const unsigned HipeLeafWords = 24;
1868 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1869 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1870 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1871 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1872 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1873
1874 assert(STI.isTargetLinux() &&
1875 "HiPE prologue is only supported on Linux operating systems.");
1876
1877 // Compute the largest caller's frame that is needed to fit the callees'
1878 // frames. This 'MaxStack' is computed from:
1879 //
1880 // a) the fixed frame size, which is the space needed for all spilled temps,
1881 // b) outgoing on-stack parameter areas, and
1882 // c) the minimum stack space this function needs to make available for the
1883 // functions it calls (a tunable ABI property).
1884 if (MFI->hasCalls()) {
1885 unsigned MoreStackForCalls = 0;
1886
1887 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1888 MBBI != MBBE; ++MBBI)
1889 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1890 MI != ME; ++MI) {
1891 if (!MI->isCall())
1892 continue;
1893
1894 // Get callee operand.
1895 const MachineOperand &MO = MI->getOperand(0);
1896
1897 // Only take account of global function calls (no closures etc.).
1898 if (!MO.isGlobal())
1899 continue;
1900
1901 const Function *F = dyn_cast<Function>(MO.getGlobal());
1902 if (!F)
1903 continue;
1904
1905 // Do not update 'MaxStack' for primitive and built-in functions
1906 // (encoded with names either starting with "erlang."/"bif_" or not
1907 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1908 // "_", such as the BIF "suspend_0") as they are executed on another
1909 // stack.
1910 if (F->getName().find("erlang.") != StringRef::npos ||
1911 F->getName().find("bif_") != StringRef::npos ||
1912 F->getName().find_first_of("._") == StringRef::npos)
1913 continue;
1914
1915 unsigned CalleeStkArity =
1916 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1917 if (HipeLeafWords - 1 > CalleeStkArity)
1918 MoreStackForCalls = std::max(MoreStackForCalls,
1919 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1920 }
1921 MaxStack += MoreStackForCalls;
1922 }
1923
1924 // If the stack frame needed is larger than the guaranteed then runtime checks
1925 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1926 if (MaxStack > Guaranteed) {
1927 MachineBasicBlock &prologueMBB = MF.front();
1928 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1929 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1930
1931 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1932 E = prologueMBB.livein_end(); I != E; I++) {
1933 stackCheckMBB->addLiveIn(*I);
1934 incStackMBB->addLiveIn(*I);
1935 }
1936
1937 MF.push_front(incStackMBB);
1938 MF.push_front(stackCheckMBB);
1939
1940 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1941 unsigned LEAop, CMPop, CALLop;
1942 if (Is64Bit) {
1943 SPReg = X86::RSP;
1944 PReg = X86::RBP;
1945 LEAop = X86::LEA64r;
1946 CMPop = X86::CMP64rm;
1947 CALLop = X86::CALL64pcrel32;
1948 SPLimitOffset = 0x90;
1949 } else {
1950 SPReg = X86::ESP;
1951 PReg = X86::EBP;
1952 LEAop = X86::LEA32r;
1953 CMPop = X86::CMP32rm;
1954 CALLop = X86::CALLpcrel32;
1955 SPLimitOffset = 0x4c;
1956 }
1957
1958 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1959 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1960 "HiPE prologue scratch register is live-in");
1961
1962 // Create new MBB for StackCheck:
1963 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1964 SPReg, false, -MaxStack);
1965 // SPLimitOffset is in a fixed heap location (pointed by BP).
1966 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1967 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1968 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&prologueMBB);
1969
1970 // Create new MBB for IncStack:
1971 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1972 addExternalSymbol("inc_stack_0");
1973 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1974 SPReg, false, -MaxStack);
1975 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1976 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1977 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1978
1979 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1980 stackCheckMBB->addSuccessor(incStackMBB, 1);
1981 incStackMBB->addSuccessor(&prologueMBB, 99);
1982 incStackMBB->addSuccessor(incStackMBB, 1);
1983 }
1984#ifdef XDEBUG
1985 MF.verify();
1986#endif
1987}
1988
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001989void X86FrameLowering::
1990eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1991 MachineBasicBlock::iterator I) const {
Eric Christopher05b81972015-02-02 17:38:43 +00001992 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1993 const TargetInstrInfo &TII = *STI.getInstrInfo();
1994 const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001995 unsigned StackPtr = RegInfo.getStackRegister();
1996 bool reserveCallFrame = hasReservedCallFrame(MF);
1997 int Opcode = I->getOpcode();
1998 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001999 bool IsLP64 = STI.isTarget64BitLP64();
2000 DebugLoc DL = I->getDebugLoc();
2001 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002002 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002003 I = MBB.erase(I);
2004
2005 if (!reserveCallFrame) {
2006 // If the stack pointer can be changed after prologue, turn the
2007 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
2008 // adjcallstackdown instruction into 'add ESP, <amt>'
2009 if (Amount == 0)
2010 return;
2011
2012 // We need to keep the stack aligned properly. To do this, we round the
2013 // amount of space needed for the outgoing arguments up to the next
2014 // alignment boundary.
David Majnemer93c22a42015-02-10 00:57:42 +00002015 unsigned StackAlign = getStackAlignment();
2016 Amount = RoundUpToAlignment(Amount, StackAlign);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002017
2018 MachineInstr *New = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002019
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002020 // Factor out the amount that gets handled inside the sequence
2021 // (Pushes of argument for frame setup, callee pops for frame destroy)
2022 Amount -= InternalAmt;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002023
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002024 if (Amount) {
2025 if (Opcode == TII.getCallFrameSetupOpcode()) {
2026 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
2027 .addReg(StackPtr).addImm(Amount);
2028 } else {
2029 assert(Opcode == TII.getCallFrameDestroyOpcode());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002030
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002031 unsigned Opc = getADDriOpcode(IsLP64, Amount);
2032 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
2033 .addReg(StackPtr).addImm(Amount);
2034 }
2035 }
2036
2037 if (New) {
2038 // The EFLAGS implicit def is dead.
2039 New->getOperand(3).setIsDead();
2040
2041 // Replace the pseudo instruction with a new instruction.
2042 MBB.insert(I, New);
2043 }
2044
2045 return;
2046 }
2047
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002048 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002049 // If we are performing frame pointer elimination and if the callee pops
2050 // something off the stack pointer, add it back. We do this until we have
2051 // more advanced stack pointer tracking ability.
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002052 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002053 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002054 .addReg(StackPtr).addImm(InternalAmt);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002055
2056 // The EFLAGS implicit def is dead.
2057 New->getOperand(3).setIsDead();
2058
2059 // We are not tracking the stack pointer adjustment by the callee, so make
2060 // sure we restore the stack pointer immediately after the call, there may
2061 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2062 MachineBasicBlock::iterator B = MBB.begin();
2063 while (I != B && !std::prev(I)->isCall())
2064 --I;
2065 MBB.insert(I, New);
2066 }
2067}
2068