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