Move copyRegToReg from MRegisterInfo to TargetInstrInfo. This is part of the
[oota-llvm.git] / lib / Target / ARM / ARMRegisterInfo.cpp
1 //===- ARMRegisterInfo.cpp - ARM 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 ARM implementation of the MRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARM.h"
15 #include "ARMAddressingModes.h"
16 #include "ARMInstrInfo.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "ARMRegisterInfo.h"
19 #include "ARMSubtarget.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineLocation.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 static cl::opt<bool> ThumbRegScavenging("enable-thumb-reg-scavenging",
40                                cl::Hidden,
41                                cl::desc("Enable register scavenging on Thumb"));
42
43 unsigned ARMRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
44   using namespace ARM;
45   switch (RegEnum) {
46   case R0:  case S0:  case D0:  return 0;
47   case R1:  case S1:  case D1:  return 1;
48   case R2:  case S2:  case D2:  return 2;
49   case R3:  case S3:  case D3:  return 3;
50   case R4:  case S4:  case D4:  return 4;
51   case R5:  case S5:  case D5:  return 5;
52   case R6:  case S6:  case D6:  return 6;
53   case R7:  case S7:  case D7:  return 7;
54   case R8:  case S8:  case D8:  return 8;
55   case R9:  case S9:  case D9:  return 9;
56   case R10: case S10: case D10: return 10;
57   case R11: case S11: case D11: return 11;
58   case R12: case S12: case D12: return 12;
59   case SP:  case S13: case D13: return 13;
60   case LR:  case S14: case D14: return 14;
61   case PC:  case S15: case D15: return 15;
62   case S16: return 16;
63   case S17: return 17;
64   case S18: return 18;
65   case S19: return 19;
66   case S20: return 20;
67   case S21: return 21;
68   case S22: return 22;
69   case S23: return 23;
70   case S24: return 24;
71   case S25: return 25;
72   case S26: return 26;
73   case S27: return 27;
74   case S28: return 28;
75   case S29: return 29;
76   case S30: return 30;
77   case S31: return 31;
78   default:
79     assert(0 && "Unknown ARM register!");
80     abort();
81   }
82 }
83
84 ARMRegisterInfo::ARMRegisterInfo(const TargetInstrInfo &tii,
85                                  const ARMSubtarget &sti)
86   : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
87     TII(tii), STI(sti),
88     FramePtr((STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11) {
89 }
90
91 bool ARMRegisterInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
92                                                 MachineBasicBlock::iterator MI,
93                                 const std::vector<CalleeSavedInfo> &CSI) const {
94   MachineFunction &MF = *MBB.getParent();
95   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
96   if (!AFI->isThumbFunction() || CSI.empty())
97     return false;
98
99   MachineInstrBuilder MIB = BuildMI(MBB, MI, TII.get(ARM::tPUSH));
100   for (unsigned i = CSI.size(); i != 0; --i) {
101     unsigned Reg = CSI[i-1].getReg();
102     // Add the callee-saved register as live-in. It's killed at the spill.
103     MBB.addLiveIn(Reg);
104     MIB.addReg(Reg, false/*isDef*/,false/*isImp*/,true/*isKill*/);
105   }
106   return true;
107 }
108
109 bool ARMRegisterInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
110                                                  MachineBasicBlock::iterator MI,
111                                 const std::vector<CalleeSavedInfo> &CSI) const {
112   MachineFunction &MF = *MBB.getParent();
113   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
114   if (!AFI->isThumbFunction() || CSI.empty())
115     return false;
116
117   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
118   MachineInstr *PopMI = new MachineInstr(TII.get(ARM::tPOP));
119   MBB.insert(MI, PopMI);
120   for (unsigned i = CSI.size(); i != 0; --i) {
121     unsigned Reg = CSI[i-1].getReg();
122     if (Reg == ARM::LR) {
123       // Special epilogue for vararg functions. See emitEpilogue
124       if (isVarArg)
125         continue;
126       Reg = ARM::PC;
127       PopMI->setInstrDescriptor(TII.get(ARM::tPOP_RET));
128       MBB.erase(MI);
129     }
130     PopMI->addOperand(MachineOperand::CreateReg(Reg, true));
131   }
132   return true;
133 }
134
135 static inline
136 const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
137   return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
138 }
139
140 static inline
141 const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
142   return MIB.addReg(0);
143 }
144
145 static const MachineInstrBuilder &ARMInstrAddOperand(MachineInstrBuilder &MIB,
146                                                      MachineOperand &MO) {
147   if (MO.isRegister())
148     MIB = MIB.addReg(MO.getReg(), MO.isDef(), MO.isImplicit());
149   else if (MO.isImmediate())
150     MIB = MIB.addImm(MO.getImm());
151   else if (MO.isFrameIndex())
152     MIB = MIB.addFrameIndex(MO.getIndex());
153   else
154     assert(0 && "Unknown operand for ARMInstrAddOperand!");
155
156   return MIB;
157 }
158
159 void ARMRegisterInfo::
160 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
161                     unsigned SrcReg, bool isKill, int FI,
162                     const TargetRegisterClass *RC) const {
163   if (RC == ARM::GPRRegisterClass) {
164     MachineFunction &MF = *MBB.getParent();
165     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
166     if (AFI->isThumbFunction())
167       BuildMI(MBB, I, TII.get(ARM::tSpill)).addReg(SrcReg, false, false, isKill)
168         .addFrameIndex(FI).addImm(0);
169     else
170       AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::STR))
171                      .addReg(SrcReg, false, false, isKill)
172                      .addFrameIndex(FI).addReg(0).addImm(0));
173   } else if (RC == ARM::DPRRegisterClass) {
174     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FSTD))
175                    .addReg(SrcReg, false, false, isKill)
176                    .addFrameIndex(FI).addImm(0));
177   } else {
178     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
179     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FSTS))
180                    .addReg(SrcReg, false, false, isKill)
181                    .addFrameIndex(FI).addImm(0));
182   }
183 }
184
185 void ARMRegisterInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
186                                      bool isKill,
187                                      SmallVectorImpl<MachineOperand> &Addr,
188                                      const TargetRegisterClass *RC,
189                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
190   unsigned Opc = 0;
191   if (RC == ARM::GPRRegisterClass) {
192     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
193     if (AFI->isThumbFunction()) {
194       Opc = Addr[0].isFrameIndex() ? ARM::tSpill : ARM::tSTR;
195       MachineInstrBuilder MIB = 
196         BuildMI(TII.get(Opc)).addReg(SrcReg, false, false, isKill);
197       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
198         MIB = ARMInstrAddOperand(MIB, Addr[i]);
199       NewMIs.push_back(MIB);
200       return;
201     }
202     Opc = ARM::STR;
203   } else if (RC == ARM::DPRRegisterClass) {
204     Opc = ARM::FSTD;
205   } else {
206     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
207     Opc = ARM::FSTS;
208   }
209
210   MachineInstrBuilder MIB = 
211     BuildMI(TII.get(Opc)).addReg(SrcReg, false, false, isKill);
212   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
213     MIB = ARMInstrAddOperand(MIB, Addr[i]);
214   AddDefaultPred(MIB);
215   NewMIs.push_back(MIB);
216   return;
217 }
218
219 void ARMRegisterInfo::
220 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
221                      unsigned DestReg, int FI,
222                      const TargetRegisterClass *RC) const {
223   if (RC == ARM::GPRRegisterClass) {
224     MachineFunction &MF = *MBB.getParent();
225     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
226     if (AFI->isThumbFunction())
227       BuildMI(MBB, I, TII.get(ARM::tRestore), DestReg)
228         .addFrameIndex(FI).addImm(0);
229     else
230       AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::LDR), DestReg)
231                      .addFrameIndex(FI).addReg(0).addImm(0));
232   } else if (RC == ARM::DPRRegisterClass) {
233     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FLDD), DestReg)
234                    .addFrameIndex(FI).addImm(0));
235   } else {
236     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
237     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FLDS), DestReg)
238                    .addFrameIndex(FI).addImm(0));
239   }
240 }
241
242 void ARMRegisterInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
243                                       SmallVectorImpl<MachineOperand> &Addr,
244                                       const TargetRegisterClass *RC,
245                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
246   unsigned Opc = 0;
247   if (RC == ARM::GPRRegisterClass) {
248     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
249     if (AFI->isThumbFunction()) {
250       Opc = Addr[0].isFrameIndex() ? ARM::tRestore : ARM::tLDR;
251       MachineInstrBuilder MIB = BuildMI(TII.get(Opc), DestReg);
252       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
253         MIB = ARMInstrAddOperand(MIB, Addr[i]);
254       NewMIs.push_back(MIB);
255       return;
256     }
257     Opc = ARM::LDR;
258   } else if (RC == ARM::DPRRegisterClass) {
259     Opc = ARM::FLDD;
260   } else {
261     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
262     Opc = ARM::FLDS;
263   }
264
265   MachineInstrBuilder MIB =  BuildMI(TII.get(Opc), DestReg);
266   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
267     MIB = ARMInstrAddOperand(MIB, Addr[i]);
268   AddDefaultPred(MIB);
269   NewMIs.push_back(MIB);
270   return;
271 }
272
273 /// emitLoadConstPool - Emits a load from constpool to materialize the
274 /// specified immediate.
275 static void emitLoadConstPool(MachineBasicBlock &MBB,
276                               MachineBasicBlock::iterator &MBBI,
277                               unsigned DestReg, int Val,
278                               ARMCC::CondCodes Pred, unsigned PredReg,
279                               const TargetInstrInfo &TII, bool isThumb) {
280   MachineFunction &MF = *MBB.getParent();
281   MachineConstantPool *ConstantPool = MF.getConstantPool();
282   Constant *C = ConstantInt::get(Type::Int32Ty, Val);
283   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 2);
284   if (isThumb)
285     BuildMI(MBB, MBBI, TII.get(ARM::tLDRcp), DestReg).addConstantPoolIndex(Idx);
286   else
287     BuildMI(MBB, MBBI, TII.get(ARM::LDRcp), DestReg).addConstantPoolIndex(Idx)
288       .addReg(0).addImm(0).addImm((unsigned)Pred).addReg(PredReg);
289 }
290
291 void ARMRegisterInfo::reMaterialize(MachineBasicBlock &MBB,
292                                     MachineBasicBlock::iterator I,
293                                     unsigned DestReg,
294                                     const MachineInstr *Orig) const {
295   if (Orig->getOpcode() == ARM::MOVi2pieces) {
296     emitLoadConstPool(MBB, I, DestReg,
297                       Orig->getOperand(1).getImm(),
298                       (ARMCC::CondCodes)Orig->getOperand(2).getImm(),
299                       Orig->getOperand(3).getReg(),
300                       TII, false);
301     return;
302   }
303
304   MachineInstr *MI = Orig->clone();
305   MI->getOperand(0).setReg(DestReg);
306   MBB.insert(I, MI);
307 }
308
309 /// isLowRegister - Returns true if the register is low register r0-r7.
310 ///
311 static bool isLowRegister(unsigned Reg) {
312   using namespace ARM;
313   switch (Reg) {
314   case R0:  case R1:  case R2:  case R3:
315   case R4:  case R5:  case R6:  case R7:
316     return true;
317   default:
318     return false;
319   }
320 }
321
322 MachineInstr *ARMRegisterInfo::foldMemoryOperand(MachineInstr *MI,
323                                                  SmallVectorImpl<unsigned> &Ops,
324                                                  int FI) const {
325   if (Ops.size() != 1) return NULL;
326
327   unsigned OpNum = Ops[0];
328   unsigned Opc = MI->getOpcode();
329   MachineInstr *NewMI = NULL;
330   switch (Opc) {
331   default: break;
332   case ARM::MOVr: {
333     if (MI->getOperand(4).getReg() == ARM::CPSR)
334       // If it is updating CPSR, then it cannot be foled.
335       break;
336     unsigned Pred = MI->getOperand(2).getImm();
337     unsigned PredReg = MI->getOperand(3).getReg();
338     if (OpNum == 0) { // move -> store
339       unsigned SrcReg = MI->getOperand(1).getReg();
340       NewMI = BuildMI(TII.get(ARM::STR)).addReg(SrcReg).addFrameIndex(FI)
341         .addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
342     } else {          // move -> load
343       unsigned DstReg = MI->getOperand(0).getReg();
344       NewMI = BuildMI(TII.get(ARM::LDR), DstReg).addFrameIndex(FI).addReg(0)
345         .addImm(0).addImm(Pred).addReg(PredReg);
346     }
347     break;
348   }
349   case ARM::tMOVr: {
350     if (OpNum == 0) { // move -> store
351       unsigned SrcReg = MI->getOperand(1).getReg();
352       if (isPhysicalRegister(SrcReg) && !isLowRegister(SrcReg))
353         // tSpill cannot take a high register operand.
354         break;
355       NewMI = BuildMI(TII.get(ARM::tSpill)).addReg(SrcReg).addFrameIndex(FI)
356         .addImm(0);
357     } else {          // move -> load
358       unsigned DstReg = MI->getOperand(0).getReg();
359       if (isPhysicalRegister(DstReg) && !isLowRegister(DstReg))
360         // tRestore cannot target a high register operand.
361         break;
362       NewMI = BuildMI(TII.get(ARM::tRestore), DstReg).addFrameIndex(FI)
363         .addImm(0);
364     }
365     break;
366   }
367   case ARM::FCPYS: {
368     unsigned Pred = MI->getOperand(2).getImm();
369     unsigned PredReg = MI->getOperand(3).getReg();
370     if (OpNum == 0) { // move -> store
371       unsigned SrcReg = MI->getOperand(1).getReg();
372       NewMI = BuildMI(TII.get(ARM::FSTS)).addReg(SrcReg).addFrameIndex(FI)
373         .addImm(0).addImm(Pred).addReg(PredReg);
374     } else {          // move -> load
375       unsigned DstReg = MI->getOperand(0).getReg();
376       NewMI = BuildMI(TII.get(ARM::FLDS), DstReg).addFrameIndex(FI)
377         .addImm(0).addImm(Pred).addReg(PredReg);
378     }
379     break;
380   }
381   case ARM::FCPYD: {
382     unsigned Pred = MI->getOperand(2).getImm();
383     unsigned PredReg = MI->getOperand(3).getReg();
384     if (OpNum == 0) { // move -> store
385       unsigned SrcReg = MI->getOperand(1).getReg();
386       NewMI = BuildMI(TII.get(ARM::FSTD)).addReg(SrcReg).addFrameIndex(FI)
387         .addImm(0).addImm(Pred).addReg(PredReg);
388     } else {          // move -> load
389       unsigned DstReg = MI->getOperand(0).getReg();
390       NewMI = BuildMI(TII.get(ARM::FLDD), DstReg).addFrameIndex(FI)
391         .addImm(0).addImm(Pred).addReg(PredReg);
392     }
393     break;
394   }
395   }
396
397   if (NewMI)
398     NewMI->copyKillDeadInfo(MI);
399   return NewMI;
400 }
401
402 bool ARMRegisterInfo::canFoldMemoryOperand(MachineInstr *MI,
403                                          SmallVectorImpl<unsigned> &Ops) const {
404   if (Ops.size() != 1) return false;
405
406   unsigned OpNum = Ops[0];
407   unsigned Opc = MI->getOpcode();
408   switch (Opc) {
409   default: break;
410   case ARM::MOVr:
411     // If it is updating CPSR, then it cannot be foled.
412     return MI->getOperand(4).getReg() != ARM::CPSR;
413   case ARM::tMOVr: {
414     if (OpNum == 0) { // move -> store
415       unsigned SrcReg = MI->getOperand(1).getReg();
416       if (isPhysicalRegister(SrcReg) && !isLowRegister(SrcReg))
417         // tSpill cannot take a high register operand.
418         return false;
419     } else {          // move -> load
420       unsigned DstReg = MI->getOperand(0).getReg();
421       if (isPhysicalRegister(DstReg) && !isLowRegister(DstReg))
422         // tRestore cannot target a high register operand.
423         return false;
424     }
425     return true;
426   }
427   case ARM::FCPYS:
428   case ARM::FCPYD:
429     return true;
430   }
431
432   return false;
433 }
434
435 const unsigned*
436 ARMRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
437   static const unsigned CalleeSavedRegs[] = {
438     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
439     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
440
441     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
442     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
443     0
444   };
445
446   static const unsigned DarwinCalleeSavedRegs[] = {
447     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
448     ARM::R11, ARM::R10, ARM::R9, ARM::R8,
449
450     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
451     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
452     0
453   };
454   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
455 }
456
457 const TargetRegisterClass* const *
458 ARMRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
459   static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
460     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
461     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
462     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
463
464     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
465     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
466     0
467   };
468   return CalleeSavedRegClasses;
469 }
470
471 BitVector ARMRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
472   // FIXME: avoid re-calculating this everytime.
473   BitVector Reserved(getNumRegs());
474   Reserved.set(ARM::SP);
475   Reserved.set(ARM::PC);
476   if (STI.isTargetDarwin() || hasFP(MF))
477     Reserved.set(FramePtr);
478   // Some targets reserve R9.
479   if (STI.isR9Reserved())
480     Reserved.set(ARM::R9);
481   return Reserved;
482 }
483
484 bool
485 ARMRegisterInfo::isReservedReg(const MachineFunction &MF, unsigned Reg) const {
486   switch (Reg) {
487   default: break;
488   case ARM::SP:
489   case ARM::PC:
490     return true;
491   case ARM::R7:
492   case ARM::R11:
493     if (FramePtr == Reg && (STI.isTargetDarwin() || hasFP(MF)))
494       return true;
495     break;
496   case ARM::R9:
497     return STI.isR9Reserved();
498   }
499
500   return false;
501 }
502
503 bool
504 ARMRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
505   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
506   return ThumbRegScavenging || !AFI->isThumbFunction();
507 }
508
509 /// hasFP - Return true if the specified function should have a dedicated frame
510 /// pointer register.  This is true if the function has variable sized allocas
511 /// or if frame pointer elimination is disabled.
512 ///
513 bool ARMRegisterInfo::hasFP(const MachineFunction &MF) const {
514   return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
515 }
516
517 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
518 // not required, we reserve argument space for call sites in the function
519 // immediately on entry to the current function. This eliminates the need for
520 // add/sub sp brackets around call sites. Returns true if the call frame is
521 // included as part of the stack frame.
522 bool ARMRegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
523   const MachineFrameInfo *FFI = MF.getFrameInfo();
524   unsigned CFSize = FFI->getMaxCallFrameSize();
525   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
526   // It's not always a good idea to include the call frame as part of the
527   // stack frame. ARM (especially Thumb) has small immediate offset to
528   // address the stack frame. So a large call frame can cause poor codegen
529   // and may even makes it impossible to scavenge a register.
530   if (AFI->isThumbFunction()) {
531     if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
532       return false;
533   } else {
534     if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
535       return false;
536   }
537   return !MF.getFrameInfo()->hasVarSizedObjects();
538 }
539
540 /// emitARMRegPlusImmediate - Emits a series of instructions to materialize
541 /// a destreg = basereg + immediate in ARM code.
542 static
543 void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
544                              MachineBasicBlock::iterator &MBBI,
545                              unsigned DestReg, unsigned BaseReg, int NumBytes,
546                              ARMCC::CondCodes Pred, unsigned PredReg,
547                              const TargetInstrInfo &TII) {
548   bool isSub = NumBytes < 0;
549   if (isSub) NumBytes = -NumBytes;
550
551   while (NumBytes) {
552     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
553     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
554     assert(ThisVal && "Didn't extract field correctly");
555     
556     // We will handle these bits from offset, clear them.
557     NumBytes &= ~ThisVal;
558     
559     // Get the properly encoded SOImmVal field.
560     int SOImmVal = ARM_AM::getSOImmVal(ThisVal);
561     assert(SOImmVal != -1 && "Bit extraction didn't work?");
562     
563     // Build the new ADD / SUB.
564     BuildMI(MBB, MBBI, TII.get(isSub ? ARM::SUBri : ARM::ADDri), DestReg)
565       .addReg(BaseReg, false, false, true).addImm(SOImmVal)
566       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
567     BaseReg = DestReg;
568   }
569 }
570
571 /// calcNumMI - Returns the number of instructions required to materialize
572 /// the specific add / sub r, c instruction.
573 static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
574                           unsigned NumBits, unsigned Scale) {
575   unsigned NumMIs = 0;
576   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
577
578   if (Opc == ARM::tADDrSPi) {
579     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
580     Bytes -= ThisVal;
581     NumMIs++;
582     NumBits = 8;
583     Scale = 1;  // Followed by a number of tADDi8.
584     Chunk = ((1 << NumBits) - 1) * Scale;
585   }
586
587   NumMIs += Bytes / Chunk;
588   if ((Bytes % Chunk) != 0)
589     NumMIs++;
590   if (ExtraOpc)
591     NumMIs++;
592   return NumMIs;
593 }
594
595 /// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
596 /// a destreg = basereg + immediate in Thumb code. Materialize the immediate
597 /// in a register using mov / mvn sequences or load the immediate from a
598 /// constpool entry.
599 static
600 void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
601                                MachineBasicBlock::iterator &MBBI,
602                                unsigned DestReg, unsigned BaseReg,
603                                int NumBytes, bool CanChangeCC,
604                                const TargetInstrInfo &TII) {
605     bool isHigh = !isLowRegister(DestReg) ||
606                   (BaseReg != 0 && !isLowRegister(BaseReg));
607     bool isSub = false;
608     // Subtract doesn't have high register version. Load the negative value
609     // if either base or dest register is a high register. Also, if do not
610     // issue sub as part of the sequence if condition register is to be
611     // preserved.
612     if (NumBytes < 0 && !isHigh && CanChangeCC) {
613       isSub = true;
614       NumBytes = -NumBytes;
615     }
616     unsigned LdReg = DestReg;
617     if (DestReg == ARM::SP) {
618       assert(BaseReg == ARM::SP && "Unexpected!");
619       LdReg = ARM::R3;
620       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R12)
621         .addReg(ARM::R3, false, false, true);
622     }
623
624     if (NumBytes <= 255 && NumBytes >= 0)
625       BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
626     else if (NumBytes < 0 && NumBytes >= -255) {
627       BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
628       BuildMI(MBB, MBBI, TII.get(ARM::tNEG), LdReg)
629         .addReg(LdReg, false, false, true);
630     } else
631       emitLoadConstPool(MBB, MBBI, LdReg, NumBytes, ARMCC::AL, 0, TII, true);
632
633     // Emit add / sub.
634     int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
635     const MachineInstrBuilder MIB = BuildMI(MBB, MBBI, TII.get(Opc), DestReg);
636     if (DestReg == ARM::SP || isSub)
637       MIB.addReg(BaseReg).addReg(LdReg, false, false, true);
638     else
639       MIB.addReg(LdReg).addReg(BaseReg, false, false, true);
640     if (DestReg == ARM::SP)
641       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R3)
642         .addReg(ARM::R12, false, false, true);
643 }
644
645 /// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
646 /// a destreg = basereg + immediate in Thumb code.
647 static
648 void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
649                                MachineBasicBlock::iterator &MBBI,
650                                unsigned DestReg, unsigned BaseReg,
651                                int NumBytes, const TargetInstrInfo &TII) {
652   bool isSub = NumBytes < 0;
653   unsigned Bytes = (unsigned)NumBytes;
654   if (isSub) Bytes = -NumBytes;
655   bool isMul4 = (Bytes & 3) == 0;
656   bool isTwoAddr = false;
657   bool DstNotEqBase = false;
658   unsigned NumBits = 1;
659   unsigned Scale = 1;
660   int Opc = 0;
661   int ExtraOpc = 0;
662
663   if (DestReg == BaseReg && BaseReg == ARM::SP) {
664     assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
665     NumBits = 7;
666     Scale = 4;
667     Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
668     isTwoAddr = true;
669   } else if (!isSub && BaseReg == ARM::SP) {
670     // r1 = add sp, 403
671     // =>
672     // r1 = add sp, 100 * 4
673     // r1 = add r1, 3
674     if (!isMul4) {
675       Bytes &= ~3;
676       ExtraOpc = ARM::tADDi3;
677     }
678     NumBits = 8;
679     Scale = 4;
680     Opc = ARM::tADDrSPi;
681   } else {
682     // sp = sub sp, c
683     // r1 = sub sp, c
684     // r8 = sub sp, c
685     if (DestReg != BaseReg)
686       DstNotEqBase = true;
687     NumBits = 8;
688     Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
689     isTwoAddr = true;
690   }
691
692   unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
693   unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
694   if (NumMIs > Threshold) {
695     // This will expand into too many instructions. Load the immediate from a
696     // constpool entry.
697     emitThumbRegPlusImmInReg(MBB, MBBI, DestReg, BaseReg, NumBytes, true, TII);
698     return;
699   }
700
701   if (DstNotEqBase) {
702     if (isLowRegister(DestReg) && isLowRegister(BaseReg)) {
703       // If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
704       unsigned Chunk = (1 << 3) - 1;
705       unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
706       Bytes -= ThisVal;
707       BuildMI(MBB, MBBI, TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3), DestReg)
708         .addReg(BaseReg, false, false, true).addImm(ThisVal);
709     } else {
710       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), DestReg)
711         .addReg(BaseReg, false, false, true);
712     }
713     BaseReg = DestReg;
714   }
715
716   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
717   while (Bytes) {
718     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
719     Bytes -= ThisVal;
720     ThisVal /= Scale;
721     // Build the new tADD / tSUB.
722     if (isTwoAddr)
723       BuildMI(MBB, MBBI, TII.get(Opc), DestReg).addReg(DestReg).addImm(ThisVal);
724     else {
725       bool isKill = BaseReg != ARM::SP;
726       BuildMI(MBB, MBBI, TII.get(Opc), DestReg)
727         .addReg(BaseReg, false, false, isKill).addImm(ThisVal);
728       BaseReg = DestReg;
729
730       if (Opc == ARM::tADDrSPi) {
731         // r4 = add sp, imm
732         // r4 = add r4, imm
733         // ...
734         NumBits = 8;
735         Scale = 1;
736         Chunk = ((1 << NumBits) - 1) * Scale;
737         Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
738         isTwoAddr = true;
739       }
740     }
741   }
742
743   if (ExtraOpc)
744     BuildMI(MBB, MBBI, TII.get(ExtraOpc), DestReg)
745       .addReg(DestReg, false, false, true)
746       .addImm(((unsigned)NumBytes) & 3);
747 }
748
749 static
750 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
751                   int NumBytes, ARMCC::CondCodes Pred, unsigned PredReg,
752                   bool isThumb, const TargetInstrInfo &TII) {
753   if (isThumb)
754     emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes, TII);
755   else
756     emitARMRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes,
757                             Pred, PredReg, TII);
758 }
759
760 void ARMRegisterInfo::
761 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
762                               MachineBasicBlock::iterator I) const {
763   if (!hasReservedCallFrame(MF)) {
764     // If we have alloca, convert as follows:
765     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
766     // ADJCALLSTACKUP   -> add, sp, sp, amount
767     MachineInstr *Old = I;
768     unsigned Amount = Old->getOperand(0).getImm();
769     if (Amount != 0) {
770       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
771       // We need to keep the stack aligned properly.  To do this, we round the
772       // amount of space needed for the outgoing arguments up to the next
773       // alignment boundary.
774       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
775       Amount = (Amount+Align-1)/Align*Align;
776
777       // Replace the pseudo instruction with a new instruction...
778       unsigned Opc = Old->getOpcode();
779       bool isThumb = AFI->isThumbFunction();
780       ARMCC::CondCodes Pred = isThumb
781         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(1).getImm();
782       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
783         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
784         unsigned PredReg = isThumb ? 0 : Old->getOperand(2).getReg();
785         emitSPUpdate(MBB, I, -Amount, Pred, PredReg, isThumb, TII);
786       } else {
787         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
788         unsigned PredReg = isThumb ? 0 : Old->getOperand(3).getReg();
789         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
790         emitSPUpdate(MBB, I, Amount, Pred, PredReg, isThumb, TII);
791       }
792     }
793   }
794   MBB.erase(I);
795 }
796
797 /// emitThumbConstant - Emit a series of instructions to materialize a
798 /// constant.
799 static void emitThumbConstant(MachineBasicBlock &MBB,
800                               MachineBasicBlock::iterator &MBBI,
801                               unsigned DestReg, int Imm,
802                               const TargetInstrInfo &TII) {
803   bool isSub = Imm < 0;
804   if (isSub) Imm = -Imm;
805
806   int Chunk = (1 << 8) - 1;
807   int ThisVal = (Imm > Chunk) ? Chunk : Imm;
808   Imm -= ThisVal;
809   BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), DestReg).addImm(ThisVal);
810   if (Imm > 0) 
811     emitThumbRegPlusImmediate(MBB, MBBI, DestReg, DestReg, Imm, TII);
812   if (isSub)
813     BuildMI(MBB, MBBI, TII.get(ARM::tNEG), DestReg)
814       .addReg(DestReg, false, false, true);
815 }
816
817 /// findScratchRegister - Find a 'free' ARM register. If register scavenger
818 /// is not being used, R12 is available. Otherwise, try for a call-clobbered
819 /// register first and then a spilled callee-saved register if that fails.
820 static
821 unsigned findScratchRegister(RegScavenger *RS, const TargetRegisterClass *RC,
822                              ARMFunctionInfo *AFI) {
823   unsigned Reg = RS ? RS->FindUnusedReg(RC, true) : (unsigned) ARM::R12;
824   if (Reg == 0)
825     // Try a already spilled CS register.
826     Reg = RS->FindUnusedReg(RC, AFI->getSpilledCSRegisters());
827
828   return Reg;
829 }
830
831 void ARMRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
832                                           int SPAdj, RegScavenger *RS) const{
833   unsigned i = 0;
834   MachineInstr &MI = *II;
835   MachineBasicBlock &MBB = *MI.getParent();
836   MachineFunction &MF = *MBB.getParent();
837   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
838   bool isThumb = AFI->isThumbFunction();
839
840   while (!MI.getOperand(i).isFrameIndex()) {
841     ++i;
842     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
843   }
844   
845   unsigned FrameReg = ARM::SP;
846   int FrameIndex = MI.getOperand(i).getIndex();
847   int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) + 
848                MF.getFrameInfo()->getStackSize() + SPAdj;
849
850   if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
851     Offset -= AFI->getGPRCalleeSavedArea1Offset();
852   else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
853     Offset -= AFI->getGPRCalleeSavedArea2Offset();
854   else if (AFI->isDPRCalleeSavedAreaFrame(FrameIndex))
855     Offset -= AFI->getDPRCalleeSavedAreaOffset();
856   else if (hasFP(MF)) {
857     assert(SPAdj == 0 && "Unexpected");
858     // There is alloca()'s in this function, must reference off the frame
859     // pointer instead.
860     FrameReg = getFrameRegister(MF);
861     Offset -= AFI->getFramePtrSpillOffset();
862   }
863
864   unsigned Opcode = MI.getOpcode();
865   const TargetInstrDescriptor &Desc = TII.get(Opcode);
866   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
867   bool isSub = false;
868
869   if (Opcode == ARM::ADDri) {
870     Offset += MI.getOperand(i+1).getImm();
871     if (Offset == 0) {
872       // Turn it into a move.
873       MI.setInstrDescriptor(TII.get(ARM::MOVr));
874       MI.getOperand(i).ChangeToRegister(FrameReg, false);
875       MI.RemoveOperand(i+1);
876       return;
877     } else if (Offset < 0) {
878       Offset = -Offset;
879       isSub = true;
880       MI.setInstrDescriptor(TII.get(ARM::SUBri));
881     }
882
883     // Common case: small offset, fits into instruction.
884     int ImmedOffset = ARM_AM::getSOImmVal(Offset);
885     if (ImmedOffset != -1) {
886       // Replace the FrameIndex with sp / fp
887       MI.getOperand(i).ChangeToRegister(FrameReg, false);
888       MI.getOperand(i+1).ChangeToImmediate(ImmedOffset);
889       return;
890     }
891     
892     // Otherwise, we fallback to common code below to form the imm offset with
893     // a sequence of ADDri instructions.  First though, pull as much of the imm
894     // into this ADDri as possible.
895     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
896     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
897     
898     // We will handle these bits from offset, clear them.
899     Offset &= ~ThisImmVal;
900     
901     // Get the properly encoded SOImmVal field.
902     int ThisSOImmVal = ARM_AM::getSOImmVal(ThisImmVal);
903     assert(ThisSOImmVal != -1 && "Bit extraction didn't work?");    
904     MI.getOperand(i+1).ChangeToImmediate(ThisSOImmVal);
905   } else if (Opcode == ARM::tADDrSPi) {
906     Offset += MI.getOperand(i+1).getImm();
907
908     // Can't use tADDrSPi if it's based off the frame pointer.
909     unsigned NumBits = 0;
910     unsigned Scale = 1;
911     if (FrameReg != ARM::SP) {
912       Opcode = ARM::tADDi3;
913       MI.setInstrDescriptor(TII.get(ARM::tADDi3));
914       NumBits = 3;
915     } else {
916       NumBits = 8;
917       Scale = 4;
918       assert((Offset & 3) == 0 &&
919              "Thumb add/sub sp, #imm immediate must be multiple of 4!");
920     }
921
922     if (Offset == 0) {
923       // Turn it into a move.
924       MI.setInstrDescriptor(TII.get(ARM::tMOVr));
925       MI.getOperand(i).ChangeToRegister(FrameReg, false);
926       MI.RemoveOperand(i+1);
927       return;
928     }
929
930     // Common case: small offset, fits into instruction.
931     unsigned Mask = (1 << NumBits) - 1;
932     if (((Offset / Scale) & ~Mask) == 0) {
933       // Replace the FrameIndex with sp / fp
934       MI.getOperand(i).ChangeToRegister(FrameReg, false);
935       MI.getOperand(i+1).ChangeToImmediate(Offset / Scale);
936       return;
937     }
938
939     unsigned DestReg = MI.getOperand(0).getReg();
940     unsigned Bytes = (Offset > 0) ? Offset : -Offset;
941     unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, NumBits, Scale);
942     // MI would expand into a large number of instructions. Don't try to
943     // simplify the immediate.
944     if (NumMIs > 2) {
945       emitThumbRegPlusImmediate(MBB, II, DestReg, FrameReg, Offset, TII);
946       MBB.erase(II);
947       return;
948     }
949
950     if (Offset > 0) {
951       // Translate r0 = add sp, imm to
952       // r0 = add sp, 255*4
953       // r0 = add r0, (imm - 255*4)
954       MI.getOperand(i).ChangeToRegister(FrameReg, false);
955       MI.getOperand(i+1).ChangeToImmediate(Mask);
956       Offset = (Offset - Mask * Scale);
957       MachineBasicBlock::iterator NII = next(II);
958       emitThumbRegPlusImmediate(MBB, NII, DestReg, DestReg, Offset, TII);
959     } else {
960       // Translate r0 = add sp, -imm to
961       // r0 = -imm (this is then translated into a series of instructons)
962       // r0 = add r0, sp
963       emitThumbConstant(MBB, II, DestReg, Offset, TII);
964       MI.setInstrDescriptor(TII.get(ARM::tADDhirr));
965       MI.getOperand(i).ChangeToRegister(DestReg, false, false, true);
966       MI.getOperand(i+1).ChangeToRegister(FrameReg, false);
967     }
968     return;
969   } else {
970     unsigned ImmIdx = 0;
971     int InstrOffs = 0;
972     unsigned NumBits = 0;
973     unsigned Scale = 1;
974     switch (AddrMode) {
975     case ARMII::AddrMode2: {
976       ImmIdx = i+2;
977       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
978       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
979         InstrOffs *= -1;
980       NumBits = 12;
981       break;
982     }
983     case ARMII::AddrMode3: {
984       ImmIdx = i+2;
985       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
986       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
987         InstrOffs *= -1;
988       NumBits = 8;
989       break;
990     }
991     case ARMII::AddrMode5: {
992       ImmIdx = i+1;
993       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
994       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
995         InstrOffs *= -1;
996       NumBits = 8;
997       Scale = 4;
998       break;
999     }
1000     case ARMII::AddrModeTs: {
1001       ImmIdx = i+1;
1002       InstrOffs = MI.getOperand(ImmIdx).getImm();
1003       NumBits = (FrameReg == ARM::SP) ? 8 : 5;
1004       Scale = 4;
1005       break;
1006     }
1007     default:
1008       assert(0 && "Unsupported addressing mode!");
1009       abort();
1010       break;
1011     }
1012
1013     Offset += InstrOffs * Scale;
1014     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1015     if (Offset < 0 && !isThumb) {
1016       Offset = -Offset;
1017       isSub = true;
1018     }
1019
1020     // Common case: small offset, fits into instruction.
1021     MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1022     int ImmedOffset = Offset / Scale;
1023     unsigned Mask = (1 << NumBits) - 1;
1024     if ((unsigned)Offset <= Mask * Scale) {
1025       // Replace the FrameIndex with sp
1026       MI.getOperand(i).ChangeToRegister(FrameReg, false);
1027       if (isSub)
1028         ImmedOffset |= 1 << NumBits;
1029       ImmOp.ChangeToImmediate(ImmedOffset);
1030       return;
1031     }
1032
1033     bool isThumSpillRestore = Opcode == ARM::tRestore || Opcode == ARM::tSpill;
1034     if (AddrMode == ARMII::AddrModeTs) {
1035       // Thumb tLDRspi, tSTRspi. These will change to instructions that use
1036       // a different base register.
1037       NumBits = 5;
1038       Mask = (1 << NumBits) - 1;
1039     }
1040     // If this is a thumb spill / restore, we will be using a constpool load to
1041     // materialize the offset.
1042     if (AddrMode == ARMII::AddrModeTs && isThumSpillRestore)
1043       ImmOp.ChangeToImmediate(0);
1044     else {
1045       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1046       ImmedOffset = ImmedOffset & Mask;
1047       if (isSub)
1048         ImmedOffset |= 1 << NumBits;
1049       ImmOp.ChangeToImmediate(ImmedOffset);
1050       Offset &= ~(Mask*Scale);
1051     }
1052   }
1053   
1054   // If we get here, the immediate doesn't fit into the instruction.  We folded
1055   // as much as possible above, handle the rest, providing a register that is
1056   // SP+LargeImm.
1057   assert(Offset && "This code isn't needed if offset already handled!");
1058
1059   if (isThumb) {
1060     if (TII.isLoad(Opcode)) {
1061       // Use the destination register to materialize sp + offset.
1062       unsigned TmpReg = MI.getOperand(0).getReg();
1063       bool UseRR = false;
1064       if (Opcode == ARM::tRestore) {
1065         if (FrameReg == ARM::SP)
1066           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
1067         else {
1068           emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, TII, true);
1069           UseRR = true;
1070         }
1071       } else
1072         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
1073       MI.setInstrDescriptor(TII.get(ARM::tLDR));
1074       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
1075       if (UseRR)
1076         // Use [reg, reg] addrmode.
1077         MI.addOperand(MachineOperand::CreateReg(FrameReg, false));
1078       else  // tLDR has an extra register operand.
1079         MI.addOperand(MachineOperand::CreateReg(0, false));
1080     } else if (TII.isStore(Opcode)) {
1081       // FIXME! This is horrific!!! We need register scavenging.
1082       // Our temporary workaround has marked r3 unavailable. Of course, r3 is
1083       // also a ABI register so it's possible that is is the register that is
1084       // being storing here. If that's the case, we do the following:
1085       // r12 = r2
1086       // Use r2 to materialize sp + offset
1087       // str r3, r2
1088       // r2 = r12
1089       unsigned ValReg = MI.getOperand(0).getReg();
1090       unsigned TmpReg = ARM::R3;
1091       bool UseRR = false;
1092       if (ValReg == ARM::R3) {
1093         BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
1094           .addReg(ARM::R2, false, false, true);
1095         TmpReg = ARM::R2;
1096       }
1097       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
1098         BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
1099           .addReg(ARM::R3, false, false, true);
1100       if (Opcode == ARM::tSpill) {
1101         if (FrameReg == ARM::SP)
1102           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
1103         else {
1104           emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, TII, true);
1105           UseRR = true;
1106         }
1107       } else
1108         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
1109       MI.setInstrDescriptor(TII.get(ARM::tSTR));
1110       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
1111       if (UseRR)  // Use [reg, reg] addrmode.
1112         MI.addOperand(MachineOperand::CreateReg(FrameReg, false));
1113       else // tSTR has an extra register operand.
1114         MI.addOperand(MachineOperand::CreateReg(0, false));
1115
1116       MachineBasicBlock::iterator NII = next(II);
1117       if (ValReg == ARM::R3)
1118         BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R2)
1119           .addReg(ARM::R12, false, false, true);
1120       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
1121         BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R3)
1122           .addReg(ARM::R12, false, false, true);
1123     } else
1124       assert(false && "Unexpected opcode!");
1125   } else {
1126     // Insert a set of r12 with the full address: r12 = sp + offset
1127     // If the offset we have is too large to fit into the instruction, we need
1128     // to form it with a series of ADDri's.  Do this by taking 8-bit chunks
1129     // out of 'Offset'.
1130     unsigned ScratchReg = findScratchRegister(RS, &ARM::GPRRegClass, AFI);
1131     if (ScratchReg == 0)
1132       // No register is "free". Scavenge a register.
1133       ScratchReg = RS->scavengeRegister(&ARM::GPRRegClass, II, SPAdj);
1134     int PIdx = MI.findFirstPredOperandIdx();
1135     ARMCC::CondCodes Pred = (PIdx == -1)
1136       ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
1137     unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1138     emitARMRegPlusImmediate(MBB, II, ScratchReg, FrameReg,
1139                             isSub ? -Offset : Offset, Pred, PredReg, TII);
1140     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1141   }
1142 }
1143
1144 static unsigned estimateStackSize(MachineFunction &MF, MachineFrameInfo *MFI) {
1145   const MachineFrameInfo *FFI = MF.getFrameInfo();
1146   int Offset = 0;
1147   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
1148     int FixedOff = -FFI->getObjectOffset(i);
1149     if (FixedOff > Offset) Offset = FixedOff;
1150   }
1151   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
1152     Offset += FFI->getObjectSize(i);
1153     unsigned Align = FFI->getObjectAlignment(i);
1154     // Adjust to alignment boundary
1155     Offset = (Offset+Align-1)/Align*Align;
1156   }
1157   return (unsigned)Offset;
1158 }
1159
1160 void
1161 ARMRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1162                                                       RegScavenger *RS) const {
1163   // This tells PEI to spill the FP as if it is any other callee-save register
1164   // to take advantage the eliminateFrameIndex machinery. This also ensures it
1165   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1166   // to combine multiple loads / stores.
1167   bool CanEliminateFrame = true;
1168   bool CS1Spilled = false;
1169   bool LRSpilled = false;
1170   unsigned NumGPRSpills = 0;
1171   SmallVector<unsigned, 4> UnspilledCS1GPRs;
1172   SmallVector<unsigned, 4> UnspilledCS2GPRs;
1173   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1174
1175   // Don't spill FP if the frame can be eliminated. This is determined
1176   // by scanning the callee-save registers to see if any is used.
1177   const unsigned *CSRegs = getCalleeSavedRegs();
1178   const TargetRegisterClass* const *CSRegClasses = getCalleeSavedRegClasses();
1179   for (unsigned i = 0; CSRegs[i]; ++i) {
1180     unsigned Reg = CSRegs[i];
1181     bool Spilled = false;
1182     if (MF.getRegInfo().isPhysRegUsed(Reg)) {
1183       AFI->setCSRegisterIsSpilled(Reg);
1184       Spilled = true;
1185       CanEliminateFrame = false;
1186     } else {
1187       // Check alias registers too.
1188       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
1189         if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
1190           Spilled = true;
1191           CanEliminateFrame = false;
1192         }
1193       }
1194     }
1195
1196     if (CSRegClasses[i] == &ARM::GPRRegClass) {
1197       if (Spilled) {
1198         NumGPRSpills++;
1199
1200         if (!STI.isTargetDarwin()) {
1201           if (Reg == ARM::LR)
1202             LRSpilled = true;
1203           CS1Spilled = true;
1204           continue;
1205         }
1206
1207         // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1208         switch (Reg) {
1209         case ARM::LR:
1210           LRSpilled = true;
1211           // Fallthrough
1212         case ARM::R4:
1213         case ARM::R5:
1214         case ARM::R6:
1215         case ARM::R7:
1216           CS1Spilled = true;
1217           break;
1218         default:
1219           break;
1220         }
1221       } else { 
1222         if (!STI.isTargetDarwin()) {
1223           UnspilledCS1GPRs.push_back(Reg);
1224           continue;
1225         }
1226
1227         switch (Reg) {
1228         case ARM::R4:
1229         case ARM::R5:
1230         case ARM::R6:
1231         case ARM::R7:
1232         case ARM::LR:
1233           UnspilledCS1GPRs.push_back(Reg);
1234           break;
1235         default:
1236           UnspilledCS2GPRs.push_back(Reg);
1237           break;
1238         }
1239       }
1240     }
1241   }
1242
1243   bool ForceLRSpill = false;
1244   if (!LRSpilled && AFI->isThumbFunction()) {
1245     unsigned FnSize = ARM::GetFunctionSize(MF);
1246     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1247     // use of BL to implement far jump. If it turns out that it's not needed
1248     // then the branch fix up path will undo it.
1249     if (FnSize >= (1 << 11)) {
1250       CanEliminateFrame = false;
1251       ForceLRSpill = true;
1252     }
1253   }
1254
1255   bool ExtraCSSpill = false;
1256   if (!CanEliminateFrame || hasFP(MF)) {
1257     AFI->setHasStackFrame(true);
1258
1259     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1260     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1261     if (!LRSpilled && CS1Spilled) {
1262       MF.getRegInfo().setPhysRegUsed(ARM::LR);
1263       AFI->setCSRegisterIsSpilled(ARM::LR);
1264       NumGPRSpills++;
1265       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
1266                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1267       ForceLRSpill = false;
1268       ExtraCSSpill = true;
1269     }
1270
1271     // Darwin ABI requires FP to point to the stack slot that contains the
1272     // previous FP.
1273     if (STI.isTargetDarwin() || hasFP(MF)) {
1274       MF.getRegInfo().setPhysRegUsed(FramePtr);
1275       NumGPRSpills++;
1276     }
1277
1278     // If stack and double are 8-byte aligned and we are spilling an odd number
1279     // of GPRs. Spill one extra callee save GPR so we won't have to pad between
1280     // the integer and double callee save areas.
1281     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1282     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1283       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1284         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1285           unsigned Reg = UnspilledCS1GPRs[i];
1286           // Don't spiil high register if the function is thumb
1287           if (!AFI->isThumbFunction() || isLowRegister(Reg) || Reg == ARM::LR) {
1288             MF.getRegInfo().setPhysRegUsed(Reg);
1289             AFI->setCSRegisterIsSpilled(Reg);
1290             if (!isReservedReg(MF, Reg))
1291               ExtraCSSpill = true;
1292             break;
1293           }
1294         }
1295       } else if (!UnspilledCS2GPRs.empty() &&
1296                  !AFI->isThumbFunction()) {
1297         unsigned Reg = UnspilledCS2GPRs.front();
1298         MF.getRegInfo().setPhysRegUsed(Reg);
1299         AFI->setCSRegisterIsSpilled(Reg);
1300         if (!isReservedReg(MF, Reg))
1301           ExtraCSSpill = true;
1302       }
1303     }
1304
1305     // Estimate if we might need to scavenge a register at some point in order
1306     // to materialize a stack offset. If so, either spill one additiona
1307     // callee-saved register or reserve a special spill slot to facilitate
1308     // register scavenging.
1309     if (RS && !ExtraCSSpill && !AFI->isThumbFunction()) {
1310       MachineFrameInfo  *MFI = MF.getFrameInfo();
1311       unsigned Size = estimateStackSize(MF, MFI);
1312       unsigned Limit = (1 << 12) - 1;
1313       for (MachineFunction::iterator BB = MF.begin(),E = MF.end();BB != E; ++BB)
1314         for (MachineBasicBlock::iterator I= BB->begin(); I != BB->end(); ++I) {
1315           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1316             if (I->getOperand(i).isFrameIndex()) {
1317               unsigned Opcode = I->getOpcode();
1318               const TargetInstrDescriptor &Desc = TII.get(Opcode);
1319               unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1320               if (AddrMode == ARMII::AddrMode3) {
1321                 Limit = (1 << 8) - 1;
1322                 goto DoneEstimating;
1323               } else if (AddrMode == ARMII::AddrMode5) {
1324                 unsigned ThisLimit = ((1 << 8) - 1) * 4;
1325                 if (ThisLimit < Limit)
1326                   Limit = ThisLimit;
1327               }
1328             }
1329         }
1330     DoneEstimating:
1331       if (Size >= Limit) {
1332         // If any non-reserved CS register isn't spilled, just spill one or two
1333         // extra. That should take care of it!
1334         unsigned NumExtras = TargetAlign / 4;
1335         SmallVector<unsigned, 2> Extras;
1336         while (NumExtras && !UnspilledCS1GPRs.empty()) {
1337           unsigned Reg = UnspilledCS1GPRs.back();
1338           UnspilledCS1GPRs.pop_back();
1339           if (!isReservedReg(MF, Reg)) {
1340             Extras.push_back(Reg);
1341             NumExtras--;
1342           }
1343         }
1344         while (NumExtras && !UnspilledCS2GPRs.empty()) {
1345           unsigned Reg = UnspilledCS2GPRs.back();
1346           UnspilledCS2GPRs.pop_back();
1347           if (!isReservedReg(MF, Reg)) {
1348             Extras.push_back(Reg);
1349             NumExtras--;
1350           }
1351         }
1352         if (Extras.size() && NumExtras == 0) {
1353           for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1354             MF.getRegInfo().setPhysRegUsed(Extras[i]);
1355             AFI->setCSRegisterIsSpilled(Extras[i]);
1356           }
1357         } else {
1358           // Reserve a slot closest to SP or frame pointer.
1359           const TargetRegisterClass *RC = &ARM::GPRRegClass;
1360           RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1361                                                            RC->getAlignment()));
1362         }
1363       }
1364     }
1365   }
1366
1367   if (ForceLRSpill) {
1368     MF.getRegInfo().setPhysRegUsed(ARM::LR);
1369     AFI->setCSRegisterIsSpilled(ARM::LR);
1370     AFI->setLRIsSpilledForFarJump(true);
1371   }
1372 }
1373
1374 /// Move iterator pass the next bunch of callee save load / store ops for
1375 /// the particular spill area (1: integer area 1, 2: integer area 2,
1376 /// 3: fp area, 0: don't care).
1377 static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
1378                                    MachineBasicBlock::iterator &MBBI,
1379                                    int Opc, unsigned Area,
1380                                    const ARMSubtarget &STI) {
1381   while (MBBI != MBB.end() &&
1382          MBBI->getOpcode() == Opc && MBBI->getOperand(1).isFrameIndex()) {
1383     if (Area != 0) {
1384       bool Done = false;
1385       unsigned Category = 0;
1386       switch (MBBI->getOperand(0).getReg()) {
1387       case ARM::R4:  case ARM::R5:  case ARM::R6: case ARM::R7:
1388       case ARM::LR:
1389         Category = 1;
1390         break;
1391       case ARM::R8:  case ARM::R9:  case ARM::R10: case ARM::R11:
1392         Category = STI.isTargetDarwin() ? 2 : 1;
1393         break;
1394       case ARM::D8:  case ARM::D9:  case ARM::D10: case ARM::D11:
1395       case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
1396         Category = 3;
1397         break;
1398       default:
1399         Done = true;
1400         break;
1401       }
1402       if (Done || Category != Area)
1403         break;
1404     }
1405
1406     ++MBBI;
1407   }
1408 }
1409
1410 void ARMRegisterInfo::emitPrologue(MachineFunction &MF) const {
1411   MachineBasicBlock &MBB = MF.front();
1412   MachineBasicBlock::iterator MBBI = MBB.begin();
1413   MachineFrameInfo  *MFI = MF.getFrameInfo();
1414   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1415   bool isThumb = AFI->isThumbFunction();
1416   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1417   unsigned NumBytes = MFI->getStackSize();
1418   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1419
1420   if (isThumb) {
1421     // Check if R3 is live in. It might have to be used as a scratch register.
1422     for (MachineRegisterInfo::livein_iterator I =MF.getRegInfo().livein_begin(),
1423          E = MF.getRegInfo().livein_end(); I != E; ++I) {
1424       if (I->first == ARM::R3) {
1425         AFI->setR3IsLiveIn(true);
1426         break;
1427       }
1428     }
1429
1430     // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
1431     NumBytes = (NumBytes + 3) & ~3;
1432     MFI->setStackSize(NumBytes);
1433   }
1434
1435   // Determine the sizes of each callee-save spill areas and record which frame
1436   // belongs to which callee-save spill areas.
1437   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1438   int FramePtrSpillFI = 0;
1439
1440   if (VARegSaveSize)
1441     emitSPUpdate(MBB, MBBI, -VARegSaveSize, ARMCC::AL, 0, isThumb, TII);
1442
1443   if (!AFI->hasStackFrame()) {
1444     if (NumBytes != 0)
1445       emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII);
1446     return;
1447   }
1448
1449   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1450     unsigned Reg = CSI[i].getReg();
1451     int FI = CSI[i].getFrameIdx();
1452     switch (Reg) {
1453     case ARM::R4:
1454     case ARM::R5:
1455     case ARM::R6:
1456     case ARM::R7:
1457     case ARM::LR:
1458       if (Reg == FramePtr)
1459         FramePtrSpillFI = FI;
1460       AFI->addGPRCalleeSavedArea1Frame(FI);
1461       GPRCS1Size += 4;
1462       break;
1463     case ARM::R8:
1464     case ARM::R9:
1465     case ARM::R10:
1466     case ARM::R11:
1467       if (Reg == FramePtr)
1468         FramePtrSpillFI = FI;
1469       if (STI.isTargetDarwin()) {
1470         AFI->addGPRCalleeSavedArea2Frame(FI);
1471         GPRCS2Size += 4;
1472       } else {
1473         AFI->addGPRCalleeSavedArea1Frame(FI);
1474         GPRCS1Size += 4;
1475       }
1476       break;
1477     default:
1478       AFI->addDPRCalleeSavedAreaFrame(FI);
1479       DPRCSSize += 8;
1480     }
1481   }
1482
1483   if (!isThumb) {
1484     // Build the new SUBri to adjust SP for integer callee-save spill area 1.
1485     emitSPUpdate(MBB, MBBI, -GPRCS1Size, ARMCC::AL, 0, isThumb, TII);
1486     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 1, STI);
1487   } else if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH)
1488     ++MBBI;
1489
1490   // Darwin ABI requires FP to point to the stack slot that contains the
1491   // previous FP.
1492   if (STI.isTargetDarwin() || hasFP(MF)) {
1493     MachineInstrBuilder MIB =
1494       BuildMI(MBB, MBBI, TII.get(isThumb ? ARM::tADDrSPi : ARM::ADDri),FramePtr)
1495       .addFrameIndex(FramePtrSpillFI).addImm(0);
1496     if (!isThumb) AddDefaultCC(AddDefaultPred(MIB));
1497   }
1498
1499   if (!isThumb) {
1500     // Build the new SUBri to adjust SP for integer callee-save spill area 2.
1501     emitSPUpdate(MBB, MBBI, -GPRCS2Size, ARMCC::AL, 0, false, TII);
1502
1503     // Build the new SUBri to adjust SP for FP callee-save spill area.
1504     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 2, STI);
1505     emitSPUpdate(MBB, MBBI, -DPRCSSize, ARMCC::AL, 0, false, TII);
1506   }
1507
1508   // Determine starting offsets of spill areas.
1509   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
1510   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
1511   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
1512   AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + NumBytes);
1513   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1514   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1515   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
1516   
1517   NumBytes = DPRCSOffset;
1518   if (NumBytes) {
1519     // Insert it after all the callee-save spills.
1520     if (!isThumb)
1521       movePastCSLoadStoreOps(MBB, MBBI, ARM::FSTD, 3, STI);
1522     emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII);
1523   }
1524
1525   if(STI.isTargetELF() && hasFP(MF)) {
1526     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
1527                              AFI->getFramePtrSpillOffset());
1528   }
1529
1530   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1531   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1532   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
1533 }
1534
1535 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
1536   for (unsigned i = 0; CSRegs[i]; ++i)
1537     if (Reg == CSRegs[i])
1538       return true;
1539   return false;
1540 }
1541
1542 static bool isCSRestore(MachineInstr *MI, const unsigned *CSRegs) {
1543   return ((MI->getOpcode() == ARM::FLDD ||
1544            MI->getOpcode() == ARM::LDR  ||
1545            MI->getOpcode() == ARM::tRestore) &&
1546           MI->getOperand(1).isFrameIndex() &&
1547           isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
1548 }
1549
1550 void ARMRegisterInfo::emitEpilogue(MachineFunction &MF,
1551                                    MachineBasicBlock &MBB) const {
1552   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1553   assert((MBBI->getOpcode() == ARM::BX_RET ||
1554           MBBI->getOpcode() == ARM::tBX_RET ||
1555           MBBI->getOpcode() == ARM::tPOP_RET) &&
1556          "Can only insert epilog into returning blocks");
1557
1558   MachineFrameInfo *MFI = MF.getFrameInfo();
1559   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1560   bool isThumb = AFI->isThumbFunction();
1561   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1562   int NumBytes = (int)MFI->getStackSize();
1563   if (!AFI->hasStackFrame()) {
1564     if (NumBytes != 0)
1565       emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1566   } else {
1567     // Unwind MBBI to point to first LDR / FLDD.
1568     const unsigned *CSRegs = getCalleeSavedRegs();
1569     if (MBBI != MBB.begin()) {
1570       do
1571         --MBBI;
1572       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
1573       if (!isCSRestore(MBBI, CSRegs))
1574         ++MBBI;
1575     }
1576
1577     // Move SP to start of FP callee save spill area.
1578     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
1579                  AFI->getGPRCalleeSavedArea2Size() +
1580                  AFI->getDPRCalleeSavedAreaSize());
1581     if (isThumb) {
1582       if (hasFP(MF)) {
1583         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1584         // Reset SP based on frame pointer only if the stack frame extends beyond
1585         // frame pointer stack slot or target is ELF and the function has FP.
1586         if (NumBytes)
1587           emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, FramePtr, -NumBytes, TII);
1588         else
1589           BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::SP).addReg(FramePtr);
1590       } else {
1591         if (MBBI->getOpcode() == ARM::tBX_RET &&
1592             &MBB.front() != MBBI &&
1593             prior(MBBI)->getOpcode() == ARM::tPOP) {
1594           MachineBasicBlock::iterator PMBBI = prior(MBBI);
1595           emitSPUpdate(MBB, PMBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1596         } else
1597           emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1598       }
1599     } else {
1600       // Darwin ABI requires FP to point to the stack slot that contains the
1601       // previous FP.
1602       if ((STI.isTargetDarwin() && NumBytes) || hasFP(MF)) {
1603         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1604         // Reset SP based on frame pointer only if the stack frame extends beyond
1605         // frame pointer stack slot or target is ELF and the function has FP.
1606         if (AFI->getGPRCalleeSavedArea2Size() ||
1607             AFI->getDPRCalleeSavedAreaSize()  ||
1608             AFI->getDPRCalleeSavedAreaOffset()||
1609             hasFP(MF))
1610           if (NumBytes)
1611             BuildMI(MBB, MBBI, TII.get(ARM::SUBri), ARM::SP).addReg(FramePtr)
1612               .addImm(NumBytes)
1613               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1614           else
1615             BuildMI(MBB, MBBI, TII.get(ARM::MOVr), ARM::SP).addReg(FramePtr)
1616               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1617       } else if (NumBytes) {
1618         emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, false, TII);
1619       }
1620
1621       // Move SP to start of integer callee save spill area 2.
1622       movePastCSLoadStoreOps(MBB, MBBI, ARM::FLDD, 3, STI);
1623       emitSPUpdate(MBB, MBBI, AFI->getDPRCalleeSavedAreaSize(), ARMCC::AL, 0,
1624                    false, TII);
1625
1626       // Move SP to start of integer callee save spill area 1.
1627       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 2, STI);
1628       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea2Size(), ARMCC::AL, 0,
1629                    false, TII);
1630
1631       // Move SP to SP upon entry to the function.
1632       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 1, STI);
1633       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea1Size(), ARMCC::AL, 0,
1634                    false, TII);
1635     }
1636   }
1637
1638   if (VARegSaveSize) {
1639     if (isThumb)
1640       // Epilogue for vararg functions: pop LR to R3 and branch off it.
1641       // FIXME: Verify this is still ok when R3 is no longer being reserved.
1642       BuildMI(MBB, MBBI, TII.get(ARM::tPOP)).addReg(ARM::R3);
1643
1644     emitSPUpdate(MBB, MBBI, VARegSaveSize, ARMCC::AL, 0, isThumb, TII);
1645
1646     if (isThumb) {
1647       BuildMI(MBB, MBBI, TII.get(ARM::tBX_RET_vararg)).addReg(ARM::R3);
1648       MBB.erase(MBBI);
1649     }
1650   }
1651 }
1652
1653 unsigned ARMRegisterInfo::getRARegister() const {
1654   return ARM::LR;
1655 }
1656
1657 unsigned ARMRegisterInfo::getFrameRegister(MachineFunction &MF) const {
1658   if (STI.isTargetDarwin() || hasFP(MF))
1659     return (STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11;
1660   else
1661     return ARM::SP;
1662 }
1663
1664 unsigned ARMRegisterInfo::getEHExceptionRegister() const {
1665   assert(0 && "What is the exception register");
1666   return 0;
1667 }
1668
1669 unsigned ARMRegisterInfo::getEHHandlerRegister() const {
1670   assert(0 && "What is the exception handler register");
1671   return 0;
1672 }
1673
1674 int ARMRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1675   assert(0 && "What is the dwarf register number");
1676   return -1;
1677 }
1678
1679 #include "ARMGenRegisterInfo.inc"
1680