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