Reapply r238011 with a fix for the trap instruction.
[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   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
569   MachineBasicBlock::iterator MBBI = MBB.begin();
570   MachineFrameInfo *MFI = MF.getFrameInfo();
571   const Function *Fn = MF.getFunction();
572   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
573   const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
574   const TargetInstrInfo &TII = *STI.getInstrInfo();
575   MachineModuleInfo &MMI = MF.getMMI();
576   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
577   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
578   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
579   bool HasFP = hasFP(MF);
580   bool Is64Bit = STI.is64Bit();
581   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
582   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
583   bool IsWin64 = STI.isCallingConvWin64(Fn->getCallingConv());
584   // Not necessarily synonymous with IsWin64.
585   bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
586   bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
587   bool NeedsDwarfCFI =
588       !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
589   bool UseLEA = STI.useLeaForSP();
590   unsigned SlotSize = RegInfo->getSlotSize();
591   unsigned FramePtr = RegInfo->getFrameRegister(MF);
592   const unsigned MachineFramePtr =
593       STI.isTarget64BitILP32()
594           ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
595           : FramePtr;
596   unsigned StackPtr = RegInfo->getStackRegister();
597   unsigned BasePtr = RegInfo->getBaseRegister();
598   DebugLoc DL;
599
600   // Add RETADDR move area to callee saved frame size.
601   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
602   if (TailCallReturnAddrDelta && IsWinEH)
603     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
604
605   if (TailCallReturnAddrDelta < 0)
606     X86FI->setCalleeSavedFrameSize(
607       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
608
609   bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
610
611   // The default stack probe size is 4096 if the function has no stackprobesize
612   // attribute.
613   unsigned StackProbeSize = 4096;
614   if (Fn->hasFnAttribute("stack-probe-size"))
615     Fn->getFnAttribute("stack-probe-size")
616         .getValueAsString()
617         .getAsInteger(0, StackProbeSize);
618
619   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
620   // function, and use up to 128 bytes of stack space, don't have a frame
621   // pointer, calls, or dynamic alloca then we do not need to adjust the
622   // stack pointer (we fit in the Red Zone). We also check that we don't
623   // push and pop from the stack.
624   if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
625       !RegInfo->needsStackRealignment(MF) &&
626       !MFI->hasVarSizedObjects() && // No dynamic alloca.
627       !MFI->adjustsStack() &&       // No calls.
628       !IsWin64 &&                   // Win64 has no Red Zone
629       !usesTheStack(MF) &&          // Don't push and pop.
630       !MF.shouldSplitStack()) {     // Regular stack
631     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
632     if (HasFP) MinSize += SlotSize;
633     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
634     MFI->setStackSize(StackSize);
635   }
636
637   // Insert stack pointer adjustment for later moving of return addr.  Only
638   // applies to tail call optimized functions where the callee argument stack
639   // size is bigger than the callers.
640   if (TailCallReturnAddrDelta < 0) {
641     MachineInstr *MI =
642       BuildMI(MBB, MBBI, DL,
643               TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
644               StackPtr)
645         .addReg(StackPtr)
646         .addImm(-TailCallReturnAddrDelta)
647         .setMIFlag(MachineInstr::FrameSetup);
648     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
649   }
650
651   // Mapping for machine moves:
652   //
653   //   DST: VirtualFP AND
654   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
655   //        ELSE                        => DW_CFA_def_cfa
656   //
657   //   SRC: VirtualFP AND
658   //        DST: Register               => DW_CFA_def_cfa_register
659   //
660   //   ELSE
661   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
662   //        REG < 64                    => DW_CFA_offset + Reg
663   //        ELSE                        => DW_CFA_offset_extended
664
665   uint64_t NumBytes = 0;
666   int stackGrowth = -SlotSize;
667
668   if (HasFP) {
669     // Calculate required stack adjustment.
670     uint64_t FrameSize = StackSize - SlotSize;
671     // If required, include space for extra hidden slot for stashing base pointer.
672     if (X86FI->getRestoreBasePointer())
673       FrameSize += SlotSize;
674
675     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
676
677     // Callee-saved registers are pushed on stack before the stack is realigned.
678     if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
679       NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
680
681     // Get the offset of the stack slot for the EBP register, which is
682     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
683     // Update the frame offset adjustment.
684     MFI->setOffsetAdjustment(-NumBytes);
685
686     // Save EBP/RBP into the appropriate stack slot.
687     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
688       .addReg(MachineFramePtr, RegState::Kill)
689       .setMIFlag(MachineInstr::FrameSetup);
690
691     if (NeedsDwarfCFI) {
692       // Mark the place where EBP/RBP was saved.
693       // Define the current CFA rule to use the provided offset.
694       assert(StackSize);
695       unsigned CFIIndex = MMI.addFrameInst(
696           MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
697       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
698           .addCFIIndex(CFIIndex);
699
700       // Change the rule for the FramePtr to be an "offset" rule.
701       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
702       CFIIndex = MMI.addFrameInst(
703           MCCFIInstruction::createOffset(nullptr,
704                                          DwarfFramePtr, 2 * stackGrowth));
705       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
706           .addCFIIndex(CFIIndex);
707     }
708
709     if (NeedsWinEH) {
710       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
711           .addImm(FramePtr)
712           .setMIFlag(MachineInstr::FrameSetup);
713     }
714
715     if (!IsWinEH) {
716       // Update EBP with the new base value.
717       BuildMI(MBB, MBBI, DL,
718               TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
719               FramePtr)
720           .addReg(StackPtr)
721           .setMIFlag(MachineInstr::FrameSetup);
722     }
723
724     if (NeedsDwarfCFI) {
725       // Mark effective beginning of when frame pointer becomes valid.
726       // Define the current CFA to use the EBP/RBP register.
727       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
728       unsigned CFIIndex = MMI.addFrameInst(
729           MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
730       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
731           .addCFIIndex(CFIIndex);
732     }
733
734     // Mark the FramePtr as live-in in every block.
735     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
736       I->addLiveIn(MachineFramePtr);
737   } else {
738     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
739   }
740
741   // Skip the callee-saved push instructions.
742   bool PushedRegs = false;
743   int StackOffset = 2 * stackGrowth;
744
745   while (MBBI != MBB.end() &&
746          (MBBI->getOpcode() == X86::PUSH32r ||
747           MBBI->getOpcode() == X86::PUSH64r)) {
748     PushedRegs = true;
749     unsigned Reg = MBBI->getOperand(0).getReg();
750     ++MBBI;
751
752     if (!HasFP && NeedsDwarfCFI) {
753       // Mark callee-saved push instruction.
754       // Define the current CFA rule to use the provided offset.
755       assert(StackSize);
756       unsigned CFIIndex = MMI.addFrameInst(
757           MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
758       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
759           .addCFIIndex(CFIIndex);
760       StackOffset += stackGrowth;
761     }
762
763     if (NeedsWinEH) {
764       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
765           MachineInstr::FrameSetup);
766     }
767   }
768
769   // Realign stack after we pushed callee-saved registers (so that we'll be
770   // able to calculate their offsets from the frame pointer).
771   // Don't do this for Win64, it needs to realign the stack after the prologue.
772   if (!IsWinEH && RegInfo->needsStackRealignment(MF)) {
773     assert(HasFP && "There should be a frame pointer if stack is realigned.");
774     uint64_t Val = -MaxAlign;
775     MachineInstr *MI =
776         BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
777                 StackPtr)
778             .addReg(StackPtr)
779             .addImm(Val)
780             .setMIFlag(MachineInstr::FrameSetup);
781
782     // The EFLAGS implicit def is dead.
783     MI->getOperand(3).setIsDead();
784   }
785
786   // If there is an SUB32ri of ESP immediately before this instruction, merge
787   // the two. This can be the case when tail call elimination is enabled and
788   // the callee has more arguments then the caller.
789   NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
790
791   // Adjust stack pointer: ESP -= numbytes.
792
793   // Windows and cygwin/mingw require a prologue helper routine when allocating
794   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
795   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
796   // stack and adjust the stack pointer in one go.  The 64-bit version of
797   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
798   // responsible for adjusting the stack pointer.  Touching the stack at 4K
799   // increments is necessary to ensure that the guard pages used by the OS
800   // virtual memory manager are allocated in correct sequence.
801   uint64_t AlignedNumBytes = NumBytes;
802   if (IsWinEH && RegInfo->needsStackRealignment(MF))
803     AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
804   if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
805     // Check whether EAX is livein for this function.
806     bool isEAXAlive = isEAXLiveIn(MF);
807
808     if (isEAXAlive) {
809       // Sanity check that EAX is not livein for this function.
810       // It should not be, so throw an assert.
811       assert(!Is64Bit && "EAX is livein in x64 case!");
812
813       // Save EAX
814       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
815         .addReg(X86::EAX, RegState::Kill)
816         .setMIFlag(MachineInstr::FrameSetup);
817     }
818
819     if (Is64Bit) {
820       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
821       // Function prologue is responsible for adjusting the stack pointer.
822       if (isUInt<32>(NumBytes)) {
823         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
824             .addImm(NumBytes)
825             .setMIFlag(MachineInstr::FrameSetup);
826       } else if (isInt<32>(NumBytes)) {
827         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
828             .addImm(NumBytes)
829             .setMIFlag(MachineInstr::FrameSetup);
830       } else {
831         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
832             .addImm(NumBytes)
833             .setMIFlag(MachineInstr::FrameSetup);
834       }
835     } else {
836       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
837       // We'll also use 4 already allocated bytes for EAX.
838       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
839         .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
840         .setMIFlag(MachineInstr::FrameSetup);
841     }
842
843     // Save a pointer to the MI where we set AX.
844     MachineBasicBlock::iterator SetRAX = MBBI;
845     --SetRAX;
846
847     // Call __chkstk, __chkstk_ms, or __alloca.
848     emitStackProbeCall(MF, MBB, MBBI, DL);
849
850     // Apply the frame setup flag to all inserted instrs.
851     for (; SetRAX != MBBI; ++SetRAX)
852       SetRAX->setFlag(MachineInstr::FrameSetup);
853
854     if (isEAXAlive) {
855       // Restore EAX
856       MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
857                                               X86::EAX),
858                                       StackPtr, false, NumBytes - 4);
859       MI->setFlag(MachineInstr::FrameSetup);
860       MBB.insert(MBBI, MI);
861     }
862   } else if (NumBytes) {
863     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
864                  UseLEA, TII, *RegInfo);
865   }
866
867   if (NeedsWinEH && NumBytes)
868     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
869         .addImm(NumBytes)
870         .setMIFlag(MachineInstr::FrameSetup);
871
872   int SEHFrameOffset = 0;
873   if (IsWinEH && HasFP) {
874     SEHFrameOffset = calculateSetFPREG(NumBytes);
875     if (SEHFrameOffset)
876       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
877                    StackPtr, false, SEHFrameOffset);
878     else
879       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr).addReg(StackPtr);
880
881     if (NeedsWinEH)
882       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
883           .addImm(FramePtr)
884           .addImm(SEHFrameOffset)
885           .setMIFlag(MachineInstr::FrameSetup);
886   }
887
888   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
889     const MachineInstr *FrameInstr = &*MBBI;
890     ++MBBI;
891
892     if (NeedsWinEH) {
893       int FI;
894       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
895         if (X86::FR64RegClass.contains(Reg)) {
896           int Offset = getFrameIndexOffset(MF, FI);
897           Offset += SEHFrameOffset;
898
899           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
900               .addImm(Reg)
901               .addImm(Offset)
902               .setMIFlag(MachineInstr::FrameSetup);
903         }
904       }
905     }
906   }
907
908   if (NeedsWinEH)
909     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
910         .setMIFlag(MachineInstr::FrameSetup);
911
912   // Realign stack after we spilled callee-saved registers (so that we'll be
913   // able to calculate their offsets from the frame pointer).
914   // Win64 requires aligning the stack after the prologue.
915   if (IsWinEH && RegInfo->needsStackRealignment(MF)) {
916     assert(HasFP && "There should be a frame pointer if stack is realigned.");
917     uint64_t Val = -MaxAlign;
918     MachineInstr *MI =
919         BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
920                 StackPtr)
921             .addReg(StackPtr)
922             .addImm(Val)
923             .setMIFlag(MachineInstr::FrameSetup);
924
925     // The EFLAGS implicit def is dead.
926     MI->getOperand(3).setIsDead();
927   }
928
929   // If we need a base pointer, set it up here. It's whatever the value
930   // of the stack pointer is at this point. Any variable size objects
931   // will be allocated after this, so we can still use the base pointer
932   // to reference locals.
933   if (RegInfo->hasBasePointer(MF)) {
934     // Update the base pointer with the current stack pointer.
935     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
936     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
937       .addReg(StackPtr)
938       .setMIFlag(MachineInstr::FrameSetup);
939     if (X86FI->getRestoreBasePointer()) {
940       // Stash value of base pointer.  Saving RSP instead of EBP shortens dependence chain.
941       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
942       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
943                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
944         .addReg(StackPtr)
945         .setMIFlag(MachineInstr::FrameSetup);
946     }
947   }
948
949   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
950     // Mark end of stack pointer adjustment.
951     if (!HasFP && NumBytes) {
952       // Define the current CFA rule to use the provided offset.
953       assert(StackSize);
954       unsigned CFIIndex = MMI.addFrameInst(
955           MCCFIInstruction::createDefCfaOffset(nullptr,
956                                                -StackSize + stackGrowth));
957
958       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
959           .addCFIIndex(CFIIndex);
960     }
961
962     // Emit DWARF info specifying the offsets of the callee-saved registers.
963     if (PushedRegs)
964       emitCalleeSavedFrameMoves(MBB, MBBI, DL);
965   }
966 }
967
968 bool X86FrameLowering::useLEAForSPInProlog(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.getSubtarget<X86Subtarget>().useLeaForSP() &&
976          (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF));
977 }
978
979 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
980                                     MachineBasicBlock &MBB) const {
981   const MachineFrameInfo *MFI = MF.getFrameInfo();
982   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
983   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
984   const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
985   const TargetInstrInfo &TII = *STI.getInstrInfo();
986   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
987   assert(MBBI != MBB.end() && "Returning block has no instructions");
988   DebugLoc DL = MBBI->getDebugLoc();
989   bool Is64Bit = STI.is64Bit();
990   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
991   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
992   const bool Is64BitILP32 = STI.isTarget64BitILP32();
993   unsigned SlotSize = RegInfo->getSlotSize();
994   unsigned FramePtr = RegInfo->getFrameRegister(MF);
995   unsigned MachineFramePtr =
996       Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
997                    : FramePtr;
998   unsigned StackPtr = RegInfo->getStackRegister();
999
1000   bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1001   bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
1002   bool UseLEAForSP = useLEAForSPInProlog(MF);
1003
1004   switch (MBBI->getOpcode()) {
1005   default:
1006     llvm_unreachable("Can only insert epilogue into returning blocks");
1007   case X86::RETQ:
1008   case X86::RETL:
1009   case X86::RETIL:
1010   case X86::RETIQ:
1011   case X86::TCRETURNdi:
1012   case X86::TCRETURNri:
1013   case X86::TCRETURNmi:
1014   case X86::TCRETURNdi64:
1015   case X86::TCRETURNri64:
1016   case X86::TCRETURNmi64:
1017   case X86::EH_RETURN:
1018   case X86::EH_RETURN64:
1019     break;  // These are ok
1020   }
1021
1022   // Get the number of bytes to allocate from the FrameInfo.
1023   uint64_t StackSize = MFI->getStackSize();
1024   uint64_t MaxAlign = calculateMaxStackAlign(MF);
1025   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1026   uint64_t NumBytes = 0;
1027
1028   if (hasFP(MF)) {
1029     // Calculate required stack adjustment.
1030     uint64_t FrameSize = StackSize - SlotSize;
1031     NumBytes = FrameSize - CSSize;
1032
1033     // Callee-saved registers were pushed on stack before the stack was
1034     // realigned.
1035     if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
1036       NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1037
1038     // Pop EBP.
1039     BuildMI(MBB, MBBI, DL,
1040             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1041   } else {
1042     NumBytes = StackSize - CSSize;
1043   }
1044   uint64_t SEHStackAllocAmt = NumBytes;
1045
1046   // Skip the callee-saved pop instructions.
1047   while (MBBI != MBB.begin()) {
1048     MachineBasicBlock::iterator PI = std::prev(MBBI);
1049     unsigned Opc = PI->getOpcode();
1050
1051     if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1052         !PI->isTerminator())
1053       break;
1054
1055     --MBBI;
1056   }
1057   MachineBasicBlock::iterator FirstCSPop = MBBI;
1058
1059   DL = MBBI->getDebugLoc();
1060
1061   // If there is an ADD32ri or SUB32ri of ESP immediately before this
1062   // instruction, merge the two instructions.
1063   if (NumBytes || MFI->hasVarSizedObjects())
1064     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1065
1066   // If dynamic alloca is used, then reset esp to point to the last callee-saved
1067   // slot before popping them off! Same applies for the case, when stack was
1068   // realigned.
1069   if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1070     if (RegInfo->needsStackRealignment(MF))
1071       MBBI = FirstCSPop;
1072     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1073     uint64_t LEAAmount = IsWinEH ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1074
1075     // There are only two legal forms of epilogue:
1076     // - add SEHAllocationSize, %rsp
1077     // - lea SEHAllocationSize(%FramePtr), %rsp
1078     //
1079     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1080     // However, we may use this sequence if we have a frame pointer because the
1081     // effects of the prologue can safely be undone.
1082     if (LEAAmount != 0) {
1083       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1084       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1085                    FramePtr, false, LEAAmount);
1086       --MBBI;
1087     } else {
1088       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1089       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1090         .addReg(FramePtr);
1091       --MBBI;
1092     }
1093   } else if (NumBytes) {
1094     // Adjust stack pointer back: ESP += numbytes.
1095     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr,
1096                  UseLEAForSP, TII, *RegInfo);
1097     --MBBI;
1098   }
1099
1100   // Windows unwinder will not invoke function's exception handler if IP is
1101   // either in prologue or in epilogue.  This behavior causes a problem when a
1102   // call immediately precedes an epilogue, because the return address points
1103   // into the epilogue.  To cope with that, we insert an epilogue marker here,
1104   // then replace it with a 'nop' if it ends up immediately after a CALL in the
1105   // final emitted code.
1106   if (NeedsWinEH)
1107     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1108
1109   // Add the return addr area delta back since we are not tail calling.
1110   int Offset = -1 * X86FI->getTCReturnAddrDelta();
1111   assert(Offset >= 0 && "TCDelta should never be positive");
1112   if (Offset) {
1113     MBBI = MBB.getFirstTerminator();
1114
1115     // Check for possible merge with preceding ADD instruction.
1116     Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1117     emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1118                  UseLEAForSP, TII, *RegInfo);
1119   }
1120 }
1121
1122 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1123                                           int FI) const {
1124   const X86RegisterInfo *RegInfo =
1125       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1126   const MachineFrameInfo *MFI = MF.getFrameInfo();
1127   // Offset will hold the offset from the stack pointer at function entry to the
1128   // object.
1129   // We need to factor in additional offsets applied during the prologue to the
1130   // frame, base, and stack pointer depending on which is used.
1131   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1132   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1133   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1134   uint64_t StackSize = MFI->getStackSize();
1135   unsigned SlotSize = RegInfo->getSlotSize();
1136   bool HasFP = hasFP(MF);
1137   bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1138   int64_t FPDelta = 0;
1139
1140   if (IsWinEH) {
1141     assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1142
1143     // Calculate required stack adjustment.
1144     uint64_t FrameSize = StackSize - SlotSize;
1145     // If required, include space for extra hidden slot for stashing base pointer.
1146     if (X86FI->getRestoreBasePointer())
1147       FrameSize += SlotSize;
1148     uint64_t NumBytes = FrameSize - CSSize;
1149
1150     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1151     if (FI && FI == X86FI->getFAIndex())
1152       return -SEHFrameOffset;
1153
1154     // FPDelta is the offset from the "traditional" FP location of the old base
1155     // pointer followed by return address and the location required by the
1156     // restricted Win64 prologue.
1157     // Add FPDelta to all offsets below that go through the frame pointer.
1158     FPDelta = FrameSize - SEHFrameOffset;
1159     assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1160            "FPDelta isn't aligned per the Win64 ABI!");
1161   }
1162
1163
1164   if (RegInfo->hasBasePointer(MF)) {
1165     assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1166     if (FI < 0) {
1167       // Skip the saved EBP.
1168       return Offset + SlotSize + FPDelta;
1169     } else {
1170       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1171       return Offset + StackSize;
1172     }
1173   } else if (RegInfo->needsStackRealignment(MF)) {
1174     if (FI < 0) {
1175       // Skip the saved EBP.
1176       return Offset + SlotSize + FPDelta;
1177     } else {
1178       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1179       return Offset + StackSize;
1180     }
1181     // FIXME: Support tail calls
1182   } else {
1183     if (!HasFP)
1184       return Offset + StackSize;
1185
1186     // Skip the saved EBP.
1187     Offset += SlotSize;
1188
1189     // Skip the RETADDR move area
1190     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1191     if (TailCallReturnAddrDelta < 0)
1192       Offset -= TailCallReturnAddrDelta;
1193   }
1194
1195   return Offset + FPDelta;
1196 }
1197
1198 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1199                                              unsigned &FrameReg) const {
1200   const X86RegisterInfo *RegInfo =
1201       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1202   // We can't calculate offset from frame pointer if the stack is realigned,
1203   // so enforce usage of stack/base pointer.  The base pointer is used when we
1204   // have dynamic allocas in addition to dynamic realignment.
1205   if (RegInfo->hasBasePointer(MF))
1206     FrameReg = RegInfo->getBaseRegister();
1207   else if (RegInfo->needsStackRealignment(MF))
1208     FrameReg = RegInfo->getStackRegister();
1209   else
1210     FrameReg = RegInfo->getFrameRegister(MF);
1211   return getFrameIndexOffset(MF, FI);
1212 }
1213
1214 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1215 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1216   const MachineFrameInfo *MFI = MF.getFrameInfo();
1217   // Does not include any dynamic realign.
1218   const uint64_t StackSize = MFI->getStackSize();
1219   {
1220 #ifndef NDEBUG
1221     const X86RegisterInfo *RegInfo =
1222         MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1223     // Note: LLVM arranges the stack as:
1224     // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1225     //      > "Stack Slots" (<--SP)
1226     // We can always address StackSlots from RSP.  We can usually (unless
1227     // needsStackRealignment) address CSRs from RSP, but sometimes need to
1228     // address them from RBP.  FixedObjects can be placed anywhere in the stack
1229     // frame depending on their specific requirements (i.e. we can actually
1230     // refer to arguments to the function which are stored in the *callers*
1231     // frame).  As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1232     // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1233
1234     assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1235
1236     // We don't handle tail calls, and shouldn't be seeing them
1237     // either.
1238     int TailCallReturnAddrDelta =
1239         MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1240     assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1241 #endif
1242   }
1243
1244   // This is how the math works out:
1245   //
1246   //  %rsp grows (i.e. gets lower) left to right. Each box below is
1247   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
1248   //  get to.
1249   //
1250   //    ----------------------------------
1251   //    | BP | Obj0 | Obj1 | ... | ObjN |
1252   //    ----------------------------------
1253   //    ^    ^      ^                   ^
1254   //    A    B      C                   E
1255   //
1256   // A is the incoming stack pointer.
1257   // (B - A) is the local area offset (-8 for x86-64) [1]
1258   // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1259   //
1260   // |(E - B)| is the StackSize (absolute value, positive).  For a
1261   // stack that grown down, this works out to be (B - E). [3]
1262   //
1263   // E is also the value of %rsp after stack has been set up, and we
1264   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
1265   // (C - E) == (C - A) - (B - A) + (B - E)
1266   //            { Using [1], [2] and [3] above }
1267   //         == getObjectOffset - LocalAreaOffset + StackSize
1268   //
1269
1270   // Get the Offset from the StackPointer
1271   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1272
1273   return Offset + StackSize;
1274 }
1275 // Simplified from getFrameIndexReference keeping only StackPointer cases
1276 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1277                                                    int FI,
1278                                                    unsigned &FrameReg) const {
1279   const X86RegisterInfo *RegInfo =
1280       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1281   assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1282
1283   FrameReg = RegInfo->getStackRegister();
1284   return getFrameIndexOffsetFromSP(MF, FI);
1285 }
1286
1287 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1288     MachineFunction &MF, const TargetRegisterInfo *TRI,
1289     std::vector<CalleeSavedInfo> &CSI) const {
1290   MachineFrameInfo *MFI = MF.getFrameInfo();
1291   const X86RegisterInfo *RegInfo =
1292       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1293   unsigned SlotSize = RegInfo->getSlotSize();
1294   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1295
1296   unsigned CalleeSavedFrameSize = 0;
1297   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1298
1299   if (hasFP(MF)) {
1300     // emitPrologue always spills frame register the first thing.
1301     SpillSlotOffset -= SlotSize;
1302     MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1303
1304     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1305     // the frame register, we can delete it from CSI list and not have to worry
1306     // about avoiding it later.
1307     unsigned FPReg = RegInfo->getFrameRegister(MF);
1308     for (unsigned i = 0; i < CSI.size(); ++i) {
1309       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1310         CSI.erase(CSI.begin() + i);
1311         break;
1312       }
1313     }
1314   }
1315
1316   // Assign slots for GPRs. It increases frame size.
1317   for (unsigned i = CSI.size(); i != 0; --i) {
1318     unsigned Reg = CSI[i - 1].getReg();
1319
1320     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1321       continue;
1322
1323     SpillSlotOffset -= SlotSize;
1324     CalleeSavedFrameSize += SlotSize;
1325
1326     int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1327     CSI[i - 1].setFrameIdx(SlotIndex);
1328   }
1329
1330   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1331
1332   // Assign slots for XMMs.
1333   for (unsigned i = CSI.size(); i != 0; --i) {
1334     unsigned Reg = CSI[i - 1].getReg();
1335     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1336       continue;
1337
1338     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1339     // ensure alignment
1340     SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1341     // spill into slot
1342     SpillSlotOffset -= RC->getSize();
1343     int SlotIndex =
1344         MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1345     CSI[i - 1].setFrameIdx(SlotIndex);
1346     MFI->ensureMaxAlignment(RC->getAlignment());
1347   }
1348
1349   return true;
1350 }
1351
1352 bool X86FrameLowering::spillCalleeSavedRegisters(
1353     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1354     const std::vector<CalleeSavedInfo> &CSI,
1355     const TargetRegisterInfo *TRI) const {
1356   DebugLoc DL = MBB.findDebugLoc(MI);
1357
1358   MachineFunction &MF = *MBB.getParent();
1359   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1360   const TargetInstrInfo &TII = *STI.getInstrInfo();
1361
1362   // Push GPRs. It increases frame size.
1363   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1364   for (unsigned i = CSI.size(); i != 0; --i) {
1365     unsigned Reg = CSI[i - 1].getReg();
1366
1367     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1368       continue;
1369     // Add the callee-saved register as live-in. It's killed at the spill.
1370     MBB.addLiveIn(Reg);
1371
1372     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1373       .setMIFlag(MachineInstr::FrameSetup);
1374   }
1375
1376   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1377   // It can be done by spilling XMMs to stack frame.
1378   for (unsigned i = CSI.size(); i != 0; --i) {
1379     unsigned Reg = CSI[i-1].getReg();
1380     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1381       continue;
1382     // Add the callee-saved register as live-in. It's killed at the spill.
1383     MBB.addLiveIn(Reg);
1384     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1385
1386     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1387                             TRI);
1388     --MI;
1389     MI->setFlag(MachineInstr::FrameSetup);
1390     ++MI;
1391   }
1392
1393   return true;
1394 }
1395
1396 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1397                                                MachineBasicBlock::iterator MI,
1398                                         const std::vector<CalleeSavedInfo> &CSI,
1399                                           const TargetRegisterInfo *TRI) const {
1400   if (CSI.empty())
1401     return false;
1402
1403   DebugLoc DL = MBB.findDebugLoc(MI);
1404
1405   MachineFunction &MF = *MBB.getParent();
1406   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1407   const TargetInstrInfo &TII = *STI.getInstrInfo();
1408
1409   // Reload XMMs from stack frame.
1410   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1411     unsigned Reg = CSI[i].getReg();
1412     if (X86::GR64RegClass.contains(Reg) ||
1413         X86::GR32RegClass.contains(Reg))
1414       continue;
1415
1416     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1417     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1418   }
1419
1420   // POP GPRs.
1421   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1422   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1423     unsigned Reg = CSI[i].getReg();
1424     if (!X86::GR64RegClass.contains(Reg) &&
1425         !X86::GR32RegClass.contains(Reg))
1426       continue;
1427
1428     BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1429   }
1430   return true;
1431 }
1432
1433 void
1434 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1435                                                        RegScavenger *RS) const {
1436   MachineFrameInfo *MFI = MF.getFrameInfo();
1437   const X86RegisterInfo *RegInfo =
1438       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1439   unsigned SlotSize = RegInfo->getSlotSize();
1440
1441   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1442   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1443
1444   if (TailCallReturnAddrDelta < 0) {
1445     // create RETURNADDR area
1446     //   arg
1447     //   arg
1448     //   RETADDR
1449     //   { ...
1450     //     RETADDR area
1451     //     ...
1452     //   }
1453     //   [EBP]
1454     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1455                            TailCallReturnAddrDelta - SlotSize, true);
1456   }
1457
1458   // Spill the BasePtr if it's used.
1459   if (RegInfo->hasBasePointer(MF))
1460     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1461 }
1462
1463 static bool
1464 HasNestArgument(const MachineFunction *MF) {
1465   const Function *F = MF->getFunction();
1466   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1467        I != E; I++) {
1468     if (I->hasNestAttr())
1469       return true;
1470   }
1471   return false;
1472 }
1473
1474 /// GetScratchRegister - Get a temp register for performing work in the
1475 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1476 /// and the properties of the function either one or two registers will be
1477 /// needed. Set primary to true for the first register, false for the second.
1478 static unsigned
1479 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1480   CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1481
1482   // Erlang stuff.
1483   if (CallingConvention == CallingConv::HiPE) {
1484     if (Is64Bit)
1485       return Primary ? X86::R14 : X86::R13;
1486     else
1487       return Primary ? X86::EBX : X86::EDI;
1488   }
1489
1490   if (Is64Bit) {
1491     if (IsLP64)
1492       return Primary ? X86::R11 : X86::R12;
1493     else
1494       return Primary ? X86::R11D : X86::R12D;
1495   }
1496
1497   bool IsNested = HasNestArgument(&MF);
1498
1499   if (CallingConvention == CallingConv::X86_FastCall ||
1500       CallingConvention == CallingConv::Fast) {
1501     if (IsNested)
1502       report_fatal_error("Segmented stacks does not support fastcall with "
1503                          "nested function.");
1504     return Primary ? X86::EAX : X86::ECX;
1505   }
1506   if (IsNested)
1507     return Primary ? X86::EDX : X86::EAX;
1508   return Primary ? X86::ECX : X86::EAX;
1509 }
1510
1511 // The stack limit in the TCB is set to this many bytes above the actual stack
1512 // limit.
1513 static const uint64_t kSplitStackAvailable = 256;
1514
1515 void X86FrameLowering::adjustForSegmentedStacks(
1516     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1517   assert(&PrologueMBB == &MF.front() &&
1518          "Shrink-wrapping is not implemented yet");
1519   MachineFrameInfo *MFI = MF.getFrameInfo();
1520   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1521   const TargetInstrInfo &TII = *STI.getInstrInfo();
1522   uint64_t StackSize;
1523   bool Is64Bit = STI.is64Bit();
1524   const bool IsLP64 = STI.isTarget64BitLP64();
1525   unsigned TlsReg, TlsOffset;
1526   DebugLoc DL;
1527
1528   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1529   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1530          "Scratch register is live-in");
1531
1532   if (MF.getFunction()->isVarArg())
1533     report_fatal_error("Segmented stacks do not support vararg functions.");
1534   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1535       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1536       !STI.isTargetDragonFly())
1537     report_fatal_error("Segmented stacks not supported on this platform.");
1538
1539   // Eventually StackSize will be calculated by a link-time pass; which will
1540   // also decide whether checking code needs to be injected into this particular
1541   // prologue.
1542   StackSize = MFI->getStackSize();
1543
1544   // Do not generate a prologue for functions with a stack of size zero
1545   if (StackSize == 0)
1546     return;
1547
1548   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1549   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1550   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1551   bool IsNested = false;
1552
1553   // We need to know if the function has a nest argument only in 64 bit mode.
1554   if (Is64Bit)
1555     IsNested = HasNestArgument(&MF);
1556
1557   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1558   // allocMBB needs to be last (terminating) instruction.
1559
1560   for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1561                                           e = PrologueMBB.livein_end();
1562        i != e; i++) {
1563     allocMBB->addLiveIn(*i);
1564     checkMBB->addLiveIn(*i);
1565   }
1566
1567   if (IsNested)
1568     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1569
1570   MF.push_front(allocMBB);
1571   MF.push_front(checkMBB);
1572
1573   // When the frame size is less than 256 we just compare the stack
1574   // boundary directly to the value of the stack pointer, per gcc.
1575   bool CompareStackPointer = StackSize < kSplitStackAvailable;
1576
1577   // Read the limit off the current stacklet off the stack_guard location.
1578   if (Is64Bit) {
1579     if (STI.isTargetLinux()) {
1580       TlsReg = X86::FS;
1581       TlsOffset = IsLP64 ? 0x70 : 0x40;
1582     } else if (STI.isTargetDarwin()) {
1583       TlsReg = X86::GS;
1584       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1585     } else if (STI.isTargetWin64()) {
1586       TlsReg = X86::GS;
1587       TlsOffset = 0x28; // pvArbitrary, reserved for application use
1588     } else if (STI.isTargetFreeBSD()) {
1589       TlsReg = X86::FS;
1590       TlsOffset = 0x18;
1591     } else if (STI.isTargetDragonFly()) {
1592       TlsReg = X86::FS;
1593       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1594     } else {
1595       report_fatal_error("Segmented stacks not supported on this platform.");
1596     }
1597
1598     if (CompareStackPointer)
1599       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1600     else
1601       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1602         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1603
1604     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1605       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1606   } else {
1607     if (STI.isTargetLinux()) {
1608       TlsReg = X86::GS;
1609       TlsOffset = 0x30;
1610     } else if (STI.isTargetDarwin()) {
1611       TlsReg = X86::GS;
1612       TlsOffset = 0x48 + 90*4;
1613     } else if (STI.isTargetWin32()) {
1614       TlsReg = X86::FS;
1615       TlsOffset = 0x14; // pvArbitrary, reserved for application use
1616     } else if (STI.isTargetDragonFly()) {
1617       TlsReg = X86::FS;
1618       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1619     } else if (STI.isTargetFreeBSD()) {
1620       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1621     } else {
1622       report_fatal_error("Segmented stacks not supported on this platform.");
1623     }
1624
1625     if (CompareStackPointer)
1626       ScratchReg = X86::ESP;
1627     else
1628       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1629         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1630
1631     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1632         STI.isTargetDragonFly()) {
1633       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1634         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1635     } else if (STI.isTargetDarwin()) {
1636
1637       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1638       unsigned ScratchReg2;
1639       bool SaveScratch2;
1640       if (CompareStackPointer) {
1641         // The primary scratch register is available for holding the TLS offset.
1642         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1643         SaveScratch2 = false;
1644       } else {
1645         // Need to use a second register to hold the TLS offset
1646         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1647
1648         // Unfortunately, with fastcc the second scratch register may hold an
1649         // argument.
1650         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1651       }
1652
1653       // If Scratch2 is live-in then it needs to be saved.
1654       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1655              "Scratch register is live-in and not saved");
1656
1657       if (SaveScratch2)
1658         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1659           .addReg(ScratchReg2, RegState::Kill);
1660
1661       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1662         .addImm(TlsOffset);
1663       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1664         .addReg(ScratchReg)
1665         .addReg(ScratchReg2).addImm(1).addReg(0)
1666         .addImm(0)
1667         .addReg(TlsReg);
1668
1669       if (SaveScratch2)
1670         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1671     }
1672   }
1673
1674   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1675   // It jumps to normal execution of the function body.
1676   BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
1677
1678   // On 32 bit we first push the arguments size and then the frame size. On 64
1679   // bit, we pass the stack frame size in r10 and the argument size in r11.
1680   if (Is64Bit) {
1681     // Functions with nested arguments use R10, so it needs to be saved across
1682     // the call to _morestack
1683
1684     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1685     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1686     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1687     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1688     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1689
1690     if (IsNested)
1691       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1692
1693     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1694       .addImm(StackSize);
1695     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1696       .addImm(X86FI->getArgumentStackSize());
1697     MF.getRegInfo().setPhysRegUsed(Reg10);
1698     MF.getRegInfo().setPhysRegUsed(Reg11);
1699   } else {
1700     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1701       .addImm(X86FI->getArgumentStackSize());
1702     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1703       .addImm(StackSize);
1704   }
1705
1706   // __morestack is in libgcc
1707   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1708     // Under the large code model, we cannot assume that __morestack lives
1709     // within 2^31 bytes of the call site, so we cannot use pc-relative
1710     // addressing. We cannot perform the call via a temporary register,
1711     // as the rax register may be used to store the static chain, and all
1712     // other suitable registers may be either callee-save or used for
1713     // parameter passing. We cannot use the stack at this point either
1714     // because __morestack manipulates the stack directly.
1715     //
1716     // To avoid these issues, perform an indirect call via a read-only memory
1717     // location containing the address.
1718     //
1719     // This solution is not perfect, as it assumes that the .rodata section
1720     // is laid out within 2^31 bytes of each function body, but this seems
1721     // to be sufficient for JIT.
1722     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1723         .addReg(X86::RIP)
1724         .addImm(0)
1725         .addReg(0)
1726         .addExternalSymbol("__morestack_addr")
1727         .addReg(0);
1728     MF.getMMI().setUsesMorestackAddr(true);
1729   } else {
1730     if (Is64Bit)
1731       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1732         .addExternalSymbol("__morestack");
1733     else
1734       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1735         .addExternalSymbol("__morestack");
1736   }
1737
1738   if (IsNested)
1739     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1740   else
1741     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1742
1743   allocMBB->addSuccessor(&PrologueMBB);
1744
1745   checkMBB->addSuccessor(allocMBB);
1746   checkMBB->addSuccessor(&PrologueMBB);
1747
1748 #ifdef XDEBUG
1749   MF.verify();
1750 #endif
1751 }
1752
1753 /// Erlang programs may need a special prologue to handle the stack size they
1754 /// might need at runtime. That is because Erlang/OTP does not implement a C
1755 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1756 /// (for more information see Eric Stenman's Ph.D. thesis:
1757 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1758 ///
1759 /// CheckStack:
1760 ///       temp0 = sp - MaxStack
1761 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1762 /// OldStart:
1763 ///       ...
1764 /// IncStack:
1765 ///       call inc_stack   # doubles the stack space
1766 ///       temp0 = sp - MaxStack
1767 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1768 void X86FrameLowering::adjustForHiPEPrologue(
1769     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1770   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1771   const TargetInstrInfo &TII = *STI.getInstrInfo();
1772   MachineFrameInfo *MFI = MF.getFrameInfo();
1773   const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
1774   const bool Is64Bit = STI.is64Bit();
1775   const bool IsLP64 = STI.isTarget64BitLP64();
1776   DebugLoc DL;
1777   // HiPE-specific values
1778   const unsigned HipeLeafWords = 24;
1779   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1780   const unsigned Guaranteed = HipeLeafWords * SlotSize;
1781   unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1782                             MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1783   unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1784
1785   assert(STI.isTargetLinux() &&
1786          "HiPE prologue is only supported on Linux operating systems.");
1787
1788   // Compute the largest caller's frame that is needed to fit the callees'
1789   // frames. This 'MaxStack' is computed from:
1790   //
1791   // a) the fixed frame size, which is the space needed for all spilled temps,
1792   // b) outgoing on-stack parameter areas, and
1793   // c) the minimum stack space this function needs to make available for the
1794   //    functions it calls (a tunable ABI property).
1795   if (MFI->hasCalls()) {
1796     unsigned MoreStackForCalls = 0;
1797
1798     for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1799          MBBI != MBBE; ++MBBI)
1800       for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1801            MI != ME; ++MI) {
1802         if (!MI->isCall())
1803           continue;
1804
1805         // Get callee operand.
1806         const MachineOperand &MO = MI->getOperand(0);
1807
1808         // Only take account of global function calls (no closures etc.).
1809         if (!MO.isGlobal())
1810           continue;
1811
1812         const Function *F = dyn_cast<Function>(MO.getGlobal());
1813         if (!F)
1814           continue;
1815
1816         // Do not update 'MaxStack' for primitive and built-in functions
1817         // (encoded with names either starting with "erlang."/"bif_" or not
1818         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1819         // "_", such as the BIF "suspend_0") as they are executed on another
1820         // stack.
1821         if (F->getName().find("erlang.") != StringRef::npos ||
1822             F->getName().find("bif_") != StringRef::npos ||
1823             F->getName().find_first_of("._") == StringRef::npos)
1824           continue;
1825
1826         unsigned CalleeStkArity =
1827           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1828         if (HipeLeafWords - 1 > CalleeStkArity)
1829           MoreStackForCalls = std::max(MoreStackForCalls,
1830                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1831       }
1832     MaxStack += MoreStackForCalls;
1833   }
1834
1835   // If the stack frame needed is larger than the guaranteed then runtime checks
1836   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1837   if (MaxStack > Guaranteed) {
1838     assert(&PrologueMBB == &MF.front() &&
1839            "Shrink-wrapping is not implemented yet");
1840     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1841     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1842
1843     for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1844                                             E = PrologueMBB.livein_end();
1845          I != E; I++) {
1846       stackCheckMBB->addLiveIn(*I);
1847       incStackMBB->addLiveIn(*I);
1848     }
1849
1850     MF.push_front(incStackMBB);
1851     MF.push_front(stackCheckMBB);
1852
1853     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1854     unsigned LEAop, CMPop, CALLop;
1855     if (Is64Bit) {
1856       SPReg = X86::RSP;
1857       PReg  = X86::RBP;
1858       LEAop = X86::LEA64r;
1859       CMPop = X86::CMP64rm;
1860       CALLop = X86::CALL64pcrel32;
1861       SPLimitOffset = 0x90;
1862     } else {
1863       SPReg = X86::ESP;
1864       PReg  = X86::EBP;
1865       LEAop = X86::LEA32r;
1866       CMPop = X86::CMP32rm;
1867       CALLop = X86::CALLpcrel32;
1868       SPLimitOffset = 0x4c;
1869     }
1870
1871     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1872     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1873            "HiPE prologue scratch register is live-in");
1874
1875     // Create new MBB for StackCheck:
1876     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1877                  SPReg, false, -MaxStack);
1878     // SPLimitOffset is in a fixed heap location (pointed by BP).
1879     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1880                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
1881     BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
1882
1883     // Create new MBB for IncStack:
1884     BuildMI(incStackMBB, DL, TII.get(CALLop)).
1885       addExternalSymbol("inc_stack_0");
1886     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1887                  SPReg, false, -MaxStack);
1888     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1889                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
1890     BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1891
1892     stackCheckMBB->addSuccessor(&PrologueMBB, 99);
1893     stackCheckMBB->addSuccessor(incStackMBB, 1);
1894     incStackMBB->addSuccessor(&PrologueMBB, 99);
1895     incStackMBB->addSuccessor(incStackMBB, 1);
1896   }
1897 #ifdef XDEBUG
1898   MF.verify();
1899 #endif
1900 }
1901
1902 void X86FrameLowering::
1903 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1904                               MachineBasicBlock::iterator I) const {
1905   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1906   const TargetInstrInfo &TII = *STI.getInstrInfo();
1907   const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
1908   unsigned StackPtr = RegInfo.getStackRegister();
1909   bool reserveCallFrame = hasReservedCallFrame(MF);
1910   unsigned Opcode = I->getOpcode();
1911   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1912   bool IsLP64 = STI.isTarget64BitLP64();
1913   DebugLoc DL = I->getDebugLoc();
1914   uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1915   uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
1916   I = MBB.erase(I);
1917
1918   if (!reserveCallFrame) {
1919     // If the stack pointer can be changed after prologue, turn the
1920     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1921     // adjcallstackdown instruction into 'add ESP, <amt>'
1922     if (Amount == 0)
1923       return;
1924
1925     // We need to keep the stack aligned properly.  To do this, we round the
1926     // amount of space needed for the outgoing arguments up to the next
1927     // alignment boundary.
1928     unsigned StackAlign = getStackAlignment();
1929     Amount = RoundUpToAlignment(Amount, StackAlign);
1930
1931     MachineInstr *New = nullptr;
1932
1933     // Factor out the amount that gets handled inside the sequence
1934     // (Pushes of argument for frame setup, callee pops for frame destroy)
1935     Amount -= InternalAmt;
1936
1937     if (Amount) {
1938       if (Opcode == TII.getCallFrameSetupOpcode()) {
1939         New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1940           .addReg(StackPtr).addImm(Amount);
1941       } else {
1942         assert(Opcode == TII.getCallFrameDestroyOpcode());
1943
1944         unsigned Opc = getADDriOpcode(IsLP64, Amount);
1945         New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1946           .addReg(StackPtr).addImm(Amount);
1947       }
1948     }
1949
1950     if (New) {
1951       // The EFLAGS implicit def is dead.
1952       New->getOperand(3).setIsDead();
1953
1954       // Replace the pseudo instruction with a new instruction.
1955       MBB.insert(I, New);
1956     }
1957
1958     return;
1959   }
1960
1961   if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
1962     // If we are performing frame pointer elimination and if the callee pops
1963     // something off the stack pointer, add it back.  We do this until we have
1964     // more advanced stack pointer tracking ability.
1965     unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
1966     MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1967       .addReg(StackPtr).addImm(InternalAmt);
1968
1969     // The EFLAGS implicit def is dead.
1970     New->getOperand(3).setIsDead();
1971
1972     // We are not tracking the stack pointer adjustment by the callee, so make
1973     // sure we restore the stack pointer immediately after the call, there may
1974     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1975     MachineBasicBlock::iterator B = MBB.begin();
1976     while (I != B && !std::prev(I)->isCall())
1977       --I;
1978     MBB.insert(I, New);
1979   }
1980 }
1981