X86RegisterInfo.cpp revision bfd23c9961d6a02df0982fe45d7f21a72a1075e1
1//===- X86RegisterInfo.cpp - X86 Register 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 the TargetRegisterInfo class.
11// This file is responsible for the frame pointer elimination optimization
12// on X86.
13//
14//===----------------------------------------------------------------------===//
15
16#include "X86.h"
17#include "X86RegisterInfo.h"
18#include "X86InstrBuilder.h"
19#include "X86MachineFunctionInfo.h"
20#include "X86Subtarget.h"
21#include "X86TargetMachine.h"
22#include "llvm/Constants.h"
23#include "llvm/Function.h"
24#include "llvm/Type.h"
25#include "llvm/CodeGen/ValueTypes.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineLocation.h"
31#include "llvm/CodeGen/MachineModuleInfo.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/Target/TargetAsmInfo.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
38#include "llvm/ADT/BitVector.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/Support/Compiler.h"
41using namespace llvm;
42
43X86RegisterInfo::X86RegisterInfo(X86TargetMachine &tm,
44                                 const TargetInstrInfo &tii)
45  : X86GenRegisterInfo(tm.getSubtarget<X86Subtarget>().is64Bit() ?
46                         X86::ADJCALLSTACKDOWN64 :
47                         X86::ADJCALLSTACKDOWN32,
48                       tm.getSubtarget<X86Subtarget>().is64Bit() ?
49                         X86::ADJCALLSTACKUP64 :
50                         X86::ADJCALLSTACKUP32),
51    TM(tm), TII(tii) {
52  // Cache some information.
53  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
54  Is64Bit = Subtarget->is64Bit();
55  IsWin64 = Subtarget->isTargetWin64();
56  StackAlign = TM.getFrameInfo()->getStackAlignment();
57  if (Is64Bit) {
58    SlotSize = 8;
59    StackPtr = X86::RSP;
60    FramePtr = X86::RBP;
61  } else {
62    SlotSize = 4;
63    StackPtr = X86::ESP;
64    FramePtr = X86::EBP;
65  }
66}
67
68// getDwarfRegNum - This function maps LLVM register identifiers to the
69// Dwarf specific numbering, used in debug info and exception tables.
70
71int X86RegisterInfo::getDwarfRegNum(unsigned RegNo, bool isEH) const {
72  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
73  unsigned Flavour = DWARFFlavour::X86_64;
74  if (!Subtarget->is64Bit()) {
75    if (Subtarget->isTargetDarwin()) {
76      if (isEH)
77        Flavour = DWARFFlavour::X86_32_DarwinEH;
78      else
79        Flavour = DWARFFlavour::X86_32_Generic;
80    } else if (Subtarget->isTargetCygMing()) {
81      // Unsupported by now, just quick fallback
82      Flavour = DWARFFlavour::X86_32_Generic;
83    } else {
84      Flavour = DWARFFlavour::X86_32_Generic;
85    }
86  }
87
88  return X86GenRegisterInfo::getDwarfRegNumFull(RegNo, Flavour);
89}
90
91// getX86RegNum - This function maps LLVM register identifiers to their X86
92// specific numbering, which is used in various places encoding instructions.
93//
94unsigned X86RegisterInfo::getX86RegNum(unsigned RegNo) {
95  switch(RegNo) {
96  case X86::RAX: case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
97  case X86::RCX: case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
98  case X86::RDX: case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
99  case X86::RBX: case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
100  case X86::RSP: case X86::ESP: case X86::SP: case X86::SPL: case X86::AH:
101    return N86::ESP;
102  case X86::RBP: case X86::EBP: case X86::BP: case X86::BPL: case X86::CH:
103    return N86::EBP;
104  case X86::RSI: case X86::ESI: case X86::SI: case X86::SIL: case X86::DH:
105    return N86::ESI;
106  case X86::RDI: case X86::EDI: case X86::DI: case X86::DIL: case X86::BH:
107    return N86::EDI;
108
109  case X86::R8:  case X86::R8D:  case X86::R8W:  case X86::R8B:
110    return N86::EAX;
111  case X86::R9:  case X86::R9D:  case X86::R9W:  case X86::R9B:
112    return N86::ECX;
113  case X86::R10: case X86::R10D: case X86::R10W: case X86::R10B:
114    return N86::EDX;
115  case X86::R11: case X86::R11D: case X86::R11W: case X86::R11B:
116    return N86::EBX;
117  case X86::R12: case X86::R12D: case X86::R12W: case X86::R12B:
118    return N86::ESP;
119  case X86::R13: case X86::R13D: case X86::R13W: case X86::R13B:
120    return N86::EBP;
121  case X86::R14: case X86::R14D: case X86::R14W: case X86::R14B:
122    return N86::ESI;
123  case X86::R15: case X86::R15D: case X86::R15W: case X86::R15B:
124    return N86::EDI;
125
126  case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
127  case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
128    return RegNo-X86::ST0;
129
130  case X86::XMM0: case X86::XMM8: case X86::MM0:
131    return 0;
132  case X86::XMM1: case X86::XMM9: case X86::MM1:
133    return 1;
134  case X86::XMM2: case X86::XMM10: case X86::MM2:
135    return 2;
136  case X86::XMM3: case X86::XMM11: case X86::MM3:
137    return 3;
138  case X86::XMM4: case X86::XMM12: case X86::MM4:
139    return 4;
140  case X86::XMM5: case X86::XMM13: case X86::MM5:
141    return 5;
142  case X86::XMM6: case X86::XMM14: case X86::MM6:
143    return 6;
144  case X86::XMM7: case X86::XMM15: case X86::MM7:
145    return 7;
146
147  default:
148    assert(isVirtualRegister(RegNo) && "Unknown physical register!");
149    assert(0 && "Register allocator hasn't allocated reg correctly yet!");
150    return 0;
151  }
152}
153
154const TargetRegisterClass *
155X86RegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
156  if (RC == &X86::CCRRegClass) {
157    if (Is64Bit)
158      return &X86::GR64RegClass;
159    else
160      return &X86::GR32RegClass;
161  }
162  return NULL;
163}
164
165const unsigned *
166X86RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
167  bool callsEHReturn = false;
168
169  if (MF) {
170    const MachineFrameInfo *MFI = MF->getFrameInfo();
171    const MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
172    callsEHReturn = (MMI ? MMI->callsEHReturn() : false);
173  }
174
175  static const unsigned CalleeSavedRegs32Bit[] = {
176    X86::ESI, X86::EDI, X86::EBX, X86::EBP,  0
177  };
178
179  static const unsigned CalleeSavedRegs32EHRet[] = {
180    X86::EAX, X86::EDX, X86::ESI, X86::EDI, X86::EBX, X86::EBP,  0
181  };
182
183  static const unsigned CalleeSavedRegs64Bit[] = {
184    X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
185  };
186
187  static const unsigned CalleeSavedRegs64EHRet[] = {
188    X86::RAX, X86::RDX, X86::RBX, X86::R12,
189    X86::R13, X86::R14, X86::R15, X86::RBP, 0
190  };
191
192  static const unsigned CalleeSavedRegsWin64[] = {
193    X86::RBX,   X86::RBP,   X86::RDI,   X86::RSI,
194    X86::R12,   X86::R13,   X86::R14,   X86::R15,
195    X86::XMM6,  X86::XMM7,  X86::XMM8,  X86::XMM9,
196    X86::XMM10, X86::XMM11, X86::XMM12, X86::XMM13,
197    X86::XMM14, X86::XMM15, 0
198  };
199
200  if (Is64Bit) {
201    if (IsWin64)
202      return CalleeSavedRegsWin64;
203    else
204      return (callsEHReturn ? CalleeSavedRegs64EHRet : CalleeSavedRegs64Bit);
205  } else {
206    return (callsEHReturn ? CalleeSavedRegs32EHRet : CalleeSavedRegs32Bit);
207  }
208}
209
210const TargetRegisterClass* const*
211X86RegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
212  bool callsEHReturn = false;
213
214  if (MF) {
215    const MachineFrameInfo *MFI = MF->getFrameInfo();
216    const MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
217    callsEHReturn = (MMI ? MMI->callsEHReturn() : false);
218  }
219
220  static const TargetRegisterClass * const CalleeSavedRegClasses32Bit[] = {
221    &X86::GR32RegClass, &X86::GR32RegClass,
222    &X86::GR32RegClass, &X86::GR32RegClass,  0
223  };
224  static const TargetRegisterClass * const CalleeSavedRegClasses32EHRet[] = {
225    &X86::GR32RegClass, &X86::GR32RegClass,
226    &X86::GR32RegClass, &X86::GR32RegClass,
227    &X86::GR32RegClass, &X86::GR32RegClass,  0
228  };
229  static const TargetRegisterClass * const CalleeSavedRegClasses64Bit[] = {
230    &X86::GR64RegClass, &X86::GR64RegClass,
231    &X86::GR64RegClass, &X86::GR64RegClass,
232    &X86::GR64RegClass, &X86::GR64RegClass, 0
233  };
234  static const TargetRegisterClass * const CalleeSavedRegClasses64EHRet[] = {
235    &X86::GR64RegClass, &X86::GR64RegClass,
236    &X86::GR64RegClass, &X86::GR64RegClass,
237    &X86::GR64RegClass, &X86::GR64RegClass,
238    &X86::GR64RegClass, &X86::GR64RegClass, 0
239  };
240  static const TargetRegisterClass * const CalleeSavedRegClassesWin64[] = {
241    &X86::GR64RegClass,  &X86::GR64RegClass,
242    &X86::GR64RegClass,  &X86::GR64RegClass,
243    &X86::GR64RegClass,  &X86::GR64RegClass,
244    &X86::GR64RegClass,  &X86::GR64RegClass,
245    &X86::VR128RegClass, &X86::VR128RegClass,
246    &X86::VR128RegClass, &X86::VR128RegClass,
247    &X86::VR128RegClass, &X86::VR128RegClass,
248    &X86::VR128RegClass, &X86::VR128RegClass,
249    &X86::VR128RegClass, &X86::VR128RegClass, 0
250  };
251
252  if (Is64Bit) {
253    if (IsWin64)
254      return CalleeSavedRegClassesWin64;
255    else
256      return (callsEHReturn ?
257              CalleeSavedRegClasses64EHRet : CalleeSavedRegClasses64Bit);
258  } else {
259    return (callsEHReturn ?
260            CalleeSavedRegClasses32EHRet : CalleeSavedRegClasses32Bit);
261  }
262}
263
264BitVector X86RegisterInfo::getReservedRegs(const MachineFunction &MF) const {
265  BitVector Reserved(getNumRegs());
266  // Set the stack-pointer register and its aliases as reserved.
267  Reserved.set(X86::RSP);
268  Reserved.set(X86::ESP);
269  Reserved.set(X86::SP);
270  Reserved.set(X86::SPL);
271  // Set the frame-pointer register and its aliases as reserved if needed.
272  if (hasFP(MF)) {
273    Reserved.set(X86::RBP);
274    Reserved.set(X86::EBP);
275    Reserved.set(X86::BP);
276    Reserved.set(X86::BPL);
277  }
278  // Mark the x87 stack registers as reserved, since they don't
279  // behave normally with respect to liveness. We don't fully
280  // model the effects of x87 stack pushes and pops after
281  // stackification.
282  Reserved.set(X86::ST0);
283  Reserved.set(X86::ST1);
284  Reserved.set(X86::ST2);
285  Reserved.set(X86::ST3);
286  Reserved.set(X86::ST4);
287  Reserved.set(X86::ST5);
288  Reserved.set(X86::ST6);
289  Reserved.set(X86::ST7);
290  return Reserved;
291}
292
293//===----------------------------------------------------------------------===//
294// Stack Frame Processing methods
295//===----------------------------------------------------------------------===//
296
297static unsigned calculateMaxStackAlignment(const MachineFrameInfo *FFI) {
298  unsigned MaxAlign = 0;
299  for (int i = FFI->getObjectIndexBegin(),
300         e = FFI->getObjectIndexEnd(); i != e; ++i) {
301    if (FFI->isDeadObjectIndex(i))
302      continue;
303    unsigned Align = FFI->getObjectAlignment(i);
304    MaxAlign = std::max(MaxAlign, Align);
305  }
306
307  return MaxAlign;
308}
309
310// hasFP - Return true if the specified function should have a dedicated frame
311// pointer register.  This is true if the function has variable sized allocas or
312// if frame pointer elimination is disabled.
313//
314bool X86RegisterInfo::hasFP(const MachineFunction &MF) const {
315  const MachineFrameInfo *MFI = MF.getFrameInfo();
316  const MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
317
318  return (NoFramePointerElim ||
319          needsStackRealignment(MF) ||
320          MFI->hasVarSizedObjects() ||
321          MFI->isFrameAddressTaken() ||
322          MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
323          (MMI && MMI->callsUnwindInit()));
324}
325
326bool X86RegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
327  const MachineFrameInfo *MFI = MF.getFrameInfo();;
328
329  // FIXME: Currently we don't support stack realignment for functions with
330  // variable-sized allocas
331  return (RealignStack &&
332          (MFI->getMaxAlignment() > StackAlign &&
333           !MFI->hasVarSizedObjects()));
334}
335
336bool X86RegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
337  return !MF.getFrameInfo()->hasVarSizedObjects();
338}
339
340int
341X86RegisterInfo::getFrameIndexOffset(MachineFunction &MF, int FI) const {
342  int Offset = MF.getFrameInfo()->getObjectOffset(FI) + SlotSize;
343  uint64_t StackSize = MF.getFrameInfo()->getStackSize();
344
345  if (needsStackRealignment(MF)) {
346    if (FI < 0)
347      // Skip the saved EBP
348      Offset += SlotSize;
349    else {
350      unsigned Align = MF.getFrameInfo()->getObjectAlignment(FI);
351      assert( (-(Offset + StackSize)) % Align == 0);
352      return Offset + StackSize;
353    }
354
355    // FIXME: Support tail calls
356  } else {
357    if (!hasFP(MF))
358      return Offset + StackSize;
359
360    // Skip the saved EBP
361    Offset += SlotSize;
362
363    // Skip the RETADDR move area
364    X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
365    int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
366    if (TailCallReturnAddrDelta < 0) Offset -= TailCallReturnAddrDelta;
367  }
368
369  return Offset;
370}
371
372void X86RegisterInfo::
373eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
374                              MachineBasicBlock::iterator I) const {
375  if (!hasReservedCallFrame(MF)) {
376    // If the stack pointer can be changed after prologue, turn the
377    // adjcallstackup instruction into a 'sub ESP, <amt>' and the
378    // adjcallstackdown instruction into 'add ESP, <amt>'
379    // TODO: consider using push / pop instead of sub + store / add
380    MachineInstr *Old = I;
381    uint64_t Amount = Old->getOperand(0).getImm();
382    if (Amount != 0) {
383      // We need to keep the stack aligned properly.  To do this, we round the
384      // amount of space needed for the outgoing arguments up to the next
385      // alignment boundary.
386      Amount = (Amount+StackAlign-1)/StackAlign*StackAlign;
387
388      MachineInstr *New = 0;
389      if (Old->getOpcode() == getCallFrameSetupOpcode()) {
390        New = BuildMI(MF, TII.get(Is64Bit ? X86::SUB64ri32 : X86::SUB32ri),
391                      StackPtr).addReg(StackPtr).addImm(Amount);
392      } else {
393        assert(Old->getOpcode() == getCallFrameDestroyOpcode());
394        // factor out the amount the callee already popped.
395        uint64_t CalleeAmt = Old->getOperand(1).getImm();
396        Amount -= CalleeAmt;
397        if (Amount) {
398          unsigned Opc = (Amount < 128) ?
399            (Is64Bit ? X86::ADD64ri8 : X86::ADD32ri8) :
400            (Is64Bit ? X86::ADD64ri32 : X86::ADD32ri);
401          New = BuildMI(MF, TII.get(Opc), StackPtr)
402            .addReg(StackPtr).addImm(Amount);
403        }
404      }
405
406      // The EFLAGS implicit def is dead.
407      New->getOperand(3).setIsDead();
408
409      // Replace the pseudo instruction with a new instruction...
410      if (New) MBB.insert(I, New);
411    }
412  } else if (I->getOpcode() == getCallFrameDestroyOpcode()) {
413    // If we are performing frame pointer elimination and if the callee pops
414    // something off the stack pointer, add it back.  We do this until we have
415    // more advanced stack pointer tracking ability.
416    if (uint64_t CalleeAmt = I->getOperand(1).getImm()) {
417      unsigned Opc = (CalleeAmt < 128) ?
418        (Is64Bit ? X86::SUB64ri8 : X86::SUB32ri8) :
419        (Is64Bit ? X86::SUB64ri32 : X86::SUB32ri);
420      MachineInstr *New =
421        BuildMI(MF, TII.get(Opc), StackPtr).addReg(StackPtr).addImm(CalleeAmt);
422      // The EFLAGS implicit def is dead.
423      New->getOperand(3).setIsDead();
424
425      MBB.insert(I, New);
426    }
427  }
428
429  MBB.erase(I);
430}
431
432void X86RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
433                                          int SPAdj, RegScavenger *RS) const{
434  assert(SPAdj == 0 && "Unexpected");
435
436  unsigned i = 0;
437  MachineInstr &MI = *II;
438  MachineFunction &MF = *MI.getParent()->getParent();
439  while (!MI.getOperand(i).isFI()) {
440    ++i;
441    assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
442  }
443
444  int FrameIndex = MI.getOperand(i).getIndex();
445
446  unsigned BasePtr;
447  if (needsStackRealignment(MF))
448    BasePtr = (FrameIndex < 0 ? FramePtr : StackPtr);
449  else
450    BasePtr = (hasFP(MF) ? FramePtr : StackPtr);
451
452  // This must be part of a four operand memory reference.  Replace the
453  // FrameIndex with base register with EBP.  Add an offset to the offset.
454  MI.getOperand(i).ChangeToRegister(BasePtr, false);
455
456  // Now add the frame object offset to the offset from EBP. Offset is a
457  // 32-bit integer.
458  int Offset = getFrameIndexOffset(MF, FrameIndex) +
459    (int)(MI.getOperand(i+3).getImm());
460
461  MI.getOperand(i+3).ChangeToImmediate(Offset);
462}
463
464void
465X86RegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
466                                                      RegScavenger *RS) const {
467  MachineFrameInfo *FFI = MF.getFrameInfo();
468
469  // Calculate and set max stack object alignment early, so we can decide
470  // whether we will need stack realignment (and thus FP).
471  unsigned MaxAlign = std::max(FFI->getMaxAlignment(),
472                               calculateMaxStackAlignment(FFI));
473
474  FFI->setMaxAlignment(MaxAlign);
475}
476
477void
478X86RegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF) const{
479  X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
480  int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
481  if (TailCallReturnAddrDelta < 0) {
482    // create RETURNADDR area
483    //   arg
484    //   arg
485    //   RETADDR
486    //   { ...
487    //     RETADDR area
488    //     ...
489    //   }
490    //   [EBP]
491    MF.getFrameInfo()->
492      CreateFixedObject(-TailCallReturnAddrDelta,
493                        (-1*SlotSize)+TailCallReturnAddrDelta);
494  }
495  if (hasFP(MF)) {
496    assert((TailCallReturnAddrDelta <= 0) &&
497           "The Delta should always be zero or negative");
498    // Create a frame entry for the EBP register that must be saved.
499    int FrameIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize,
500                                                        (int)SlotSize * -2+
501                                                       TailCallReturnAddrDelta);
502    assert(FrameIdx == MF.getFrameInfo()->getObjectIndexBegin() &&
503           "Slot for EBP register must be last in order to be found!");
504  }
505}
506
507/// emitSPUpdate - Emit a series of instructions to increment / decrement the
508/// stack pointer by a constant value.
509static
510void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
511                  unsigned StackPtr, int64_t NumBytes, bool Is64Bit,
512                  const TargetInstrInfo &TII) {
513  bool isSub = NumBytes < 0;
514  uint64_t Offset = isSub ? -NumBytes : NumBytes;
515  unsigned Opc = isSub
516    ? ((Offset < 128) ?
517       (Is64Bit ? X86::SUB64ri8 : X86::SUB32ri8) :
518       (Is64Bit ? X86::SUB64ri32 : X86::SUB32ri))
519    : ((Offset < 128) ?
520       (Is64Bit ? X86::ADD64ri8 : X86::ADD32ri8) :
521       (Is64Bit ? X86::ADD64ri32 : X86::ADD32ri));
522  uint64_t Chunk = (1LL << 31) - 1;
523
524  while (Offset) {
525    uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
526    MachineInstr *MI =
527      BuildMI(MBB, MBBI, TII.get(Opc), StackPtr).addReg(StackPtr).addImm(ThisVal);
528    // The EFLAGS implicit def is dead.
529    MI->getOperand(3).setIsDead();
530    Offset -= ThisVal;
531  }
532}
533
534// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
535static
536void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
537                      unsigned StackPtr, uint64_t *NumBytes = NULL) {
538  if (MBBI == MBB.begin()) return;
539
540  MachineBasicBlock::iterator PI = prior(MBBI);
541  unsigned Opc = PI->getOpcode();
542  if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
543       Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
544      PI->getOperand(0).getReg() == StackPtr) {
545    if (NumBytes)
546      *NumBytes += PI->getOperand(2).getImm();
547    MBB.erase(PI);
548  } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
549              Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
550             PI->getOperand(0).getReg() == StackPtr) {
551    if (NumBytes)
552      *NumBytes -= PI->getOperand(2).getImm();
553    MBB.erase(PI);
554  }
555}
556
557// mergeSPUpdatesUp - Merge two stack-manipulating instructions lower iterator.
558static
559void mergeSPUpdatesDown(MachineBasicBlock &MBB,
560                        MachineBasicBlock::iterator &MBBI,
561                        unsigned StackPtr, uint64_t *NumBytes = NULL) {
562  return;
563
564  if (MBBI == MBB.end()) return;
565
566  MachineBasicBlock::iterator NI = next(MBBI);
567  if (NI == MBB.end()) return;
568
569  unsigned Opc = NI->getOpcode();
570  if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
571       Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
572      NI->getOperand(0).getReg() == StackPtr) {
573    if (NumBytes)
574      *NumBytes -= NI->getOperand(2).getImm();
575    MBB.erase(NI);
576    MBBI = NI;
577  } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
578              Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
579             NI->getOperand(0).getReg() == StackPtr) {
580    if (NumBytes)
581      *NumBytes += NI->getOperand(2).getImm();
582    MBB.erase(NI);
583    MBBI = NI;
584  }
585}
586
587/// mergeSPUpdates - Checks the instruction before/after the passed
588/// instruction. If it is an ADD/SUB instruction it is deleted
589/// argument and the stack adjustment is returned as a positive value for ADD
590/// and a negative for SUB.
591static int mergeSPUpdates(MachineBasicBlock &MBB,
592                           MachineBasicBlock::iterator &MBBI,
593                           unsigned StackPtr,
594                           bool doMergeWithPrevious) {
595
596  if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
597      (!doMergeWithPrevious && MBBI == MBB.end()))
598    return 0;
599
600  int Offset = 0;
601
602  MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
603  MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : next(MBBI);
604  unsigned Opc = PI->getOpcode();
605  if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
606       Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
607      PI->getOperand(0).getReg() == StackPtr){
608    Offset += PI->getOperand(2).getImm();
609    MBB.erase(PI);
610    if (!doMergeWithPrevious) MBBI = NI;
611  } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
612              Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
613             PI->getOperand(0).getReg() == StackPtr) {
614    Offset -= PI->getOperand(2).getImm();
615    MBB.erase(PI);
616    if (!doMergeWithPrevious) MBBI = NI;
617  }
618
619  return Offset;
620}
621
622void X86RegisterInfo::emitFrameMoves(MachineFunction &MF,
623                                     unsigned FrameLabelId,
624                                     unsigned ReadyLabelId) const {
625  MachineFrameInfo *MFI = MF.getFrameInfo();
626  MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
627  if (!MMI)
628    return;
629
630  uint64_t StackSize = MFI->getStackSize();
631  std::vector<MachineMove> &Moves = MMI->getFrameMoves();
632  const TargetData *TD = MF.getTarget().getTargetData();
633
634  // Calculate amount of bytes used for return address storing
635  int stackGrowth =
636    (MF.getTarget().getFrameInfo()->getStackGrowthDirection() ==
637     TargetFrameInfo::StackGrowsUp ?
638     TD->getPointerSize() : -TD->getPointerSize());
639
640  if (StackSize) {
641    // Show update of SP.
642    if (hasFP(MF)) {
643      // Adjust SP
644      MachineLocation SPDst(MachineLocation::VirtualFP);
645      MachineLocation SPSrc(MachineLocation::VirtualFP, 2*stackGrowth);
646      Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
647    } else {
648      MachineLocation SPDst(MachineLocation::VirtualFP);
649      MachineLocation SPSrc(MachineLocation::VirtualFP,
650                            -StackSize+stackGrowth);
651      Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
652    }
653  } else {
654    //FIXME: Verify & implement for FP
655    MachineLocation SPDst(StackPtr);
656    MachineLocation SPSrc(StackPtr, stackGrowth);
657    Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
658  }
659
660  // Add callee saved registers to move list.
661  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
662
663  // FIXME: This is dirty hack. The code itself is pretty mess right now.
664  // It should be rewritten from scratch and generalized sometimes.
665
666  // Determine maximum offset (minumum due to stack growth)
667  int64_t MaxOffset = 0;
668  for (unsigned I = 0, E = CSI.size(); I!=E; ++I)
669    MaxOffset = std::min(MaxOffset,
670                         MFI->getObjectOffset(CSI[I].getFrameIdx()));
671
672  // Calculate offsets
673  int64_t saveAreaOffset = (hasFP(MF) ? 3 : 2)*stackGrowth;
674  for (unsigned I = 0, E = CSI.size(); I!=E; ++I) {
675    int64_t Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
676    unsigned Reg = CSI[I].getReg();
677    Offset = (MaxOffset-Offset+saveAreaOffset);
678    MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
679    MachineLocation CSSrc(Reg);
680    Moves.push_back(MachineMove(FrameLabelId, CSDst, CSSrc));
681  }
682
683  if (hasFP(MF)) {
684    // Save FP
685    MachineLocation FPDst(MachineLocation::VirtualFP, 2*stackGrowth);
686    MachineLocation FPSrc(FramePtr);
687    Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc));
688  }
689
690  MachineLocation FPDst(hasFP(MF) ? FramePtr : StackPtr);
691  MachineLocation FPSrc(MachineLocation::VirtualFP);
692  Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc));
693}
694
695
696void X86RegisterInfo::emitPrologue(MachineFunction &MF) const {
697  MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
698  MachineFrameInfo *MFI = MF.getFrameInfo();
699  const Function* Fn = MF.getFunction();
700  const X86Subtarget* Subtarget = &MF.getTarget().getSubtarget<X86Subtarget>();
701  MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
702  X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
703  MachineBasicBlock::iterator MBBI = MBB.begin();
704  bool needsFrameMoves = (MMI && MMI->hasDebugInfo()) ||
705                          !Fn->doesNotThrow() ||
706                          UnwindTablesMandatory;
707  // Prepare for frame info.
708  unsigned FrameLabelId = 0;
709
710  // Get the number of bytes to allocate from the FrameInfo.
711  uint64_t StackSize = MFI->getStackSize();
712  // Get desired stack alignment
713  uint64_t MaxAlign  = MFI->getMaxAlignment();
714
715  // Add RETADDR move area to callee saved frame size.
716  int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
717  if (TailCallReturnAddrDelta < 0)
718    X86FI->setCalleeSavedFrameSize(
719          X86FI->getCalleeSavedFrameSize() +(-TailCallReturnAddrDelta));
720
721  // Insert stack pointer adjustment for later moving of return addr.  Only
722  // applies to tail call optimized functions where the callee argument stack
723  // size is bigger than the callers.
724  if (TailCallReturnAddrDelta < 0) {
725    MachineInstr *MI =
726      BuildMI(MBB, MBBI, TII.get(Is64Bit? X86::SUB64ri32 : X86::SUB32ri),
727              StackPtr).addReg(StackPtr).addImm(-TailCallReturnAddrDelta);
728    // The EFLAGS implicit def is dead.
729    MI->getOperand(3).setIsDead();
730  }
731
732  uint64_t NumBytes = 0;
733  if (hasFP(MF)) {
734    // Calculate required stack adjustment
735    uint64_t FrameSize = StackSize - SlotSize;
736    if (needsStackRealignment(MF))
737      FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
738
739    NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
740
741    // Get the offset of the stack slot for the EBP register... which is
742    // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
743    // Update the frame offset adjustment.
744    MFI->setOffsetAdjustment(-NumBytes);
745
746    // Save EBP into the appropriate stack slot...
747    BuildMI(MBB, MBBI, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
748      .addReg(FramePtr, /*isDef=*/false, /*isImp=*/false, /*isKill=*/true);
749
750    if (needsFrameMoves) {
751      // Mark effective beginning of when frame pointer becomes valid.
752      FrameLabelId = MMI->NextLabelID();
753      BuildMI(MBB, MBBI, TII.get(X86::DBG_LABEL)).addImm(FrameLabelId);
754    }
755
756    // Update EBP with the new base value...
757    BuildMI(MBB, MBBI, TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
758      .addReg(StackPtr);
759
760    // Mark the FramePtr as live-in in every block except the entry.
761    for (MachineFunction::iterator I = next(MF.begin()), E = MF.end();
762         I != E; ++I)
763      I->addLiveIn(FramePtr);
764
765    // Realign stack
766    if (needsStackRealignment(MF)) {
767      MachineInstr *MI =
768        BuildMI(MBB, MBBI,
769                TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
770                StackPtr).addReg(StackPtr).addImm(-MaxAlign);
771      // The EFLAGS implicit def is dead.
772      MI->getOperand(3).setIsDead();
773    }
774  } else
775    NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
776
777  unsigned ReadyLabelId = 0;
778  if (needsFrameMoves) {
779    // Mark effective beginning of when frame pointer is ready.
780    ReadyLabelId = MMI->NextLabelID();
781    BuildMI(MBB, MBBI, TII.get(X86::DBG_LABEL)).addImm(ReadyLabelId);
782  }
783
784  // Skip the callee-saved push instructions.
785  while (MBBI != MBB.end() &&
786         (MBBI->getOpcode() == X86::PUSH32r ||
787          MBBI->getOpcode() == X86::PUSH64r))
788    ++MBBI;
789
790  if (NumBytes) {   // adjust stack pointer: ESP -= numbytes
791    if (NumBytes >= 4096 && Subtarget->isTargetCygMing()) {
792      // Check, whether EAX is livein for this function
793      bool isEAXAlive = false;
794      for (MachineRegisterInfo::livein_iterator
795           II = MF.getRegInfo().livein_begin(),
796           EE = MF.getRegInfo().livein_end(); (II != EE) && !isEAXAlive; ++II) {
797        unsigned Reg = II->first;
798        isEAXAlive = (Reg == X86::EAX || Reg == X86::AX ||
799                      Reg == X86::AH || Reg == X86::AL);
800      }
801
802      // Function prologue calls _alloca to probe the stack when allocating
803      // more than 4k bytes in one go. Touching the stack at 4K increments is
804      // necessary to ensure that the guard pages used by the OS virtual memory
805      // manager are allocated in correct sequence.
806      if (!isEAXAlive) {
807        BuildMI(MBB, MBBI, TII.get(X86::MOV32ri), X86::EAX).addImm(NumBytes);
808        BuildMI(MBB, MBBI, TII.get(X86::CALLpcrel32))
809          .addExternalSymbol("_alloca");
810      } else {
811        // Save EAX
812        BuildMI(MBB, MBBI, TII.get(X86::PUSH32r))
813          .addReg(X86::EAX, /*isDef=*/false, /*isImp=*/false, /*isKill=*/true);
814        // Allocate NumBytes-4 bytes on stack. We'll also use 4 already
815        // allocated bytes for EAX.
816        BuildMI(MBB, MBBI, TII.get(X86::MOV32ri), X86::EAX).addImm(NumBytes-4);
817        BuildMI(MBB, MBBI, TII.get(X86::CALLpcrel32))
818          .addExternalSymbol("_alloca");
819        // Restore EAX
820        MachineInstr *MI = addRegOffset(BuildMI(MF, TII.get(X86::MOV32rm),X86::EAX),
821                                        StackPtr, false, NumBytes-4);
822        MBB.insert(MBBI, MI);
823      }
824    } else {
825      // If there is an SUB32ri of ESP immediately before this instruction,
826      // merge the two. This can be the case when tail call elimination is
827      // enabled and the callee has more arguments then the caller.
828      NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
829      // If there is an ADD32ri or SUB32ri of ESP immediately after this
830      // instruction, merge the two instructions.
831      mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
832
833      if (NumBytes)
834        emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, TII);
835    }
836  }
837
838  if (needsFrameMoves)
839    emitFrameMoves(MF, FrameLabelId, ReadyLabelId);
840}
841
842void X86RegisterInfo::emitEpilogue(MachineFunction &MF,
843                                   MachineBasicBlock &MBB) const {
844  const MachineFrameInfo *MFI = MF.getFrameInfo();
845  X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
846  MachineBasicBlock::iterator MBBI = prior(MBB.end());
847  unsigned RetOpcode = MBBI->getOpcode();
848
849  switch (RetOpcode) {
850  case X86::RET:
851  case X86::RETI:
852  case X86::TCRETURNdi:
853  case X86::TCRETURNri:
854  case X86::TCRETURNri64:
855  case X86::TCRETURNdi64:
856  case X86::EH_RETURN:
857  case X86::EH_RETURN64:
858  case X86::TAILJMPd:
859  case X86::TAILJMPr:
860  case X86::TAILJMPm: break;  // These are ok
861  default:
862    assert(0 && "Can only insert epilog into returning blocks");
863  }
864
865  // Get the number of bytes to allocate from the FrameInfo
866  uint64_t StackSize = MFI->getStackSize();
867  uint64_t MaxAlign  = MFI->getMaxAlignment();
868  unsigned CSSize = X86FI->getCalleeSavedFrameSize();
869  uint64_t NumBytes = 0;
870
871  if (hasFP(MF)) {
872    // Calculate required stack adjustment
873    uint64_t FrameSize = StackSize - SlotSize;
874    if (needsStackRealignment(MF))
875      FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
876
877    NumBytes = FrameSize - CSSize;
878
879    // pop EBP.
880    BuildMI(MBB, MBBI, TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
881  } else
882    NumBytes = StackSize - CSSize;
883
884  // Skip the callee-saved pop instructions.
885  MachineBasicBlock::iterator LastCSPop = MBBI;
886  while (MBBI != MBB.begin()) {
887    MachineBasicBlock::iterator PI = prior(MBBI);
888    unsigned Opc = PI->getOpcode();
889    if (Opc != X86::POP32r && Opc != X86::POP64r &&
890        !PI->getDesc().isTerminator())
891      break;
892    --MBBI;
893  }
894
895  // If there is an ADD32ri or SUB32ri of ESP immediately before this
896  // instruction, merge the two instructions.
897  if (NumBytes || MFI->hasVarSizedObjects())
898    mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
899
900  // If dynamic alloca is used, then reset esp to point to the last callee-saved
901  // slot before popping them off! Same applies for the case, when stack was
902  // realigned
903  if (needsStackRealignment(MF)) {
904    // We cannot use LEA here, because stack pointer was realigned. We need to
905    // deallocate local frame back
906    if (CSSize) {
907      emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII);
908      MBBI = prior(LastCSPop);
909    }
910
911    BuildMI(MBB, MBBI,
912            TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
913            StackPtr).addReg(FramePtr);
914  } else if (MFI->hasVarSizedObjects()) {
915    if (CSSize) {
916      unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
917      MachineInstr *MI = addRegOffset(BuildMI(MF, TII.get(Opc), StackPtr),
918                                      FramePtr, false, -CSSize);
919      MBB.insert(MBBI, MI);
920    } else
921      BuildMI(MBB, MBBI, TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
922              StackPtr).addReg(FramePtr);
923
924  } else {
925    // adjust stack pointer back: ESP += numbytes
926    if (NumBytes)
927      emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII);
928  }
929
930  // We're returning from function via eh_return.
931  if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
932    MBBI = prior(MBB.end());
933    MachineOperand &DestAddr  = MBBI->getOperand(0);
934    assert(DestAddr.isReg() && "Offset should be in register!");
935    BuildMI(MBB, MBBI,
936            TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
937            StackPtr).addReg(DestAddr.getReg());
938  // Tail call return: adjust the stack pointer and jump to callee
939  } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
940             RetOpcode== X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64) {
941    MBBI = prior(MBB.end());
942    MachineOperand &JumpTarget = MBBI->getOperand(0);
943    MachineOperand &StackAdjust = MBBI->getOperand(1);
944    assert(StackAdjust.isImm() && "Expecting immediate value.");
945
946    // Adjust stack pointer.
947    int StackAdj = StackAdjust.getImm();
948    int MaxTCDelta = X86FI->getTCReturnAddrDelta();
949    int Offset = 0;
950    assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
951    // Incoporate the retaddr area.
952    Offset = StackAdj-MaxTCDelta;
953    assert(Offset >= 0 && "Offset should never be negative");
954    if (Offset) {
955      // Check for possible merge with preceeding ADD instruction.
956      Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
957      emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII);
958    }
959    // Jump to label or value in register.
960    if (RetOpcode == X86::TCRETURNdi|| RetOpcode == X86::TCRETURNdi64)
961      BuildMI(MBB, MBBI, TII.get(X86::TAILJMPd)).
962        addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
963    else if (RetOpcode== X86::TCRETURNri64) {
964      BuildMI(MBB, MBBI, TII.get(X86::TAILJMPr64), JumpTarget.getReg());
965    } else
966       BuildMI(MBB, MBBI, TII.get(X86::TAILJMPr), JumpTarget.getReg());
967    // Delete the pseudo instruction TCRETURN.
968    MBB.erase(MBBI);
969  } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
970             (X86FI->getTCReturnAddrDelta() < 0)) {
971    // Add the return addr area delta back since we are not tail calling.
972    int delta = -1*X86FI->getTCReturnAddrDelta();
973    MBBI = prior(MBB.end());
974    // Check for possible merge with preceeding ADD instruction.
975    delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
976    emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII);
977  }
978}
979
980unsigned X86RegisterInfo::getRARegister() const {
981  if (Is64Bit)
982    return X86::RIP;  // Should have dwarf #16
983  else
984    return X86::EIP;  // Should have dwarf #8
985}
986
987unsigned X86RegisterInfo::getFrameRegister(MachineFunction &MF) const {
988  return hasFP(MF) ? FramePtr : StackPtr;
989}
990
991void X86RegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves)
992                                                                         const {
993  // Calculate amount of bytes used for return address storing
994  int stackGrowth = (Is64Bit ? -8 : -4);
995
996  // Initial state of the frame pointer is esp+4.
997  MachineLocation Dst(MachineLocation::VirtualFP);
998  MachineLocation Src(StackPtr, stackGrowth);
999  Moves.push_back(MachineMove(0, Dst, Src));
1000
1001  // Add return address to move list
1002  MachineLocation CSDst(StackPtr, stackGrowth);
1003  MachineLocation CSSrc(getRARegister());
1004  Moves.push_back(MachineMove(0, CSDst, CSSrc));
1005}
1006
1007unsigned X86RegisterInfo::getEHExceptionRegister() const {
1008  assert(0 && "What is the exception register");
1009  return 0;
1010}
1011
1012unsigned X86RegisterInfo::getEHHandlerRegister() const {
1013  assert(0 && "What is the exception handler register");
1014  return 0;
1015}
1016
1017namespace llvm {
1018unsigned getX86SubSuperRegister(unsigned Reg, MVT VT, bool High) {
1019  switch (VT.getSimpleVT()) {
1020  default: return Reg;
1021  case MVT::i8:
1022    if (High) {
1023      switch (Reg) {
1024      default: return 0;
1025      case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1026        return X86::AH;
1027      case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1028        return X86::DH;
1029      case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1030        return X86::CH;
1031      case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1032        return X86::BH;
1033      }
1034    } else {
1035      switch (Reg) {
1036      default: return 0;
1037      case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1038        return X86::AL;
1039      case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1040        return X86::DL;
1041      case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1042        return X86::CL;
1043      case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1044        return X86::BL;
1045      case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
1046        return X86::SIL;
1047      case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
1048        return X86::DIL;
1049      case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
1050        return X86::BPL;
1051      case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
1052        return X86::SPL;
1053      case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
1054        return X86::R8B;
1055      case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
1056        return X86::R9B;
1057      case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
1058        return X86::R10B;
1059      case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
1060        return X86::R11B;
1061      case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
1062        return X86::R12B;
1063      case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
1064        return X86::R13B;
1065      case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
1066        return X86::R14B;
1067      case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
1068        return X86::R15B;
1069      }
1070    }
1071  case MVT::i16:
1072    switch (Reg) {
1073    default: return Reg;
1074    case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1075      return X86::AX;
1076    case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1077      return X86::DX;
1078    case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1079      return X86::CX;
1080    case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1081      return X86::BX;
1082    case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
1083      return X86::SI;
1084    case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
1085      return X86::DI;
1086    case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
1087      return X86::BP;
1088    case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
1089      return X86::SP;
1090    case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
1091      return X86::R8W;
1092    case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
1093      return X86::R9W;
1094    case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
1095      return X86::R10W;
1096    case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
1097      return X86::R11W;
1098    case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
1099      return X86::R12W;
1100    case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
1101      return X86::R13W;
1102    case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
1103      return X86::R14W;
1104    case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
1105      return X86::R15W;
1106    }
1107  case MVT::i32:
1108    switch (Reg) {
1109    default: return Reg;
1110    case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1111      return X86::EAX;
1112    case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1113      return X86::EDX;
1114    case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1115      return X86::ECX;
1116    case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1117      return X86::EBX;
1118    case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
1119      return X86::ESI;
1120    case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
1121      return X86::EDI;
1122    case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
1123      return X86::EBP;
1124    case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
1125      return X86::ESP;
1126    case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
1127      return X86::R8D;
1128    case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
1129      return X86::R9D;
1130    case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
1131      return X86::R10D;
1132    case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
1133      return X86::R11D;
1134    case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
1135      return X86::R12D;
1136    case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
1137      return X86::R13D;
1138    case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
1139      return X86::R14D;
1140    case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
1141      return X86::R15D;
1142    }
1143  case MVT::i64:
1144    switch (Reg) {
1145    default: return Reg;
1146    case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1147      return X86::RAX;
1148    case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1149      return X86::RDX;
1150    case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1151      return X86::RCX;
1152    case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1153      return X86::RBX;
1154    case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
1155      return X86::RSI;
1156    case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
1157      return X86::RDI;
1158    case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
1159      return X86::RBP;
1160    case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
1161      return X86::RSP;
1162    case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
1163      return X86::R8;
1164    case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
1165      return X86::R9;
1166    case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
1167      return X86::R10;
1168    case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
1169      return X86::R11;
1170    case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
1171      return X86::R12;
1172    case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
1173      return X86::R13;
1174    case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
1175      return X86::R14;
1176    case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
1177      return X86::R15;
1178    }
1179  }
1180
1181  return Reg;
1182}
1183}
1184
1185#include "X86GenRegisterInfo.inc"
1186
1187namespace {
1188  struct VISIBILITY_HIDDEN MSAC : public MachineFunctionPass {
1189    static char ID;
1190    MSAC() : MachineFunctionPass(&ID) {}
1191
1192    virtual bool runOnMachineFunction(MachineFunction &MF) {
1193      MachineFrameInfo *FFI = MF.getFrameInfo();
1194      MachineRegisterInfo &RI = MF.getRegInfo();
1195
1196      // Calculate max stack alignment of all already allocated stack objects.
1197      unsigned MaxAlign = calculateMaxStackAlignment(FFI);
1198
1199      // Be over-conservative: scan over all vreg defs and find, whether vector
1200      // registers are used. If yes - there is probability, that vector register
1201      // will be spilled and thus stack needs to be aligned properly.
1202      for (unsigned RegNum = TargetRegisterInfo::FirstVirtualRegister;
1203           RegNum < RI.getLastVirtReg(); ++RegNum)
1204        MaxAlign = std::max(MaxAlign, RI.getRegClass(RegNum)->getAlignment());
1205
1206      FFI->setMaxAlignment(MaxAlign);
1207
1208      return false;
1209    }
1210
1211    virtual const char *getPassName() const {
1212      return "X86 Maximal Stack Alignment Calculator";
1213    }
1214  };
1215
1216  char MSAC::ID = 0;
1217}
1218
1219FunctionPass*
1220llvm::createX86MaxStackAlignmentCalculatorPass() { return new MSAC(); }
1221