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