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