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