LLVM API Documentation

X86FrameLowering.cpp
Go to the documentation of this file.
00001 //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the X86 implementation of TargetFrameLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "X86FrameLowering.h"
00015 #include "X86InstrBuilder.h"
00016 #include "X86InstrInfo.h"
00017 #include "X86MachineFunctionInfo.h"
00018 #include "X86Subtarget.h"
00019 #include "X86TargetMachine.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/CodeGen/MachineFrameInfo.h"
00022 #include "llvm/CodeGen/MachineFunction.h"
00023 #include "llvm/CodeGen/MachineInstrBuilder.h"
00024 #include "llvm/CodeGen/MachineModuleInfo.h"
00025 #include "llvm/CodeGen/MachineRegisterInfo.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/MC/MCAsmInfo.h"
00029 #include "llvm/MC/MCSymbol.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Target/TargetOptions.h"
00032 #include "llvm/Support/Debug.h"
00033 #include <cstdlib>
00034 
00035 using namespace llvm;
00036 
00037 // FIXME: completely move here.
00038 extern cl::opt<bool> ForceStackAlign;
00039 
00040 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
00041   return !MF.getFrameInfo()->hasVarSizedObjects();
00042 }
00043 
00044 /// hasFP - Return true if the specified function should have a dedicated frame
00045 /// pointer register.  This is true if the function has variable sized allocas
00046 /// or if frame pointer elimination is disabled.
00047 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
00048   const MachineFrameInfo *MFI = MF.getFrameInfo();
00049   const MachineModuleInfo &MMI = MF.getMMI();
00050   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
00051 
00052   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
00053           RegInfo->needsStackRealignment(MF) ||
00054           MFI->hasVarSizedObjects() ||
00055           MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
00056           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
00057           MMI.callsUnwindInit() || MMI.callsEHReturn() ||
00058           MFI->hasStackMap() || MFI->hasPatchPoint());
00059 }
00060 
00061 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
00062   if (IsLP64) {
00063     if (isInt<8>(Imm))
00064       return X86::SUB64ri8;
00065     return X86::SUB64ri32;
00066   } else {
00067     if (isInt<8>(Imm))
00068       return X86::SUB32ri8;
00069     return X86::SUB32ri;
00070   }
00071 }
00072 
00073 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
00074   if (IsLP64) {
00075     if (isInt<8>(Imm))
00076       return X86::ADD64ri8;
00077     return X86::ADD64ri32;
00078   } else {
00079     if (isInt<8>(Imm))
00080       return X86::ADD32ri8;
00081     return X86::ADD32ri;
00082   }
00083 }
00084 
00085 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
00086   if (IsLP64) {
00087     if (isInt<8>(Imm))
00088       return X86::AND64ri8;
00089     return X86::AND64ri32;
00090   }
00091   if (isInt<8>(Imm))
00092     return X86::AND32ri8;
00093   return X86::AND32ri;
00094 }
00095 
00096 static unsigned getLEArOpcode(unsigned IsLP64) {
00097   return IsLP64 ? X86::LEA64r : X86::LEA32r;
00098 }
00099 
00100 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
00101 /// when it reaches the "return" instruction. We can then pop a stack object
00102 /// to this register without worry about clobbering it.
00103 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
00104                                        MachineBasicBlock::iterator &MBBI,
00105                                        const TargetRegisterInfo &TRI,
00106                                        bool Is64Bit) {
00107   const MachineFunction *MF = MBB.getParent();
00108   const Function *F = MF->getFunction();
00109   if (!F || MF->getMMI().callsEHReturn())
00110     return 0;
00111 
00112   static const uint16_t CallerSavedRegs32Bit[] = {
00113     X86::EAX, X86::EDX, X86::ECX, 0
00114   };
00115 
00116   static const uint16_t CallerSavedRegs64Bit[] = {
00117     X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
00118     X86::R8,  X86::R9,  X86::R10, X86::R11, 0
00119   };
00120 
00121   unsigned Opc = MBBI->getOpcode();
00122   switch (Opc) {
00123   default: return 0;
00124   case X86::RETL:
00125   case X86::RETQ:
00126   case X86::RETIL:
00127   case X86::RETIQ:
00128   case X86::TCRETURNdi:
00129   case X86::TCRETURNri:
00130   case X86::TCRETURNmi:
00131   case X86::TCRETURNdi64:
00132   case X86::TCRETURNri64:
00133   case X86::TCRETURNmi64:
00134   case X86::EH_RETURN:
00135   case X86::EH_RETURN64: {
00136     SmallSet<uint16_t, 8> Uses;
00137     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
00138       MachineOperand &MO = MBBI->getOperand(i);
00139       if (!MO.isReg() || MO.isDef())
00140         continue;
00141       unsigned Reg = MO.getReg();
00142       if (!Reg)
00143         continue;
00144       for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
00145         Uses.insert(*AI);
00146     }
00147 
00148     const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
00149     for (; *CS; ++CS)
00150       if (!Uses.count(*CS))
00151         return *CS;
00152   }
00153   }
00154 
00155   return 0;
00156 }
00157 
00158 
00159 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
00160 /// stack pointer by a constant value.
00161 static
00162 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
00163                   unsigned StackPtr, int64_t NumBytes,
00164                   bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
00165                   const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
00166   bool isSub = NumBytes < 0;
00167   uint64_t Offset = isSub ? -NumBytes : NumBytes;
00168   unsigned Opc;
00169   if (UseLEA)
00170     Opc = getLEArOpcode(Is64BitStackPtr);
00171   else
00172     Opc = isSub
00173       ? getSUBriOpcode(Is64BitStackPtr, Offset)
00174       : getADDriOpcode(Is64BitStackPtr, Offset);
00175 
00176   uint64_t Chunk = (1LL << 31) - 1;
00177   DebugLoc DL = MBB.findDebugLoc(MBBI);
00178 
00179   while (Offset) {
00180     uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
00181     if (ThisVal == (Is64BitTarget ? 8 : 4)) {
00182       // Use push / pop instead.
00183       unsigned Reg = isSub
00184         ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
00185         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
00186       if (Reg) {
00187         Opc = isSub
00188           ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
00189           : (Is64BitTarget ? X86::POP64r  : X86::POP32r);
00190         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
00191           .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
00192         if (isSub)
00193           MI->setFlag(MachineInstr::FrameSetup);
00194         Offset -= ThisVal;
00195         continue;
00196       }
00197     }
00198 
00199     MachineInstr *MI = nullptr;
00200 
00201     if (UseLEA) {
00202       MI =  addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
00203                           StackPtr, false, isSub ? -ThisVal : ThisVal);
00204     } else {
00205       MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
00206             .addReg(StackPtr)
00207             .addImm(ThisVal);
00208       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
00209     }
00210 
00211     if (isSub)
00212       MI->setFlag(MachineInstr::FrameSetup);
00213 
00214     Offset -= ThisVal;
00215   }
00216 }
00217 
00218 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
00219 static
00220 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
00221                       unsigned StackPtr, uint64_t *NumBytes = nullptr) {
00222   if (MBBI == MBB.begin()) return;
00223 
00224   MachineBasicBlock::iterator PI = std::prev(MBBI);
00225   unsigned Opc = PI->getOpcode();
00226   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
00227        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
00228        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
00229       PI->getOperand(0).getReg() == StackPtr) {
00230     if (NumBytes)
00231       *NumBytes += PI->getOperand(2).getImm();
00232     MBB.erase(PI);
00233   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
00234               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
00235              PI->getOperand(0).getReg() == StackPtr) {
00236     if (NumBytes)
00237       *NumBytes -= PI->getOperand(2).getImm();
00238     MBB.erase(PI);
00239   }
00240 }
00241 
00242 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
00243 /// iterator.
00244 static
00245 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
00246                         MachineBasicBlock::iterator &MBBI,
00247                         unsigned StackPtr, uint64_t *NumBytes = nullptr) {
00248   // FIXME:  THIS ISN'T RUN!!!
00249   return;
00250 
00251   if (MBBI == MBB.end()) return;
00252 
00253   MachineBasicBlock::iterator NI = std::next(MBBI);
00254   if (NI == MBB.end()) return;
00255 
00256   unsigned Opc = NI->getOpcode();
00257   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
00258        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
00259       NI->getOperand(0).getReg() == StackPtr) {
00260     if (NumBytes)
00261       *NumBytes -= NI->getOperand(2).getImm();
00262     MBB.erase(NI);
00263     MBBI = NI;
00264   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
00265               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
00266              NI->getOperand(0).getReg() == StackPtr) {
00267     if (NumBytes)
00268       *NumBytes += NI->getOperand(2).getImm();
00269     MBB.erase(NI);
00270     MBBI = NI;
00271   }
00272 }
00273 
00274 /// mergeSPUpdates - Checks the instruction before/after the passed
00275 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
00276 /// the stack adjustment is returned as a positive value for ADD/LEA and a
00277 /// negative for SUB.
00278 static int mergeSPUpdates(MachineBasicBlock &MBB,
00279                           MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
00280                           bool doMergeWithPrevious) {
00281   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
00282       (!doMergeWithPrevious && MBBI == MBB.end()))
00283     return 0;
00284 
00285   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
00286   MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
00287                                                        : std::next(MBBI);
00288   unsigned Opc = PI->getOpcode();
00289   int Offset = 0;
00290 
00291   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
00292        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
00293        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
00294       PI->getOperand(0).getReg() == StackPtr){
00295     Offset += PI->getOperand(2).getImm();
00296     MBB.erase(PI);
00297     if (!doMergeWithPrevious) MBBI = NI;
00298   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
00299               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
00300              PI->getOperand(0).getReg() == StackPtr) {
00301     Offset -= PI->getOperand(2).getImm();
00302     MBB.erase(PI);
00303     if (!doMergeWithPrevious) MBBI = NI;
00304   }
00305 
00306   return Offset;
00307 }
00308 
00309 static bool isEAXLiveIn(MachineFunction &MF) {
00310   for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
00311        EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
00312     unsigned Reg = II->first;
00313 
00314     if (Reg == X86::EAX || Reg == X86::AX ||
00315         Reg == X86::AH || Reg == X86::AL)
00316       return true;
00317   }
00318 
00319   return false;
00320 }
00321 
00322 void
00323 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
00324                                             MachineBasicBlock::iterator MBBI,
00325                                             DebugLoc DL) const {
00326   MachineFunction &MF = *MBB.getParent();
00327   MachineFrameInfo *MFI = MF.getFrameInfo();
00328   MachineModuleInfo &MMI = MF.getMMI();
00329   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
00330   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
00331 
00332   // Add callee saved registers to move list.
00333   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
00334   if (CSI.empty()) return;
00335 
00336   // Calculate offsets.
00337   for (std::vector<CalleeSavedInfo>::const_iterator
00338          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
00339     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
00340     unsigned Reg = I->getReg();
00341 
00342     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
00343     unsigned CFIIndex =
00344         MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
00345                                                         Offset));
00346     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00347         .addCFIIndex(CFIIndex);
00348   }
00349 }
00350 
00351 /// usesTheStack - This function checks if any of the users of EFLAGS
00352 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
00353 /// to use the stack, and if we don't adjust the stack we clobber the first
00354 /// frame index.
00355 /// See X86InstrInfo::copyPhysReg.
00356 static bool usesTheStack(const MachineFunction &MF) {
00357   const MachineRegisterInfo &MRI = MF.getRegInfo();
00358 
00359   for (MachineRegisterInfo::reg_instr_iterator
00360        ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
00361        ri != re; ++ri)
00362     if (ri->isCopy())
00363       return true;
00364 
00365   return false;
00366 }
00367 
00368 void X86FrameLowering::getStackProbeFunction(const X86Subtarget &STI,
00369                                              unsigned &CallOp,
00370                                              const char *&Symbol) {
00371   CallOp = STI.is64Bit() ? X86::W64ALLOCA : X86::CALLpcrel32;
00372 
00373   if (STI.is64Bit()) {
00374     if (STI.isTargetCygMing()) {
00375       Symbol = "___chkstk_ms";
00376     } else {
00377       Symbol = "__chkstk";
00378     }
00379   } else if (STI.isTargetCygMing())
00380     Symbol = "_alloca";
00381   else
00382     Symbol = "_chkstk";
00383 }
00384 
00385 /// emitPrologue - Push callee-saved registers onto the stack, which
00386 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
00387 /// space for local variables. Also emit labels used by the exception handler to
00388 /// generate the exception handling frames.
00389 
00390 /*
00391   Here's a gist of what gets emitted:
00392 
00393   ; Establish frame pointer, if needed
00394   [if needs FP]
00395       push  %rbp
00396       .cfi_def_cfa_offset 16
00397       .cfi_offset %rbp, -16
00398       .seh_pushreg %rpb
00399       mov  %rsp, %rbp
00400       .cfi_def_cfa_register %rbp
00401 
00402   ; Spill general-purpose registers
00403   [for all callee-saved GPRs]
00404       pushq %<reg>
00405       [if not needs FP]
00406          .cfi_def_cfa_offset (offset from RETADDR)
00407       .seh_pushreg %<reg>
00408 
00409   ; If the required stack alignment > default stack alignment
00410   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
00411   ; of unknown size in the stack frame.
00412   [if stack needs re-alignment]
00413       and  $MASK, %rsp
00414 
00415   ; Allocate space for locals
00416   [if target is Windows and allocated space > 4096 bytes]
00417       ; Windows needs special care for allocations larger
00418       ; than one page.
00419       mov $NNN, %rax
00420       call ___chkstk_ms/___chkstk
00421       sub  %rax, %rsp
00422   [else]
00423       sub  $NNN, %rsp
00424 
00425   [if needs FP]
00426       .seh_stackalloc (size of XMM spill slots)
00427       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
00428   [else]
00429       .seh_stackalloc NNN
00430 
00431   ; Spill XMMs
00432   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
00433   ; they may get spilled on any platform, if the current function
00434   ; calls @llvm.eh.unwind.init
00435   [if needs FP]
00436       [for all callee-saved XMM registers]
00437           movaps  %<xmm reg>, -MMM(%rbp)
00438       [for all callee-saved XMM registers]
00439           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
00440               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
00441   [else]
00442       [for all callee-saved XMM registers]
00443           movaps  %<xmm reg>, KKK(%rsp)
00444       [for all callee-saved XMM registers]
00445           .seh_savexmm %<xmm reg>, KKK
00446 
00447   .seh_endprologue
00448 
00449   [if needs base pointer]
00450       mov  %rsp, %rbx
00451 
00452   ; Emit CFI info
00453   [if needs FP]
00454       [for all callee-saved registers]
00455           .cfi_offset %<reg>, (offset from %rbp)
00456   [else]
00457        .cfi_def_cfa_offset (offset from RETADDR)
00458       [for all callee-saved registers]
00459           .cfi_offset %<reg>, (offset from %rsp)
00460 
00461   Notes:
00462   - .seh directives are emitted only for Windows 64 ABI
00463   - .cfi directives are emitted for all other ABIs
00464   - for 32-bit code, substitute %e?? registers for %r??
00465 */
00466 
00467 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
00468   MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
00469   MachineBasicBlock::iterator MBBI = MBB.begin();
00470   MachineFrameInfo *MFI = MF.getFrameInfo();
00471   const Function *Fn = MF.getFunction();
00472   const X86RegisterInfo *RegInfo =
00473       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
00474   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
00475   MachineModuleInfo &MMI = MF.getMMI();
00476   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
00477   uint64_t MaxAlign  = MFI->getMaxAlignment(); // Desired stack alignment.
00478   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
00479   bool HasFP = hasFP(MF);
00480   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
00481   bool Is64Bit = STI.is64Bit();
00482   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
00483   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
00484   bool IsWin64 = STI.isTargetWin64();
00485   // Not necessarily synonymous with IsWin64.
00486   bool IsWinEH = MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
00487                  ExceptionHandling::ItaniumWinEH;
00488   bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
00489   bool NeedsDwarfCFI =
00490       !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
00491   bool UseLEA = STI.useLeaForSP();
00492   unsigned StackAlign = getStackAlignment();
00493   unsigned SlotSize = RegInfo->getSlotSize();
00494   unsigned FramePtr = RegInfo->getFrameRegister(MF);
00495   const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
00496                  getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
00497   unsigned StackPtr = RegInfo->getStackRegister();
00498   unsigned BasePtr = RegInfo->getBaseRegister();
00499   DebugLoc DL;
00500 
00501   // If we're forcing a stack realignment we can't rely on just the frame
00502   // info, we need to know the ABI stack alignment as well in case we
00503   // have a call out.  Otherwise just make sure we have some alignment - we'll
00504   // go with the minimum SlotSize.
00505   if (ForceStackAlign) {
00506     if (MFI->hasCalls())
00507       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
00508     else if (MaxAlign < SlotSize)
00509       MaxAlign = SlotSize;
00510   }
00511 
00512   // Add RETADDR move area to callee saved frame size.
00513   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
00514   if (TailCallReturnAddrDelta < 0)
00515     X86FI->setCalleeSavedFrameSize(
00516       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
00517 
00518   bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMacho());
00519   
00520   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
00521   // function, and use up to 128 bytes of stack space, don't have a frame
00522   // pointer, calls, or dynamic alloca then we do not need to adjust the
00523   // stack pointer (we fit in the Red Zone). We also check that we don't
00524   // push and pop from the stack.
00525   if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00526                                                    Attribute::NoRedZone) &&
00527       !RegInfo->needsStackRealignment(MF) &&
00528       !MFI->hasVarSizedObjects() &&                     // No dynamic alloca.
00529       !MFI->adjustsStack() &&                           // No calls.
00530       !IsWin64 &&                                       // Win64 has no Red Zone
00531       !usesTheStack(MF) &&                              // Don't push and pop.
00532       !MF.shouldSplitStack()) {                         // Regular stack
00533     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
00534     if (HasFP) MinSize += SlotSize;
00535     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
00536     MFI->setStackSize(StackSize);
00537   }
00538 
00539   // Insert stack pointer adjustment for later moving of return addr.  Only
00540   // applies to tail call optimized functions where the callee argument stack
00541   // size is bigger than the callers.
00542   if (TailCallReturnAddrDelta < 0) {
00543     MachineInstr *MI =
00544       BuildMI(MBB, MBBI, DL,
00545               TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
00546               StackPtr)
00547         .addReg(StackPtr)
00548         .addImm(-TailCallReturnAddrDelta)
00549         .setMIFlag(MachineInstr::FrameSetup);
00550     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
00551   }
00552 
00553   // Mapping for machine moves:
00554   //
00555   //   DST: VirtualFP AND
00556   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
00557   //        ELSE                        => DW_CFA_def_cfa
00558   //
00559   //   SRC: VirtualFP AND
00560   //        DST: Register               => DW_CFA_def_cfa_register
00561   //
00562   //   ELSE
00563   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
00564   //        REG < 64                    => DW_CFA_offset + Reg
00565   //        ELSE                        => DW_CFA_offset_extended
00566 
00567   uint64_t NumBytes = 0;
00568   int stackGrowth = -SlotSize;
00569 
00570   if (HasFP) {
00571     // Calculate required stack adjustment.
00572     uint64_t FrameSize = StackSize - SlotSize;
00573     if (RegInfo->needsStackRealignment(MF)) {
00574       // Callee-saved registers are pushed on stack before the stack
00575       // is realigned.
00576       FrameSize -= X86FI->getCalleeSavedFrameSize();
00577       NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
00578     } else {
00579       NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
00580     }
00581 
00582     // Get the offset of the stack slot for the EBP register, which is
00583     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
00584     // Update the frame offset adjustment.
00585     MFI->setOffsetAdjustment(-NumBytes);
00586 
00587     // Save EBP/RBP into the appropriate stack slot.
00588     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
00589       .addReg(MachineFramePtr, RegState::Kill)
00590       .setMIFlag(MachineInstr::FrameSetup);
00591 
00592     if (NeedsDwarfCFI) {
00593       // Mark the place where EBP/RBP was saved.
00594       // Define the current CFA rule to use the provided offset.
00595       assert(StackSize);
00596       unsigned CFIIndex = MMI.addFrameInst(
00597           MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
00598       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00599           .addCFIIndex(CFIIndex);
00600 
00601       // Change the rule for the FramePtr to be an "offset" rule.
00602       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
00603       CFIIndex = MMI.addFrameInst(
00604           MCCFIInstruction::createOffset(nullptr,
00605                                          DwarfFramePtr, 2 * stackGrowth));
00606       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00607           .addCFIIndex(CFIIndex);
00608     }
00609 
00610     if (NeedsWinEH) {
00611       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
00612           .addImm(FramePtr)
00613           .setMIFlag(MachineInstr::FrameSetup);
00614     }
00615 
00616     // Update EBP with the new base value.
00617     BuildMI(MBB, MBBI, DL,
00618             TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
00619         .addReg(StackPtr)
00620         .setMIFlag(MachineInstr::FrameSetup);
00621 
00622     if (NeedsDwarfCFI) {
00623       // Mark effective beginning of when frame pointer becomes valid.
00624       // Define the current CFA to use the EBP/RBP register.
00625       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
00626       unsigned CFIIndex = MMI.addFrameInst(
00627           MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
00628       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00629           .addCFIIndex(CFIIndex);
00630     }
00631 
00632     // Mark the FramePtr as live-in in every block.
00633     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
00634       I->addLiveIn(MachineFramePtr);
00635   } else {
00636     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
00637   }
00638 
00639   // Skip the callee-saved push instructions.
00640   bool PushedRegs = false;
00641   int StackOffset = 2 * stackGrowth;
00642 
00643   while (MBBI != MBB.end() &&
00644          (MBBI->getOpcode() == X86::PUSH32r ||
00645           MBBI->getOpcode() == X86::PUSH64r)) {
00646     PushedRegs = true;
00647     unsigned Reg = MBBI->getOperand(0).getReg();
00648     ++MBBI;
00649 
00650     if (!HasFP && NeedsDwarfCFI) {
00651       // Mark callee-saved push instruction.
00652       // Define the current CFA rule to use the provided offset.
00653       assert(StackSize);
00654       unsigned CFIIndex = MMI.addFrameInst(
00655           MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
00656       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00657           .addCFIIndex(CFIIndex);
00658       StackOffset += stackGrowth;
00659     }
00660 
00661     if (NeedsWinEH) {
00662       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
00663           MachineInstr::FrameSetup);
00664     }
00665   }
00666 
00667   // Realign stack after we pushed callee-saved registers (so that we'll be
00668   // able to calculate their offsets from the frame pointer).
00669   if (RegInfo->needsStackRealignment(MF)) {
00670     assert(HasFP && "There should be a frame pointer if stack is realigned.");
00671     uint64_t Val = -MaxAlign;
00672     MachineInstr *MI =
00673       BuildMI(MBB, MBBI, DL,
00674               TII.get(getANDriOpcode(Uses64BitFramePtr, Val)), StackPtr)
00675       .addReg(StackPtr)
00676       .addImm(Val)
00677       .setMIFlag(MachineInstr::FrameSetup);
00678 
00679     // The EFLAGS implicit def is dead.
00680     MI->getOperand(3).setIsDead();
00681   }
00682 
00683   // If there is an SUB32ri of ESP immediately before this instruction, merge
00684   // the two. This can be the case when tail call elimination is enabled and
00685   // the callee has more arguments then the caller.
00686   NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
00687 
00688   // If there is an ADD32ri or SUB32ri of ESP immediately after this
00689   // instruction, merge the two instructions.
00690   mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
00691 
00692   // Adjust stack pointer: ESP -= numbytes.
00693 
00694   static const size_t PageSize = 4096;
00695 
00696   // Windows and cygwin/mingw require a prologue helper routine when allocating
00697   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
00698   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
00699   // stack and adjust the stack pointer in one go.  The 64-bit version of
00700   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
00701   // responsible for adjusting the stack pointer.  Touching the stack at 4K
00702   // increments is necessary to ensure that the guard pages used by the OS
00703   // virtual memory manager are allocated in correct sequence.
00704   if (NumBytes >= PageSize && UseStackProbe) {
00705     const char *StackProbeSymbol;
00706     unsigned CallOp;
00707 
00708     getStackProbeFunction(STI, CallOp, StackProbeSymbol);
00709 
00710     // Check whether EAX is livein for this function.
00711     bool isEAXAlive = isEAXLiveIn(MF);
00712 
00713     if (isEAXAlive) {
00714       // Sanity check that EAX is not livein for this function.
00715       // It should not be, so throw an assert.
00716       assert(!Is64Bit && "EAX is livein in x64 case!");
00717 
00718       // Save EAX
00719       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
00720         .addReg(X86::EAX, RegState::Kill)
00721         .setMIFlag(MachineInstr::FrameSetup);
00722     }
00723 
00724     if (Is64Bit) {
00725       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
00726       // Function prologue is responsible for adjusting the stack pointer.
00727       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
00728         .addImm(NumBytes)
00729         .setMIFlag(MachineInstr::FrameSetup);
00730     } else {
00731       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
00732       // We'll also use 4 already allocated bytes for EAX.
00733       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
00734         .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
00735         .setMIFlag(MachineInstr::FrameSetup);
00736     }
00737 
00738     BuildMI(MBB, MBBI, DL,
00739             TII.get(CallOp))
00740       .addExternalSymbol(StackProbeSymbol)
00741       .addReg(StackPtr,    RegState::Define | RegState::Implicit)
00742       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
00743       .setMIFlag(MachineInstr::FrameSetup);
00744 
00745     if (Is64Bit) {
00746       // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
00747       // themself. It also does not clobber %rax so we can reuse it when
00748       // adjusting %rsp.
00749       BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
00750         .addReg(StackPtr)
00751         .addReg(X86::RAX)
00752         .setMIFlag(MachineInstr::FrameSetup);
00753     }
00754     if (isEAXAlive) {
00755       // Restore EAX
00756       MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
00757                                               X86::EAX),
00758                                       StackPtr, false, NumBytes - 4);
00759       MI->setFlag(MachineInstr::FrameSetup);
00760       MBB.insert(MBBI, MI);
00761     }
00762   } else if (NumBytes) {
00763     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
00764                  UseLEA, TII, *RegInfo);
00765   }
00766 
00767   int SEHFrameOffset = 0;
00768   if (NeedsWinEH) {
00769     if (HasFP) {
00770       // We need to set frame base offset low enough such that all saved
00771       // register offsets would be positive relative to it, but we can't
00772       // just use NumBytes, because .seh_setframe offset must be <=240.
00773       // So we pretend to have only allocated enough space to spill the
00774       // non-volatile registers.
00775       // We don't care about the rest of stack allocation, because unwinder
00776       // will restore SP to (BP - SEHFrameOffset)
00777       for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
00778         int offset = MFI->getObjectOffset(Info.getFrameIdx());
00779         SEHFrameOffset = std::max(SEHFrameOffset, std::abs(offset));
00780       }
00781       SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
00782 
00783       // This only needs to account for XMM spill slots, GPR slots
00784       // are covered by the .seh_pushreg's emitted above.
00785       unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
00786       if (Size) {
00787         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
00788             .addImm(Size)
00789             .setMIFlag(MachineInstr::FrameSetup);
00790       }
00791 
00792       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
00793           .addImm(FramePtr)
00794           .addImm(SEHFrameOffset)
00795           .setMIFlag(MachineInstr::FrameSetup);
00796     } else {
00797       // SP will be the base register for restoring XMMs
00798       if (NumBytes) {
00799         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
00800             .addImm(NumBytes)
00801             .setMIFlag(MachineInstr::FrameSetup);
00802       }
00803     }
00804   }
00805 
00806   // Skip the rest of register spilling code
00807   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
00808     ++MBBI;
00809 
00810   // Emit SEH info for non-GPRs
00811   if (NeedsWinEH) {
00812     for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
00813       unsigned Reg = Info.getReg();
00814       if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
00815         continue;
00816       assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
00817 
00818       int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
00819       Offset += SEHFrameOffset;
00820 
00821       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
00822           .addImm(Reg)
00823           .addImm(Offset)
00824           .setMIFlag(MachineInstr::FrameSetup);
00825     }
00826 
00827     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
00828         .setMIFlag(MachineInstr::FrameSetup);
00829   }
00830 
00831   // If we need a base pointer, set it up here. It's whatever the value
00832   // of the stack pointer is at this point. Any variable size objects
00833   // will be allocated after this, so we can still use the base pointer
00834   // to reference locals.
00835   if (RegInfo->hasBasePointer(MF)) {
00836     // Update the base pointer with the current stack pointer.
00837     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
00838     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
00839       .addReg(StackPtr)
00840       .setMIFlag(MachineInstr::FrameSetup);
00841   }
00842 
00843   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
00844     // Mark end of stack pointer adjustment.
00845     if (!HasFP && NumBytes) {
00846       // Define the current CFA rule to use the provided offset.
00847       assert(StackSize);
00848       unsigned CFIIndex = MMI.addFrameInst(
00849           MCCFIInstruction::createDefCfaOffset(nullptr,
00850                                                -StackSize + stackGrowth));
00851 
00852       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00853           .addCFIIndex(CFIIndex);
00854     }
00855 
00856     // Emit DWARF info specifying the offsets of the callee-saved registers.
00857     if (PushedRegs)
00858       emitCalleeSavedFrameMoves(MBB, MBBI, DL);
00859   }
00860 }
00861 
00862 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
00863                                     MachineBasicBlock &MBB) const {
00864   const MachineFrameInfo *MFI = MF.getFrameInfo();
00865   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
00866   const X86RegisterInfo *RegInfo =
00867       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
00868   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
00869   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
00870   assert(MBBI != MBB.end() && "Returning block has no instructions");
00871   unsigned RetOpcode = MBBI->getOpcode();
00872   DebugLoc DL = MBBI->getDebugLoc();
00873   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
00874   bool Is64Bit = STI.is64Bit();
00875   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
00876   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
00877   const bool Is64BitILP32 = STI.isTarget64BitILP32();
00878   bool UseLEA = STI.useLeaForSP();
00879   unsigned StackAlign = getStackAlignment();
00880   unsigned SlotSize = RegInfo->getSlotSize();
00881   unsigned FramePtr = RegInfo->getFrameRegister(MF);
00882   unsigned MachineFramePtr = Is64BitILP32 ?
00883              getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
00884   unsigned StackPtr = RegInfo->getStackRegister();
00885 
00886   bool IsWinEH = MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
00887                  ExceptionHandling::ItaniumWinEH;
00888   bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
00889 
00890   switch (RetOpcode) {
00891   default:
00892     llvm_unreachable("Can only insert epilog into returning blocks");
00893   case X86::RETQ:
00894   case X86::RETL:
00895   case X86::RETIL:
00896   case X86::RETIQ:
00897   case X86::TCRETURNdi:
00898   case X86::TCRETURNri:
00899   case X86::TCRETURNmi:
00900   case X86::TCRETURNdi64:
00901   case X86::TCRETURNri64:
00902   case X86::TCRETURNmi64:
00903   case X86::EH_RETURN:
00904   case X86::EH_RETURN64:
00905     break;  // These are ok
00906   }
00907 
00908   // Get the number of bytes to allocate from the FrameInfo.
00909   uint64_t StackSize = MFI->getStackSize();
00910   uint64_t MaxAlign  = MFI->getMaxAlignment();
00911   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
00912   uint64_t NumBytes = 0;
00913 
00914   // If we're forcing a stack realignment we can't rely on just the frame
00915   // info, we need to know the ABI stack alignment as well in case we
00916   // have a call out.  Otherwise just make sure we have some alignment - we'll
00917   // go with the minimum.
00918   if (ForceStackAlign) {
00919     if (MFI->hasCalls())
00920       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
00921     else
00922       MaxAlign = MaxAlign ? MaxAlign : 4;
00923   }
00924 
00925   if (hasFP(MF)) {
00926     // Calculate required stack adjustment.
00927     uint64_t FrameSize = StackSize - SlotSize;
00928     if (RegInfo->needsStackRealignment(MF)) {
00929       // Callee-saved registers were pushed on stack before the stack
00930       // was realigned.
00931       FrameSize -= CSSize;
00932       NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
00933     } else {
00934       NumBytes = FrameSize - CSSize;
00935     }
00936 
00937     // Pop EBP.
00938     BuildMI(MBB, MBBI, DL,
00939             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
00940   } else {
00941     NumBytes = StackSize - CSSize;
00942   }
00943 
00944   // Skip the callee-saved pop instructions.
00945   while (MBBI != MBB.begin()) {
00946     MachineBasicBlock::iterator PI = std::prev(MBBI);
00947     unsigned Opc = PI->getOpcode();
00948 
00949     if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
00950         !PI->isTerminator())
00951       break;
00952 
00953     --MBBI;
00954   }
00955   MachineBasicBlock::iterator FirstCSPop = MBBI;
00956 
00957   DL = MBBI->getDebugLoc();
00958 
00959   // If there is an ADD32ri or SUB32ri of ESP immediately before this
00960   // instruction, merge the two instructions.
00961   if (NumBytes || MFI->hasVarSizedObjects())
00962     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
00963 
00964   // If dynamic alloca is used, then reset esp to point to the last callee-saved
00965   // slot before popping them off! Same applies for the case, when stack was
00966   // realigned.
00967   if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
00968     if (RegInfo->needsStackRealignment(MF))
00969       MBBI = FirstCSPop;
00970     if (CSSize != 0) {
00971       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
00972       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
00973                    FramePtr, false, -CSSize);
00974       --MBBI;
00975     } else {
00976       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
00977       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
00978         .addReg(FramePtr);
00979       --MBBI;
00980     }
00981   } else if (NumBytes) {
00982     // Adjust stack pointer back: ESP += numbytes.
00983     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
00984                  TII, *RegInfo);
00985     --MBBI;
00986   }
00987 
00988   // Windows unwinder will not invoke function's exception handler if IP is
00989   // either in prologue or in epilogue.  This behavior causes a problem when a
00990   // call immediately precedes an epilogue, because the return address points
00991   // into the epilogue.  To cope with that, we insert an epilogue marker here,
00992   // then replace it with a 'nop' if it ends up immediately after a CALL in the
00993   // final emitted code.
00994   if (NeedsWinEH)
00995     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
00996 
00997   // We're returning from function via eh_return.
00998   if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
00999     MBBI = MBB.getLastNonDebugInstr();
01000     MachineOperand &DestAddr  = MBBI->getOperand(0);
01001     assert(DestAddr.isReg() && "Offset should be in register!");
01002     BuildMI(MBB, MBBI, DL,
01003             TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
01004             StackPtr).addReg(DestAddr.getReg());
01005   } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
01006              RetOpcode == X86::TCRETURNmi ||
01007              RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
01008              RetOpcode == X86::TCRETURNmi64) {
01009     bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
01010     // Tail call return: adjust the stack pointer and jump to callee.
01011     MBBI = MBB.getLastNonDebugInstr();
01012     MachineOperand &JumpTarget = MBBI->getOperand(0);
01013     MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
01014     assert(StackAdjust.isImm() && "Expecting immediate value.");
01015 
01016     // Adjust stack pointer.
01017     int StackAdj = StackAdjust.getImm();
01018     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
01019     int Offset = 0;
01020     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
01021 
01022     // Incoporate the retaddr area.
01023     Offset = StackAdj-MaxTCDelta;
01024     assert(Offset >= 0 && "Offset should never be negative");
01025 
01026     if (Offset) {
01027       // Check for possible merge with preceding ADD instruction.
01028       Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
01029       emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
01030                    UseLEA, TII, *RegInfo);
01031     }
01032 
01033     // Jump to label or value in register.
01034     if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
01035       MachineInstrBuilder MIB =
01036         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
01037                                        ? X86::TAILJMPd : X86::TAILJMPd64));
01038       if (JumpTarget.isGlobal())
01039         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
01040                              JumpTarget.getTargetFlags());
01041       else {
01042         assert(JumpTarget.isSymbol());
01043         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
01044                               JumpTarget.getTargetFlags());
01045       }
01046     } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
01047       MachineInstrBuilder MIB =
01048         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
01049                                        ? X86::TAILJMPm : X86::TAILJMPm64));
01050       for (unsigned i = 0; i != 5; ++i)
01051         MIB.addOperand(MBBI->getOperand(i));
01052     } else if (RetOpcode == X86::TCRETURNri64) {
01053       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
01054         addReg(JumpTarget.getReg(), RegState::Kill);
01055     } else {
01056       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
01057         addReg(JumpTarget.getReg(), RegState::Kill);
01058     }
01059 
01060     MachineInstr *NewMI = std::prev(MBBI);
01061     NewMI->copyImplicitOps(MF, MBBI);
01062 
01063     // Delete the pseudo instruction TCRETURN.
01064     MBB.erase(MBBI);
01065   } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
01066               RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
01067              (X86FI->getTCReturnAddrDelta() < 0)) {
01068     // Add the return addr area delta back since we are not tail calling.
01069     int delta = -1*X86FI->getTCReturnAddrDelta();
01070     MBBI = MBB.getLastNonDebugInstr();
01071 
01072     // Check for possible merge with preceding ADD instruction.
01073     delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
01074     emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
01075                  *RegInfo);
01076   }
01077 }
01078 
01079 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
01080                                           int FI) const {
01081   const X86RegisterInfo *RegInfo =
01082       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01083   const MachineFrameInfo *MFI = MF.getFrameInfo();
01084   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
01085   uint64_t StackSize = MFI->getStackSize();
01086 
01087   if (RegInfo->hasBasePointer(MF)) {
01088     assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
01089     if (FI < 0) {
01090       // Skip the saved EBP.
01091       return Offset + RegInfo->getSlotSize();
01092     } else {
01093       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
01094       return Offset + StackSize;
01095     }
01096   } else if (RegInfo->needsStackRealignment(MF)) {
01097     if (FI < 0) {
01098       // Skip the saved EBP.
01099       return Offset + RegInfo->getSlotSize();
01100     } else {
01101       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
01102       return Offset + StackSize;
01103     }
01104     // FIXME: Support tail calls
01105   } else {
01106     if (!hasFP(MF))
01107       return Offset + StackSize;
01108 
01109     // Skip the saved EBP.
01110     Offset += RegInfo->getSlotSize();
01111 
01112     // Skip the RETADDR move area
01113     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01114     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
01115     if (TailCallReturnAddrDelta < 0)
01116       Offset -= TailCallReturnAddrDelta;
01117   }
01118 
01119   return Offset;
01120 }
01121 
01122 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
01123                                              unsigned &FrameReg) const {
01124   const X86RegisterInfo *RegInfo =
01125       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01126   // We can't calculate offset from frame pointer if the stack is realigned,
01127   // so enforce usage of stack/base pointer.  The base pointer is used when we
01128   // have dynamic allocas in addition to dynamic realignment.
01129   if (RegInfo->hasBasePointer(MF))
01130     FrameReg = RegInfo->getBaseRegister();
01131   else if (RegInfo->needsStackRealignment(MF))
01132     FrameReg = RegInfo->getStackRegister();
01133   else
01134     FrameReg = RegInfo->getFrameRegister(MF);
01135   return getFrameIndexOffset(MF, FI);
01136 }
01137 
01138 bool X86FrameLowering::assignCalleeSavedSpillSlots(
01139     MachineFunction &MF, const TargetRegisterInfo *TRI,
01140     std::vector<CalleeSavedInfo> &CSI) const {
01141   MachineFrameInfo *MFI = MF.getFrameInfo();
01142   const X86RegisterInfo *RegInfo =
01143       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01144   unsigned SlotSize = RegInfo->getSlotSize();
01145   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01146 
01147   unsigned CalleeSavedFrameSize = 0;
01148   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
01149 
01150   if (hasFP(MF)) {
01151     // emitPrologue always spills frame register the first thing.
01152     SpillSlotOffset -= SlotSize;
01153     MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
01154 
01155     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
01156     // the frame register, we can delete it from CSI list and not have to worry
01157     // about avoiding it later.
01158     unsigned FPReg = RegInfo->getFrameRegister(MF);
01159     for (unsigned i = 0; i < CSI.size(); ++i) {
01160       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
01161         CSI.erase(CSI.begin() + i);
01162         break;
01163       }
01164     }
01165   }
01166 
01167   // Assign slots for GPRs. It increases frame size.
01168   for (unsigned i = CSI.size(); i != 0; --i) {
01169     unsigned Reg = CSI[i - 1].getReg();
01170 
01171     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
01172       continue;
01173 
01174     SpillSlotOffset -= SlotSize;
01175     CalleeSavedFrameSize += SlotSize;
01176 
01177     int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
01178     CSI[i - 1].setFrameIdx(SlotIndex);
01179   }
01180 
01181   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
01182 
01183   // Assign slots for XMMs.
01184   for (unsigned i = CSI.size(); i != 0; --i) {
01185     unsigned Reg = CSI[i - 1].getReg();
01186     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
01187       continue;
01188 
01189     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
01190     // ensure alignment
01191     SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
01192     // spill into slot
01193     SpillSlotOffset -= RC->getSize();
01194     int SlotIndex =
01195         MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
01196     CSI[i - 1].setFrameIdx(SlotIndex);
01197     MFI->ensureMaxAlignment(RC->getAlignment());
01198   }
01199 
01200   return true;
01201 }
01202 
01203 bool X86FrameLowering::spillCalleeSavedRegisters(
01204     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
01205     const std::vector<CalleeSavedInfo> &CSI,
01206     const TargetRegisterInfo *TRI) const {
01207   DebugLoc DL = MBB.findDebugLoc(MI);
01208 
01209   MachineFunction &MF = *MBB.getParent();
01210   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01211   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01212 
01213   // Push GPRs. It increases frame size.
01214   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
01215   for (unsigned i = CSI.size(); i != 0; --i) {
01216     unsigned Reg = CSI[i - 1].getReg();
01217 
01218     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
01219       continue;
01220     // Add the callee-saved register as live-in. It's killed at the spill.
01221     MBB.addLiveIn(Reg);
01222 
01223     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
01224       .setMIFlag(MachineInstr::FrameSetup);
01225   }
01226 
01227   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
01228   // It can be done by spilling XMMs to stack frame.
01229   for (unsigned i = CSI.size(); i != 0; --i) {
01230     unsigned Reg = CSI[i-1].getReg();
01231     if (X86::GR64RegClass.contains(Reg) ||
01232         X86::GR32RegClass.contains(Reg))
01233       continue;
01234     // Add the callee-saved register as live-in. It's killed at the spill.
01235     MBB.addLiveIn(Reg);
01236     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01237 
01238     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
01239                             TRI);
01240     --MI;
01241     MI->setFlag(MachineInstr::FrameSetup);
01242     ++MI;
01243   }
01244 
01245   return true;
01246 }
01247 
01248 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
01249                                                MachineBasicBlock::iterator MI,
01250                                         const std::vector<CalleeSavedInfo> &CSI,
01251                                           const TargetRegisterInfo *TRI) const {
01252   if (CSI.empty())
01253     return false;
01254 
01255   DebugLoc DL = MBB.findDebugLoc(MI);
01256 
01257   MachineFunction &MF = *MBB.getParent();
01258   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01259   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01260 
01261   // Reload XMMs from stack frame.
01262   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01263     unsigned Reg = CSI[i].getReg();
01264     if (X86::GR64RegClass.contains(Reg) ||
01265         X86::GR32RegClass.contains(Reg))
01266       continue;
01267 
01268     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01269     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
01270   }
01271 
01272   // POP GPRs.
01273   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
01274   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01275     unsigned Reg = CSI[i].getReg();
01276     if (!X86::GR64RegClass.contains(Reg) &&
01277         !X86::GR32RegClass.contains(Reg))
01278       continue;
01279 
01280     BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
01281   }
01282   return true;
01283 }
01284 
01285 void
01286 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
01287                                                        RegScavenger *RS) const {
01288   MachineFrameInfo *MFI = MF.getFrameInfo();
01289   const X86RegisterInfo *RegInfo =
01290       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01291   unsigned SlotSize = RegInfo->getSlotSize();
01292 
01293   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01294   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
01295 
01296   if (TailCallReturnAddrDelta < 0) {
01297     // create RETURNADDR area
01298     //   arg
01299     //   arg
01300     //   RETADDR
01301     //   { ...
01302     //     RETADDR area
01303     //     ...
01304     //   }
01305     //   [EBP]
01306     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
01307                            TailCallReturnAddrDelta - SlotSize, true);
01308   }
01309 
01310   // Spill the BasePtr if it's used.
01311   if (RegInfo->hasBasePointer(MF))
01312     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
01313 }
01314 
01315 static bool
01316 HasNestArgument(const MachineFunction *MF) {
01317   const Function *F = MF->getFunction();
01318   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
01319        I != E; I++) {
01320     if (I->hasNestAttr())
01321       return true;
01322   }
01323   return false;
01324 }
01325 
01326 /// GetScratchRegister - Get a temp register for performing work in the
01327 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
01328 /// and the properties of the function either one or two registers will be
01329 /// needed. Set primary to true for the first register, false for the second.
01330 static unsigned
01331 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
01332   CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
01333 
01334   // Erlang stuff.
01335   if (CallingConvention == CallingConv::HiPE) {
01336     if (Is64Bit)
01337       return Primary ? X86::R14 : X86::R13;
01338     else
01339       return Primary ? X86::EBX : X86::EDI;
01340   }
01341 
01342   if (Is64Bit) {
01343     if (IsLP64)
01344       return Primary ? X86::R11 : X86::R12;
01345     else
01346       return Primary ? X86::R11D : X86::R12D;
01347   }
01348 
01349   bool IsNested = HasNestArgument(&MF);
01350 
01351   if (CallingConvention == CallingConv::X86_FastCall ||
01352       CallingConvention == CallingConv::Fast) {
01353     if (IsNested)
01354       report_fatal_error("Segmented stacks does not support fastcall with "
01355                          "nested function.");
01356     return Primary ? X86::EAX : X86::ECX;
01357   }
01358   if (IsNested)
01359     return Primary ? X86::EDX : X86::EAX;
01360   return Primary ? X86::ECX : X86::EAX;
01361 }
01362 
01363 // The stack limit in the TCB is set to this many bytes above the actual stack
01364 // limit.
01365 static const uint64_t kSplitStackAvailable = 256;
01366 
01367 void
01368 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
01369   MachineBasicBlock &prologueMBB = MF.front();
01370   MachineFrameInfo *MFI = MF.getFrameInfo();
01371   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01372   uint64_t StackSize;
01373   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01374   bool Is64Bit = STI.is64Bit();
01375   const bool IsLP64 = STI.isTarget64BitLP64();
01376   unsigned TlsReg, TlsOffset;
01377   DebugLoc DL;
01378 
01379   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
01380   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
01381          "Scratch register is live-in");
01382 
01383   if (MF.getFunction()->isVarArg())
01384     report_fatal_error("Segmented stacks do not support vararg functions.");
01385   if (!STI.isTargetLinux() && !STI.isTargetDarwin() &&
01386       !STI.isTargetWin32() && !STI.isTargetWin64() && !STI.isTargetFreeBSD())
01387     report_fatal_error("Segmented stacks not supported on this platform.");
01388 
01389   // Eventually StackSize will be calculated by a link-time pass; which will
01390   // also decide whether checking code needs to be injected into this particular
01391   // prologue.
01392   StackSize = MFI->getStackSize();
01393 
01394   // Do not generate a prologue for functions with a stack of size zero
01395   if (StackSize == 0)
01396     return;
01397 
01398   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
01399   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
01400   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01401   bool IsNested = false;
01402 
01403   // We need to know if the function has a nest argument only in 64 bit mode.
01404   if (Is64Bit)
01405     IsNested = HasNestArgument(&MF);
01406 
01407   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
01408   // allocMBB needs to be last (terminating) instruction.
01409 
01410   for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
01411          e = prologueMBB.livein_end(); i != e; i++) {
01412     allocMBB->addLiveIn(*i);
01413     checkMBB->addLiveIn(*i);
01414   }
01415 
01416   if (IsNested)
01417     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
01418 
01419   MF.push_front(allocMBB);
01420   MF.push_front(checkMBB);
01421 
01422   // When the frame size is less than 256 we just compare the stack
01423   // boundary directly to the value of the stack pointer, per gcc.
01424   bool CompareStackPointer = StackSize < kSplitStackAvailable;
01425 
01426   // Read the limit off the current stacklet off the stack_guard location.
01427   if (Is64Bit) {
01428     if (STI.isTargetLinux()) {
01429       TlsReg = X86::FS;
01430       TlsOffset = IsLP64 ? 0x70 : 0x40;
01431     } else if (STI.isTargetDarwin()) {
01432       TlsReg = X86::GS;
01433       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
01434     } else if (STI.isTargetWin64()) {
01435       TlsReg = X86::GS;
01436       TlsOffset = 0x28; // pvArbitrary, reserved for application use
01437     } else if (STI.isTargetFreeBSD()) {
01438       TlsReg = X86::FS;
01439       TlsOffset = 0x18;
01440     } else {
01441       report_fatal_error("Segmented stacks not supported on this platform.");
01442     }
01443 
01444     if (CompareStackPointer)
01445       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
01446     else
01447       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
01448         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
01449 
01450     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
01451       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
01452   } else {
01453     if (STI.isTargetLinux()) {
01454       TlsReg = X86::GS;
01455       TlsOffset = 0x30;
01456     } else if (STI.isTargetDarwin()) {
01457       TlsReg = X86::GS;
01458       TlsOffset = 0x48 + 90*4;
01459     } else if (STI.isTargetWin32()) {
01460       TlsReg = X86::FS;
01461       TlsOffset = 0x14; // pvArbitrary, reserved for application use
01462     } else if (STI.isTargetFreeBSD()) {
01463       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
01464     } else {
01465       report_fatal_error("Segmented stacks not supported on this platform.");
01466     }
01467 
01468     if (CompareStackPointer)
01469       ScratchReg = X86::ESP;
01470     else
01471       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
01472         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
01473 
01474     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64()) {
01475       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
01476         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
01477     } else if (STI.isTargetDarwin()) {
01478 
01479       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
01480       unsigned ScratchReg2;
01481       bool SaveScratch2;
01482       if (CompareStackPointer) {
01483         // The primary scratch register is available for holding the TLS offset.
01484         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
01485         SaveScratch2 = false;
01486       } else {
01487         // Need to use a second register to hold the TLS offset
01488         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
01489 
01490         // Unfortunately, with fastcc the second scratch register may hold an
01491         // argument.
01492         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
01493       }
01494 
01495       // If Scratch2 is live-in then it needs to be saved.
01496       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
01497              "Scratch register is live-in and not saved");
01498 
01499       if (SaveScratch2)
01500         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
01501           .addReg(ScratchReg2, RegState::Kill);
01502 
01503       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
01504         .addImm(TlsOffset);
01505       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
01506         .addReg(ScratchReg)
01507         .addReg(ScratchReg2).addImm(1).addReg(0)
01508         .addImm(0)
01509         .addReg(TlsReg);
01510 
01511       if (SaveScratch2)
01512         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
01513     }
01514   }
01515 
01516   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
01517   // It jumps to normal execution of the function body.
01518   BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
01519 
01520   // On 32 bit we first push the arguments size and then the frame size. On 64
01521   // bit, we pass the stack frame size in r10 and the argument size in r11.
01522   if (Is64Bit) {
01523     // Functions with nested arguments use R10, so it needs to be saved across
01524     // the call to _morestack
01525 
01526     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
01527     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
01528     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
01529     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
01530     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
01531 
01532     if (IsNested)
01533       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
01534 
01535     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
01536       .addImm(StackSize);
01537     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
01538       .addImm(X86FI->getArgumentStackSize());
01539     MF.getRegInfo().setPhysRegUsed(Reg10);
01540     MF.getRegInfo().setPhysRegUsed(Reg11);
01541   } else {
01542     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
01543       .addImm(X86FI->getArgumentStackSize());
01544     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
01545       .addImm(StackSize);
01546   }
01547 
01548   // __morestack is in libgcc
01549   if (Is64Bit)
01550     BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
01551       .addExternalSymbol("__morestack");
01552   else
01553     BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
01554       .addExternalSymbol("__morestack");
01555 
01556   if (IsNested)
01557     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
01558   else
01559     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
01560 
01561   allocMBB->addSuccessor(&prologueMBB);
01562 
01563   checkMBB->addSuccessor(allocMBB);
01564   checkMBB->addSuccessor(&prologueMBB);
01565 
01566 #ifdef XDEBUG
01567   MF.verify();
01568 #endif
01569 }
01570 
01571 /// Erlang programs may need a special prologue to handle the stack size they
01572 /// might need at runtime. That is because Erlang/OTP does not implement a C
01573 /// stack but uses a custom implementation of hybrid stack/heap architecture.
01574 /// (for more information see Eric Stenman's Ph.D. thesis:
01575 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
01576 ///
01577 /// CheckStack:
01578 ///       temp0 = sp - MaxStack
01579 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
01580 /// OldStart:
01581 ///       ...
01582 /// IncStack:
01583 ///       call inc_stack   # doubles the stack space
01584 ///       temp0 = sp - MaxStack
01585 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
01586 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
01587   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01588   MachineFrameInfo *MFI = MF.getFrameInfo();
01589   const unsigned SlotSize =
01590       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
01591           ->getSlotSize();
01592   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01593   const bool Is64Bit = STI.is64Bit();
01594   const bool IsLP64 = STI.isTarget64BitLP64();
01595   DebugLoc DL;
01596   // HiPE-specific values
01597   const unsigned HipeLeafWords = 24;
01598   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
01599   const unsigned Guaranteed = HipeLeafWords * SlotSize;
01600   unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
01601                             MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
01602   unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
01603 
01604   assert(STI.isTargetLinux() &&
01605          "HiPE prologue is only supported on Linux operating systems.");
01606 
01607   // Compute the largest caller's frame that is needed to fit the callees'
01608   // frames. This 'MaxStack' is computed from:
01609   //
01610   // a) the fixed frame size, which is the space needed for all spilled temps,
01611   // b) outgoing on-stack parameter areas, and
01612   // c) the minimum stack space this function needs to make available for the
01613   //    functions it calls (a tunable ABI property).
01614   if (MFI->hasCalls()) {
01615     unsigned MoreStackForCalls = 0;
01616 
01617     for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
01618          MBBI != MBBE; ++MBBI)
01619       for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
01620            MI != ME; ++MI) {
01621         if (!MI->isCall())
01622           continue;
01623 
01624         // Get callee operand.
01625         const MachineOperand &MO = MI->getOperand(0);
01626 
01627         // Only take account of global function calls (no closures etc.).
01628         if (!MO.isGlobal())
01629           continue;
01630 
01631         const Function *F = dyn_cast<Function>(MO.getGlobal());
01632         if (!F)
01633           continue;
01634 
01635         // Do not update 'MaxStack' for primitive and built-in functions
01636         // (encoded with names either starting with "erlang."/"bif_" or not
01637         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
01638         // "_", such as the BIF "suspend_0") as they are executed on another
01639         // stack.
01640         if (F->getName().find("erlang.") != StringRef::npos ||
01641             F->getName().find("bif_") != StringRef::npos ||
01642             F->getName().find_first_of("._") == StringRef::npos)
01643           continue;
01644 
01645         unsigned CalleeStkArity =
01646           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
01647         if (HipeLeafWords - 1 > CalleeStkArity)
01648           MoreStackForCalls = std::max(MoreStackForCalls,
01649                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
01650       }
01651     MaxStack += MoreStackForCalls;
01652   }
01653 
01654   // If the stack frame needed is larger than the guaranteed then runtime checks
01655   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
01656   if (MaxStack > Guaranteed) {
01657     MachineBasicBlock &prologueMBB = MF.front();
01658     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
01659     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
01660 
01661     for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
01662            E = prologueMBB.livein_end(); I != E; I++) {
01663       stackCheckMBB->addLiveIn(*I);
01664       incStackMBB->addLiveIn(*I);
01665     }
01666 
01667     MF.push_front(incStackMBB);
01668     MF.push_front(stackCheckMBB);
01669 
01670     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
01671     unsigned LEAop, CMPop, CALLop;
01672     if (Is64Bit) {
01673       SPReg = X86::RSP;
01674       PReg  = X86::RBP;
01675       LEAop = X86::LEA64r;
01676       CMPop = X86::CMP64rm;
01677       CALLop = X86::CALL64pcrel32;
01678       SPLimitOffset = 0x90;
01679     } else {
01680       SPReg = X86::ESP;
01681       PReg  = X86::EBP;
01682       LEAop = X86::LEA32r;
01683       CMPop = X86::CMP32rm;
01684       CALLop = X86::CALLpcrel32;
01685       SPLimitOffset = 0x4c;
01686     }
01687 
01688     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
01689     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
01690            "HiPE prologue scratch register is live-in");
01691 
01692     // Create new MBB for StackCheck:
01693     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
01694                  SPReg, false, -MaxStack);
01695     // SPLimitOffset is in a fixed heap location (pointed by BP).
01696     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
01697                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
01698     BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_4)).addMBB(&prologueMBB);
01699 
01700     // Create new MBB for IncStack:
01701     BuildMI(incStackMBB, DL, TII.get(CALLop)).
01702       addExternalSymbol("inc_stack_0");
01703     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
01704                  SPReg, false, -MaxStack);
01705     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
01706                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
01707     BuildMI(incStackMBB, DL, TII.get(X86::JLE_4)).addMBB(incStackMBB);
01708 
01709     stackCheckMBB->addSuccessor(&prologueMBB, 99);
01710     stackCheckMBB->addSuccessor(incStackMBB, 1);
01711     incStackMBB->addSuccessor(&prologueMBB, 99);
01712     incStackMBB->addSuccessor(incStackMBB, 1);
01713   }
01714 #ifdef XDEBUG
01715   MF.verify();
01716 #endif
01717 }
01718 
01719 void X86FrameLowering::
01720 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
01721                               MachineBasicBlock::iterator I) const {
01722   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01723   const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
01724                                        MF.getSubtarget().getRegisterInfo());
01725   unsigned StackPtr = RegInfo.getStackRegister();
01726   bool reseveCallFrame = hasReservedCallFrame(MF);
01727   int Opcode = I->getOpcode();
01728   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
01729   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01730   bool IsLP64 = STI.isTarget64BitLP64();
01731   DebugLoc DL = I->getDebugLoc();
01732   uint64_t Amount = !reseveCallFrame ? I->getOperand(0).getImm() : 0;
01733   uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
01734   I = MBB.erase(I);
01735 
01736   if (!reseveCallFrame) {
01737     // If the stack pointer can be changed after prologue, turn the
01738     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
01739     // adjcallstackdown instruction into 'add ESP, <amt>'
01740     // TODO: consider using push / pop instead of sub + store / add
01741     if (Amount == 0)
01742       return;
01743 
01744     // We need to keep the stack aligned properly.  To do this, we round the
01745     // amount of space needed for the outgoing arguments up to the next
01746     // alignment boundary.
01747     unsigned StackAlign = MF.getTarget()
01748                               .getSubtargetImpl()
01749                               ->getFrameLowering()
01750                               ->getStackAlignment();
01751     Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
01752 
01753     MachineInstr *New = nullptr;
01754     if (Opcode == TII.getCallFrameSetupOpcode()) {
01755       New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
01756                     StackPtr)
01757         .addReg(StackPtr)
01758         .addImm(Amount);
01759     } else {
01760       assert(Opcode == TII.getCallFrameDestroyOpcode());
01761 
01762       // Factor out the amount the callee already popped.
01763       Amount -= CalleeAmt;
01764 
01765       if (Amount) {
01766         unsigned Opc = getADDriOpcode(IsLP64, Amount);
01767         New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
01768           .addReg(StackPtr).addImm(Amount);
01769       }
01770     }
01771 
01772     if (New) {
01773       // The EFLAGS implicit def is dead.
01774       New->getOperand(3).setIsDead();
01775 
01776       // Replace the pseudo instruction with a new instruction.
01777       MBB.insert(I, New);
01778     }
01779 
01780     return;
01781   }
01782 
01783   if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
01784     // If we are performing frame pointer elimination and if the callee pops
01785     // something off the stack pointer, add it back.  We do this until we have
01786     // more advanced stack pointer tracking ability.
01787     unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
01788     MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
01789       .addReg(StackPtr).addImm(CalleeAmt);
01790 
01791     // The EFLAGS implicit def is dead.
01792     New->getOperand(3).setIsDead();
01793 
01794     // We are not tracking the stack pointer adjustment by the callee, so make
01795     // sure we restore the stack pointer immediately after the call, there may
01796     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
01797     MachineBasicBlock::iterator B = MBB.begin();
01798     while (I != B && !std::prev(I)->isCall())
01799       --I;
01800     MBB.insert(I, New);
01801   }
01802 }
01803