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