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