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