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