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