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