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