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