Revert "[X86] Cache variables that only depend on the subtarget"
[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 IsWin64CC = STI.isCallingConvWin64(Fn->getCallingConv());
590   // Not necessarily synonymous with IsWin64CC.
591   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
592   bool NeedsWinCFI = IsWin64Prologue && Fn->needsUnwindTableEntry();
593   bool NeedsDwarfCFI =
594       !IsWin64Prologue && (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 && IsWin64Prologue)
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       !IsWin64CC &&                 // 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) && !IsWin64Prologue)
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 (NeedsWinCFI) {
712       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
713           .addImm(FramePtr)
714           .setMIFlag(MachineInstr::FrameSetup);
715     }
716
717     if (!IsWin64Prologue) {
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 (NeedsWinCFI) {
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 (!IsWin64Prologue && 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 (IsWin64Prologue && 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 (NeedsWinCFI && 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 (IsWin64Prologue && 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 (NeedsWinCFI)
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 (NeedsWinCFI) {
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 (NeedsWinCFI)
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 (IsWin64Prologue && 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 IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1019   bool NeedsWinCFI =
1020       IsWin64Prologue && MF.getFunction()->needsUnwindTableEntry();
1021   bool UseLEAForSP = canUseLEAForSPInEpilogue(MF);
1022   // If we can use LEA for SP but we shouldn't, check that none
1023   // of the terminators uses the eflags. Otherwise we will insert
1024   // a ADD that will redefine the eflags and break the condition.
1025   // Alternatively, we could move the ADD, but this may not be possible
1026   // and is an optimization anyway.
1027   if (UseLEAForSP && !MF.getSubtarget<X86Subtarget>().useLeaForSP())
1028     UseLEAForSP = terminatorsNeedFlagsAsInput(MBB);
1029   // If that assert breaks, that means we do not do the right thing
1030   // in canUseAsEpilogue.
1031   assert((UseLEAForSP || !terminatorsNeedFlagsAsInput(MBB)) &&
1032          "We shouldn't have allowed this insertion point");
1033
1034   // Get the number of bytes to allocate from the FrameInfo.
1035   uint64_t StackSize = MFI->getStackSize();
1036   uint64_t MaxAlign = calculateMaxStackAlign(MF);
1037   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1038   uint64_t NumBytes = 0;
1039
1040   if (hasFP(MF)) {
1041     // Calculate required stack adjustment.
1042     uint64_t FrameSize = StackSize - SlotSize;
1043     NumBytes = FrameSize - CSSize;
1044
1045     // Callee-saved registers were pushed on stack before the stack was
1046     // realigned.
1047     if (RegInfo->needsStackRealignment(MF) && !IsWin64Prologue)
1048       NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1049
1050     // Pop EBP.
1051     BuildMI(MBB, MBBI, DL,
1052             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1053   } else {
1054     NumBytes = StackSize - CSSize;
1055   }
1056   uint64_t SEHStackAllocAmt = NumBytes;
1057
1058   // Skip the callee-saved pop instructions.
1059   while (MBBI != MBB.begin()) {
1060     MachineBasicBlock::iterator PI = std::prev(MBBI);
1061     unsigned Opc = PI->getOpcode();
1062
1063     if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1064         !PI->isTerminator())
1065       break;
1066
1067     --MBBI;
1068   }
1069   MachineBasicBlock::iterator FirstCSPop = MBBI;
1070
1071   if (MBBI != MBB.end())
1072     DL = MBBI->getDebugLoc();
1073
1074   // If there is an ADD32ri or SUB32ri of ESP immediately before this
1075   // instruction, merge the two instructions.
1076   if (NumBytes || MFI->hasVarSizedObjects())
1077     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1078
1079   // If dynamic alloca is used, then reset esp to point to the last callee-saved
1080   // slot before popping them off! Same applies for the case, when stack was
1081   // realigned.
1082   if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1083     if (RegInfo->needsStackRealignment(MF))
1084       MBBI = FirstCSPop;
1085     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1086     uint64_t LEAAmount =
1087         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1088
1089     // There are only two legal forms of epilogue:
1090     // - add SEHAllocationSize, %rsp
1091     // - lea SEHAllocationSize(%FramePtr), %rsp
1092     //
1093     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1094     // However, we may use this sequence if we have a frame pointer because the
1095     // effects of the prologue can safely be undone.
1096     if (LEAAmount != 0) {
1097       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1098       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1099                    FramePtr, false, LEAAmount);
1100       --MBBI;
1101     } else {
1102       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1103       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1104         .addReg(FramePtr);
1105       --MBBI;
1106     }
1107   } else if (NumBytes) {
1108     // Adjust stack pointer back: ESP += numbytes.
1109     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr,
1110                  UseLEAForSP, TII, *RegInfo);
1111     --MBBI;
1112   }
1113
1114   // Windows unwinder will not invoke function's exception handler if IP is
1115   // either in prologue or in epilogue.  This behavior causes a problem when a
1116   // call immediately precedes an epilogue, because the return address points
1117   // into the epilogue.  To cope with that, we insert an epilogue marker here,
1118   // then replace it with a 'nop' if it ends up immediately after a CALL in the
1119   // final emitted code.
1120   if (NeedsWinCFI)
1121     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1122
1123   // Add the return addr area delta back since we are not tail calling.
1124   int Offset = -1 * X86FI->getTCReturnAddrDelta();
1125   assert(Offset >= 0 && "TCDelta should never be positive");
1126   if (Offset) {
1127     MBBI = MBB.getFirstTerminator();
1128
1129     // Check for possible merge with preceding ADD instruction.
1130     Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1131     emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1132                  UseLEAForSP, TII, *RegInfo);
1133   }
1134 }
1135
1136 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1137                                           int FI) const {
1138   const X86RegisterInfo *RegInfo =
1139       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1140   const MachineFrameInfo *MFI = MF.getFrameInfo();
1141   // Offset will hold the offset from the stack pointer at function entry to the
1142   // object.
1143   // We need to factor in additional offsets applied during the prologue to the
1144   // frame, base, and stack pointer depending on which is used.
1145   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1146   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1147   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1148   uint64_t StackSize = MFI->getStackSize();
1149   unsigned SlotSize = RegInfo->getSlotSize();
1150   bool HasFP = hasFP(MF);
1151   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1152   int64_t FPDelta = 0;
1153
1154   if (IsWin64Prologue) {
1155     assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1156
1157     // Calculate required stack adjustment.
1158     uint64_t FrameSize = StackSize - SlotSize;
1159     // If required, include space for extra hidden slot for stashing base pointer.
1160     if (X86FI->getRestoreBasePointer())
1161       FrameSize += SlotSize;
1162     uint64_t NumBytes = FrameSize - CSSize;
1163
1164     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1165     if (FI && FI == X86FI->getFAIndex())
1166       return -SEHFrameOffset;
1167
1168     // FPDelta is the offset from the "traditional" FP location of the old base
1169     // pointer followed by return address and the location required by the
1170     // restricted Win64 prologue.
1171     // Add FPDelta to all offsets below that go through the frame pointer.
1172     FPDelta = FrameSize - SEHFrameOffset;
1173     assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1174            "FPDelta isn't aligned per the Win64 ABI!");
1175   }
1176
1177
1178   if (RegInfo->hasBasePointer(MF)) {
1179     assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1180     if (FI < 0) {
1181       // Skip the saved EBP.
1182       return Offset + SlotSize + FPDelta;
1183     } else {
1184       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1185       return Offset + StackSize;
1186     }
1187   } else if (RegInfo->needsStackRealignment(MF)) {
1188     if (FI < 0) {
1189       // Skip the saved EBP.
1190       return Offset + SlotSize + FPDelta;
1191     } else {
1192       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1193       return Offset + StackSize;
1194     }
1195     // FIXME: Support tail calls
1196   } else {
1197     if (!HasFP)
1198       return Offset + StackSize;
1199
1200     // Skip the saved EBP.
1201     Offset += SlotSize;
1202
1203     // Skip the RETADDR move area
1204     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1205     if (TailCallReturnAddrDelta < 0)
1206       Offset -= TailCallReturnAddrDelta;
1207   }
1208
1209   return Offset + FPDelta;
1210 }
1211
1212 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1213                                              unsigned &FrameReg) const {
1214   const X86RegisterInfo *RegInfo =
1215       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1216   // We can't calculate offset from frame pointer if the stack is realigned,
1217   // so enforce usage of stack/base pointer.  The base pointer is used when we
1218   // have dynamic allocas in addition to dynamic realignment.
1219   if (RegInfo->hasBasePointer(MF))
1220     FrameReg = RegInfo->getBaseRegister();
1221   else if (RegInfo->needsStackRealignment(MF))
1222     FrameReg = RegInfo->getStackRegister();
1223   else
1224     FrameReg = RegInfo->getFrameRegister(MF);
1225   return getFrameIndexOffset(MF, FI);
1226 }
1227
1228 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1229 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1230   const MachineFrameInfo *MFI = MF.getFrameInfo();
1231   // Does not include any dynamic realign.
1232   const uint64_t StackSize = MFI->getStackSize();
1233   {
1234 #ifndef NDEBUG
1235     const X86RegisterInfo *RegInfo =
1236         MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1237     // Note: LLVM arranges the stack as:
1238     // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1239     //      > "Stack Slots" (<--SP)
1240     // We can always address StackSlots from RSP.  We can usually (unless
1241     // needsStackRealignment) address CSRs from RSP, but sometimes need to
1242     // address them from RBP.  FixedObjects can be placed anywhere in the stack
1243     // frame depending on their specific requirements (i.e. we can actually
1244     // refer to arguments to the function which are stored in the *callers*
1245     // frame).  As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1246     // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1247
1248     assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1249
1250     // We don't handle tail calls, and shouldn't be seeing them
1251     // either.
1252     int TailCallReturnAddrDelta =
1253         MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1254     assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1255 #endif
1256   }
1257
1258   // This is how the math works out:
1259   //
1260   //  %rsp grows (i.e. gets lower) left to right. Each box below is
1261   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
1262   //  get to.
1263   //
1264   //    ----------------------------------
1265   //    | BP | Obj0 | Obj1 | ... | ObjN |
1266   //    ----------------------------------
1267   //    ^    ^      ^                   ^
1268   //    A    B      C                   E
1269   //
1270   // A is the incoming stack pointer.
1271   // (B - A) is the local area offset (-8 for x86-64) [1]
1272   // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1273   //
1274   // |(E - B)| is the StackSize (absolute value, positive).  For a
1275   // stack that grown down, this works out to be (B - E). [3]
1276   //
1277   // E is also the value of %rsp after stack has been set up, and we
1278   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
1279   // (C - E) == (C - A) - (B - A) + (B - E)
1280   //            { Using [1], [2] and [3] above }
1281   //         == getObjectOffset - LocalAreaOffset + StackSize
1282   //
1283
1284   // Get the Offset from the StackPointer
1285   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1286
1287   return Offset + StackSize;
1288 }
1289 // Simplified from getFrameIndexReference keeping only StackPointer cases
1290 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1291                                                    int FI,
1292                                                    unsigned &FrameReg) const {
1293   const X86RegisterInfo *RegInfo =
1294       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1295   assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1296
1297   FrameReg = RegInfo->getStackRegister();
1298   return getFrameIndexOffsetFromSP(MF, FI);
1299 }
1300
1301 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1302     MachineFunction &MF, const TargetRegisterInfo *TRI,
1303     std::vector<CalleeSavedInfo> &CSI) const {
1304   MachineFrameInfo *MFI = MF.getFrameInfo();
1305   const X86RegisterInfo *RegInfo =
1306       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1307   unsigned SlotSize = RegInfo->getSlotSize();
1308   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1309
1310   unsigned CalleeSavedFrameSize = 0;
1311   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1312
1313   if (hasFP(MF)) {
1314     // emitPrologue always spills frame register the first thing.
1315     SpillSlotOffset -= SlotSize;
1316     MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1317
1318     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1319     // the frame register, we can delete it from CSI list and not have to worry
1320     // about avoiding it later.
1321     unsigned FPReg = RegInfo->getFrameRegister(MF);
1322     for (unsigned i = 0; i < CSI.size(); ++i) {
1323       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1324         CSI.erase(CSI.begin() + i);
1325         break;
1326       }
1327     }
1328   }
1329
1330   // Assign slots for GPRs. It increases frame size.
1331   for (unsigned i = CSI.size(); i != 0; --i) {
1332     unsigned Reg = CSI[i - 1].getReg();
1333
1334     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1335       continue;
1336
1337     SpillSlotOffset -= SlotSize;
1338     CalleeSavedFrameSize += SlotSize;
1339
1340     int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1341     CSI[i - 1].setFrameIdx(SlotIndex);
1342   }
1343
1344   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1345
1346   // Assign slots for XMMs.
1347   for (unsigned i = CSI.size(); i != 0; --i) {
1348     unsigned Reg = CSI[i - 1].getReg();
1349     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1350       continue;
1351
1352     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1353     // ensure alignment
1354     SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1355     // spill into slot
1356     SpillSlotOffset -= RC->getSize();
1357     int SlotIndex =
1358         MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1359     CSI[i - 1].setFrameIdx(SlotIndex);
1360     MFI->ensureMaxAlignment(RC->getAlignment());
1361   }
1362
1363   return true;
1364 }
1365
1366 bool X86FrameLowering::spillCalleeSavedRegisters(
1367     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1368     const std::vector<CalleeSavedInfo> &CSI,
1369     const TargetRegisterInfo *TRI) const {
1370   DebugLoc DL = MBB.findDebugLoc(MI);
1371
1372   MachineFunction &MF = *MBB.getParent();
1373   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1374   const TargetInstrInfo &TII = *STI.getInstrInfo();
1375
1376   // Push GPRs. It increases frame size.
1377   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1378   for (unsigned i = CSI.size(); i != 0; --i) {
1379     unsigned Reg = CSI[i - 1].getReg();
1380
1381     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1382       continue;
1383     // Add the callee-saved register as live-in. It's killed at the spill.
1384     MBB.addLiveIn(Reg);
1385
1386     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1387       .setMIFlag(MachineInstr::FrameSetup);
1388   }
1389
1390   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1391   // It can be done by spilling XMMs to stack frame.
1392   for (unsigned i = CSI.size(); i != 0; --i) {
1393     unsigned Reg = CSI[i-1].getReg();
1394     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1395       continue;
1396     // Add the callee-saved register as live-in. It's killed at the spill.
1397     MBB.addLiveIn(Reg);
1398     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1399
1400     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1401                             TRI);
1402     --MI;
1403     MI->setFlag(MachineInstr::FrameSetup);
1404     ++MI;
1405   }
1406
1407   return true;
1408 }
1409
1410 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1411                                                MachineBasicBlock::iterator MI,
1412                                         const std::vector<CalleeSavedInfo> &CSI,
1413                                           const TargetRegisterInfo *TRI) const {
1414   if (CSI.empty())
1415     return false;
1416
1417   DebugLoc DL = MBB.findDebugLoc(MI);
1418
1419   MachineFunction &MF = *MBB.getParent();
1420   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1421   const TargetInstrInfo &TII = *STI.getInstrInfo();
1422
1423   // Reload XMMs from stack frame.
1424   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1425     unsigned Reg = CSI[i].getReg();
1426     if (X86::GR64RegClass.contains(Reg) ||
1427         X86::GR32RegClass.contains(Reg))
1428       continue;
1429
1430     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1431     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1432   }
1433
1434   // POP GPRs.
1435   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1436   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1437     unsigned Reg = CSI[i].getReg();
1438     if (!X86::GR64RegClass.contains(Reg) &&
1439         !X86::GR32RegClass.contains(Reg))
1440       continue;
1441
1442     BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1443   }
1444   return true;
1445 }
1446
1447 void
1448 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1449                                                        RegScavenger *RS) const {
1450   MachineFrameInfo *MFI = MF.getFrameInfo();
1451   const X86RegisterInfo *RegInfo =
1452       MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1453   unsigned SlotSize = RegInfo->getSlotSize();
1454
1455   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1456   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1457
1458   if (TailCallReturnAddrDelta < 0) {
1459     // create RETURNADDR area
1460     //   arg
1461     //   arg
1462     //   RETADDR
1463     //   { ...
1464     //     RETADDR area
1465     //     ...
1466     //   }
1467     //   [EBP]
1468     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1469                            TailCallReturnAddrDelta - SlotSize, true);
1470   }
1471
1472   // Spill the BasePtr if it's used.
1473   if (RegInfo->hasBasePointer(MF))
1474     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1475 }
1476
1477 static bool
1478 HasNestArgument(const MachineFunction *MF) {
1479   const Function *F = MF->getFunction();
1480   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1481        I != E; I++) {
1482     if (I->hasNestAttr())
1483       return true;
1484   }
1485   return false;
1486 }
1487
1488 /// GetScratchRegister - Get a temp register for performing work in the
1489 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1490 /// and the properties of the function either one or two registers will be
1491 /// needed. Set primary to true for the first register, false for the second.
1492 static unsigned
1493 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1494   CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1495
1496   // Erlang stuff.
1497   if (CallingConvention == CallingConv::HiPE) {
1498     if (Is64Bit)
1499       return Primary ? X86::R14 : X86::R13;
1500     else
1501       return Primary ? X86::EBX : X86::EDI;
1502   }
1503
1504   if (Is64Bit) {
1505     if (IsLP64)
1506       return Primary ? X86::R11 : X86::R12;
1507     else
1508       return Primary ? X86::R11D : X86::R12D;
1509   }
1510
1511   bool IsNested = HasNestArgument(&MF);
1512
1513   if (CallingConvention == CallingConv::X86_FastCall ||
1514       CallingConvention == CallingConv::Fast) {
1515     if (IsNested)
1516       report_fatal_error("Segmented stacks does not support fastcall with "
1517                          "nested function.");
1518     return Primary ? X86::EAX : X86::ECX;
1519   }
1520   if (IsNested)
1521     return Primary ? X86::EDX : X86::EAX;
1522   return Primary ? X86::ECX : X86::EAX;
1523 }
1524
1525 // The stack limit in the TCB is set to this many bytes above the actual stack
1526 // limit.
1527 static const uint64_t kSplitStackAvailable = 256;
1528
1529 void X86FrameLowering::adjustForSegmentedStacks(
1530     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1531   MachineFrameInfo *MFI = MF.getFrameInfo();
1532   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1533   const TargetInstrInfo &TII = *STI.getInstrInfo();
1534   uint64_t StackSize;
1535   bool Is64Bit = STI.is64Bit();
1536   const bool IsLP64 = STI.isTarget64BitLP64();
1537   unsigned TlsReg, TlsOffset;
1538   DebugLoc DL;
1539
1540   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1541   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1542          "Scratch register is live-in");
1543
1544   if (MF.getFunction()->isVarArg())
1545     report_fatal_error("Segmented stacks do not support vararg functions.");
1546   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1547       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1548       !STI.isTargetDragonFly())
1549     report_fatal_error("Segmented stacks not supported on this platform.");
1550
1551   // Eventually StackSize will be calculated by a link-time pass; which will
1552   // also decide whether checking code needs to be injected into this particular
1553   // prologue.
1554   StackSize = MFI->getStackSize();
1555
1556   // Do not generate a prologue for functions with a stack of size zero
1557   if (StackSize == 0)
1558     return;
1559
1560   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1561   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1562   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1563   bool IsNested = false;
1564
1565   // We need to know if the function has a nest argument only in 64 bit mode.
1566   if (Is64Bit)
1567     IsNested = HasNestArgument(&MF);
1568
1569   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1570   // allocMBB needs to be last (terminating) instruction.
1571
1572   for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1573                                           e = PrologueMBB.livein_end();
1574        i != e; i++) {
1575     allocMBB->addLiveIn(*i);
1576     checkMBB->addLiveIn(*i);
1577   }
1578
1579   if (IsNested)
1580     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1581
1582   MF.push_front(allocMBB);
1583   MF.push_front(checkMBB);
1584
1585   // When the frame size is less than 256 we just compare the stack
1586   // boundary directly to the value of the stack pointer, per gcc.
1587   bool CompareStackPointer = StackSize < kSplitStackAvailable;
1588
1589   // Read the limit off the current stacklet off the stack_guard location.
1590   if (Is64Bit) {
1591     if (STI.isTargetLinux()) {
1592       TlsReg = X86::FS;
1593       TlsOffset = IsLP64 ? 0x70 : 0x40;
1594     } else if (STI.isTargetDarwin()) {
1595       TlsReg = X86::GS;
1596       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1597     } else if (STI.isTargetWin64()) {
1598       TlsReg = X86::GS;
1599       TlsOffset = 0x28; // pvArbitrary, reserved for application use
1600     } else if (STI.isTargetFreeBSD()) {
1601       TlsReg = X86::FS;
1602       TlsOffset = 0x18;
1603     } else if (STI.isTargetDragonFly()) {
1604       TlsReg = X86::FS;
1605       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1606     } else {
1607       report_fatal_error("Segmented stacks not supported on this platform.");
1608     }
1609
1610     if (CompareStackPointer)
1611       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1612     else
1613       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1614         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1615
1616     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1617       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1618   } else {
1619     if (STI.isTargetLinux()) {
1620       TlsReg = X86::GS;
1621       TlsOffset = 0x30;
1622     } else if (STI.isTargetDarwin()) {
1623       TlsReg = X86::GS;
1624       TlsOffset = 0x48 + 90*4;
1625     } else if (STI.isTargetWin32()) {
1626       TlsReg = X86::FS;
1627       TlsOffset = 0x14; // pvArbitrary, reserved for application use
1628     } else if (STI.isTargetDragonFly()) {
1629       TlsReg = X86::FS;
1630       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1631     } else if (STI.isTargetFreeBSD()) {
1632       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1633     } else {
1634       report_fatal_error("Segmented stacks not supported on this platform.");
1635     }
1636
1637     if (CompareStackPointer)
1638       ScratchReg = X86::ESP;
1639     else
1640       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1641         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1642
1643     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1644         STI.isTargetDragonFly()) {
1645       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1646         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1647     } else if (STI.isTargetDarwin()) {
1648
1649       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1650       unsigned ScratchReg2;
1651       bool SaveScratch2;
1652       if (CompareStackPointer) {
1653         // The primary scratch register is available for holding the TLS offset.
1654         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1655         SaveScratch2 = false;
1656       } else {
1657         // Need to use a second register to hold the TLS offset
1658         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1659
1660         // Unfortunately, with fastcc the second scratch register may hold an
1661         // argument.
1662         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1663       }
1664
1665       // If Scratch2 is live-in then it needs to be saved.
1666       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1667              "Scratch register is live-in and not saved");
1668
1669       if (SaveScratch2)
1670         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1671           .addReg(ScratchReg2, RegState::Kill);
1672
1673       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1674         .addImm(TlsOffset);
1675       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1676         .addReg(ScratchReg)
1677         .addReg(ScratchReg2).addImm(1).addReg(0)
1678         .addImm(0)
1679         .addReg(TlsReg);
1680
1681       if (SaveScratch2)
1682         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1683     }
1684   }
1685
1686   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1687   // It jumps to normal execution of the function body.
1688   BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
1689
1690   // On 32 bit we first push the arguments size and then the frame size. On 64
1691   // bit, we pass the stack frame size in r10 and the argument size in r11.
1692   if (Is64Bit) {
1693     // Functions with nested arguments use R10, so it needs to be saved across
1694     // the call to _morestack
1695
1696     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1697     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1698     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1699     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1700     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1701
1702     if (IsNested)
1703       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1704
1705     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1706       .addImm(StackSize);
1707     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1708       .addImm(X86FI->getArgumentStackSize());
1709     MF.getRegInfo().setPhysRegUsed(Reg10);
1710     MF.getRegInfo().setPhysRegUsed(Reg11);
1711   } else {
1712     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1713       .addImm(X86FI->getArgumentStackSize());
1714     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1715       .addImm(StackSize);
1716   }
1717
1718   // __morestack is in libgcc
1719   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1720     // Under the large code model, we cannot assume that __morestack lives
1721     // within 2^31 bytes of the call site, so we cannot use pc-relative
1722     // addressing. We cannot perform the call via a temporary register,
1723     // as the rax register may be used to store the static chain, and all
1724     // other suitable registers may be either callee-save or used for
1725     // parameter passing. We cannot use the stack at this point either
1726     // because __morestack manipulates the stack directly.
1727     //
1728     // To avoid these issues, perform an indirect call via a read-only memory
1729     // location containing the address.
1730     //
1731     // This solution is not perfect, as it assumes that the .rodata section
1732     // is laid out within 2^31 bytes of each function body, but this seems
1733     // to be sufficient for JIT.
1734     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1735         .addReg(X86::RIP)
1736         .addImm(0)
1737         .addReg(0)
1738         .addExternalSymbol("__morestack_addr")
1739         .addReg(0);
1740     MF.getMMI().setUsesMorestackAddr(true);
1741   } else {
1742     if (Is64Bit)
1743       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1744         .addExternalSymbol("__morestack");
1745     else
1746       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1747         .addExternalSymbol("__morestack");
1748   }
1749
1750   if (IsNested)
1751     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1752   else
1753     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1754
1755   allocMBB->addSuccessor(&PrologueMBB);
1756
1757   checkMBB->addSuccessor(allocMBB);
1758   checkMBB->addSuccessor(&PrologueMBB);
1759
1760 #ifdef XDEBUG
1761   MF.verify();
1762 #endif
1763 }
1764
1765 /// Erlang programs may need a special prologue to handle the stack size they
1766 /// might need at runtime. That is because Erlang/OTP does not implement a C
1767 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1768 /// (for more information see Eric Stenman's Ph.D. thesis:
1769 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1770 ///
1771 /// CheckStack:
1772 ///       temp0 = sp - MaxStack
1773 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1774 /// OldStart:
1775 ///       ...
1776 /// IncStack:
1777 ///       call inc_stack   # doubles the stack space
1778 ///       temp0 = sp - MaxStack
1779 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1780 void X86FrameLowering::adjustForHiPEPrologue(
1781     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1782   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1783   const TargetInstrInfo &TII = *STI.getInstrInfo();
1784   MachineFrameInfo *MFI = MF.getFrameInfo();
1785   const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
1786   const bool Is64Bit = STI.is64Bit();
1787   const bool IsLP64 = STI.isTarget64BitLP64();
1788   DebugLoc DL;
1789   // HiPE-specific values
1790   const unsigned HipeLeafWords = 24;
1791   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1792   const unsigned Guaranteed = HipeLeafWords * SlotSize;
1793   unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1794                             MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1795   unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1796
1797   assert(STI.isTargetLinux() &&
1798          "HiPE prologue is only supported on Linux operating systems.");
1799
1800   // Compute the largest caller's frame that is needed to fit the callees'
1801   // frames. This 'MaxStack' is computed from:
1802   //
1803   // a) the fixed frame size, which is the space needed for all spilled temps,
1804   // b) outgoing on-stack parameter areas, and
1805   // c) the minimum stack space this function needs to make available for the
1806   //    functions it calls (a tunable ABI property).
1807   if (MFI->hasCalls()) {
1808     unsigned MoreStackForCalls = 0;
1809
1810     for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1811          MBBI != MBBE; ++MBBI)
1812       for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1813            MI != ME; ++MI) {
1814         if (!MI->isCall())
1815           continue;
1816
1817         // Get callee operand.
1818         const MachineOperand &MO = MI->getOperand(0);
1819
1820         // Only take account of global function calls (no closures etc.).
1821         if (!MO.isGlobal())
1822           continue;
1823
1824         const Function *F = dyn_cast<Function>(MO.getGlobal());
1825         if (!F)
1826           continue;
1827
1828         // Do not update 'MaxStack' for primitive and built-in functions
1829         // (encoded with names either starting with "erlang."/"bif_" or not
1830         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1831         // "_", such as the BIF "suspend_0") as they are executed on another
1832         // stack.
1833         if (F->getName().find("erlang.") != StringRef::npos ||
1834             F->getName().find("bif_") != StringRef::npos ||
1835             F->getName().find_first_of("._") == StringRef::npos)
1836           continue;
1837
1838         unsigned CalleeStkArity =
1839           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1840         if (HipeLeafWords - 1 > CalleeStkArity)
1841           MoreStackForCalls = std::max(MoreStackForCalls,
1842                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1843       }
1844     MaxStack += MoreStackForCalls;
1845   }
1846
1847   // If the stack frame needed is larger than the guaranteed then runtime checks
1848   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1849   if (MaxStack > Guaranteed) {
1850     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1851     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1852
1853     for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1854                                             E = PrologueMBB.livein_end();
1855          I != E; I++) {
1856       stackCheckMBB->addLiveIn(*I);
1857       incStackMBB->addLiveIn(*I);
1858     }
1859
1860     MF.push_front(incStackMBB);
1861     MF.push_front(stackCheckMBB);
1862
1863     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1864     unsigned LEAop, CMPop, CALLop;
1865     if (Is64Bit) {
1866       SPReg = X86::RSP;
1867       PReg  = X86::RBP;
1868       LEAop = X86::LEA64r;
1869       CMPop = X86::CMP64rm;
1870       CALLop = X86::CALL64pcrel32;
1871       SPLimitOffset = 0x90;
1872     } else {
1873       SPReg = X86::ESP;
1874       PReg  = X86::EBP;
1875       LEAop = X86::LEA32r;
1876       CMPop = X86::CMP32rm;
1877       CALLop = X86::CALLpcrel32;
1878       SPLimitOffset = 0x4c;
1879     }
1880
1881     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1882     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1883            "HiPE prologue scratch register is live-in");
1884
1885     // Create new MBB for StackCheck:
1886     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1887                  SPReg, false, -MaxStack);
1888     // SPLimitOffset is in a fixed heap location (pointed by BP).
1889     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1890                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
1891     BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
1892
1893     // Create new MBB for IncStack:
1894     BuildMI(incStackMBB, DL, TII.get(CALLop)).
1895       addExternalSymbol("inc_stack_0");
1896     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1897                  SPReg, false, -MaxStack);
1898     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1899                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
1900     BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1901
1902     stackCheckMBB->addSuccessor(&PrologueMBB, 99);
1903     stackCheckMBB->addSuccessor(incStackMBB, 1);
1904     incStackMBB->addSuccessor(&PrologueMBB, 99);
1905     incStackMBB->addSuccessor(incStackMBB, 1);
1906   }
1907 #ifdef XDEBUG
1908   MF.verify();
1909 #endif
1910 }
1911
1912 void X86FrameLowering::
1913 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1914                               MachineBasicBlock::iterator I) const {
1915   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1916   const TargetInstrInfo &TII = *STI.getInstrInfo();
1917   const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
1918   unsigned StackPtr = RegInfo.getStackRegister();
1919   bool reserveCallFrame = hasReservedCallFrame(MF);
1920   unsigned Opcode = I->getOpcode();
1921   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1922   bool IsLP64 = STI.isTarget64BitLP64();
1923   DebugLoc DL = I->getDebugLoc();
1924   uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1925   uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
1926   I = MBB.erase(I);
1927
1928   if (!reserveCallFrame) {
1929     // If the stack pointer can be changed after prologue, turn the
1930     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1931     // adjcallstackdown instruction into 'add ESP, <amt>'
1932     if (Amount == 0)
1933       return;
1934
1935     // We need to keep the stack aligned properly.  To do this, we round the
1936     // amount of space needed for the outgoing arguments up to the next
1937     // alignment boundary.
1938     unsigned StackAlign = getStackAlignment();
1939     Amount = RoundUpToAlignment(Amount, StackAlign);
1940
1941     MachineInstr *New = nullptr;
1942
1943     // Factor out the amount that gets handled inside the sequence
1944     // (Pushes of argument for frame setup, callee pops for frame destroy)
1945     Amount -= InternalAmt;
1946
1947     if (Amount) {
1948       if (Opcode == TII.getCallFrameSetupOpcode()) {
1949         New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1950           .addReg(StackPtr).addImm(Amount);
1951       } else {
1952         assert(Opcode == TII.getCallFrameDestroyOpcode());
1953
1954         unsigned Opc = getADDriOpcode(IsLP64, Amount);
1955         New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1956           .addReg(StackPtr).addImm(Amount);
1957       }
1958     }
1959
1960     if (New) {
1961       // The EFLAGS implicit def is dead.
1962       New->getOperand(3).setIsDead();
1963
1964       // Replace the pseudo instruction with a new instruction.
1965       MBB.insert(I, New);
1966     }
1967
1968     return;
1969   }
1970
1971   if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
1972     // If we are performing frame pointer elimination and if the callee pops
1973     // something off the stack pointer, add it back.  We do this until we have
1974     // more advanced stack pointer tracking ability.
1975     unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
1976     MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1977       .addReg(StackPtr).addImm(InternalAmt);
1978
1979     // The EFLAGS implicit def is dead.
1980     New->getOperand(3).setIsDead();
1981
1982     // We are not tracking the stack pointer adjustment by the callee, so make
1983     // sure we restore the stack pointer immediately after the call, there may
1984     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1985     MachineBasicBlock::iterator B = MBB.begin();
1986     while (I != B && !std::prev(I)->isCall())
1987       --I;
1988     MBB.insert(I, New);
1989   }
1990 }
1991
1992 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1993   assert(MBB.getParent() && "Block is not attached to a function!");
1994
1995   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
1996     return true;
1997
1998   // If we cannot use LEA to adjust SP, we may need to use ADD, which
1999   // clobbers the EFLAGS. Check that none of the terminators reads the
2000   // EFLAGS, and if one uses it, conservatively assume this is not
2001   // safe to insert the epilogue here.
2002   return !terminatorsNeedFlagsAsInput(MBB);
2003 }