Revert r138826 until PR10834 can be fixed.
[oota-llvm.git] / lib / Target / X86 / X86FrameLowering.cpp
1 //=======- X86FrameLowering.cpp - X86 Frame Information --------*- C++ -*-====//
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/Function.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/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/ADT/SmallSet.h"
32
33 using namespace llvm;
34
35 // FIXME: completely move here.
36 extern cl::opt<bool> ForceStackAlign;
37
38 // FIXME: Remove once linker support is available. The feature exists only on
39 // Darwin at the moment.
40 static cl::opt<bool>
41 GenerateCompactUnwind("gen-compact-unwind",
42                       cl::desc("Generate compact unwind encoding"),
43                       cl::Hidden);
44
45 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
46   return !MF.getFrameInfo()->hasVarSizedObjects();
47 }
48
49 /// hasFP - Return true if the specified function should have a dedicated frame
50 /// pointer register.  This is true if the function has variable sized allocas
51 /// or if frame pointer elimination is disabled.
52 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
53   const MachineFrameInfo *MFI = MF.getFrameInfo();
54   const MachineModuleInfo &MMI = MF.getMMI();
55   const TargetRegisterInfo *RI = TM.getRegisterInfo();
56
57   return (DisableFramePointerElim(MF) ||
58           RI->needsStackRealignment(MF) ||
59           MFI->hasVarSizedObjects() ||
60           MFI->isFrameAddressTaken() ||
61           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
62           MMI.callsUnwindInit());
63 }
64
65 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
66   if (is64Bit) {
67     if (isInt<8>(Imm))
68       return X86::SUB64ri8;
69     return X86::SUB64ri32;
70   } else {
71     if (isInt<8>(Imm))
72       return X86::SUB32ri8;
73     return X86::SUB32ri;
74   }
75 }
76
77 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
78   if (is64Bit) {
79     if (isInt<8>(Imm))
80       return X86::ADD64ri8;
81     return X86::ADD64ri32;
82   } else {
83     if (isInt<8>(Imm))
84       return X86::ADD32ri8;
85     return X86::ADD32ri;
86   }
87 }
88
89 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
90 /// when it reaches the "return" instruction. We can then pop a stack object
91 /// to this register without worry about clobbering it.
92 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
93                                        MachineBasicBlock::iterator &MBBI,
94                                        const TargetRegisterInfo &TRI,
95                                        bool Is64Bit) {
96   const MachineFunction *MF = MBB.getParent();
97   const Function *F = MF->getFunction();
98   if (!F || MF->getMMI().callsEHReturn())
99     return 0;
100
101   static const unsigned CallerSavedRegs32Bit[] = {
102     X86::EAX, X86::EDX, X86::ECX, 0
103   };
104
105   static const unsigned CallerSavedRegs64Bit[] = {
106     X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
107     X86::R8,  X86::R9,  X86::R10, X86::R11, 0
108   };
109
110   unsigned Opc = MBBI->getOpcode();
111   switch (Opc) {
112   default: return 0;
113   case X86::RET:
114   case X86::RETI:
115   case X86::TCRETURNdi:
116   case X86::TCRETURNri:
117   case X86::TCRETURNmi:
118   case X86::TCRETURNdi64:
119   case X86::TCRETURNri64:
120   case X86::TCRETURNmi64:
121   case X86::EH_RETURN:
122   case X86::EH_RETURN64: {
123     SmallSet<unsigned, 8> Uses;
124     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
125       MachineOperand &MO = MBBI->getOperand(i);
126       if (!MO.isReg() || MO.isDef())
127         continue;
128       unsigned Reg = MO.getReg();
129       if (!Reg)
130         continue;
131       for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
132         Uses.insert(*AsI);
133     }
134
135     const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
136     for (; *CS; ++CS)
137       if (!Uses.count(*CS))
138         return *CS;
139   }
140   }
141
142   return 0;
143 }
144
145
146 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
147 /// stack pointer by a constant value.
148 static
149 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
150                   unsigned StackPtr, int64_t NumBytes,
151                   bool Is64Bit, const TargetInstrInfo &TII,
152                   const TargetRegisterInfo &TRI) {
153   bool isSub = NumBytes < 0;
154   uint64_t Offset = isSub ? -NumBytes : NumBytes;
155   unsigned Opc = isSub ?
156     getSUBriOpcode(Is64Bit, Offset) :
157     getADDriOpcode(Is64Bit, Offset);
158   uint64_t Chunk = (1LL << 31) - 1;
159   DebugLoc DL = MBB.findDebugLoc(MBBI);
160
161   while (Offset) {
162     uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
163     if (ThisVal == (Is64Bit ? 8 : 4)) {
164       // Use push / pop instead.
165       unsigned Reg = isSub
166         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
167         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
168       if (Reg) {
169         Opc = isSub
170           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
171           : (Is64Bit ? X86::POP64r  : X86::POP32r);
172         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
173           .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
174         if (isSub)
175           MI->setFlag(MachineInstr::FrameSetup);
176         Offset -= ThisVal;
177         continue;
178       }
179     }
180
181     MachineInstr *MI =
182       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
183       .addReg(StackPtr)
184       .addImm(ThisVal);
185     if (isSub)
186       MI->setFlag(MachineInstr::FrameSetup);
187     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
188     Offset -= ThisVal;
189   }
190 }
191
192 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
193 static
194 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
195                       unsigned StackPtr, uint64_t *NumBytes = NULL) {
196   if (MBBI == MBB.begin()) return;
197
198   MachineBasicBlock::iterator PI = prior(MBBI);
199   unsigned Opc = PI->getOpcode();
200   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
201        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
202       PI->getOperand(0).getReg() == StackPtr) {
203     if (NumBytes)
204       *NumBytes += PI->getOperand(2).getImm();
205     MBB.erase(PI);
206   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
207               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
208              PI->getOperand(0).getReg() == StackPtr) {
209     if (NumBytes)
210       *NumBytes -= PI->getOperand(2).getImm();
211     MBB.erase(PI);
212   }
213 }
214
215 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
216 static
217 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
218                         MachineBasicBlock::iterator &MBBI,
219                         unsigned StackPtr, uint64_t *NumBytes = NULL) {
220   // FIXME: THIS ISN'T RUN!!!
221   return;
222
223   if (MBBI == MBB.end()) return;
224
225   MachineBasicBlock::iterator NI = llvm::next(MBBI);
226   if (NI == MBB.end()) return;
227
228   unsigned Opc = NI->getOpcode();
229   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
230        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
231       NI->getOperand(0).getReg() == StackPtr) {
232     if (NumBytes)
233       *NumBytes -= NI->getOperand(2).getImm();
234     MBB.erase(NI);
235     MBBI = NI;
236   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
237               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
238              NI->getOperand(0).getReg() == StackPtr) {
239     if (NumBytes)
240       *NumBytes += NI->getOperand(2).getImm();
241     MBB.erase(NI);
242     MBBI = NI;
243   }
244 }
245
246 /// mergeSPUpdates - Checks the instruction before/after the passed
247 /// instruction. If it is an ADD/SUB instruction it is deleted argument and the
248 /// stack adjustment is returned as a positive value for ADD and a negative for
249 /// SUB.
250 static int mergeSPUpdates(MachineBasicBlock &MBB,
251                            MachineBasicBlock::iterator &MBBI,
252                            unsigned StackPtr,
253                            bool doMergeWithPrevious) {
254   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
255       (!doMergeWithPrevious && MBBI == MBB.end()))
256     return 0;
257
258   MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
259   MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
260   unsigned Opc = PI->getOpcode();
261   int Offset = 0;
262
263   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
264        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
265       PI->getOperand(0).getReg() == StackPtr){
266     Offset += PI->getOperand(2).getImm();
267     MBB.erase(PI);
268     if (!doMergeWithPrevious) MBBI = NI;
269   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
270               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
271              PI->getOperand(0).getReg() == StackPtr) {
272     Offset -= PI->getOperand(2).getImm();
273     MBB.erase(PI);
274     if (!doMergeWithPrevious) MBBI = NI;
275   }
276
277   return Offset;
278 }
279
280 static bool isEAXLiveIn(MachineFunction &MF) {
281   for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
282        EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
283     unsigned Reg = II->first;
284
285     if (Reg == X86::EAX || Reg == X86::AX ||
286         Reg == X86::AH || Reg == X86::AL)
287       return true;
288   }
289
290   return false;
291 }
292
293 void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
294                                                  MCSymbol *Label,
295                                                  unsigned FramePtr) const {
296   MachineFrameInfo *MFI = MF.getFrameInfo();
297   MachineModuleInfo &MMI = MF.getMMI();
298
299   // Add callee saved registers to move list.
300   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
301   if (CSI.empty()) return;
302
303   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
304   const TargetData *TD = TM.getTargetData();
305   bool HasFP = hasFP(MF);
306
307   // Calculate amount of bytes used for return address storing.
308   int stackGrowth = -TD->getPointerSize();
309
310   // FIXME: This is dirty hack. The code itself is pretty mess right now.
311   // It should be rewritten from scratch and generalized sometimes.
312
313   // Determine maximum offset (minimum due to stack growth).
314   int64_t MaxOffset = 0;
315   for (std::vector<CalleeSavedInfo>::const_iterator
316          I = CSI.begin(), E = CSI.end(); I != E; ++I)
317     MaxOffset = std::min(MaxOffset,
318                          MFI->getObjectOffset(I->getFrameIdx()));
319
320   // Calculate offsets.
321   int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
322   for (std::vector<CalleeSavedInfo>::const_iterator
323          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
324     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
325     unsigned Reg = I->getReg();
326     Offset = MaxOffset - Offset + saveAreaOffset;
327
328     // Don't output a new machine move if we're re-saving the frame
329     // pointer. This happens when the PrologEpilogInserter has inserted an extra
330     // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
331     // generates one when frame pointers are used. If we generate a "machine
332     // move" for this extra "PUSH", the linker will lose track of the fact that
333     // the frame pointer should have the value of the first "PUSH" when it's
334     // trying to unwind.
335     //
336     // FIXME: This looks inelegant. It's possibly correct, but it's covering up
337     //        another bug. I.e., one where we generate a prolog like this:
338     //
339     //          pushl  %ebp
340     //          movl   %esp, %ebp
341     //          pushl  %ebp
342     //          pushl  %esi
343     //           ...
344     //
345     //        The immediate re-push of EBP is unnecessary. At the least, it's an
346     //        optimization bug. EBP can be used as a scratch register in certain
347     //        cases, but probably not when we have a frame pointer.
348     if (HasFP && FramePtr == Reg)
349       continue;
350
351     MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
352     MachineLocation CSSrc(Reg);
353     Moves.push_back(MachineMove(Label, CSDst, CSSrc));
354   }
355 }
356
357 /// getCompactUnwindRegNum - Get the compact unwind number for a given
358 /// register. The number corresponds to the enum lists in
359 /// compact_unwind_encoding.h.
360 static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
361   int Idx = 1;
362   for (; *CURegs; ++CURegs, ++Idx)
363     if (*CURegs == Reg)
364       return Idx;
365
366   return -1;
367 }
368
369 /// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
370 /// used with frameless stacks. It is passed the number of registers to be saved
371 /// and an array of the registers saved.
372 static uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[6],
373                                                          unsigned RegCount,
374                                                          bool Is64Bit) {
375   // The saved registers are numbered from 1 to 6. In order to encode the order
376   // in which they were saved, we re-number them according to their place in the
377   // register order. The re-numbering is relative to the last re-numbered
378   // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
379   //
380   //    Orig  Re-Num
381   //    ----  ------
382   //     6       6
383   //     2       2
384   //     4       3
385   //     5       3
386   //
387   static const unsigned CU32BitRegs[] = {
388     X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
389   };
390   static const unsigned CU64BitRegs[] = {
391     X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
392   };
393   const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
394
395   uint32_t RenumRegs[6];
396   for (unsigned i = 6 - RegCount; i < 6; ++i) {
397     int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
398     if (CUReg == -1) return ~0U;
399     SavedRegs[i] = CUReg;
400
401     unsigned Countless = 0;
402     for (unsigned j = 6 - RegCount; j < i; ++j)
403       if (SavedRegs[j] < SavedRegs[i])
404         ++Countless;
405
406     RenumRegs[i] = SavedRegs[i] - Countless - 1;
407   }
408
409   // Take the renumbered values and encode them into a 10-bit number.
410   uint32_t permutationEncoding = 0;
411   switch (RegCount) {
412   case 6:
413     permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
414                            + 6 * RenumRegs[2] +  2 * RenumRegs[3]
415                            +     RenumRegs[4];
416     break;
417   case 5:
418     permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
419                            + 6 * RenumRegs[3] +  2 * RenumRegs[4]
420                            +     RenumRegs[5];
421     break;
422   case 4:
423     permutationEncoding |=  60 * RenumRegs[2] + 12 * RenumRegs[3]
424                            + 3 * RenumRegs[4] +      RenumRegs[5];
425     break;
426   case 3:
427     permutationEncoding |=  20 * RenumRegs[3] +  4 * RenumRegs[4]
428                            +     RenumRegs[5];
429     break;
430   case 2:
431     permutationEncoding |=   5 * RenumRegs[4] +      RenumRegs[5];
432     break;
433   case 1:
434     permutationEncoding |=       RenumRegs[5];
435     break;
436   }
437
438   assert((permutationEncoding & 0x3FF) == permutationEncoding &&
439          "Invalid compact register encoding!");
440   return permutationEncoding;
441 }
442
443 /// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
444 /// compact encoding with a frame pointer.
445 static uint32_t encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[6],
446                                                       bool Is64Bit) {
447   static const unsigned CU32BitRegs[] = {
448     X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
449   };
450   static const unsigned CU64BitRegs[] = {
451     X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
452   };
453   const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
454
455   // Encode the registers in the order they were saved, 3-bits per register. The
456   // registers are numbered from 1 to 6.
457   uint32_t RegEnc = 0;
458   for (int I = 5; I >= 0; --I) {
459     unsigned Reg = SavedRegs[I];
460     if (Reg == 0) break;
461     int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
462     if (CURegNum == -1)
463       return ~0U;
464     RegEnc |= (CURegNum & 0x7) << (5 - I);
465   }
466
467   assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
468   return RegEnc;
469 }
470
471 uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
472   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
473   unsigned FramePtr = RegInfo->getFrameRegister(MF);
474   unsigned StackPtr = RegInfo->getStackRegister();
475
476   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
477   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
478
479   bool Is64Bit = STI.is64Bit();
480   bool HasFP = hasFP(MF);
481
482   unsigned SavedRegs[6] = { 0, 0, 0, 0, 0, 0 };
483   int SavedRegIdx = 6;
484
485   unsigned OffsetSize = (Is64Bit ? 8 : 4);
486
487   unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
488   unsigned PushInstrSize = 1;
489   unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
490   unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
491   unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
492   unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
493
494   unsigned StackDivide = (Is64Bit ? 8 : 4);
495
496   unsigned InstrOffset = 0;
497   unsigned CFAOffset = 0;
498   unsigned StackAdjust = 0;
499
500   MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
501   bool ExpectEnd = false;
502   for (MachineBasicBlock::iterator
503          MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
504     MachineInstr &MI = *MBBI;
505     unsigned Opc = MI.getOpcode();
506     if (Opc == X86::PROLOG_LABEL) continue;
507     if (!MI.getFlag(MachineInstr::FrameSetup)) break;
508
509     // We don't exect any more prolog instructions.
510     if (ExpectEnd) return 0;
511
512     if (Opc == PushInstr) {
513       // If there are too many saved registers, we cannot use compact encoding.
514       if (--SavedRegIdx < 0) return 0;
515
516       SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
517       CFAOffset += OffsetSize;
518       InstrOffset += PushInstrSize;
519     } else if (Opc == MoveInstr) {
520       unsigned SrcReg = MI.getOperand(1).getReg();
521       unsigned DstReg = MI.getOperand(0).getReg();
522
523       if (DstReg != FramePtr || SrcReg != StackPtr)
524         return 0;
525
526       CFAOffset = 0;
527       memset(SavedRegs, 0, sizeof(SavedRegs));
528       InstrOffset += MoveInstrSize;
529     } else if (Opc == SubtractInstr) {
530       if (StackAdjust)
531         // We all ready have a stack pointer adjustment.
532         return 0;
533
534       if (!MI.getOperand(0).isReg() ||
535           MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
536           MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
537         // We need this to be a stack adjustment pointer. Something like:
538         //
539         //   %RSP<def> = SUB64ri8 %RSP, 48
540         return 0;
541
542       StackAdjust = MI.getOperand(2).getImm() / StackDivide;
543       SubtractInstrIdx += InstrOffset;
544       ExpectEnd = true;
545     }
546   }
547
548   // Encode that we are using EBP/RBP as the frame pointer.
549   uint32_t CompactUnwindEncoding = 0;
550   CFAOffset /= StackDivide;
551   if (HasFP) {
552     if ((CFAOffset & 0xFF) != CFAOffset)
553       // Offset was too big for compact encoding.
554       return 0;
555
556     // Get the encoding of the saved registers when we have a frame pointer.
557     uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
558     if (RegEnc == ~0U)
559       return 0;
560
561     CompactUnwindEncoding |= 0x01000000;
562     CompactUnwindEncoding |= (CFAOffset & 0xFF) << 16;
563     CompactUnwindEncoding |= RegEnc & 0x7FFF;
564   } else {
565     unsigned FullOffset = CFAOffset + StackAdjust;
566     if ((FullOffset & 0xFF) == FullOffset) {
567       // Frameless stack.
568       CompactUnwindEncoding |= 0x02000000;
569       CompactUnwindEncoding |= (FullOffset & 0xFF) << 16;
570     } else {
571       if ((CFAOffset & 0x7) != CFAOffset)
572         // The extra stack adjustments are too big for us to handle.
573         return 0;
574
575       // Frameless stack with an offset too large for us to encode compactly.
576       CompactUnwindEncoding |= 0x03000000;
577
578       // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
579       // instruction.
580       CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
581
582       // Encode any extra stack stack changes (done via push instructions).
583       CompactUnwindEncoding |= (CFAOffset & 0x7) << 13;
584     }
585
586     // Get the encoding of the saved registers when we don't have a frame
587     // pointer.
588     uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
589                                                                6 - SavedRegIdx,
590                                                                Is64Bit);
591     if (RegEnc == ~0U) return 0;
592     CompactUnwindEncoding |= RegEnc & 0x3FF;
593   }
594
595   return CompactUnwindEncoding;
596 }
597
598 /// emitPrologue - Push callee-saved registers onto the stack, which
599 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
600 /// space for local variables. Also emit labels used by the exception handler to
601 /// generate the exception handling frames.
602 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
603   MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
604   MachineBasicBlock::iterator MBBI = MBB.begin();
605   MachineFrameInfo *MFI = MF.getFrameInfo();
606   const Function *Fn = MF.getFunction();
607   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
608   const X86InstrInfo &TII = *TM.getInstrInfo();
609   MachineModuleInfo &MMI = MF.getMMI();
610   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
611   bool needsFrameMoves = MMI.hasDebugInfo() ||
612     Fn->needsUnwindTableEntry();
613   uint64_t MaxAlign  = MFI->getMaxAlignment(); // Desired stack alignment.
614   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
615   bool HasFP = hasFP(MF);
616   bool Is64Bit = STI.is64Bit();
617   bool IsWin64 = STI.isTargetWin64();
618   unsigned StackAlign = getStackAlignment();
619   unsigned SlotSize = RegInfo->getSlotSize();
620   unsigned FramePtr = RegInfo->getFrameRegister(MF);
621   unsigned StackPtr = RegInfo->getStackRegister();
622   DebugLoc DL;
623
624   // If we're forcing a stack realignment we can't rely on just the frame
625   // info, we need to know the ABI stack alignment as well in case we
626   // have a call out.  Otherwise just make sure we have some alignment - we'll
627   // go with the minimum SlotSize.
628   if (ForceStackAlign) {
629     if (MFI->hasCalls())
630       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
631     else if (MaxAlign < SlotSize)
632       MaxAlign = SlotSize;
633   }
634
635   // Add RETADDR move area to callee saved frame size.
636   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
637   if (TailCallReturnAddrDelta < 0)
638     X86FI->setCalleeSavedFrameSize(
639       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
640
641   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
642   // function, and use up to 128 bytes of stack space, don't have a frame
643   // pointer, calls, or dynamic alloca then we do not need to adjust the
644   // stack pointer (we fit in the Red Zone).
645   if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
646       !RegInfo->needsStackRealignment(MF) &&
647       !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
648       !MFI->adjustsStack() &&                      // No calls.
649       !IsWin64 &&                                  // Win64 has no Red Zone
650       !EnableSegmentedStacks) {                    // Regular stack
651     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
652     if (HasFP) MinSize += SlotSize;
653     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
654     MFI->setStackSize(StackSize);
655   }
656
657   // Insert stack pointer adjustment for later moving of return addr.  Only
658   // applies to tail call optimized functions where the callee argument stack
659   // size is bigger than the callers.
660   if (TailCallReturnAddrDelta < 0) {
661     MachineInstr *MI =
662       BuildMI(MBB, MBBI, DL,
663               TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
664               StackPtr)
665         .addReg(StackPtr)
666         .addImm(-TailCallReturnAddrDelta)
667         .setMIFlag(MachineInstr::FrameSetup);
668     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
669   }
670
671   // Mapping for machine moves:
672   //
673   //   DST: VirtualFP AND
674   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
675   //        ELSE                        => DW_CFA_def_cfa
676   //
677   //   SRC: VirtualFP AND
678   //        DST: Register               => DW_CFA_def_cfa_register
679   //
680   //   ELSE
681   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
682   //        REG < 64                    => DW_CFA_offset + Reg
683   //        ELSE                        => DW_CFA_offset_extended
684
685   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
686   const TargetData *TD = MF.getTarget().getTargetData();
687   uint64_t NumBytes = 0;
688   int stackGrowth = -TD->getPointerSize();
689
690   if (HasFP) {
691     // Calculate required stack adjustment.
692     uint64_t FrameSize = StackSize - SlotSize;
693     if (RegInfo->needsStackRealignment(MF))
694       FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
695
696     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
697
698     // Get the offset of the stack slot for the EBP register, which is
699     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
700     // Update the frame offset adjustment.
701     MFI->setOffsetAdjustment(-NumBytes);
702
703     // Save EBP/RBP into the appropriate stack slot.
704     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
705       .addReg(FramePtr, RegState::Kill)
706       .setMIFlag(MachineInstr::FrameSetup);
707
708     if (needsFrameMoves) {
709       // Mark the place where EBP/RBP was saved.
710       MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
711       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
712         .addSym(FrameLabel);
713
714       // Define the current CFA rule to use the provided offset.
715       if (StackSize) {
716         MachineLocation SPDst(MachineLocation::VirtualFP);
717         MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
718         Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
719       } else {
720         MachineLocation SPDst(StackPtr);
721         MachineLocation SPSrc(StackPtr, stackGrowth);
722         Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
723       }
724
725       // Change the rule for the FramePtr to be an "offset" rule.
726       MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
727       MachineLocation FPSrc(FramePtr);
728       Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
729     }
730
731     // Update EBP with the new base value.
732     BuildMI(MBB, MBBI, DL,
733             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
734         .addReg(StackPtr)
735         .setMIFlag(MachineInstr::FrameSetup);
736
737     if (needsFrameMoves) {
738       // Mark effective beginning of when frame pointer becomes valid.
739       MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
740       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
741         .addSym(FrameLabel);
742
743       // Define the current CFA to use the EBP/RBP register.
744       MachineLocation FPDst(FramePtr);
745       MachineLocation FPSrc(MachineLocation::VirtualFP);
746       Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
747     }
748
749     // Mark the FramePtr as live-in in every block except the entry.
750     for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
751          I != E; ++I)
752       I->addLiveIn(FramePtr);
753
754     // Realign stack
755     if (RegInfo->needsStackRealignment(MF)) {
756       MachineInstr *MI =
757         BuildMI(MBB, MBBI, DL,
758                 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
759         .addReg(StackPtr)
760         .addImm(-MaxAlign)
761         .setMIFlag(MachineInstr::FrameSetup);
762
763       // The EFLAGS implicit def is dead.
764       MI->getOperand(3).setIsDead();
765     }
766   } else {
767     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
768   }
769
770   // Skip the callee-saved push instructions.
771   bool PushedRegs = false;
772   int StackOffset = 2 * stackGrowth;
773
774   while (MBBI != MBB.end() &&
775          (MBBI->getOpcode() == X86::PUSH32r ||
776           MBBI->getOpcode() == X86::PUSH64r)) {
777     PushedRegs = true;
778     MBBI->setFlag(MachineInstr::FrameSetup);
779     ++MBBI;
780
781     if (!HasFP && needsFrameMoves) {
782       // Mark callee-saved push instruction.
783       MCSymbol *Label = MMI.getContext().CreateTempSymbol();
784       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
785
786       // Define the current CFA rule to use the provided offset.
787       unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
788       MachineLocation SPDst(Ptr);
789       MachineLocation SPSrc(Ptr, StackOffset);
790       Moves.push_back(MachineMove(Label, SPDst, SPSrc));
791       StackOffset += stackGrowth;
792     }
793   }
794
795   DL = MBB.findDebugLoc(MBBI);
796
797   // If there is an SUB32ri of ESP immediately before this instruction, merge
798   // the two. This can be the case when tail call elimination is enabled and
799   // the callee has more arguments then the caller.
800   NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
801
802   // If there is an ADD32ri or SUB32ri of ESP immediately after this
803   // instruction, merge the two instructions.
804   mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
805
806   // Adjust stack pointer: ESP -= numbytes.
807
808   // Windows and cygwin/mingw require a prologue helper routine when allocating
809   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
810   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
811   // stack and adjust the stack pointer in one go.  The 64-bit version of
812   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
813   // responsible for adjusting the stack pointer.  Touching the stack at 4K
814   // increments is necessary to ensure that the guard pages used by the OS
815   // virtual memory manager are allocated in correct sequence.
816   if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
817     const char *StackProbeSymbol;
818     bool isSPUpdateNeeded = false;
819
820     if (Is64Bit) {
821       if (STI.isTargetCygMing())
822         StackProbeSymbol = "___chkstk";
823       else {
824         StackProbeSymbol = "__chkstk";
825         isSPUpdateNeeded = true;
826       }
827     } else if (STI.isTargetCygMing())
828       StackProbeSymbol = "_alloca";
829     else
830       StackProbeSymbol = "_chkstk";
831
832     // Check whether EAX is livein for this function.
833     bool isEAXAlive = isEAXLiveIn(MF);
834
835     if (isEAXAlive) {
836       // Sanity check that EAX is not livein for this function.
837       // It should not be, so throw an assert.
838       assert(!Is64Bit && "EAX is livein in x64 case!");
839
840       // Save EAX
841       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
842         .addReg(X86::EAX, RegState::Kill)
843         .setMIFlag(MachineInstr::FrameSetup);
844     }
845
846     if (Is64Bit) {
847       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
848       // Function prologue is responsible for adjusting the stack pointer.
849       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
850         .addImm(NumBytes)
851         .setMIFlag(MachineInstr::FrameSetup);
852     } else {
853       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
854       // We'll also use 4 already allocated bytes for EAX.
855       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
856         .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
857         .setMIFlag(MachineInstr::FrameSetup);
858     }
859
860     BuildMI(MBB, MBBI, DL,
861             TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
862       .addExternalSymbol(StackProbeSymbol)
863       .addReg(StackPtr,    RegState::Define | RegState::Implicit)
864       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
865       .setMIFlag(MachineInstr::FrameSetup);
866
867     // MSVC x64's __chkstk needs to adjust %rsp.
868     // FIXME: %rax preserves the offset and should be available.
869     if (isSPUpdateNeeded)
870       emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
871                    TII, *RegInfo);
872
873     if (isEAXAlive) {
874         // Restore EAX
875         MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
876                                                 X86::EAX),
877                                         StackPtr, false, NumBytes - 4);
878         MI->setFlag(MachineInstr::FrameSetup);
879         MBB.insert(MBBI, MI);
880     }
881   } else if (NumBytes)
882     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
883                  TII, *RegInfo);
884
885   if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
886     // Mark end of stack pointer adjustment.
887     MCSymbol *Label = MMI.getContext().CreateTempSymbol();
888     BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
889       .addSym(Label);
890
891     if (!HasFP && NumBytes) {
892       // Define the current CFA rule to use the provided offset.
893       if (StackSize) {
894         MachineLocation SPDst(MachineLocation::VirtualFP);
895         MachineLocation SPSrc(MachineLocation::VirtualFP,
896                               -StackSize + stackGrowth);
897         Moves.push_back(MachineMove(Label, SPDst, SPSrc));
898       } else {
899         MachineLocation SPDst(StackPtr);
900         MachineLocation SPSrc(StackPtr, stackGrowth);
901         Moves.push_back(MachineMove(Label, SPDst, SPSrc));
902       }
903     }
904
905     // Emit DWARF info specifying the offsets of the callee-saved registers.
906     if (PushedRegs)
907       emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
908   }
909
910   // Darwin 10.7 and greater has support for compact unwind encoding.
911   if (GenerateCompactUnwind && STI.getTargetTriple().isMacOSX() &&
912       !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
913     MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
914 }
915
916 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
917                                     MachineBasicBlock &MBB) const {
918   const MachineFrameInfo *MFI = MF.getFrameInfo();
919   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
920   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
921   const X86InstrInfo &TII = *TM.getInstrInfo();
922   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
923   assert(MBBI != MBB.end() && "Returning block has no instructions");
924   unsigned RetOpcode = MBBI->getOpcode();
925   DebugLoc DL = MBBI->getDebugLoc();
926   bool Is64Bit = STI.is64Bit();
927   unsigned StackAlign = getStackAlignment();
928   unsigned SlotSize = RegInfo->getSlotSize();
929   unsigned FramePtr = RegInfo->getFrameRegister(MF);
930   unsigned StackPtr = RegInfo->getStackRegister();
931
932   switch (RetOpcode) {
933   default:
934     llvm_unreachable("Can only insert epilog into returning blocks");
935   case X86::RET:
936   case X86::RETI:
937   case X86::TCRETURNdi:
938   case X86::TCRETURNri:
939   case X86::TCRETURNmi:
940   case X86::TCRETURNdi64:
941   case X86::TCRETURNri64:
942   case X86::TCRETURNmi64:
943   case X86::EH_RETURN:
944   case X86::EH_RETURN64:
945     break;  // These are ok
946   }
947
948   // Get the number of bytes to allocate from the FrameInfo.
949   uint64_t StackSize = MFI->getStackSize();
950   uint64_t MaxAlign  = MFI->getMaxAlignment();
951   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
952   uint64_t NumBytes = 0;
953
954   // If we're forcing a stack realignment we can't rely on just the frame
955   // info, we need to know the ABI stack alignment as well in case we
956   // have a call out.  Otherwise just make sure we have some alignment - we'll
957   // go with the minimum.
958   if (ForceStackAlign) {
959     if (MFI->hasCalls())
960       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
961     else
962       MaxAlign = MaxAlign ? MaxAlign : 4;
963   }
964
965   if (hasFP(MF)) {
966     // Calculate required stack adjustment.
967     uint64_t FrameSize = StackSize - SlotSize;
968     if (RegInfo->needsStackRealignment(MF))
969       FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
970
971     NumBytes = FrameSize - CSSize;
972
973     // Pop EBP.
974     BuildMI(MBB, MBBI, DL,
975             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
976   } else {
977     NumBytes = StackSize - CSSize;
978   }
979
980   // Skip the callee-saved pop instructions.
981   MachineBasicBlock::iterator LastCSPop = MBBI;
982   while (MBBI != MBB.begin()) {
983     MachineBasicBlock::iterator PI = prior(MBBI);
984     unsigned Opc = PI->getOpcode();
985
986     if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
987         !PI->getDesc().isTerminator())
988       break;
989
990     --MBBI;
991   }
992
993   DL = MBBI->getDebugLoc();
994
995   // If there is an ADD32ri or SUB32ri of ESP immediately before this
996   // instruction, merge the two instructions.
997   if (NumBytes || MFI->hasVarSizedObjects())
998     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
999
1000   // If dynamic alloca is used, then reset esp to point to the last callee-saved
1001   // slot before popping them off! Same applies for the case, when stack was
1002   // realigned.
1003   if (RegInfo->needsStackRealignment(MF)) {
1004     // We cannot use LEA here, because stack pointer was realigned. We need to
1005     // deallocate local frame back.
1006     if (CSSize) {
1007       emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1008       MBBI = prior(LastCSPop);
1009     }
1010
1011     BuildMI(MBB, MBBI, DL,
1012             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1013             StackPtr).addReg(FramePtr);
1014   } else if (MFI->hasVarSizedObjects()) {
1015     if (CSSize) {
1016       unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1017       MachineInstr *MI =
1018         addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1019                      FramePtr, false, -CSSize);
1020       MBB.insert(MBBI, MI);
1021     } else {
1022       BuildMI(MBB, MBBI, DL,
1023               TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1024         .addReg(FramePtr);
1025     }
1026   } else if (NumBytes) {
1027     // Adjust stack pointer back: ESP += numbytes.
1028     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1029   }
1030
1031   // We're returning from function via eh_return.
1032   if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1033     MBBI = MBB.getLastNonDebugInstr();
1034     MachineOperand &DestAddr  = MBBI->getOperand(0);
1035     assert(DestAddr.isReg() && "Offset should be in register!");
1036     BuildMI(MBB, MBBI, DL,
1037             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1038             StackPtr).addReg(DestAddr.getReg());
1039   } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1040              RetOpcode == X86::TCRETURNmi ||
1041              RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1042              RetOpcode == X86::TCRETURNmi64) {
1043     bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1044     // Tail call return: adjust the stack pointer and jump to callee.
1045     MBBI = MBB.getLastNonDebugInstr();
1046     MachineOperand &JumpTarget = MBBI->getOperand(0);
1047     MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1048     assert(StackAdjust.isImm() && "Expecting immediate value.");
1049
1050     // Adjust stack pointer.
1051     int StackAdj = StackAdjust.getImm();
1052     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1053     int Offset = 0;
1054     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1055
1056     // Incoporate the retaddr area.
1057     Offset = StackAdj-MaxTCDelta;
1058     assert(Offset >= 0 && "Offset should never be negative");
1059
1060     if (Offset) {
1061       // Check for possible merge with preceding ADD instruction.
1062       Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1063       emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
1064     }
1065
1066     // Jump to label or value in register.
1067     if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1068       MachineInstrBuilder MIB =
1069         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1070                                        ? X86::TAILJMPd : X86::TAILJMPd64));
1071       if (JumpTarget.isGlobal())
1072         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1073                              JumpTarget.getTargetFlags());
1074       else {
1075         assert(JumpTarget.isSymbol());
1076         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1077                               JumpTarget.getTargetFlags());
1078       }
1079     } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1080       MachineInstrBuilder MIB =
1081         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1082                                        ? X86::TAILJMPm : X86::TAILJMPm64));
1083       for (unsigned i = 0; i != 5; ++i)
1084         MIB.addOperand(MBBI->getOperand(i));
1085     } else if (RetOpcode == X86::TCRETURNri64) {
1086       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1087         addReg(JumpTarget.getReg(), RegState::Kill);
1088     } else {
1089       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1090         addReg(JumpTarget.getReg(), RegState::Kill);
1091     }
1092
1093     MachineInstr *NewMI = prior(MBBI);
1094     for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1095       NewMI->addOperand(MBBI->getOperand(i));
1096
1097     // Delete the pseudo instruction TCRETURN.
1098     MBB.erase(MBBI);
1099   } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1100              (X86FI->getTCReturnAddrDelta() < 0)) {
1101     // Add the return addr area delta back since we are not tail calling.
1102     int delta = -1*X86FI->getTCReturnAddrDelta();
1103     MBBI = MBB.getLastNonDebugInstr();
1104
1105     // Check for possible merge with preceding ADD instruction.
1106     delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1107     emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
1108   }
1109 }
1110
1111 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
1112   const X86RegisterInfo *RI =
1113     static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1114   const MachineFrameInfo *MFI = MF.getFrameInfo();
1115   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1116   uint64_t StackSize = MFI->getStackSize();
1117
1118   if (RI->needsStackRealignment(MF)) {
1119     if (FI < 0) {
1120       // Skip the saved EBP.
1121       Offset += RI->getSlotSize();
1122     } else {
1123       unsigned Align = MFI->getObjectAlignment(FI);
1124       assert((-(Offset + StackSize)) % Align == 0);
1125       Align = 0;
1126       return Offset + StackSize;
1127     }
1128     // FIXME: Support tail calls
1129   } else {
1130     if (!hasFP(MF))
1131       return Offset + StackSize;
1132
1133     // Skip the saved EBP.
1134     Offset += RI->getSlotSize();
1135
1136     // Skip the RETADDR move area
1137     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1138     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1139     if (TailCallReturnAddrDelta < 0)
1140       Offset -= TailCallReturnAddrDelta;
1141   }
1142
1143   return Offset;
1144 }
1145
1146 bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1147                                              MachineBasicBlock::iterator MI,
1148                                         const std::vector<CalleeSavedInfo> &CSI,
1149                                           const TargetRegisterInfo *TRI) const {
1150   if (CSI.empty())
1151     return false;
1152
1153   DebugLoc DL = MBB.findDebugLoc(MI);
1154
1155   MachineFunction &MF = *MBB.getParent();
1156
1157   unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1158   unsigned FPReg = TRI->getFrameRegister(MF);
1159   unsigned CalleeFrameSize = 0;
1160
1161   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1162   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1163
1164   // Push GPRs. It increases frame size.
1165   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1166   for (unsigned i = CSI.size(); i != 0; --i) {
1167     unsigned Reg = CSI[i-1].getReg();
1168     if (!X86::GR64RegClass.contains(Reg) &&
1169         !X86::GR32RegClass.contains(Reg))
1170       continue;
1171     // Add the callee-saved register as live-in. It's killed at the spill.
1172     MBB.addLiveIn(Reg);
1173     if (Reg == FPReg)
1174       // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1175       continue;
1176     CalleeFrameSize += SlotSize;
1177     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1178       .setMIFlag(MachineInstr::FrameSetup);
1179   }
1180
1181   X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
1182
1183   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1184   // It can be done by spilling XMMs to stack frame.
1185   // Note that only Win64 ABI might spill XMMs.
1186   for (unsigned i = CSI.size(); i != 0; --i) {
1187     unsigned Reg = CSI[i-1].getReg();
1188     if (X86::GR64RegClass.contains(Reg) ||
1189         X86::GR32RegClass.contains(Reg))
1190       continue;
1191     // Add the callee-saved register as live-in. It's killed at the spill.
1192     MBB.addLiveIn(Reg);
1193     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1194     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1195                             RC, TRI);
1196   }
1197
1198   return true;
1199 }
1200
1201 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1202                                                MachineBasicBlock::iterator MI,
1203                                         const std::vector<CalleeSavedInfo> &CSI,
1204                                           const TargetRegisterInfo *TRI) const {
1205   if (CSI.empty())
1206     return false;
1207
1208   DebugLoc DL = MBB.findDebugLoc(MI);
1209
1210   MachineFunction &MF = *MBB.getParent();
1211   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1212
1213   // Reload XMMs from stack frame.
1214   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1215     unsigned Reg = CSI[i].getReg();
1216     if (X86::GR64RegClass.contains(Reg) ||
1217         X86::GR32RegClass.contains(Reg))
1218       continue;
1219     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1220     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1221                              RC, TRI);
1222   }
1223
1224   // POP GPRs.
1225   unsigned FPReg = TRI->getFrameRegister(MF);
1226   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1227   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1228     unsigned Reg = CSI[i].getReg();
1229     if (!X86::GR64RegClass.contains(Reg) &&
1230         !X86::GR32RegClass.contains(Reg))
1231       continue;
1232     if (Reg == FPReg)
1233       // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1234       continue;
1235     BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1236   }
1237   return true;
1238 }
1239
1240 void
1241 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1242                                                    RegScavenger *RS) const {
1243   MachineFrameInfo *MFI = MF.getFrameInfo();
1244   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1245   unsigned SlotSize = RegInfo->getSlotSize();
1246
1247   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1248   int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1249
1250   if (TailCallReturnAddrDelta < 0) {
1251     // create RETURNADDR area
1252     //   arg
1253     //   arg
1254     //   RETADDR
1255     //   { ...
1256     //     RETADDR area
1257     //     ...
1258     //   }
1259     //   [EBP]
1260     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1261                            (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1262   }
1263
1264   if (hasFP(MF)) {
1265     assert((TailCallReturnAddrDelta <= 0) &&
1266            "The Delta should always be zero or negative");
1267     const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
1268
1269     // Create a frame entry for the EBP register that must be saved.
1270     int FrameIdx = MFI->CreateFixedObject(SlotSize,
1271                                           -(int)SlotSize +
1272                                           TFI.getOffsetOfLocalArea() +
1273                                           TailCallReturnAddrDelta,
1274                                           true);
1275     assert(FrameIdx == MFI->getObjectIndexBegin() &&
1276            "Slot for EBP register must be last in order to be found!");
1277     FrameIdx = 0;
1278   }
1279 }
1280
1281 static bool
1282 HasNestArgument(const MachineFunction *MF) {
1283   const Function *F = MF->getFunction();
1284   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1285        I != E; I++) {
1286     if (I->hasNestAttr())
1287       return true;
1288   }
1289   return false;
1290 }
1291
1292 static unsigned
1293 GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
1294   if (Is64Bit) {
1295     return X86::R11;
1296   } else {
1297     CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1298     bool IsNested = HasNestArgument(&MF);
1299
1300     if (CallingConvention == CallingConv::X86_FastCall) {
1301       if (IsNested) {
1302         report_fatal_error("Segmented stacks does not support fastcall with "
1303                            "nested function.");
1304         return -1;
1305       } else {
1306         return X86::EAX;
1307       }
1308     } else {
1309       if (IsNested)
1310         return X86::EDX;
1311       else
1312         return X86::ECX;
1313     }
1314   }
1315 }
1316
1317 void
1318 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1319   MachineBasicBlock &prologueMBB = MF.front();
1320   MachineFrameInfo *MFI = MF.getFrameInfo();
1321   const X86InstrInfo &TII = *TM.getInstrInfo();
1322   uint64_t StackSize;
1323   bool Is64Bit = STI.is64Bit();
1324   unsigned TlsReg, TlsOffset;
1325   DebugLoc DL;
1326   const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1327
1328   unsigned ScratchReg = GetScratchRegister(Is64Bit, MF);
1329   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1330          "Scratch register is live-in");
1331
1332   if (MF.getFunction()->isVarArg())
1333     report_fatal_error("Segmented stacks do not support vararg functions.");
1334   if (!ST->isTargetLinux())
1335     report_fatal_error("Segmented stacks supported only on linux.");
1336
1337   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1338   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1339   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1340   bool IsNested = false;
1341
1342   // We need to know if the function has a nest argument only in 64 bit mode.
1343   if (Is64Bit)
1344     IsNested = HasNestArgument(&MF);
1345
1346   for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1347          e = prologueMBB.livein_end(); i != e; i++) {
1348     allocMBB->addLiveIn(*i);
1349     checkMBB->addLiveIn(*i);
1350   }
1351
1352   if (IsNested)
1353     allocMBB->addLiveIn(X86::R10);
1354
1355   MF.push_front(allocMBB);
1356   MF.push_front(checkMBB);
1357
1358   // Eventually StackSize will be calculated by a link-time pass; which will
1359   // also decide whether checking code needs to be injected into this particular
1360   // prologue.
1361   StackSize = MFI->getStackSize();
1362
1363   // Read the limit off the current stacklet off the stack_guard location.
1364   if (Is64Bit) {
1365     TlsReg = X86::FS;
1366     TlsOffset = 0x70;
1367
1368     BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1369       .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1370     BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1371       .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1372   } else {
1373     TlsReg = X86::GS;
1374     TlsOffset = 0x30;
1375
1376     BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1377       .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1378     BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1379       .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1380   }
1381
1382   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1383   // It jumps to normal execution of the function body.
1384   BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
1385
1386   // On 32 bit we first push the arguments size and then the frame size. On 64
1387   // bit, we pass the stack frame size in r10 and the argument size in r11.
1388   if (Is64Bit) {
1389     // Functions with nested arguments use R10, so it needs to be saved across
1390     // the call to _morestack
1391
1392     if (IsNested)
1393       BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1394
1395     BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1396       .addImm(StackSize);
1397     BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1398       .addImm(X86FI->getArgumentStackSize());
1399     MF.getRegInfo().setPhysRegUsed(X86::R10);
1400     MF.getRegInfo().setPhysRegUsed(X86::R11);
1401   } else {
1402     // Since we'll call __morestack, stack alignment needs to be preserved.
1403     BuildMI(allocMBB, DL, TII.get(X86::SUB32ri), X86::ESP).addReg(X86::ESP)
1404       .addImm(8);
1405     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1406       .addImm(X86FI->getArgumentStackSize());
1407     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1408       .addImm(StackSize);
1409   }
1410
1411   // __morestack is in libgcc
1412   if (Is64Bit)
1413     BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1414       .addExternalSymbol("__morestack");
1415   else
1416     BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1417       .addExternalSymbol("__morestack");
1418
1419   // __morestack only seems to remove 8 bytes off the stack. Add back the
1420   // additional 8 bytes we added before pushing the arguments.
1421   if (!Is64Bit)
1422     BuildMI(allocMBB, DL, TII.get(X86::ADD32ri), X86::ESP).addReg(X86::ESP)
1423       .addImm(8);
1424   BuildMI(allocMBB, DL, TII.get(X86::RET));
1425
1426   if (Is64Bit && IsNested)
1427     BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::R10).addReg(X86::RAX);
1428
1429   allocMBB->addSuccessor(&prologueMBB);
1430   checkMBB->addSuccessor(allocMBB);
1431   checkMBB->addSuccessor(&prologueMBB);
1432
1433 #ifndef NDEBUG
1434   MF.verify();
1435 #endif
1436 }