96954fc901b907065c15188074cf2bfea919d8d6
[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
34 using namespace llvm;
35
36 // FIXME: completely move here.
37 extern cl::opt<bool> ForceStackAlign;
38
39 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
40   return !MF.getFrameInfo()->hasVarSizedObjects();
41 }
42
43 /// hasFP - Return true if the specified function should have a dedicated frame
44 /// pointer register.  This is true if the function has variable sized allocas
45 /// or if frame pointer elimination is disabled.
46 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
47   const MachineFrameInfo *MFI = MF.getFrameInfo();
48   const MachineModuleInfo &MMI = MF.getMMI();
49   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
50
51   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
52           RegInfo->needsStackRealignment(MF) ||
53           MFI->hasVarSizedObjects() ||
54           MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
55           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
56           MMI.callsUnwindInit() || MMI.callsEHReturn());
57 }
58
59 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
60   if (IsLP64) {
61     if (isInt<8>(Imm))
62       return X86::SUB64ri8;
63     return X86::SUB64ri32;
64   } else {
65     if (isInt<8>(Imm))
66       return X86::SUB32ri8;
67     return X86::SUB32ri;
68   }
69 }
70
71 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
72   if (IsLP64) {
73     if (isInt<8>(Imm))
74       return X86::ADD64ri8;
75     return X86::ADD64ri32;
76   } else {
77     if (isInt<8>(Imm))
78       return X86::ADD32ri8;
79     return X86::ADD32ri;
80   }
81 }
82
83 static unsigned getLEArOpcode(unsigned IsLP64) {
84   return IsLP64 ? X86::LEA64r : X86::LEA32r;
85 }
86
87 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
88 /// when it reaches the "return" instruction. We can then pop a stack object
89 /// to this register without worry about clobbering it.
90 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
91                                        MachineBasicBlock::iterator &MBBI,
92                                        const TargetRegisterInfo &TRI,
93                                        bool Is64Bit) {
94   const MachineFunction *MF = MBB.getParent();
95   const Function *F = MF->getFunction();
96   if (!F || MF->getMMI().callsEHReturn())
97     return 0;
98
99   static const uint16_t CallerSavedRegs32Bit[] = {
100     X86::EAX, X86::EDX, X86::ECX, 0
101   };
102
103   static const uint16_t CallerSavedRegs64Bit[] = {
104     X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
105     X86::R8,  X86::R9,  X86::R10, X86::R11, 0
106   };
107
108   unsigned Opc = MBBI->getOpcode();
109   switch (Opc) {
110   default: return 0;
111   case X86::RETL:
112   case X86::RETQ:
113   case X86::RETIL:
114   case X86::RETIQ:
115   case X86::TCRETURNdi:
116   case X86::TCRETURNri:
117   case X86::TCRETURNmi:
118   case X86::TCRETURNdi64:
119   case X86::TCRETURNri64:
120   case X86::TCRETURNmi64:
121   case X86::EH_RETURN:
122   case X86::EH_RETURN64: {
123     SmallSet<uint16_t, 8> Uses;
124     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
125       MachineOperand &MO = MBBI->getOperand(i);
126       if (!MO.isReg() || MO.isDef())
127         continue;
128       unsigned Reg = MO.getReg();
129       if (!Reg)
130         continue;
131       for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
132         Uses.insert(*AI);
133     }
134
135     const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
136     for (; *CS; ++CS)
137       if (!Uses.count(*CS))
138         return *CS;
139   }
140   }
141
142   return 0;
143 }
144
145
146 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
147 /// stack pointer by a constant value.
148 static
149 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
150                   unsigned StackPtr, int64_t NumBytes,
151                   bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
152                   const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
153   bool isSub = NumBytes < 0;
154   uint64_t Offset = isSub ? -NumBytes : NumBytes;
155   unsigned Opc;
156   if (UseLEA)
157     Opc = getLEArOpcode(Is64BitStackPtr);
158   else
159     Opc = isSub
160       ? getSUBriOpcode(Is64BitStackPtr, Offset)
161       : getADDriOpcode(Is64BitStackPtr, Offset);
162
163   uint64_t Chunk = (1LL << 31) - 1;
164   DebugLoc DL = MBB.findDebugLoc(MBBI);
165
166   while (Offset) {
167     uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
168     if (ThisVal == (Is64BitTarget ? 8 : 4)) {
169       // Use push / pop instead.
170       unsigned Reg = isSub
171         ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
172         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
173       if (Reg) {
174         Opc = isSub
175           ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
176           : (Is64BitTarget ? X86::POP64r  : X86::POP32r);
177         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
178           .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
179         if (isSub)
180           MI->setFlag(MachineInstr::FrameSetup);
181         Offset -= ThisVal;
182         continue;
183       }
184     }
185
186     MachineInstr *MI = nullptr;
187
188     if (UseLEA) {
189       MI =  addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
190                           StackPtr, false, isSub ? -ThisVal : ThisVal);
191     } else {
192       MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
193             .addReg(StackPtr)
194             .addImm(ThisVal);
195       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
196     }
197
198     if (isSub)
199       MI->setFlag(MachineInstr::FrameSetup);
200
201     Offset -= ThisVal;
202   }
203 }
204
205 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
206 static
207 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
208                       unsigned StackPtr, uint64_t *NumBytes = nullptr) {
209   if (MBBI == MBB.begin()) return;
210
211   MachineBasicBlock::iterator PI = std::prev(MBBI);
212   unsigned Opc = PI->getOpcode();
213   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
214        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
215        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
216       PI->getOperand(0).getReg() == StackPtr) {
217     if (NumBytes)
218       *NumBytes += PI->getOperand(2).getImm();
219     MBB.erase(PI);
220   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
221               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
222              PI->getOperand(0).getReg() == StackPtr) {
223     if (NumBytes)
224       *NumBytes -= PI->getOperand(2).getImm();
225     MBB.erase(PI);
226   }
227 }
228
229 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
230 /// iterator.
231 static
232 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
233                         MachineBasicBlock::iterator &MBBI,
234                         unsigned StackPtr, uint64_t *NumBytes = nullptr) {
235   // FIXME:  THIS ISN'T RUN!!!
236   return;
237
238   if (MBBI == MBB.end()) return;
239
240   MachineBasicBlock::iterator NI = std::next(MBBI);
241   if (NI == MBB.end()) return;
242
243   unsigned Opc = NI->getOpcode();
244   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
245        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
246       NI->getOperand(0).getReg() == StackPtr) {
247     if (NumBytes)
248       *NumBytes -= NI->getOperand(2).getImm();
249     MBB.erase(NI);
250     MBBI = NI;
251   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
252               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
253              NI->getOperand(0).getReg() == StackPtr) {
254     if (NumBytes)
255       *NumBytes += NI->getOperand(2).getImm();
256     MBB.erase(NI);
257     MBBI = NI;
258   }
259 }
260
261 /// mergeSPUpdates - Checks the instruction before/after the passed
262 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
263 /// the stack adjustment is returned as a positive value for ADD/LEA and a
264 /// negative for SUB.
265 static int mergeSPUpdates(MachineBasicBlock &MBB,
266                           MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
267                           bool doMergeWithPrevious) {
268   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
269       (!doMergeWithPrevious && MBBI == MBB.end()))
270     return 0;
271
272   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
273   MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
274                                                        : std::next(MBBI);
275   unsigned Opc = PI->getOpcode();
276   int Offset = 0;
277
278   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
279        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
280        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
281       PI->getOperand(0).getReg() == StackPtr){
282     Offset += PI->getOperand(2).getImm();
283     MBB.erase(PI);
284     if (!doMergeWithPrevious) MBBI = NI;
285   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
286               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
287              PI->getOperand(0).getReg() == StackPtr) {
288     Offset -= PI->getOperand(2).getImm();
289     MBB.erase(PI);
290     if (!doMergeWithPrevious) MBBI = NI;
291   }
292
293   return Offset;
294 }
295
296 static bool isEAXLiveIn(MachineFunction &MF) {
297   for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
298        EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
299     unsigned Reg = II->first;
300
301     if (Reg == X86::EAX || Reg == X86::AX ||
302         Reg == X86::AH || Reg == X86::AL)
303       return true;
304   }
305
306   return false;
307 }
308
309 void
310 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
311                                             MachineBasicBlock::iterator MBBI,
312                                             DebugLoc DL) const {
313   MachineFunction &MF = *MBB.getParent();
314   MachineFrameInfo *MFI = MF.getFrameInfo();
315   MachineModuleInfo &MMI = MF.getMMI();
316   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
317   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
318
319   // Add callee saved registers to move list.
320   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
321   if (CSI.empty()) return;
322
323   // Calculate offsets.
324   for (std::vector<CalleeSavedInfo>::const_iterator
325          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
326     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
327     unsigned Reg = I->getReg();
328
329     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
330     unsigned CFIIndex =
331         MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
332                                                         Offset));
333     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
334         .addCFIIndex(CFIIndex);
335   }
336 }
337
338 /// usesTheStack - This function checks if any of the users of EFLAGS
339 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
340 /// to use the stack, and if we don't adjust the stack we clobber the first
341 /// frame index.
342 /// See X86InstrInfo::copyPhysReg.
343 static bool usesTheStack(const MachineFunction &MF) {
344   const MachineRegisterInfo &MRI = MF.getRegInfo();
345
346   for (MachineRegisterInfo::reg_instr_iterator
347        ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
348        ri != re; ++ri)
349     if (ri->isCopy())
350       return true;
351
352   return false;
353 }
354
355 void X86FrameLowering::getStackProbeFunction(const X86Subtarget &STI,
356                                              unsigned &CallOp,
357                                              const char *&Symbol) {
358   CallOp = STI.is64Bit() ? X86::W64ALLOCA : X86::CALLpcrel32;
359
360   if (STI.is64Bit()) {
361     if (STI.isTargetCygMing()) {
362       Symbol = "___chkstk_ms";
363     } else {
364       Symbol = "__chkstk";
365     }
366   } else if (STI.isTargetCygMing())
367     Symbol = "_alloca";
368   else
369     Symbol = "_chkstk";
370 }
371
372 /// emitPrologue - Push callee-saved registers onto the stack, which
373 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
374 /// space for local variables. Also emit labels used by the exception handler to
375 /// generate the exception handling frames.
376
377 /*
378   Here's a gist of what gets emitted:
379
380   ; Establish frame pointer, if needed
381   [if needs FP]
382       push  %rbp
383       .cfi_def_cfa_offset 16
384       .cfi_offset %rbp, -16
385       .seh_pushreg %rpb
386       mov  %rsp, %rbp
387       .cfi_def_cfa_register %rbp
388
389   ; Spill general-purpose registers
390   [for all callee-saved GPRs]
391       pushq %<reg>
392       [if not needs FP]
393          .cfi_def_cfa_offset (offset from RETADDR)
394       .seh_pushreg %<reg>
395
396   ; If the required stack alignment > default stack alignment
397   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
398   ; of unknown size in the stack frame.
399   [if stack needs re-alignment]
400       and  $MASK, %rsp
401
402   ; Allocate space for locals
403   [if target is Windows and allocated space > 4096 bytes]
404       ; Windows needs special care for allocations larger
405       ; than one page.
406       mov $NNN, %rax
407       call ___chkstk_ms/___chkstk
408       sub  %rax, %rsp
409   [else]
410       sub  $NNN, %rsp
411
412   [if needs FP]
413       .seh_stackalloc (size of XMM spill slots)
414       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
415   [else]
416       .seh_stackalloc NNN
417
418   ; Spill XMMs
419   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
420   ; they may get spilled on any platform, if the current function
421   ; calls @llvm.eh.unwind.init
422   [if needs FP]
423       [for all callee-saved XMM registers]
424           movaps  %<xmm reg>, -MMM(%rbp)
425       [for all callee-saved XMM registers]
426           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
427               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
428   [else]
429       [for all callee-saved XMM registers]
430           movaps  %<xmm reg>, KKK(%rsp)
431       [for all callee-saved XMM registers]
432           .seh_savexmm %<xmm reg>, KKK
433
434   .seh_endprologue
435
436   [if needs base pointer]
437       mov  %rsp, %rbx
438
439   ; Emit CFI info
440   [if needs FP]
441       [for all callee-saved registers]
442           .cfi_offset %<reg>, (offset from %rbp)
443   [else]
444        .cfi_def_cfa_offset (offset from RETADDR)
445       [for all callee-saved registers]
446           .cfi_offset %<reg>, (offset from %rsp)
447
448   Notes:
449   - .seh directives are emitted only for Windows 64 ABI
450   - .cfi directives are emitted for all other ABIs
451   - for 32-bit code, substitute %e?? registers for %r??
452 */
453
454 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
455   MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
456   MachineBasicBlock::iterator MBBI = MBB.begin();
457   MachineFrameInfo *MFI = MF.getFrameInfo();
458   const Function *Fn = MF.getFunction();
459   const X86RegisterInfo *RegInfo =
460       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
461   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
462   MachineModuleInfo &MMI = MF.getMMI();
463   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
464   uint64_t MaxAlign  = MFI->getMaxAlignment(); // Desired stack alignment.
465   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
466   bool HasFP = hasFP(MF);
467   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
468   bool Is64Bit = STI.is64Bit();
469   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
470   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
471   bool IsWin64 = STI.isTargetWin64();
472   bool IsWinEH =
473       MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
474       ExceptionHandling::WinEH; // Not necessarily synonymous with IsWin64.
475   bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
476   bool NeedsDwarfCFI =
477       !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
478   bool UseLEA = STI.useLeaForSP();
479   unsigned StackAlign = getStackAlignment();
480   unsigned SlotSize = RegInfo->getSlotSize();
481   unsigned FramePtr = RegInfo->getFrameRegister(MF);
482   const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
483                  getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
484   unsigned StackPtr = RegInfo->getStackRegister();
485   unsigned BasePtr = RegInfo->getBaseRegister();
486   DebugLoc DL;
487
488   // If we're forcing a stack realignment we can't rely on just the frame
489   // info, we need to know the ABI stack alignment as well in case we
490   // have a call out.  Otherwise just make sure we have some alignment - we'll
491   // go with the minimum SlotSize.
492   if (ForceStackAlign) {
493     if (MFI->hasCalls())
494       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
495     else if (MaxAlign < SlotSize)
496       MaxAlign = SlotSize;
497   }
498
499   // Add RETADDR move area to callee saved frame size.
500   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
501   if (TailCallReturnAddrDelta < 0)
502     X86FI->setCalleeSavedFrameSize(
503       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
504
505   bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMacho());
506   
507   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
508   // function, and use up to 128 bytes of stack space, don't have a frame
509   // pointer, calls, or dynamic alloca then we do not need to adjust the
510   // stack pointer (we fit in the Red Zone). We also check that we don't
511   // push and pop from the stack.
512   if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
513                                                    Attribute::NoRedZone) &&
514       !RegInfo->needsStackRealignment(MF) &&
515       !MFI->hasVarSizedObjects() &&                     // No dynamic alloca.
516       !MFI->adjustsStack() &&                           // No calls.
517       !IsWin64 &&                                       // Win64 has no Red Zone
518       !usesTheStack(MF) &&                              // Don't push and pop.
519       !MF.shouldSplitStack()) {                         // Regular stack
520     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
521     if (HasFP) MinSize += SlotSize;
522     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
523     MFI->setStackSize(StackSize);
524   }
525
526   // Insert stack pointer adjustment for later moving of return addr.  Only
527   // applies to tail call optimized functions where the callee argument stack
528   // size is bigger than the callers.
529   if (TailCallReturnAddrDelta < 0) {
530     MachineInstr *MI =
531       BuildMI(MBB, MBBI, DL,
532               TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
533               StackPtr)
534         .addReg(StackPtr)
535         .addImm(-TailCallReturnAddrDelta)
536         .setMIFlag(MachineInstr::FrameSetup);
537     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
538   }
539
540   // Mapping for machine moves:
541   //
542   //   DST: VirtualFP AND
543   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
544   //        ELSE                        => DW_CFA_def_cfa
545   //
546   //   SRC: VirtualFP AND
547   //        DST: Register               => DW_CFA_def_cfa_register
548   //
549   //   ELSE
550   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
551   //        REG < 64                    => DW_CFA_offset + Reg
552   //        ELSE                        => DW_CFA_offset_extended
553
554   uint64_t NumBytes = 0;
555   int stackGrowth = -SlotSize;
556
557   if (HasFP) {
558     // Calculate required stack adjustment.
559     uint64_t FrameSize = StackSize - SlotSize;
560     if (RegInfo->needsStackRealignment(MF)) {
561       // Callee-saved registers are pushed on stack before the stack
562       // is realigned.
563       FrameSize -= X86FI->getCalleeSavedFrameSize();
564       NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
565     } else {
566       NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
567     }
568
569     // Get the offset of the stack slot for the EBP register, which is
570     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
571     // Update the frame offset adjustment.
572     MFI->setOffsetAdjustment(-NumBytes);
573
574     // Save EBP/RBP into the appropriate stack slot.
575     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
576       .addReg(MachineFramePtr, RegState::Kill)
577       .setMIFlag(MachineInstr::FrameSetup);
578
579     if (NeedsDwarfCFI) {
580       // Mark the place where EBP/RBP was saved.
581       // Define the current CFA rule to use the provided offset.
582       assert(StackSize);
583       unsigned CFIIndex = MMI.addFrameInst(
584           MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
585       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
586           .addCFIIndex(CFIIndex);
587
588       // Change the rule for the FramePtr to be an "offset" rule.
589       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
590       CFIIndex = MMI.addFrameInst(
591           MCCFIInstruction::createOffset(nullptr,
592                                          DwarfFramePtr, 2 * stackGrowth));
593       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
594           .addCFIIndex(CFIIndex);
595     }
596
597     if (NeedsWinEH) {
598       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
599           .addImm(FramePtr)
600           .setMIFlag(MachineInstr::FrameSetup);
601     }
602
603     // Update EBP with the new base value.
604     BuildMI(MBB, MBBI, DL,
605             TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
606         .addReg(StackPtr)
607         .setMIFlag(MachineInstr::FrameSetup);
608
609     if (NeedsDwarfCFI) {
610       // Mark effective beginning of when frame pointer becomes valid.
611       // Define the current CFA to use the EBP/RBP register.
612       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
613       unsigned CFIIndex = MMI.addFrameInst(
614           MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
615       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
616           .addCFIIndex(CFIIndex);
617     }
618
619     // Mark the FramePtr as live-in in every block.
620     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
621       I->addLiveIn(MachineFramePtr);
622   } else {
623     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
624   }
625
626   // Skip the callee-saved push instructions.
627   bool PushedRegs = false;
628   int StackOffset = 2 * stackGrowth;
629
630   while (MBBI != MBB.end() &&
631          (MBBI->getOpcode() == X86::PUSH32r ||
632           MBBI->getOpcode() == X86::PUSH64r)) {
633     PushedRegs = true;
634     unsigned Reg = MBBI->getOperand(0).getReg();
635     ++MBBI;
636
637     if (!HasFP && NeedsDwarfCFI) {
638       // Mark callee-saved push instruction.
639       // Define the current CFA rule to use the provided offset.
640       assert(StackSize);
641       unsigned CFIIndex = MMI.addFrameInst(
642           MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
643       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
644           .addCFIIndex(CFIIndex);
645       StackOffset += stackGrowth;
646     }
647
648     if (NeedsWinEH) {
649       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
650           MachineInstr::FrameSetup);
651     }
652   }
653
654   // Realign stack after we pushed callee-saved registers (so that we'll be
655   // able to calculate their offsets from the frame pointer).
656   if (RegInfo->needsStackRealignment(MF)) {
657     assert(HasFP && "There should be a frame pointer if stack is realigned.");
658     MachineInstr *MI =
659       BuildMI(MBB, MBBI, DL,
660               TII.get(Uses64BitFramePtr ? X86::AND64ri32 : X86::AND32ri), StackPtr)
661       .addReg(StackPtr)
662       .addImm(-MaxAlign)
663       .setMIFlag(MachineInstr::FrameSetup);
664
665     // The EFLAGS implicit def is dead.
666     MI->getOperand(3).setIsDead();
667   }
668
669   // If there is an SUB32ri of ESP immediately before this instruction, merge
670   // the two. This can be the case when tail call elimination is enabled and
671   // the callee has more arguments then the caller.
672   NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
673
674   // If there is an ADD32ri or SUB32ri of ESP immediately after this
675   // instruction, merge the two instructions.
676   mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
677
678   // Adjust stack pointer: ESP -= numbytes.
679
680   static const size_t PageSize = 4096;
681
682   // Windows and cygwin/mingw require a prologue helper routine when allocating
683   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
684   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
685   // stack and adjust the stack pointer in one go.  The 64-bit version of
686   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
687   // responsible for adjusting the stack pointer.  Touching the stack at 4K
688   // increments is necessary to ensure that the guard pages used by the OS
689   // virtual memory manager are allocated in correct sequence.
690   if (NumBytes >= PageSize && UseStackProbe) {
691     const char *StackProbeSymbol;
692     unsigned CallOp;
693
694     getStackProbeFunction(STI, CallOp, StackProbeSymbol);
695
696     // Check whether EAX is livein for this function.
697     bool isEAXAlive = isEAXLiveIn(MF);
698
699     if (isEAXAlive) {
700       // Sanity check that EAX is not livein for this function.
701       // It should not be, so throw an assert.
702       assert(!Is64Bit && "EAX is livein in x64 case!");
703
704       // Save EAX
705       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
706         .addReg(X86::EAX, RegState::Kill)
707         .setMIFlag(MachineInstr::FrameSetup);
708     }
709
710     if (Is64Bit) {
711       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
712       // Function prologue is responsible for adjusting the stack pointer.
713       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
714         .addImm(NumBytes)
715         .setMIFlag(MachineInstr::FrameSetup);
716     } else {
717       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
718       // We'll also use 4 already allocated bytes for EAX.
719       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
720         .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
721         .setMIFlag(MachineInstr::FrameSetup);
722     }
723
724     BuildMI(MBB, MBBI, DL,
725             TII.get(CallOp))
726       .addExternalSymbol(StackProbeSymbol)
727       .addReg(StackPtr,    RegState::Define | RegState::Implicit)
728       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
729       .setMIFlag(MachineInstr::FrameSetup);
730
731     if (Is64Bit) {
732       // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
733       // themself. It also does not clobber %rax so we can reuse it when
734       // adjusting %rsp.
735       BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
736         .addReg(StackPtr)
737         .addReg(X86::RAX)
738         .setMIFlag(MachineInstr::FrameSetup);
739     }
740     if (isEAXAlive) {
741       // Restore EAX
742       MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
743                                               X86::EAX),
744                                       StackPtr, false, NumBytes - 4);
745       MI->setFlag(MachineInstr::FrameSetup);
746       MBB.insert(MBBI, MI);
747     }
748   } else if (NumBytes) {
749     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
750                  UseLEA, TII, *RegInfo);
751   }
752
753   int SEHFrameOffset = 0;
754   if (NeedsWinEH) {
755     if (HasFP) {
756       // We need to set frame base offset low enough such that all saved
757       // register offsets would be positive relative to it, but we can't
758       // just use NumBytes, because .seh_setframe offset must be <=240.
759       // So we pretend to have only allocated enough space to spill the
760       // non-volatile registers.
761       // We don't care about the rest of stack allocation, because unwinder
762       // will restore SP to (BP - SEHFrameOffset)
763       for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
764         int offset = MFI->getObjectOffset(Info.getFrameIdx());
765         SEHFrameOffset = std::max(SEHFrameOffset, abs(offset));
766       }
767       SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
768
769       // This only needs to account for XMM spill slots, GPR slots
770       // are covered by the .seh_pushreg's emitted above.
771       unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
772       if (Size) {
773         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
774             .addImm(Size)
775             .setMIFlag(MachineInstr::FrameSetup);
776       }
777
778       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
779           .addImm(FramePtr)
780           .addImm(SEHFrameOffset)
781           .setMIFlag(MachineInstr::FrameSetup);
782     } else {
783       // SP will be the base register for restoring XMMs
784       if (NumBytes) {
785         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
786             .addImm(NumBytes)
787             .setMIFlag(MachineInstr::FrameSetup);
788       }
789     }
790   }
791
792   // Skip the rest of register spilling code
793   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
794     ++MBBI;
795
796   // Emit SEH info for non-GPRs
797   if (NeedsWinEH) {
798     for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
799       unsigned Reg = Info.getReg();
800       if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
801         continue;
802       assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
803
804       int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
805       Offset += SEHFrameOffset;
806
807       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
808           .addImm(Reg)
809           .addImm(Offset)
810           .setMIFlag(MachineInstr::FrameSetup);
811     }
812
813     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
814         .setMIFlag(MachineInstr::FrameSetup);
815   }
816
817   // If we need a base pointer, set it up here. It's whatever the value
818   // of the stack pointer is at this point. Any variable size objects
819   // will be allocated after this, so we can still use the base pointer
820   // to reference locals.
821   if (RegInfo->hasBasePointer(MF)) {
822     // Update the base pointer with the current stack pointer.
823     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
824     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
825       .addReg(StackPtr)
826       .setMIFlag(MachineInstr::FrameSetup);
827   }
828
829   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
830     // Mark end of stack pointer adjustment.
831     if (!HasFP && NumBytes) {
832       // Define the current CFA rule to use the provided offset.
833       assert(StackSize);
834       unsigned CFIIndex = MMI.addFrameInst(
835           MCCFIInstruction::createDefCfaOffset(nullptr,
836                                                -StackSize + stackGrowth));
837
838       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
839           .addCFIIndex(CFIIndex);
840     }
841
842     // Emit DWARF info specifying the offsets of the callee-saved registers.
843     if (PushedRegs)
844       emitCalleeSavedFrameMoves(MBB, MBBI, DL);
845   }
846 }
847
848 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
849                                     MachineBasicBlock &MBB) const {
850   const MachineFrameInfo *MFI = MF.getFrameInfo();
851   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
852   const X86RegisterInfo *RegInfo =
853       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
854   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
855   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
856   assert(MBBI != MBB.end() && "Returning block has no instructions");
857   unsigned RetOpcode = MBBI->getOpcode();
858   DebugLoc DL = MBBI->getDebugLoc();
859   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
860   bool Is64Bit = STI.is64Bit();
861   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
862   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
863   const bool Is64BitILP32 = STI.isTarget64BitILP32();
864   bool UseLEA = STI.useLeaForSP();
865   unsigned StackAlign = getStackAlignment();
866   unsigned SlotSize = RegInfo->getSlotSize();
867   unsigned FramePtr = RegInfo->getFrameRegister(MF);
868   unsigned MachineFramePtr = Is64BitILP32 ?
869              getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
870   unsigned StackPtr = RegInfo->getStackRegister();
871
872   bool IsWinEH =
873       MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
874       ExceptionHandling::WinEH;
875   bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
876
877   switch (RetOpcode) {
878   default:
879     llvm_unreachable("Can only insert epilog into returning blocks");
880   case X86::RETQ:
881   case X86::RETL:
882   case X86::RETIL:
883   case X86::RETIQ:
884   case X86::TCRETURNdi:
885   case X86::TCRETURNri:
886   case X86::TCRETURNmi:
887   case X86::TCRETURNdi64:
888   case X86::TCRETURNri64:
889   case X86::TCRETURNmi64:
890   case X86::EH_RETURN:
891   case X86::EH_RETURN64:
892     break;  // These are ok
893   }
894
895   // Get the number of bytes to allocate from the FrameInfo.
896   uint64_t StackSize = MFI->getStackSize();
897   uint64_t MaxAlign  = MFI->getMaxAlignment();
898   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
899   uint64_t NumBytes = 0;
900
901   // If we're forcing a stack realignment we can't rely on just the frame
902   // info, we need to know the ABI stack alignment as well in case we
903   // have a call out.  Otherwise just make sure we have some alignment - we'll
904   // go with the minimum.
905   if (ForceStackAlign) {
906     if (MFI->hasCalls())
907       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
908     else
909       MaxAlign = MaxAlign ? MaxAlign : 4;
910   }
911
912   if (hasFP(MF)) {
913     // Calculate required stack adjustment.
914     uint64_t FrameSize = StackSize - SlotSize;
915     if (RegInfo->needsStackRealignment(MF)) {
916       // Callee-saved registers were pushed on stack before the stack
917       // was realigned.
918       FrameSize -= CSSize;
919       NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
920     } else {
921       NumBytes = FrameSize - CSSize;
922     }
923
924     // Pop EBP.
925     BuildMI(MBB, MBBI, DL,
926             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
927   } else {
928     NumBytes = StackSize - CSSize;
929   }
930
931   // Skip the callee-saved pop instructions.
932   while (MBBI != MBB.begin()) {
933     MachineBasicBlock::iterator PI = std::prev(MBBI);
934     unsigned Opc = PI->getOpcode();
935
936     if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
937         !PI->isTerminator())
938       break;
939
940     --MBBI;
941   }
942   MachineBasicBlock::iterator FirstCSPop = MBBI;
943
944   DL = MBBI->getDebugLoc();
945
946   // If there is an ADD32ri or SUB32ri of ESP immediately before this
947   // instruction, merge the two instructions.
948   if (NumBytes || MFI->hasVarSizedObjects())
949     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
950
951   // If dynamic alloca is used, then reset esp to point to the last callee-saved
952   // slot before popping them off! Same applies for the case, when stack was
953   // realigned.
954   if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
955     if (RegInfo->needsStackRealignment(MF))
956       MBBI = FirstCSPop;
957     if (CSSize != 0) {
958       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
959       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
960                    FramePtr, false, -CSSize);
961       --MBBI;
962     } else {
963       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
964       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
965         .addReg(FramePtr);
966       --MBBI;
967     }
968   } else if (NumBytes) {
969     // Adjust stack pointer back: ESP += numbytes.
970     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
971                  TII, *RegInfo);
972     --MBBI;
973   }
974
975   // Windows unwinder will not invoke function's exception handler if IP is
976   // either in prologue or in epilogue.  This behavior causes a problem when a
977   // call immediately precedes an epilogue, because the return address points
978   // into the epilogue.  To cope with that, we insert an epilogue marker here,
979   // then replace it with a 'nop' if it ends up immediately after a CALL in the
980   // final emitted code.
981   if (NeedsWinEH)
982     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
983
984   // We're returning from function via eh_return.
985   if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
986     MBBI = MBB.getLastNonDebugInstr();
987     MachineOperand &DestAddr  = MBBI->getOperand(0);
988     assert(DestAddr.isReg() && "Offset should be in register!");
989     BuildMI(MBB, MBBI, DL,
990             TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
991             StackPtr).addReg(DestAddr.getReg());
992   } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
993              RetOpcode == X86::TCRETURNmi ||
994              RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
995              RetOpcode == X86::TCRETURNmi64) {
996     bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
997     // Tail call return: adjust the stack pointer and jump to callee.
998     MBBI = MBB.getLastNonDebugInstr();
999     MachineOperand &JumpTarget = MBBI->getOperand(0);
1000     MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1001     assert(StackAdjust.isImm() && "Expecting immediate value.");
1002
1003     // Adjust stack pointer.
1004     int StackAdj = StackAdjust.getImm();
1005     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1006     int Offset = 0;
1007     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1008
1009     // Incoporate the retaddr area.
1010     Offset = StackAdj-MaxTCDelta;
1011     assert(Offset >= 0 && "Offset should never be negative");
1012
1013     if (Offset) {
1014       // Check for possible merge with preceding ADD instruction.
1015       Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1016       emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1017                    UseLEA, TII, *RegInfo);
1018     }
1019
1020     // Jump to label or value in register.
1021     if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1022       MachineInstrBuilder MIB =
1023         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1024                                        ? X86::TAILJMPd : X86::TAILJMPd64));
1025       if (JumpTarget.isGlobal())
1026         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1027                              JumpTarget.getTargetFlags());
1028       else {
1029         assert(JumpTarget.isSymbol());
1030         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1031                               JumpTarget.getTargetFlags());
1032       }
1033     } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1034       MachineInstrBuilder MIB =
1035         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1036                                        ? X86::TAILJMPm : X86::TAILJMPm64));
1037       for (unsigned i = 0; i != 5; ++i)
1038         MIB.addOperand(MBBI->getOperand(i));
1039     } else if (RetOpcode == X86::TCRETURNri64) {
1040       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1041         addReg(JumpTarget.getReg(), RegState::Kill);
1042     } else {
1043       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1044         addReg(JumpTarget.getReg(), RegState::Kill);
1045     }
1046
1047     MachineInstr *NewMI = std::prev(MBBI);
1048     NewMI->copyImplicitOps(MF, MBBI);
1049
1050     // Delete the pseudo instruction TCRETURN.
1051     MBB.erase(MBBI);
1052   } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1053               RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1054              (X86FI->getTCReturnAddrDelta() < 0)) {
1055     // Add the return addr area delta back since we are not tail calling.
1056     int delta = -1*X86FI->getTCReturnAddrDelta();
1057     MBBI = MBB.getLastNonDebugInstr();
1058
1059     // Check for possible merge with preceding ADD instruction.
1060     delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1061     emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1062                  *RegInfo);
1063   }
1064 }
1065
1066 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1067                                           int FI) const {
1068   const X86RegisterInfo *RegInfo =
1069       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1070   const MachineFrameInfo *MFI = MF.getFrameInfo();
1071   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1072   uint64_t StackSize = MFI->getStackSize();
1073
1074   if (RegInfo->hasBasePointer(MF)) {
1075     assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1076     if (FI < 0) {
1077       // Skip the saved EBP.
1078       return Offset + RegInfo->getSlotSize();
1079     } else {
1080       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1081       return Offset + StackSize;
1082     }
1083   } else if (RegInfo->needsStackRealignment(MF)) {
1084     if (FI < 0) {
1085       // Skip the saved EBP.
1086       return Offset + RegInfo->getSlotSize();
1087     } else {
1088       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1089       return Offset + StackSize;
1090     }
1091     // FIXME: Support tail calls
1092   } else {
1093     if (!hasFP(MF))
1094       return Offset + StackSize;
1095
1096     // Skip the saved EBP.
1097     Offset += RegInfo->getSlotSize();
1098
1099     // Skip the RETADDR move area
1100     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1101     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1102     if (TailCallReturnAddrDelta < 0)
1103       Offset -= TailCallReturnAddrDelta;
1104   }
1105
1106   return Offset;
1107 }
1108
1109 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1110                                              unsigned &FrameReg) const {
1111   const X86RegisterInfo *RegInfo =
1112       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1113   // We can't calculate offset from frame pointer if the stack is realigned,
1114   // so enforce usage of stack/base pointer.  The base pointer is used when we
1115   // have dynamic allocas in addition to dynamic realignment.
1116   if (RegInfo->hasBasePointer(MF))
1117     FrameReg = RegInfo->getBaseRegister();
1118   else if (RegInfo->needsStackRealignment(MF))
1119     FrameReg = RegInfo->getStackRegister();
1120   else
1121     FrameReg = RegInfo->getFrameRegister(MF);
1122   return getFrameIndexOffset(MF, FI);
1123 }
1124
1125 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1126     MachineFunction &MF, const TargetRegisterInfo *TRI,
1127     std::vector<CalleeSavedInfo> &CSI) const {
1128   MachineFrameInfo *MFI = MF.getFrameInfo();
1129   const X86RegisterInfo *RegInfo =
1130       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1131   unsigned SlotSize = RegInfo->getSlotSize();
1132   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1133
1134   unsigned CalleeSavedFrameSize = 0;
1135   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1136
1137   if (hasFP(MF)) {
1138     // emitPrologue always spills frame register the first thing.
1139     SpillSlotOffset -= SlotSize;
1140     MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1141
1142     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1143     // the frame register, we can delete it from CSI list and not have to worry
1144     // about avoiding it later.
1145     unsigned FPReg = RegInfo->getFrameRegister(MF);
1146     for (unsigned i = 0; i < CSI.size(); ++i) {
1147       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1148         CSI.erase(CSI.begin() + i);
1149         break;
1150       }
1151     }
1152   }
1153
1154   // Assign slots for GPRs. It increases frame size.
1155   for (unsigned i = CSI.size(); i != 0; --i) {
1156     unsigned Reg = CSI[i - 1].getReg();
1157
1158     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1159       continue;
1160
1161     SpillSlotOffset -= SlotSize;
1162     CalleeSavedFrameSize += SlotSize;
1163
1164     int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1165     CSI[i - 1].setFrameIdx(SlotIndex);
1166   }
1167
1168   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1169
1170   // Assign slots for XMMs.
1171   for (unsigned i = CSI.size(); i != 0; --i) {
1172     unsigned Reg = CSI[i - 1].getReg();
1173     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1174       continue;
1175
1176     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1177     // ensure alignment
1178     SpillSlotOffset -= abs(SpillSlotOffset) % RC->getAlignment();
1179     // spill into slot
1180     SpillSlotOffset -= RC->getSize();
1181     int SlotIndex =
1182         MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1183     CSI[i - 1].setFrameIdx(SlotIndex);
1184     MFI->ensureMaxAlignment(RC->getAlignment());
1185   }
1186
1187   return true;
1188 }
1189
1190 bool X86FrameLowering::spillCalleeSavedRegisters(
1191     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1192     const std::vector<CalleeSavedInfo> &CSI,
1193     const TargetRegisterInfo *TRI) const {
1194   DebugLoc DL = MBB.findDebugLoc(MI);
1195
1196   MachineFunction &MF = *MBB.getParent();
1197   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1198   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1199
1200   // Push GPRs. It increases frame size.
1201   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1202   for (unsigned i = CSI.size(); i != 0; --i) {
1203     unsigned Reg = CSI[i - 1].getReg();
1204
1205     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1206       continue;
1207     // Add the callee-saved register as live-in. It's killed at the spill.
1208     MBB.addLiveIn(Reg);
1209
1210     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1211       .setMIFlag(MachineInstr::FrameSetup);
1212   }
1213
1214   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1215   // It can be done by spilling XMMs to stack frame.
1216   for (unsigned i = CSI.size(); i != 0; --i) {
1217     unsigned Reg = CSI[i-1].getReg();
1218     if (X86::GR64RegClass.contains(Reg) ||
1219         X86::GR32RegClass.contains(Reg))
1220       continue;
1221     // Add the callee-saved register as live-in. It's killed at the spill.
1222     MBB.addLiveIn(Reg);
1223     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1224
1225     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1226                             TRI);
1227     --MI;
1228     MI->setFlag(MachineInstr::FrameSetup);
1229     ++MI;
1230   }
1231
1232   return true;
1233 }
1234
1235 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1236                                                MachineBasicBlock::iterator MI,
1237                                         const std::vector<CalleeSavedInfo> &CSI,
1238                                           const TargetRegisterInfo *TRI) const {
1239   if (CSI.empty())
1240     return false;
1241
1242   DebugLoc DL = MBB.findDebugLoc(MI);
1243
1244   MachineFunction &MF = *MBB.getParent();
1245   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1246   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1247
1248   // Reload XMMs from stack frame.
1249   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1250     unsigned Reg = CSI[i].getReg();
1251     if (X86::GR64RegClass.contains(Reg) ||
1252         X86::GR32RegClass.contains(Reg))
1253       continue;
1254
1255     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1256     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1257   }
1258
1259   // POP GPRs.
1260   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1261   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1262     unsigned Reg = CSI[i].getReg();
1263     if (!X86::GR64RegClass.contains(Reg) &&
1264         !X86::GR32RegClass.contains(Reg))
1265       continue;
1266
1267     BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1268   }
1269   return true;
1270 }
1271
1272 void
1273 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1274                                                        RegScavenger *RS) const {
1275   MachineFrameInfo *MFI = MF.getFrameInfo();
1276   const X86RegisterInfo *RegInfo =
1277       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1278   unsigned SlotSize = RegInfo->getSlotSize();
1279
1280   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1281   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1282
1283   if (TailCallReturnAddrDelta < 0) {
1284     // create RETURNADDR area
1285     //   arg
1286     //   arg
1287     //   RETADDR
1288     //   { ...
1289     //     RETADDR area
1290     //     ...
1291     //   }
1292     //   [EBP]
1293     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1294                            TailCallReturnAddrDelta - SlotSize, true);
1295   }
1296
1297   // Spill the BasePtr if it's used.
1298   if (RegInfo->hasBasePointer(MF))
1299     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1300 }
1301
1302 static bool
1303 HasNestArgument(const MachineFunction *MF) {
1304   const Function *F = MF->getFunction();
1305   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1306        I != E; I++) {
1307     if (I->hasNestAttr())
1308       return true;
1309   }
1310   return false;
1311 }
1312
1313 /// GetScratchRegister - Get a temp register for performing work in the
1314 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1315 /// and the properties of the function either one or two registers will be
1316 /// needed. Set primary to true for the first register, false for the second.
1317 static unsigned
1318 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1319   CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1320
1321   // Erlang stuff.
1322   if (CallingConvention == CallingConv::HiPE) {
1323     if (Is64Bit)
1324       return Primary ? X86::R14 : X86::R13;
1325     else
1326       return Primary ? X86::EBX : X86::EDI;
1327   }
1328
1329   if (Is64Bit) {
1330     if (IsLP64)
1331       return Primary ? X86::R11 : X86::R12;
1332     else
1333       return Primary ? X86::R11D : X86::R12D;
1334   }
1335
1336   bool IsNested = HasNestArgument(&MF);
1337
1338   if (CallingConvention == CallingConv::X86_FastCall ||
1339       CallingConvention == CallingConv::Fast) {
1340     if (IsNested)
1341       report_fatal_error("Segmented stacks does not support fastcall with "
1342                          "nested function.");
1343     return Primary ? X86::EAX : X86::ECX;
1344   }
1345   if (IsNested)
1346     return Primary ? X86::EDX : X86::EAX;
1347   return Primary ? X86::ECX : X86::EAX;
1348 }
1349
1350 // The stack limit in the TCB is set to this many bytes above the actual stack
1351 // limit.
1352 static const uint64_t kSplitStackAvailable = 256;
1353
1354 void
1355 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1356   MachineBasicBlock &prologueMBB = MF.front();
1357   MachineFrameInfo *MFI = MF.getFrameInfo();
1358   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1359   uint64_t StackSize;
1360   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1361   bool Is64Bit = STI.is64Bit();
1362   const bool IsLP64 = STI.isTarget64BitLP64();
1363   unsigned TlsReg, TlsOffset;
1364   DebugLoc DL;
1365
1366   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1367   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1368          "Scratch register is live-in");
1369
1370   if (MF.getFunction()->isVarArg())
1371     report_fatal_error("Segmented stacks do not support vararg functions.");
1372   if (!STI.isTargetLinux() && !STI.isTargetDarwin() &&
1373       !STI.isTargetWin32() && !STI.isTargetWin64() && !STI.isTargetFreeBSD())
1374     report_fatal_error("Segmented stacks not supported on this platform.");
1375
1376   // Eventually StackSize will be calculated by a link-time pass; which will
1377   // also decide whether checking code needs to be injected into this particular
1378   // prologue.
1379   StackSize = MFI->getStackSize();
1380
1381   // Do not generate a prologue for functions with a stack of size zero
1382   if (StackSize == 0)
1383     return;
1384
1385   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1386   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1387   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1388   bool IsNested = false;
1389
1390   // We need to know if the function has a nest argument only in 64 bit mode.
1391   if (Is64Bit)
1392     IsNested = HasNestArgument(&MF);
1393
1394   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1395   // allocMBB needs to be last (terminating) instruction.
1396
1397   for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1398          e = prologueMBB.livein_end(); i != e; i++) {
1399     allocMBB->addLiveIn(*i);
1400     checkMBB->addLiveIn(*i);
1401   }
1402
1403   if (IsNested)
1404     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1405
1406   MF.push_front(allocMBB);
1407   MF.push_front(checkMBB);
1408
1409   // When the frame size is less than 256 we just compare the stack
1410   // boundary directly to the value of the stack pointer, per gcc.
1411   bool CompareStackPointer = StackSize < kSplitStackAvailable;
1412
1413   // Read the limit off the current stacklet off the stack_guard location.
1414   if (Is64Bit) {
1415     if (STI.isTargetLinux()) {
1416       TlsReg = X86::FS;
1417       TlsOffset = IsLP64 ? 0x70 : 0x40;
1418     } else if (STI.isTargetDarwin()) {
1419       TlsReg = X86::GS;
1420       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1421     } else if (STI.isTargetWin64()) {
1422       TlsReg = X86::GS;
1423       TlsOffset = 0x28; // pvArbitrary, reserved for application use
1424     } else if (STI.isTargetFreeBSD()) {
1425       TlsReg = X86::FS;
1426       TlsOffset = 0x18;
1427     } else {
1428       report_fatal_error("Segmented stacks not supported on this platform.");
1429     }
1430
1431     if (CompareStackPointer)
1432       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1433     else
1434       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1435         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1436
1437     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1438       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1439   } else {
1440     if (STI.isTargetLinux()) {
1441       TlsReg = X86::GS;
1442       TlsOffset = 0x30;
1443     } else if (STI.isTargetDarwin()) {
1444       TlsReg = X86::GS;
1445       TlsOffset = 0x48 + 90*4;
1446     } else if (STI.isTargetWin32()) {
1447       TlsReg = X86::FS;
1448       TlsOffset = 0x14; // pvArbitrary, reserved for application use
1449     } else if (STI.isTargetFreeBSD()) {
1450       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1451     } else {
1452       report_fatal_error("Segmented stacks not supported on this platform.");
1453     }
1454
1455     if (CompareStackPointer)
1456       ScratchReg = X86::ESP;
1457     else
1458       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1459         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1460
1461     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64()) {
1462       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1463         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1464     } else if (STI.isTargetDarwin()) {
1465
1466       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1467       unsigned ScratchReg2;
1468       bool SaveScratch2;
1469       if (CompareStackPointer) {
1470         // The primary scratch register is available for holding the TLS offset.
1471         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1472         SaveScratch2 = false;
1473       } else {
1474         // Need to use a second register to hold the TLS offset
1475         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1476
1477         // Unfortunately, with fastcc the second scratch register may hold an
1478         // argument.
1479         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1480       }
1481
1482       // If Scratch2 is live-in then it needs to be saved.
1483       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1484              "Scratch register is live-in and not saved");
1485
1486       if (SaveScratch2)
1487         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1488           .addReg(ScratchReg2, RegState::Kill);
1489
1490       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1491         .addImm(TlsOffset);
1492       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1493         .addReg(ScratchReg)
1494         .addReg(ScratchReg2).addImm(1).addReg(0)
1495         .addImm(0)
1496         .addReg(TlsReg);
1497
1498       if (SaveScratch2)
1499         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1500     }
1501   }
1502
1503   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1504   // It jumps to normal execution of the function body.
1505   BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
1506
1507   // On 32 bit we first push the arguments size and then the frame size. On 64
1508   // bit, we pass the stack frame size in r10 and the argument size in r11.
1509   if (Is64Bit) {
1510     // Functions with nested arguments use R10, so it needs to be saved across
1511     // the call to _morestack
1512
1513     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1514     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1515     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1516     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1517     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1518
1519     if (IsNested)
1520       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1521
1522     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1523       .addImm(StackSize);
1524     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1525       .addImm(X86FI->getArgumentStackSize());
1526     MF.getRegInfo().setPhysRegUsed(Reg10);
1527     MF.getRegInfo().setPhysRegUsed(Reg11);
1528   } else {
1529     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1530       .addImm(X86FI->getArgumentStackSize());
1531     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1532       .addImm(StackSize);
1533   }
1534
1535   // __morestack is in libgcc
1536   if (Is64Bit)
1537     BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1538       .addExternalSymbol("__morestack");
1539   else
1540     BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1541       .addExternalSymbol("__morestack");
1542
1543   if (IsNested)
1544     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1545   else
1546     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1547
1548   allocMBB->addSuccessor(&prologueMBB);
1549
1550   checkMBB->addSuccessor(allocMBB);
1551   checkMBB->addSuccessor(&prologueMBB);
1552
1553 #ifdef XDEBUG
1554   MF.verify();
1555 #endif
1556 }
1557
1558 /// Erlang programs may need a special prologue to handle the stack size they
1559 /// might need at runtime. That is because Erlang/OTP does not implement a C
1560 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1561 /// (for more information see Eric Stenman's Ph.D. thesis:
1562 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1563 ///
1564 /// CheckStack:
1565 ///       temp0 = sp - MaxStack
1566 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1567 /// OldStart:
1568 ///       ...
1569 /// IncStack:
1570 ///       call inc_stack   # doubles the stack space
1571 ///       temp0 = sp - MaxStack
1572 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1573 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
1574   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1575   MachineFrameInfo *MFI = MF.getFrameInfo();
1576   const unsigned SlotSize =
1577       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1578           ->getSlotSize();
1579   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1580   const bool Is64Bit = STI.is64Bit();
1581   const bool IsLP64 = STI.isTarget64BitLP64();
1582   DebugLoc DL;
1583   // HiPE-specific values
1584   const unsigned HipeLeafWords = 24;
1585   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1586   const unsigned Guaranteed = HipeLeafWords * SlotSize;
1587   unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1588                             MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1589   unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1590
1591   assert(STI.isTargetLinux() &&
1592          "HiPE prologue is only supported on Linux operating systems.");
1593
1594   // Compute the largest caller's frame that is needed to fit the callees'
1595   // frames. This 'MaxStack' is computed from:
1596   //
1597   // a) the fixed frame size, which is the space needed for all spilled temps,
1598   // b) outgoing on-stack parameter areas, and
1599   // c) the minimum stack space this function needs to make available for the
1600   //    functions it calls (a tunable ABI property).
1601   if (MFI->hasCalls()) {
1602     unsigned MoreStackForCalls = 0;
1603
1604     for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1605          MBBI != MBBE; ++MBBI)
1606       for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1607            MI != ME; ++MI) {
1608         if (!MI->isCall())
1609           continue;
1610
1611         // Get callee operand.
1612         const MachineOperand &MO = MI->getOperand(0);
1613
1614         // Only take account of global function calls (no closures etc.).
1615         if (!MO.isGlobal())
1616           continue;
1617
1618         const Function *F = dyn_cast<Function>(MO.getGlobal());
1619         if (!F)
1620           continue;
1621
1622         // Do not update 'MaxStack' for primitive and built-in functions
1623         // (encoded with names either starting with "erlang."/"bif_" or not
1624         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1625         // "_", such as the BIF "suspend_0") as they are executed on another
1626         // stack.
1627         if (F->getName().find("erlang.") != StringRef::npos ||
1628             F->getName().find("bif_") != StringRef::npos ||
1629             F->getName().find_first_of("._") == StringRef::npos)
1630           continue;
1631
1632         unsigned CalleeStkArity =
1633           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1634         if (HipeLeafWords - 1 > CalleeStkArity)
1635           MoreStackForCalls = std::max(MoreStackForCalls,
1636                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1637       }
1638     MaxStack += MoreStackForCalls;
1639   }
1640
1641   // If the stack frame needed is larger than the guaranteed then runtime checks
1642   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1643   if (MaxStack > Guaranteed) {
1644     MachineBasicBlock &prologueMBB = MF.front();
1645     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1646     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1647
1648     for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1649            E = prologueMBB.livein_end(); I != E; I++) {
1650       stackCheckMBB->addLiveIn(*I);
1651       incStackMBB->addLiveIn(*I);
1652     }
1653
1654     MF.push_front(incStackMBB);
1655     MF.push_front(stackCheckMBB);
1656
1657     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1658     unsigned LEAop, CMPop, CALLop;
1659     if (Is64Bit) {
1660       SPReg = X86::RSP;
1661       PReg  = X86::RBP;
1662       LEAop = X86::LEA64r;
1663       CMPop = X86::CMP64rm;
1664       CALLop = X86::CALL64pcrel32;
1665       SPLimitOffset = 0x90;
1666     } else {
1667       SPReg = X86::ESP;
1668       PReg  = X86::EBP;
1669       LEAop = X86::LEA32r;
1670       CMPop = X86::CMP32rm;
1671       CALLop = X86::CALLpcrel32;
1672       SPLimitOffset = 0x4c;
1673     }
1674
1675     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1676     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1677            "HiPE prologue scratch register is live-in");
1678
1679     // Create new MBB for StackCheck:
1680     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1681                  SPReg, false, -MaxStack);
1682     // SPLimitOffset is in a fixed heap location (pointed by BP).
1683     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1684                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
1685     BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_4)).addMBB(&prologueMBB);
1686
1687     // Create new MBB for IncStack:
1688     BuildMI(incStackMBB, DL, TII.get(CALLop)).
1689       addExternalSymbol("inc_stack_0");
1690     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1691                  SPReg, false, -MaxStack);
1692     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1693                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
1694     BuildMI(incStackMBB, DL, TII.get(X86::JLE_4)).addMBB(incStackMBB);
1695
1696     stackCheckMBB->addSuccessor(&prologueMBB, 99);
1697     stackCheckMBB->addSuccessor(incStackMBB, 1);
1698     incStackMBB->addSuccessor(&prologueMBB, 99);
1699     incStackMBB->addSuccessor(incStackMBB, 1);
1700   }
1701 #ifdef XDEBUG
1702   MF.verify();
1703 #endif
1704 }
1705
1706 void X86FrameLowering::
1707 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1708                               MachineBasicBlock::iterator I) const {
1709   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1710   const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1711                                        MF.getSubtarget().getRegisterInfo());
1712   unsigned StackPtr = RegInfo.getStackRegister();
1713   bool reseveCallFrame = hasReservedCallFrame(MF);
1714   int Opcode = I->getOpcode();
1715   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1716   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1717   bool IsLP64 = STI.isTarget64BitLP64();
1718   DebugLoc DL = I->getDebugLoc();
1719   uint64_t Amount = !reseveCallFrame ? I->getOperand(0).getImm() : 0;
1720   uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
1721   I = MBB.erase(I);
1722
1723   if (!reseveCallFrame) {
1724     // If the stack pointer can be changed after prologue, turn the
1725     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1726     // adjcallstackdown instruction into 'add ESP, <amt>'
1727     // TODO: consider using push / pop instead of sub + store / add
1728     if (Amount == 0)
1729       return;
1730
1731     // We need to keep the stack aligned properly.  To do this, we round the
1732     // amount of space needed for the outgoing arguments up to the next
1733     // alignment boundary.
1734     unsigned StackAlign = MF.getTarget()
1735                               .getSubtargetImpl()
1736                               ->getFrameLowering()
1737                               ->getStackAlignment();
1738     Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
1739
1740     MachineInstr *New = nullptr;
1741     if (Opcode == TII.getCallFrameSetupOpcode()) {
1742       New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
1743                     StackPtr)
1744         .addReg(StackPtr)
1745         .addImm(Amount);
1746     } else {
1747       assert(Opcode == TII.getCallFrameDestroyOpcode());
1748
1749       // Factor out the amount the callee already popped.
1750       Amount -= CalleeAmt;
1751
1752       if (Amount) {
1753         unsigned Opc = getADDriOpcode(IsLP64, Amount);
1754         New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1755           .addReg(StackPtr).addImm(Amount);
1756       }
1757     }
1758
1759     if (New) {
1760       // The EFLAGS implicit def is dead.
1761       New->getOperand(3).setIsDead();
1762
1763       // Replace the pseudo instruction with a new instruction.
1764       MBB.insert(I, New);
1765     }
1766
1767     return;
1768   }
1769
1770   if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
1771     // If we are performing frame pointer elimination and if the callee pops
1772     // something off the stack pointer, add it back.  We do this until we have
1773     // more advanced stack pointer tracking ability.
1774     unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
1775     MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1776       .addReg(StackPtr).addImm(CalleeAmt);
1777
1778     // The EFLAGS implicit def is dead.
1779     New->getOperand(3).setIsDead();
1780
1781     // We are not tracking the stack pointer adjustment by the callee, so make
1782     // sure we restore the stack pointer immediately after the call, there may
1783     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1784     MachineBasicBlock::iterator B = MBB.begin();
1785     while (I != B && !std::prev(I)->isCall())
1786       --I;
1787     MBB.insert(I, New);
1788   }
1789 }
1790