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