edfacc72e0c5ee12513f15ae955b9e8e8549a424
[oota-llvm.git] / lib / Target / ARM / ARMBaseRegisterInfo.cpp
1 //===- ARMBaseRegisterInfo.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 base ARM implementation of TargetRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARM.h"
15 #include "ARMAddressingModes.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMInstrInfo.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineLocation.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/BitVector.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/Support/CommandLine.h"
41
42 namespace llvm {
43 cl::opt<bool>
44 ReuseFrameIndexVals("arm-reuse-frame-index-vals", cl::Hidden, cl::init(true),
45           cl::desc("Reuse repeated frame index values"));
46 static cl::opt<bool>
47 ForceAllBaseRegAlloc("arm-force-base-reg-alloc", cl::Hidden, cl::init(true),
48           cl::desc("Force use of virtual base registers for stack load/store"));
49 static cl::opt<bool>
50 EnableLocalStackAlloc("enable-local-stack-alloc", cl::init(false), cl::Hidden,
51           cl::desc("Enable pre-regalloc stack frame index allocation"));
52 }
53
54 using namespace llvm;
55
56 unsigned ARMBaseRegisterInfo::getRegisterNumbering(unsigned RegEnum,
57                                                    bool *isSPVFP) {
58   if (isSPVFP)
59     *isSPVFP = false;
60
61   using namespace ARM;
62   switch (RegEnum) {
63   default:
64     llvm_unreachable("Unknown ARM register!");
65   case R0:  case D0:  case Q0:  return 0;
66   case R1:  case D1:  case Q1:  return 1;
67   case R2:  case D2:  case Q2:  return 2;
68   case R3:  case D3:  case Q3:  return 3;
69   case R4:  case D4:  case Q4:  return 4;
70   case R5:  case D5:  case Q5:  return 5;
71   case R6:  case D6:  case Q6:  return 6;
72   case R7:  case D7:  case Q7:  return 7;
73   case R8:  case D8:  case Q8:  return 8;
74   case R9:  case D9:  case Q9:  return 9;
75   case R10: case D10: case Q10: return 10;
76   case R11: case D11: case Q11: return 11;
77   case R12: case D12: case Q12: return 12;
78   case SP:  case D13: case Q13: return 13;
79   case LR:  case D14: case Q14: return 14;
80   case PC:  case D15: case Q15: return 15;
81
82   case D16: return 16;
83   case D17: return 17;
84   case D18: return 18;
85   case D19: return 19;
86   case D20: return 20;
87   case D21: return 21;
88   case D22: return 22;
89   case D23: return 23;
90   case D24: return 24;
91   case D25: return 25;
92   case D26: return 26;
93   case D27: return 27;
94   case D28: return 28;
95   case D29: return 29;
96   case D30: return 30;
97   case D31: return 31;
98
99   case S0: case S1: case S2: case S3:
100   case S4: case S5: case S6: case S7:
101   case S8: case S9: case S10: case S11:
102   case S12: case S13: case S14: case S15:
103   case S16: case S17: case S18: case S19:
104   case S20: case S21: case S22: case S23:
105   case S24: case S25: case S26: case S27:
106   case S28: case S29: case S30: case S31: {
107     if (isSPVFP)
108       *isSPVFP = true;
109     switch (RegEnum) {
110     default: return 0; // Avoid compile time warning.
111     case S0: return 0;
112     case S1: return 1;
113     case S2: return 2;
114     case S3: return 3;
115     case S4: return 4;
116     case S5: return 5;
117     case S6: return 6;
118     case S7: return 7;
119     case S8: return 8;
120     case S9: return 9;
121     case S10: return 10;
122     case S11: return 11;
123     case S12: return 12;
124     case S13: return 13;
125     case S14: return 14;
126     case S15: return 15;
127     case S16: return 16;
128     case S17: return 17;
129     case S18: return 18;
130     case S19: return 19;
131     case S20: return 20;
132     case S21: return 21;
133     case S22: return 22;
134     case S23: return 23;
135     case S24: return 24;
136     case S25: return 25;
137     case S26: return 26;
138     case S27: return 27;
139     case S28: return 28;
140     case S29: return 29;
141     case S30: return 30;
142     case S31: return 31;
143     }
144   }
145   }
146 }
147
148 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
149                                          const ARMSubtarget &sti)
150   : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
151     TII(tii), STI(sti),
152     FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11) {
153 }
154
155 const unsigned*
156 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
157   static const unsigned CalleeSavedRegs[] = {
158     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
159     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
160
161     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
162     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
163     0
164   };
165
166   static const unsigned DarwinCalleeSavedRegs[] = {
167     // Darwin ABI deviates from ARM standard ABI. R9 is not a callee-saved
168     // register.
169     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
170     ARM::R11, ARM::R10, ARM::R8,
171
172     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
173     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
174     0
175   };
176   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
177 }
178
179 BitVector ARMBaseRegisterInfo::
180 getReservedRegs(const MachineFunction &MF) const {
181   // FIXME: avoid re-calculating this everytime.
182   BitVector Reserved(getNumRegs());
183   Reserved.set(ARM::SP);
184   Reserved.set(ARM::PC);
185   Reserved.set(ARM::FPSCR);
186   if (hasFP(MF))
187     Reserved.set(FramePtr);
188   // Some targets reserve R9.
189   if (STI.isR9Reserved())
190     Reserved.set(ARM::R9);
191   return Reserved;
192 }
193
194 bool ARMBaseRegisterInfo::isReservedReg(const MachineFunction &MF,
195                                         unsigned Reg) const {
196   switch (Reg) {
197   default: break;
198   case ARM::SP:
199   case ARM::PC:
200     return true;
201   case ARM::R7:
202   case ARM::R11:
203     if (FramePtr == Reg && hasFP(MF))
204       return true;
205     break;
206   case ARM::R9:
207     return STI.isR9Reserved();
208   }
209
210   return false;
211 }
212
213 const TargetRegisterClass *
214 ARMBaseRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
215                                               const TargetRegisterClass *B,
216                                               unsigned SubIdx) const {
217   switch (SubIdx) {
218   default: return 0;
219   case ARM::ssub_0:
220   case ARM::ssub_1:
221   case ARM::ssub_2:
222   case ARM::ssub_3: {
223     // S sub-registers.
224     if (A->getSize() == 8) {
225       if (B == &ARM::SPR_8RegClass)
226         return &ARM::DPR_8RegClass;
227       assert(B == &ARM::SPRRegClass && "Expecting SPR register class!");
228       if (A == &ARM::DPR_8RegClass)
229         return A;
230       return &ARM::DPR_VFP2RegClass;
231     }
232
233     if (A->getSize() == 16) {
234       if (B == &ARM::SPR_8RegClass)
235         return &ARM::QPR_8RegClass;
236       return &ARM::QPR_VFP2RegClass;
237     }
238
239     if (A->getSize() == 32) {
240       if (B == &ARM::SPR_8RegClass)
241         return 0;  // Do not allow coalescing!
242       return &ARM::QQPR_VFP2RegClass;
243     }
244
245     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
246     return 0;  // Do not allow coalescing!
247   }
248   case ARM::dsub_0:
249   case ARM::dsub_1:
250   case ARM::dsub_2:
251   case ARM::dsub_3: {
252     // D sub-registers.
253     if (A->getSize() == 16) {
254       if (B == &ARM::DPR_VFP2RegClass)
255         return &ARM::QPR_VFP2RegClass;
256       if (B == &ARM::DPR_8RegClass)
257         return 0;  // Do not allow coalescing!
258       return A;
259     }
260
261     if (A->getSize() == 32) {
262       if (B == &ARM::DPR_VFP2RegClass)
263         return &ARM::QQPR_VFP2RegClass;
264       if (B == &ARM::DPR_8RegClass)
265         return 0;  // Do not allow coalescing!
266       return A;
267     }
268
269     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
270     if (B != &ARM::DPRRegClass)
271       return 0;  // Do not allow coalescing!
272     return A;
273   }
274   case ARM::dsub_4:
275   case ARM::dsub_5:
276   case ARM::dsub_6:
277   case ARM::dsub_7: {
278     // D sub-registers of QQQQ registers.
279     if (A->getSize() == 64 && B == &ARM::DPRRegClass)
280       return A;
281     return 0;  // Do not allow coalescing!
282   }
283
284   case ARM::qsub_0:
285   case ARM::qsub_1: {
286     // Q sub-registers.
287     if (A->getSize() == 32) {
288       if (B == &ARM::QPR_VFP2RegClass)
289         return &ARM::QQPR_VFP2RegClass;
290       if (B == &ARM::QPR_8RegClass)
291         return 0;  // Do not allow coalescing!
292       return A;
293     }
294
295     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
296     if (B == &ARM::QPRRegClass)
297       return A;
298     return 0;  // Do not allow coalescing!
299   }
300   case ARM::qsub_2:
301   case ARM::qsub_3: {
302     // Q sub-registers of QQQQ registers.
303     if (A->getSize() == 64 && B == &ARM::QPRRegClass)
304       return A;
305     return 0;  // Do not allow coalescing!
306   }
307   }
308   return 0;
309 }
310
311 bool
312 ARMBaseRegisterInfo::canCombineSubRegIndices(const TargetRegisterClass *RC,
313                                           SmallVectorImpl<unsigned> &SubIndices,
314                                           unsigned &NewSubIdx) const {
315
316   unsigned Size = RC->getSize() * 8;
317   if (Size < 6)
318     return 0;
319
320   NewSubIdx = 0;  // Whole register.
321   unsigned NumRegs = SubIndices.size();
322   if (NumRegs == 8) {
323     // 8 D registers -> 1 QQQQ register.
324     return (Size == 512 &&
325             SubIndices[0] == ARM::dsub_0 &&
326             SubIndices[1] == ARM::dsub_1 &&
327             SubIndices[2] == ARM::dsub_2 &&
328             SubIndices[3] == ARM::dsub_3 &&
329             SubIndices[4] == ARM::dsub_4 &&
330             SubIndices[5] == ARM::dsub_5 &&
331             SubIndices[6] == ARM::dsub_6 &&
332             SubIndices[7] == ARM::dsub_7);
333   } else if (NumRegs == 4) {
334     if (SubIndices[0] == ARM::qsub_0) {
335       // 4 Q registers -> 1 QQQQ register.
336       return (Size == 512 &&
337               SubIndices[1] == ARM::qsub_1 &&
338               SubIndices[2] == ARM::qsub_2 &&
339               SubIndices[3] == ARM::qsub_3);
340     } else if (SubIndices[0] == ARM::dsub_0) {
341       // 4 D registers -> 1 QQ register.
342       if (Size >= 256 &&
343           SubIndices[1] == ARM::dsub_1 &&
344           SubIndices[2] == ARM::dsub_2 &&
345           SubIndices[3] == ARM::dsub_3) {
346         if (Size == 512)
347           NewSubIdx = ARM::qqsub_0;
348         return true;
349       }
350     } else if (SubIndices[0] == ARM::dsub_4) {
351       // 4 D registers -> 1 QQ register (2nd).
352       if (Size == 512 &&
353           SubIndices[1] == ARM::dsub_5 &&
354           SubIndices[2] == ARM::dsub_6 &&
355           SubIndices[3] == ARM::dsub_7) {
356         NewSubIdx = ARM::qqsub_1;
357         return true;
358       }
359     } else if (SubIndices[0] == ARM::ssub_0) {
360       // 4 S registers -> 1 Q register.
361       if (Size >= 128 &&
362           SubIndices[1] == ARM::ssub_1 &&
363           SubIndices[2] == ARM::ssub_2 &&
364           SubIndices[3] == ARM::ssub_3) {
365         if (Size >= 256)
366           NewSubIdx = ARM::qsub_0;
367         return true;
368       }
369     }
370   } else if (NumRegs == 2) {
371     if (SubIndices[0] == ARM::qsub_0) {
372       // 2 Q registers -> 1 QQ register.
373       if (Size >= 256 && SubIndices[1] == ARM::qsub_1) {
374         if (Size == 512)
375           NewSubIdx = ARM::qqsub_0;
376         return true;
377       }
378     } else if (SubIndices[0] == ARM::qsub_2) {
379       // 2 Q registers -> 1 QQ register (2nd).
380       if (Size == 512 && SubIndices[1] == ARM::qsub_3) {
381         NewSubIdx = ARM::qqsub_1;
382         return true;
383       }
384     } else if (SubIndices[0] == ARM::dsub_0) {
385       // 2 D registers -> 1 Q register.
386       if (Size >= 128 && SubIndices[1] == ARM::dsub_1) {
387         if (Size >= 256)
388           NewSubIdx = ARM::qsub_0;
389         return true;
390       }
391     } else if (SubIndices[0] == ARM::dsub_2) {
392       // 2 D registers -> 1 Q register (2nd).
393       if (Size >= 256 && SubIndices[1] == ARM::dsub_3) {
394         NewSubIdx = ARM::qsub_1;
395         return true;
396       }
397     } else if (SubIndices[0] == ARM::dsub_4) {
398       // 2 D registers -> 1 Q register (3rd).
399       if (Size == 512 && SubIndices[1] == ARM::dsub_5) {
400         NewSubIdx = ARM::qsub_2;
401         return true;
402       }
403     } else if (SubIndices[0] == ARM::dsub_6) {
404       // 2 D registers -> 1 Q register (3rd).
405       if (Size == 512 && SubIndices[1] == ARM::dsub_7) {
406         NewSubIdx = ARM::qsub_3;
407         return true;
408       }
409     } else if (SubIndices[0] == ARM::ssub_0) {
410       // 2 S registers -> 1 D register.
411       if (SubIndices[1] == ARM::ssub_1) {
412         if (Size >= 128)
413           NewSubIdx = ARM::dsub_0;
414         return true;
415       }
416     } else if (SubIndices[0] == ARM::ssub_2) {
417       // 2 S registers -> 1 D register (2nd).
418       if (Size >= 128 && SubIndices[1] == ARM::ssub_3) {
419         NewSubIdx = ARM::dsub_1;
420         return true;
421       }
422     }
423   }
424   return false;
425 }
426
427
428 const TargetRegisterClass *
429 ARMBaseRegisterInfo::getPointerRegClass(unsigned Kind) const {
430   return ARM::GPRRegisterClass;
431 }
432
433 /// getAllocationOrder - Returns the register allocation order for a specified
434 /// register class in the form of a pair of TargetRegisterClass iterators.
435 std::pair<TargetRegisterClass::iterator,TargetRegisterClass::iterator>
436 ARMBaseRegisterInfo::getAllocationOrder(const TargetRegisterClass *RC,
437                                         unsigned HintType, unsigned HintReg,
438                                         const MachineFunction &MF) const {
439   // Alternative register allocation orders when favoring even / odd registers
440   // of register pairs.
441
442   // No FP, R9 is available.
443   static const unsigned GPREven1[] = {
444     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8, ARM::R10,
445     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7,
446     ARM::R9, ARM::R11
447   };
448   static const unsigned GPROdd1[] = {
449     ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R9, ARM::R11,
450     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
451     ARM::R8, ARM::R10
452   };
453
454   // FP is R7, R9 is available.
455   static const unsigned GPREven2[] = {
456     ARM::R0, ARM::R2, ARM::R4,          ARM::R8, ARM::R10,
457     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6,
458     ARM::R9, ARM::R11
459   };
460   static const unsigned GPROdd2[] = {
461     ARM::R1, ARM::R3, ARM::R5,          ARM::R9, ARM::R11,
462     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
463     ARM::R8, ARM::R10
464   };
465
466   // FP is R11, R9 is available.
467   static const unsigned GPREven3[] = {
468     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8,
469     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7,
470     ARM::R9
471   };
472   static const unsigned GPROdd3[] = {
473     ARM::R1, ARM::R3, ARM::R5, ARM::R6, ARM::R9,
474     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R7,
475     ARM::R8
476   };
477
478   // No FP, R9 is not available.
479   static const unsigned GPREven4[] = {
480     ARM::R0, ARM::R2, ARM::R4, ARM::R6,          ARM::R10,
481     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8,
482     ARM::R11
483   };
484   static const unsigned GPROdd4[] = {
485     ARM::R1, ARM::R3, ARM::R5, ARM::R7,          ARM::R11,
486     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
487     ARM::R10
488   };
489
490   // FP is R7, R9 is not available.
491   static const unsigned GPREven5[] = {
492     ARM::R0, ARM::R2, ARM::R4,                   ARM::R10,
493     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6, ARM::R8,
494     ARM::R11
495   };
496   static const unsigned GPROdd5[] = {
497     ARM::R1, ARM::R3, ARM::R5,                   ARM::R11,
498     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
499     ARM::R10
500   };
501
502   // FP is R11, R9 is not available.
503   static const unsigned GPREven6[] = {
504     ARM::R0, ARM::R2, ARM::R4, ARM::R6,
505     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8
506   };
507   static const unsigned GPROdd6[] = {
508     ARM::R1, ARM::R3, ARM::R5, ARM::R7,
509     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8
510   };
511
512
513   if (HintType == ARMRI::RegPairEven) {
514     if (isPhysicalRegister(HintReg) && getRegisterPairEven(HintReg, MF) == 0)
515       // It's no longer possible to fulfill this hint. Return the default
516       // allocation order.
517       return std::make_pair(RC->allocation_order_begin(MF),
518                             RC->allocation_order_end(MF));
519
520     if (!hasFP(MF)) {
521       if (!STI.isR9Reserved())
522         return std::make_pair(GPREven1,
523                               GPREven1 + (sizeof(GPREven1)/sizeof(unsigned)));
524       else
525         return std::make_pair(GPREven4,
526                               GPREven4 + (sizeof(GPREven4)/sizeof(unsigned)));
527     } else if (FramePtr == ARM::R7) {
528       if (!STI.isR9Reserved())
529         return std::make_pair(GPREven2,
530                               GPREven2 + (sizeof(GPREven2)/sizeof(unsigned)));
531       else
532         return std::make_pair(GPREven5,
533                               GPREven5 + (sizeof(GPREven5)/sizeof(unsigned)));
534     } else { // FramePtr == ARM::R11
535       if (!STI.isR9Reserved())
536         return std::make_pair(GPREven3,
537                               GPREven3 + (sizeof(GPREven3)/sizeof(unsigned)));
538       else
539         return std::make_pair(GPREven6,
540                               GPREven6 + (sizeof(GPREven6)/sizeof(unsigned)));
541     }
542   } else if (HintType == ARMRI::RegPairOdd) {
543     if (isPhysicalRegister(HintReg) && getRegisterPairOdd(HintReg, MF) == 0)
544       // It's no longer possible to fulfill this hint. Return the default
545       // allocation order.
546       return std::make_pair(RC->allocation_order_begin(MF),
547                             RC->allocation_order_end(MF));
548
549     if (!hasFP(MF)) {
550       if (!STI.isR9Reserved())
551         return std::make_pair(GPROdd1,
552                               GPROdd1 + (sizeof(GPROdd1)/sizeof(unsigned)));
553       else
554         return std::make_pair(GPROdd4,
555                               GPROdd4 + (sizeof(GPROdd4)/sizeof(unsigned)));
556     } else if (FramePtr == ARM::R7) {
557       if (!STI.isR9Reserved())
558         return std::make_pair(GPROdd2,
559                               GPROdd2 + (sizeof(GPROdd2)/sizeof(unsigned)));
560       else
561         return std::make_pair(GPROdd5,
562                               GPROdd5 + (sizeof(GPROdd5)/sizeof(unsigned)));
563     } else { // FramePtr == ARM::R11
564       if (!STI.isR9Reserved())
565         return std::make_pair(GPROdd3,
566                               GPROdd3 + (sizeof(GPROdd3)/sizeof(unsigned)));
567       else
568         return std::make_pair(GPROdd6,
569                               GPROdd6 + (sizeof(GPROdd6)/sizeof(unsigned)));
570     }
571   }
572   return std::make_pair(RC->allocation_order_begin(MF),
573                         RC->allocation_order_end(MF));
574 }
575
576 /// ResolveRegAllocHint - Resolves the specified register allocation hint
577 /// to a physical register. Returns the physical register if it is successful.
578 unsigned
579 ARMBaseRegisterInfo::ResolveRegAllocHint(unsigned Type, unsigned Reg,
580                                          const MachineFunction &MF) const {
581   if (Reg == 0 || !isPhysicalRegister(Reg))
582     return 0;
583   if (Type == 0)
584     return Reg;
585   else if (Type == (unsigned)ARMRI::RegPairOdd)
586     // Odd register.
587     return getRegisterPairOdd(Reg, MF);
588   else if (Type == (unsigned)ARMRI::RegPairEven)
589     // Even register.
590     return getRegisterPairEven(Reg, MF);
591   return 0;
592 }
593
594 void
595 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
596                                         MachineFunction &MF) const {
597   MachineRegisterInfo *MRI = &MF.getRegInfo();
598   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
599   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
600        Hint.first == (unsigned)ARMRI::RegPairEven) &&
601       Hint.second && TargetRegisterInfo::isVirtualRegister(Hint.second)) {
602     // If 'Reg' is one of the even / odd register pair and it's now changed
603     // (e.g. coalesced) into a different register. The other register of the
604     // pair allocation hint must be updated to reflect the relationship
605     // change.
606     unsigned OtherReg = Hint.second;
607     Hint = MRI->getRegAllocationHint(OtherReg);
608     if (Hint.second == Reg)
609       // Make sure the pair has not already divorced.
610       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
611   }
612 }
613
614 /// hasFP - Return true if the specified function should have a dedicated frame
615 /// pointer register.  This is true if the function has variable sized allocas
616 /// or if frame pointer elimination is disabled.
617 ///
618 bool ARMBaseRegisterInfo::hasFP(const MachineFunction &MF) const {
619   // Mac OS X requires FP not to be clobbered for backtracing purpose.
620   if (STI.isTargetDarwin())
621     return true;
622
623   const MachineFrameInfo *MFI = MF.getFrameInfo();
624   // Always eliminate non-leaf frame pointers.
625   return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
626           needsStackRealignment(MF) ||
627           MFI->hasVarSizedObjects() ||
628           MFI->isFrameAddressTaken());
629 }
630
631 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
632   const MachineFrameInfo *MFI = MF.getFrameInfo();
633   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
634   return (RealignStack &&
635           !AFI->isThumb1OnlyFunction() &&
636           !MFI->hasVarSizedObjects());
637 }
638
639 bool ARMBaseRegisterInfo::
640 needsStackRealignment(const MachineFunction &MF) const {
641   const MachineFrameInfo *MFI = MF.getFrameInfo();
642   const Function *F = MF.getFunction();
643   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
644   unsigned StackAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
645   bool requiresRealignment = ((MFI->getMaxAlignment() > StackAlign) ||
646                                F->hasFnAttr(Attribute::StackAlignment));
647     
648   // FIXME: Currently we don't support stack realignment for functions with
649   //        variable-sized allocas.
650   // FIXME: It's more complicated than this...
651   if (0 && requiresRealignment && MFI->hasVarSizedObjects())
652     report_fatal_error(
653       "Stack realignment in presense of dynamic allocas is not supported");
654   
655   // FIXME: This probably isn't the right place for this.
656   if (0 && requiresRealignment && AFI->isThumb1OnlyFunction())
657     report_fatal_error(
658       "Stack realignment in thumb1 functions is not supported");
659   
660   return requiresRealignment && canRealignStack(MF);
661 }
662
663 bool ARMBaseRegisterInfo::
664 cannotEliminateFrame(const MachineFunction &MF) const {
665   const MachineFrameInfo *MFI = MF.getFrameInfo();
666   if (DisableFramePointerElim(MF) && MFI->adjustsStack())
667     return true;
668   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
669     || needsStackRealignment(MF);
670 }
671
672 /// estimateStackSize - Estimate and return the size of the frame.
673 static unsigned estimateStackSize(MachineFunction &MF) {
674   const MachineFrameInfo *FFI = MF.getFrameInfo();
675   int Offset = 0;
676   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
677     int FixedOff = -FFI->getObjectOffset(i);
678     if (FixedOff > Offset) Offset = FixedOff;
679   }
680   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
681     if (FFI->isDeadObjectIndex(i))
682       continue;
683     Offset += FFI->getObjectSize(i);
684     unsigned Align = FFI->getObjectAlignment(i);
685     // Adjust to alignment boundary
686     Offset = (Offset+Align-1)/Align*Align;
687   }
688   return (unsigned)Offset;
689 }
690
691 /// estimateRSStackSizeLimit - Look at each instruction that references stack
692 /// frames and return the stack size limit beyond which some of these
693 /// instructions will require a scratch register during their expansion later.
694 unsigned
695 ARMBaseRegisterInfo::estimateRSStackSizeLimit(MachineFunction &MF) const {
696   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
697   unsigned Limit = (1 << 12) - 1;
698   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
699     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
700          I != E; ++I) {
701       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
702         if (!I->getOperand(i).isFI()) continue;
703
704         // When using ADDri to get the address of a stack object, 255 is the
705         // largest offset guaranteed to fit in the immediate offset.
706         if (I->getOpcode() == ARM::ADDri) {
707           Limit = std::min(Limit, (1U << 8) - 1);
708           break;
709         }
710
711         // Otherwise check the addressing mode.
712         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
713         case ARMII::AddrMode3:
714         case ARMII::AddrModeT2_i8:
715           Limit = std::min(Limit, (1U << 8) - 1);
716           break;
717         case ARMII::AddrMode5:
718         case ARMII::AddrModeT2_i8s4:
719           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
720           break;
721         case ARMII::AddrModeT2_i12:
722           // i12 supports only positive offset so these will be converted to
723           // i8 opcodes. See llvm::rewriteT2FrameIndex.
724           if (hasFP(MF) && AFI->hasStackFrame())
725             Limit = std::min(Limit, (1U << 8) - 1);
726           break;
727         case ARMII::AddrMode6:
728           // Addressing mode 6 (load/store) instructions can't encode an
729           // immediate offset for stack references.
730           return 0;
731         default:
732           break;
733         }
734         break; // At most one FI per instruction
735       }
736     }
737   }
738
739   return Limit;
740 }
741
742 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
743                                        const ARMBaseInstrInfo &TII) {
744   unsigned FnSize = 0;
745   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
746        MBBI != E; ++MBBI) {
747     const MachineBasicBlock &MBB = *MBBI;
748     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
749          I != E; ++I)
750       FnSize += TII.GetInstSizeInBytes(I);
751   }
752   return FnSize;
753 }
754
755 void
756 ARMBaseRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
757                                                        RegScavenger *RS) const {
758   // This tells PEI to spill the FP as if it is any other callee-save register
759   // to take advantage the eliminateFrameIndex machinery. This also ensures it
760   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
761   // to combine multiple loads / stores.
762   bool CanEliminateFrame = true;
763   bool CS1Spilled = false;
764   bool LRSpilled = false;
765   unsigned NumGPRSpills = 0;
766   SmallVector<unsigned, 4> UnspilledCS1GPRs;
767   SmallVector<unsigned, 4> UnspilledCS2GPRs;
768   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
769   MachineFrameInfo *MFI = MF.getFrameInfo();
770
771   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
772   // scratch register.
773   // FIXME: It will be better just to find spare register here.
774   if (needsStackRealignment(MF) &&
775       AFI->isThumb2Function())
776     MF.getRegInfo().setPhysRegUsed(ARM::R4);
777
778   // Spill LR if Thumb1 function uses variable length argument lists.
779   if (AFI->isThumb1OnlyFunction() && AFI->getVarArgsRegSaveSize() > 0)
780     MF.getRegInfo().setPhysRegUsed(ARM::LR);
781
782   // Don't spill FP if the frame can be eliminated. This is determined
783   // by scanning the callee-save registers to see if any is used.
784   const unsigned *CSRegs = getCalleeSavedRegs();
785   for (unsigned i = 0; CSRegs[i]; ++i) {
786     unsigned Reg = CSRegs[i];
787     bool Spilled = false;
788     if (MF.getRegInfo().isPhysRegUsed(Reg)) {
789       AFI->setCSRegisterIsSpilled(Reg);
790       Spilled = true;
791       CanEliminateFrame = false;
792     } else {
793       // Check alias registers too.
794       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
795         if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
796           Spilled = true;
797           CanEliminateFrame = false;
798         }
799       }
800     }
801
802     if (!ARM::GPRRegisterClass->contains(Reg))
803       continue;
804
805     if (Spilled) {
806       NumGPRSpills++;
807
808       if (!STI.isTargetDarwin()) {
809         if (Reg == ARM::LR)
810           LRSpilled = true;
811         CS1Spilled = true;
812         continue;
813       }
814
815       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
816       switch (Reg) {
817       case ARM::LR:
818         LRSpilled = true;
819         // Fallthrough
820       case ARM::R4:
821       case ARM::R5:
822       case ARM::R6:
823       case ARM::R7:
824         CS1Spilled = true;
825         break;
826       default:
827         break;
828       }
829     } else {
830       if (!STI.isTargetDarwin()) {
831         UnspilledCS1GPRs.push_back(Reg);
832         continue;
833       }
834
835       switch (Reg) {
836       case ARM::R4:
837       case ARM::R5:
838       case ARM::R6:
839       case ARM::R7:
840       case ARM::LR:
841         UnspilledCS1GPRs.push_back(Reg);
842         break;
843       default:
844         UnspilledCS2GPRs.push_back(Reg);
845         break;
846       }
847     }
848   }
849
850   bool ForceLRSpill = false;
851   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
852     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
853     // Force LR to be spilled if the Thumb function size is > 2048. This enables
854     // use of BL to implement far jump. If it turns out that it's not needed
855     // then the branch fix up path will undo it.
856     if (FnSize >= (1 << 11)) {
857       CanEliminateFrame = false;
858       ForceLRSpill = true;
859     }
860   }
861
862   // If any of the stack slot references may be out of range of an immediate
863   // offset, make sure a register (or a spill slot) is available for the
864   // register scavenger. Note that if we're indexing off the frame pointer, the
865   // effective stack size is 4 bytes larger since the FP points to the stack
866   // slot of the previous FP. Also, if we have variable sized objects in the
867   // function, stack slot references will often be negative, and some of
868   // our instructions are positive-offset only, so conservatively consider
869   // that case to want a spill slot (or register) as well. Similarly, if
870   // the function adjusts the stack pointer during execution and the
871   // adjustments aren't already part of our stack size estimate, our offset
872   // calculations may be off, so be conservative.
873   // FIXME: We could add logic to be more precise about negative offsets
874   //        and which instructions will need a scratch register for them. Is it
875   //        worth the effort and added fragility?
876   bool BigStack =
877     (RS &&
878      (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
879       estimateRSStackSizeLimit(MF)))
880     || MFI->hasVarSizedObjects()
881     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
882
883   bool ExtraCSSpill = false;
884   if (BigStack || !CanEliminateFrame || cannotEliminateFrame(MF)) {
885     AFI->setHasStackFrame(true);
886
887     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
888     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
889     if (!LRSpilled && CS1Spilled) {
890       MF.getRegInfo().setPhysRegUsed(ARM::LR);
891       AFI->setCSRegisterIsSpilled(ARM::LR);
892       NumGPRSpills++;
893       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
894                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
895       ForceLRSpill = false;
896       ExtraCSSpill = true;
897     }
898
899     if (hasFP(MF)) {
900       MF.getRegInfo().setPhysRegUsed(FramePtr);
901       NumGPRSpills++;
902     }
903
904     // If stack and double are 8-byte aligned and we are spilling an odd number
905     // of GPRs. Spill one extra callee save GPR so we won't have to pad between
906     // the integer and double callee save areas.
907     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
908     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
909       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
910         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
911           unsigned Reg = UnspilledCS1GPRs[i];
912           // Don't spill high register if the function is thumb1
913           if (!AFI->isThumb1OnlyFunction() ||
914               isARMLowRegister(Reg) || Reg == ARM::LR) {
915             MF.getRegInfo().setPhysRegUsed(Reg);
916             AFI->setCSRegisterIsSpilled(Reg);
917             if (!isReservedReg(MF, Reg))
918               ExtraCSSpill = true;
919             break;
920           }
921         }
922       } else if (!UnspilledCS2GPRs.empty() &&
923                  !AFI->isThumb1OnlyFunction()) {
924         unsigned Reg = UnspilledCS2GPRs.front();
925         MF.getRegInfo().setPhysRegUsed(Reg);
926         AFI->setCSRegisterIsSpilled(Reg);
927         if (!isReservedReg(MF, Reg))
928           ExtraCSSpill = true;
929       }
930     }
931
932     // Estimate if we might need to scavenge a register at some point in order
933     // to materialize a stack offset. If so, either spill one additional
934     // callee-saved register or reserve a special spill slot to facilitate
935     // register scavenging. Thumb1 needs a spill slot for stack pointer
936     // adjustments also, even when the frame itself is small.
937     if (BigStack && !ExtraCSSpill) {
938       // If any non-reserved CS register isn't spilled, just spill one or two
939       // extra. That should take care of it!
940       unsigned NumExtras = TargetAlign / 4;
941       SmallVector<unsigned, 2> Extras;
942       while (NumExtras && !UnspilledCS1GPRs.empty()) {
943         unsigned Reg = UnspilledCS1GPRs.back();
944         UnspilledCS1GPRs.pop_back();
945         if (!isReservedReg(MF, Reg) &&
946             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
947              Reg == ARM::LR)) {
948           Extras.push_back(Reg);
949           NumExtras--;
950         }
951       }
952       // For non-Thumb1 functions, also check for hi-reg CS registers
953       if (!AFI->isThumb1OnlyFunction()) {
954         while (NumExtras && !UnspilledCS2GPRs.empty()) {
955           unsigned Reg = UnspilledCS2GPRs.back();
956           UnspilledCS2GPRs.pop_back();
957           if (!isReservedReg(MF, Reg)) {
958             Extras.push_back(Reg);
959             NumExtras--;
960           }
961         }
962       }
963       if (Extras.size() && NumExtras == 0) {
964         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
965           MF.getRegInfo().setPhysRegUsed(Extras[i]);
966           AFI->setCSRegisterIsSpilled(Extras[i]);
967         }
968       } else if (!AFI->isThumb1OnlyFunction()) {
969         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
970         // closest to SP or frame pointer.
971         const TargetRegisterClass *RC = ARM::GPRRegisterClass;
972         RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
973                                                            RC->getAlignment(),
974                                                            false));
975       }
976     }
977   }
978
979   if (ForceLRSpill) {
980     MF.getRegInfo().setPhysRegUsed(ARM::LR);
981     AFI->setCSRegisterIsSpilled(ARM::LR);
982     AFI->setLRIsSpilledForFarJump(true);
983   }
984 }
985
986 unsigned ARMBaseRegisterInfo::getRARegister() const {
987   return ARM::LR;
988 }
989
990 unsigned 
991 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
992   if (hasFP(MF))
993     return FramePtr;
994   return ARM::SP;
995 }
996
997 // Provide a base+offset reference to an FI slot for debug info. It's the
998 // same as what we use for resolving the code-gen references for now.
999 // FIXME: This can go wrong when references are SP-relative and simple call
1000 //        frames aren't used.
1001 int
1002 ARMBaseRegisterInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
1003                                             unsigned &FrameReg) const {
1004   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
1005 }
1006
1007 int
1008 ARMBaseRegisterInfo::ResolveFrameIndexReference(const MachineFunction &MF,
1009                                                 int FI,
1010                                                 unsigned &FrameReg,
1011                                                 int SPAdj) const {
1012   const MachineFrameInfo *MFI = MF.getFrameInfo();
1013   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1014   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
1015   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
1016   bool isFixed = MFI->isFixedObjectIndex(FI);
1017
1018   FrameReg = ARM::SP;
1019   Offset += SPAdj;
1020   if (AFI->isGPRCalleeSavedArea1Frame(FI))
1021     return Offset - AFI->getGPRCalleeSavedArea1Offset();
1022   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
1023     return Offset - AFI->getGPRCalleeSavedArea2Offset();
1024   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
1025     return Offset - AFI->getDPRCalleeSavedAreaOffset();
1026
1027   // When dynamically realigning the stack, use the frame pointer for
1028   // parameters, and the stack pointer for locals.
1029   if (needsStackRealignment(MF)) {
1030     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
1031     if (isFixed) {
1032       FrameReg = getFrameRegister(MF);
1033       Offset = FPOffset;
1034     }
1035     return Offset;
1036   }
1037
1038   // If there is a frame pointer, use it when we can.
1039   if (hasFP(MF) && AFI->hasStackFrame()) {
1040     // Use frame pointer to reference fixed objects. Use it for locals if
1041     // there are VLAs (and thus the SP isn't reliable as a base).
1042     if (isFixed || MFI->hasVarSizedObjects()) {
1043       FrameReg = getFrameRegister(MF);
1044       Offset = FPOffset;
1045     } else if (AFI->isThumb2Function()) {
1046       // In Thumb2 mode, the negative offset is very limited. Try to avoid
1047       // out of range references.
1048       if (FPOffset >= -255 && FPOffset < 0) {
1049         FrameReg = getFrameRegister(MF);
1050         Offset = FPOffset;
1051       }
1052     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
1053       // Otherwise, use SP or FP, whichever is closer to the stack slot.
1054       FrameReg = getFrameRegister(MF);
1055       Offset = FPOffset;
1056     }
1057   }
1058   return Offset;
1059 }
1060
1061 int
1062 ARMBaseRegisterInfo::getFrameIndexOffset(const MachineFunction &MF,
1063                                          int FI) const {
1064   unsigned FrameReg;
1065   return getFrameIndexReference(MF, FI, FrameReg);
1066 }
1067
1068 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
1069   llvm_unreachable("What is the exception register");
1070   return 0;
1071 }
1072
1073 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
1074   llvm_unreachable("What is the exception handler register");
1075   return 0;
1076 }
1077
1078 int ARMBaseRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1079   return ARMGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
1080 }
1081
1082 unsigned ARMBaseRegisterInfo::getRegisterPairEven(unsigned Reg,
1083                                               const MachineFunction &MF) const {
1084   switch (Reg) {
1085   default: break;
1086   // Return 0 if either register of the pair is a special register.
1087   // So no R12, etc.
1088   case ARM::R1:
1089     return ARM::R0;
1090   case ARM::R3:
1091     return ARM::R2;
1092   case ARM::R5:
1093     return ARM::R4;
1094   case ARM::R7:
1095     return isReservedReg(MF, ARM::R7)  ? 0 : ARM::R6;
1096   case ARM::R9:
1097     return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R8;
1098   case ARM::R11:
1099     return isReservedReg(MF, ARM::R11) ? 0 : ARM::R10;
1100
1101   case ARM::S1:
1102     return ARM::S0;
1103   case ARM::S3:
1104     return ARM::S2;
1105   case ARM::S5:
1106     return ARM::S4;
1107   case ARM::S7:
1108     return ARM::S6;
1109   case ARM::S9:
1110     return ARM::S8;
1111   case ARM::S11:
1112     return ARM::S10;
1113   case ARM::S13:
1114     return ARM::S12;
1115   case ARM::S15:
1116     return ARM::S14;
1117   case ARM::S17:
1118     return ARM::S16;
1119   case ARM::S19:
1120     return ARM::S18;
1121   case ARM::S21:
1122     return ARM::S20;
1123   case ARM::S23:
1124     return ARM::S22;
1125   case ARM::S25:
1126     return ARM::S24;
1127   case ARM::S27:
1128     return ARM::S26;
1129   case ARM::S29:
1130     return ARM::S28;
1131   case ARM::S31:
1132     return ARM::S30;
1133
1134   case ARM::D1:
1135     return ARM::D0;
1136   case ARM::D3:
1137     return ARM::D2;
1138   case ARM::D5:
1139     return ARM::D4;
1140   case ARM::D7:
1141     return ARM::D6;
1142   case ARM::D9:
1143     return ARM::D8;
1144   case ARM::D11:
1145     return ARM::D10;
1146   case ARM::D13:
1147     return ARM::D12;
1148   case ARM::D15:
1149     return ARM::D14;
1150   case ARM::D17:
1151     return ARM::D16;
1152   case ARM::D19:
1153     return ARM::D18;
1154   case ARM::D21:
1155     return ARM::D20;
1156   case ARM::D23:
1157     return ARM::D22;
1158   case ARM::D25:
1159     return ARM::D24;
1160   case ARM::D27:
1161     return ARM::D26;
1162   case ARM::D29:
1163     return ARM::D28;
1164   case ARM::D31:
1165     return ARM::D30;
1166   }
1167
1168   return 0;
1169 }
1170
1171 unsigned ARMBaseRegisterInfo::getRegisterPairOdd(unsigned Reg,
1172                                              const MachineFunction &MF) const {
1173   switch (Reg) {
1174   default: break;
1175   // Return 0 if either register of the pair is a special register.
1176   // So no R12, etc.
1177   case ARM::R0:
1178     return ARM::R1;
1179   case ARM::R2:
1180     return ARM::R3;
1181   case ARM::R4:
1182     return ARM::R5;
1183   case ARM::R6:
1184     return isReservedReg(MF, ARM::R7)  ? 0 : ARM::R7;
1185   case ARM::R8:
1186     return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R9;
1187   case ARM::R10:
1188     return isReservedReg(MF, ARM::R11) ? 0 : ARM::R11;
1189
1190   case ARM::S0:
1191     return ARM::S1;
1192   case ARM::S2:
1193     return ARM::S3;
1194   case ARM::S4:
1195     return ARM::S5;
1196   case ARM::S6:
1197     return ARM::S7;
1198   case ARM::S8:
1199     return ARM::S9;
1200   case ARM::S10:
1201     return ARM::S11;
1202   case ARM::S12:
1203     return ARM::S13;
1204   case ARM::S14:
1205     return ARM::S15;
1206   case ARM::S16:
1207     return ARM::S17;
1208   case ARM::S18:
1209     return ARM::S19;
1210   case ARM::S20:
1211     return ARM::S21;
1212   case ARM::S22:
1213     return ARM::S23;
1214   case ARM::S24:
1215     return ARM::S25;
1216   case ARM::S26:
1217     return ARM::S27;
1218   case ARM::S28:
1219     return ARM::S29;
1220   case ARM::S30:
1221     return ARM::S31;
1222
1223   case ARM::D0:
1224     return ARM::D1;
1225   case ARM::D2:
1226     return ARM::D3;
1227   case ARM::D4:
1228     return ARM::D5;
1229   case ARM::D6:
1230     return ARM::D7;
1231   case ARM::D8:
1232     return ARM::D9;
1233   case ARM::D10:
1234     return ARM::D11;
1235   case ARM::D12:
1236     return ARM::D13;
1237   case ARM::D14:
1238     return ARM::D15;
1239   case ARM::D16:
1240     return ARM::D17;
1241   case ARM::D18:
1242     return ARM::D19;
1243   case ARM::D20:
1244     return ARM::D21;
1245   case ARM::D22:
1246     return ARM::D23;
1247   case ARM::D24:
1248     return ARM::D25;
1249   case ARM::D26:
1250     return ARM::D27;
1251   case ARM::D28:
1252     return ARM::D29;
1253   case ARM::D30:
1254     return ARM::D31;
1255   }
1256
1257   return 0;
1258 }
1259
1260 /// emitLoadConstPool - Emits a load from constpool to materialize the
1261 /// specified immediate.
1262 void ARMBaseRegisterInfo::
1263 emitLoadConstPool(MachineBasicBlock &MBB,
1264                   MachineBasicBlock::iterator &MBBI,
1265                   DebugLoc dl,
1266                   unsigned DestReg, unsigned SubIdx, int Val,
1267                   ARMCC::CondCodes Pred,
1268                   unsigned PredReg) const {
1269   MachineFunction &MF = *MBB.getParent();
1270   MachineConstantPool *ConstantPool = MF.getConstantPool();
1271   const Constant *C =
1272         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
1273   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
1274
1275   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
1276     .addReg(DestReg, getDefRegState(true), SubIdx)
1277     .addConstantPoolIndex(Idx)
1278     .addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
1279 }
1280
1281 bool ARMBaseRegisterInfo::
1282 requiresRegisterScavenging(const MachineFunction &MF) const {
1283   return true;
1284 }
1285
1286 bool ARMBaseRegisterInfo::
1287 requiresFrameIndexScavenging(const MachineFunction &MF) const {
1288   return true;
1289 }
1290
1291 bool ARMBaseRegisterInfo::
1292 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
1293   return EnableLocalStackAlloc;
1294 }
1295
1296 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
1297 // not required, we reserve argument space for call sites in the function
1298 // immediately on entry to the current function. This eliminates the need for
1299 // add/sub sp brackets around call sites. Returns true if the call frame is
1300 // included as part of the stack frame.
1301 bool ARMBaseRegisterInfo::
1302 hasReservedCallFrame(const MachineFunction &MF) const {
1303   const MachineFrameInfo *FFI = MF.getFrameInfo();
1304   unsigned CFSize = FFI->getMaxCallFrameSize();
1305   // It's not always a good idea to include the call frame as part of the
1306   // stack frame. ARM (especially Thumb) has small immediate offset to
1307   // address the stack frame. So a large call frame can cause poor codegen
1308   // and may even makes it impossible to scavenge a register.
1309   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
1310     return false;
1311
1312   return !MF.getFrameInfo()->hasVarSizedObjects();
1313 }
1314
1315 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
1316 // call frame pseudos can be simplified. Unlike most targets, having a FP
1317 // is not sufficient here since we still may reference some objects via SP
1318 // even when FP is available in Thumb2 mode.
1319 bool ARMBaseRegisterInfo::
1320 canSimplifyCallFramePseudos(const MachineFunction &MF) const {
1321   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
1322 }
1323
1324 static void
1325 emitSPUpdate(bool isARM,
1326              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
1327              DebugLoc dl, const ARMBaseInstrInfo &TII,
1328              int NumBytes,
1329              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
1330   if (isARM)
1331     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1332                             Pred, PredReg, TII);
1333   else
1334     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1335                            Pred, PredReg, TII);
1336 }
1337
1338
1339 void ARMBaseRegisterInfo::
1340 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1341                               MachineBasicBlock::iterator I) const {
1342   if (!hasReservedCallFrame(MF)) {
1343     // If we have alloca, convert as follows:
1344     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1345     // ADJCALLSTACKUP   -> add, sp, sp, amount
1346     MachineInstr *Old = I;
1347     DebugLoc dl = Old->getDebugLoc();
1348     unsigned Amount = Old->getOperand(0).getImm();
1349     if (Amount != 0) {
1350       // We need to keep the stack aligned properly.  To do this, we round the
1351       // amount of space needed for the outgoing arguments up to the next
1352       // alignment boundary.
1353       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1354       Amount = (Amount+Align-1)/Align*Align;
1355
1356       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1357       assert(!AFI->isThumb1OnlyFunction() &&
1358              "This eliminateCallFramePseudoInstr does not support Thumb1!");
1359       bool isARM = !AFI->isThumbFunction();
1360
1361       // Replace the pseudo instruction with a new instruction...
1362       unsigned Opc = Old->getOpcode();
1363       int PIdx = Old->findFirstPredOperandIdx();
1364       ARMCC::CondCodes Pred = (PIdx == -1)
1365         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1366       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1367         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1368         unsigned PredReg = Old->getOperand(2).getReg();
1369         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
1370       } else {
1371         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1372         unsigned PredReg = Old->getOperand(3).getReg();
1373         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1374         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
1375       }
1376     }
1377   }
1378   MBB.erase(I);
1379 }
1380
1381
1382 int64_t ARMBaseRegisterInfo::
1383 getFrameIndexInstrOffset(MachineInstr *MI, int Idx) const {
1384   const TargetInstrDesc &Desc = MI->getDesc();
1385   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1386   int64_t InstrOffs = 0;;
1387   int Scale = 1;
1388   unsigned ImmIdx = 0;
1389   switch(AddrMode) {
1390   case ARMII::AddrModeT2_i8:
1391   case ARMII::AddrModeT2_i12:
1392     // i8 supports only negative, and i12 supports only positive, so
1393     // based on Offset sign, consider the appropriate instruction
1394     InstrOffs = MI->getOperand(Idx+1).getImm();
1395     Scale = 1;
1396     break;
1397   case ARMII::AddrMode5: {
1398     // VFP address mode.
1399     const MachineOperand &OffOp = MI->getOperand(Idx+1);
1400     int InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
1401     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
1402       InstrOffs = -InstrOffs;
1403     Scale = 4;
1404     break;
1405   }
1406   case ARMII::AddrMode2: {
1407     ImmIdx = Idx+2;
1408     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
1409     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1410       InstrOffs = -InstrOffs;
1411     break;
1412   }
1413   case ARMII::AddrMode3: {
1414     ImmIdx = Idx+2;
1415     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
1416     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1417       InstrOffs = -InstrOffs;
1418     break;
1419   }
1420   case ARMII::AddrModeT1_s: {
1421     ImmIdx = Idx+1;
1422     InstrOffs = MI->getOperand(ImmIdx).getImm();
1423     Scale = 4;
1424     break;
1425   }
1426   default:
1427     llvm_unreachable("Unsupported addressing mode!");
1428     break;
1429   }
1430
1431   return InstrOffs * Scale;
1432 }
1433
1434 /// needsFrameBaseReg - Returns true if the instruction's frame index
1435 /// reference would be better served by a base register other than FP
1436 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1437 /// references it should create new base registers for.
1438 bool ARMBaseRegisterInfo::
1439 needsFrameBaseReg(MachineInstr *MI, unsigned operand) const {
1440   assert (MI->getOperand(operand).isFI() &&
1441           "needsFrameBaseReg() called on non Frame Index operand!");
1442
1443   // It's the load/store FI references that cause issues, as it can be difficult
1444   // to materialize the offset if it won't fit in the literal field. Estimate
1445   // based on the size of the local frame and some conservative assumptions
1446   // about the rest of the stack frame (note, this is pre-regalloc, so
1447   // we don't know everything for certain yet) whether this offset is likely
1448   // to be out of range of the immediate. Return true if so.
1449
1450   // We only generate virtual base registers for loads and stores, so
1451   // return false for everything else.
1452   unsigned Opc = MI->getOpcode();
1453   switch (Opc) {
1454   case ARM::LDR: case ARM::LDRH: case ARM::LDRB:
1455   case ARM::STR: case ARM::STRH: case ARM::STRB:
1456   case ARM::t2LDRi12: case ARM::t2LDRi8:
1457   case ARM::t2STRi12: case ARM::t2STRi8:
1458   case ARM::VLDRS: case ARM::VLDRD:
1459   case ARM::VSTRS: case ARM::VSTRD:
1460   case ARM::tSTRspi: case ARM::tLDRspi:
1461     if (ForceAllBaseRegAlloc)
1462       return true;
1463     break;
1464   default:
1465     return false;
1466   }
1467
1468   // FIXME: TODO
1469   // Without a virtual base register, if the function has variable sized
1470   // objects, all fixed-size local references will be via the frame pointer,
1471   // otherwise via the stack pointer. Approximate the offset and see if it's
1472   // legal for the instruction.
1473
1474   return true;
1475 }
1476
1477 /// materializeFrameBaseRegister - Insert defining instruction(s) for
1478 /// BaseReg to be a pointer to FrameIdx before insertion point I.
1479 void ARMBaseRegisterInfo::
1480 materializeFrameBaseRegister(MachineBasicBlock::iterator I, unsigned BaseReg,
1481                              int FrameIdx, int64_t Offset) const {
1482   ARMFunctionInfo *AFI =
1483     I->getParent()->getParent()->getInfo<ARMFunctionInfo>();
1484   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
1485     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
1486
1487   MachineInstrBuilder MIB =
1488     BuildMI(*I->getParent(), I, I->getDebugLoc(), TII.get(ADDriOpc), BaseReg)
1489     .addFrameIndex(FrameIdx).addImm(Offset);
1490   if (!AFI->isThumb1OnlyFunction())
1491     AddDefaultCC(AddDefaultPred(MIB));
1492 }
1493
1494 void
1495 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
1496                                        unsigned BaseReg, int64_t Offset) const {
1497   MachineInstr &MI = *I;
1498   MachineBasicBlock &MBB = *MI.getParent();
1499   MachineFunction &MF = *MBB.getParent();
1500   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1501   int Off = Offset; // ARM doesn't need the general 64-bit offsets
1502   unsigned i = 0;
1503
1504   assert(!AFI->isThumb1OnlyFunction() &&
1505          "This resolveFrameIndex does not support Thumb1!");
1506
1507   while (!MI.getOperand(i).isFI()) {
1508     ++i;
1509     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1510   }
1511   bool Done = false;
1512   if (!AFI->isThumbFunction())
1513     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
1514   else {
1515     assert(AFI->isThumb2Function());
1516     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
1517   }
1518   assert (Done && "Unable to resolve frame index!");
1519 }
1520
1521 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1522                                              int64_t Offset) const {
1523   const TargetInstrDesc &Desc = MI->getDesc();
1524   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1525   unsigned i = 0;
1526
1527   while (!MI->getOperand(i).isFI()) {
1528     ++i;
1529     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
1530   }
1531
1532   // AddrMode4 and AddrMode6 cannot handle any offset.
1533   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
1534     return Offset == 0;
1535
1536   unsigned NumBits = 0;
1537   unsigned Scale = 1;
1538   unsigned ImmIdx = 0;
1539   int InstrOffs = 0;;
1540   bool isSigned = true;
1541   switch(AddrMode) {
1542   case ARMII::AddrModeT2_i8:
1543   case ARMII::AddrModeT2_i12:
1544     // i8 supports only negative, and i12 supports only positive, so
1545     // based on Offset sign, consider the appropriate instruction
1546     InstrOffs = MI->getOperand(i+1).getImm();
1547     Scale = 1;
1548     if (Offset < 0) {
1549       NumBits = 8;
1550       Offset = -Offset;
1551     } else {
1552       NumBits = 12;
1553     }
1554     break;
1555   case ARMII::AddrMode5: {
1556     // VFP address mode.
1557     const MachineOperand &OffOp = MI->getOperand(i+1);
1558     int InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
1559     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
1560       InstrOffs = -InstrOffs;
1561     NumBits = 8;
1562     Scale = 4;
1563     break;
1564   }
1565   case ARMII::AddrMode2: {
1566     ImmIdx = i+2;
1567     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
1568     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1569       InstrOffs = -InstrOffs;
1570     NumBits = 12;
1571     break;
1572   }
1573   case ARMII::AddrMode3: {
1574     ImmIdx = i+2;
1575     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
1576     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1577       InstrOffs = -InstrOffs;
1578     NumBits = 8;
1579     break;
1580   }
1581   case ARMII::AddrModeT1_s: {
1582     ImmIdx = i+1;
1583     InstrOffs = MI->getOperand(ImmIdx).getImm();
1584     NumBits = 5;
1585     Scale = 4;
1586     isSigned = false;
1587     break;
1588   }
1589   default:
1590     llvm_unreachable("Unsupported addressing mode!");
1591     break;
1592   }
1593
1594   Offset += InstrOffs * Scale;
1595   assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1596   if (isSigned && Offset < 0)
1597     Offset = -Offset;
1598
1599   unsigned Mask = (1 << NumBits) - 1;
1600   if ((unsigned)Offset <= Mask * Scale)
1601     return true;
1602
1603   return false;
1604 }
1605
1606 unsigned
1607 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1608                                          int SPAdj, FrameIndexValue *Value,
1609                                          RegScavenger *RS) const {
1610   unsigned i = 0;
1611   MachineInstr &MI = *II;
1612   MachineBasicBlock &MBB = *MI.getParent();
1613   MachineFunction &MF = *MBB.getParent();
1614   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1615   assert(!AFI->isThumb1OnlyFunction() &&
1616          "This eliminateFrameIndex does not support Thumb1!");
1617
1618   while (!MI.getOperand(i).isFI()) {
1619     ++i;
1620     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1621   }
1622
1623   int FrameIndex = MI.getOperand(i).getIndex();
1624   unsigned FrameReg;
1625
1626   int Offset = ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
1627
1628   // Special handling of dbg_value instructions.
1629   if (MI.isDebugValue()) {
1630     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
1631     MI.getOperand(i+1).ChangeToImmediate(Offset);
1632     return 0;
1633   }
1634
1635   // Modify MI as necessary to handle as much of 'Offset' as possible
1636   bool Done = false;
1637   if (!AFI->isThumbFunction())
1638     Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
1639   else {
1640     assert(AFI->isThumb2Function());
1641     Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
1642   }
1643   if (Done)
1644     return 0;
1645
1646   // If we get here, the immediate doesn't fit into the instruction.  We folded
1647   // as much as possible above, handle the rest, providing a register that is
1648   // SP+LargeImm.
1649   assert((Offset ||
1650           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
1651           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
1652          "This code isn't needed if offset already handled!");
1653
1654   unsigned ScratchReg = 0;
1655   int PIdx = MI.findFirstPredOperandIdx();
1656   ARMCC::CondCodes Pred = (PIdx == -1)
1657     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
1658   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1659   if (Offset == 0)
1660     // Must be addrmode4/6.
1661     MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
1662   else {
1663     ScratchReg = MF.getRegInfo().createVirtualRegister(ARM::GPRRegisterClass);
1664     if (Value) {
1665       Value->first = FrameReg; // use the frame register as a kind indicator
1666       Value->second = Offset;
1667     }
1668     if (!AFI->isThumbFunction())
1669       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1670                               Offset, Pred, PredReg, TII);
1671     else {
1672       assert(AFI->isThumb2Function());
1673       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1674                              Offset, Pred, PredReg, TII);
1675     }
1676     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1677     if (!ReuseFrameIndexVals)
1678       ScratchReg = 0;
1679   }
1680   return ScratchReg;
1681 }
1682
1683 /// Move iterator past the next bunch of callee save load / store ops for
1684 /// the particular spill area (1: integer area 1, 2: integer area 2,
1685 /// 3: fp area, 0: don't care).
1686 static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
1687                                    MachineBasicBlock::iterator &MBBI,
1688                                    int Opc1, int Opc2, unsigned Area,
1689                                    const ARMSubtarget &STI) {
1690   while (MBBI != MBB.end() &&
1691          ((MBBI->getOpcode() == Opc1) || (MBBI->getOpcode() == Opc2)) &&
1692          MBBI->getOperand(1).isFI()) {
1693     if (Area != 0) {
1694       bool Done = false;
1695       unsigned Category = 0;
1696       switch (MBBI->getOperand(0).getReg()) {
1697       case ARM::R4:  case ARM::R5:  case ARM::R6: case ARM::R7:
1698       case ARM::LR:
1699         Category = 1;
1700         break;
1701       case ARM::R8:  case ARM::R9:  case ARM::R10: case ARM::R11:
1702         Category = STI.isTargetDarwin() ? 2 : 1;
1703         break;
1704       case ARM::D8:  case ARM::D9:  case ARM::D10: case ARM::D11:
1705       case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
1706         Category = 3;
1707         break;
1708       default:
1709         Done = true;
1710         break;
1711       }
1712       if (Done || Category != Area)
1713         break;
1714     }
1715
1716     ++MBBI;
1717   }
1718 }
1719
1720 void ARMBaseRegisterInfo::
1721 emitPrologue(MachineFunction &MF) const {
1722   MachineBasicBlock &MBB = MF.front();
1723   MachineBasicBlock::iterator MBBI = MBB.begin();
1724   MachineFrameInfo  *MFI = MF.getFrameInfo();
1725   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1726   assert(!AFI->isThumb1OnlyFunction() &&
1727          "This emitPrologue does not support Thumb1!");
1728   bool isARM = !AFI->isThumbFunction();
1729   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1730   unsigned NumBytes = MFI->getStackSize();
1731   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1732   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1733
1734   // Determine the sizes of each callee-save spill areas and record which frame
1735   // belongs to which callee-save spill areas.
1736   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1737   int FramePtrSpillFI = 0;
1738
1739   // Allocate the vararg register save area. This is not counted in NumBytes.
1740   if (VARegSaveSize)
1741     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
1742
1743   if (!AFI->hasStackFrame()) {
1744     if (NumBytes != 0)
1745       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
1746     return;
1747   }
1748
1749   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1750     unsigned Reg = CSI[i].getReg();
1751     int FI = CSI[i].getFrameIdx();
1752     switch (Reg) {
1753     case ARM::R4:
1754     case ARM::R5:
1755     case ARM::R6:
1756     case ARM::R7:
1757     case ARM::LR:
1758       if (Reg == FramePtr)
1759         FramePtrSpillFI = FI;
1760       AFI->addGPRCalleeSavedArea1Frame(FI);
1761       GPRCS1Size += 4;
1762       break;
1763     case ARM::R8:
1764     case ARM::R9:
1765     case ARM::R10:
1766     case ARM::R11:
1767       if (Reg == FramePtr)
1768         FramePtrSpillFI = FI;
1769       if (STI.isTargetDarwin()) {
1770         AFI->addGPRCalleeSavedArea2Frame(FI);
1771         GPRCS2Size += 4;
1772       } else {
1773         AFI->addGPRCalleeSavedArea1Frame(FI);
1774         GPRCS1Size += 4;
1775       }
1776       break;
1777     default:
1778       AFI->addDPRCalleeSavedAreaFrame(FI);
1779       DPRCSSize += 8;
1780     }
1781   }
1782
1783   // Build the new SUBri to adjust SP for integer callee-save spill area 1.
1784   emitSPUpdate(isARM, MBB, MBBI, dl, TII, -GPRCS1Size);
1785   movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, ARM::t2STRi12, 1, STI);
1786
1787   // Set FP to point to the stack slot that contains the previous FP.
1788   // For Darwin, FP is R7, which has now been stored in spill area 1.
1789   // Otherwise, if this is not Darwin, all the callee-saved registers go
1790   // into spill area 1, including the FP in R11.  In either case, it is
1791   // now safe to emit this assignment.
1792   bool HasFP = hasFP(MF);
1793   if (HasFP) {
1794     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
1795     MachineInstrBuilder MIB =
1796       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
1797       .addFrameIndex(FramePtrSpillFI).addImm(0);
1798     AddDefaultCC(AddDefaultPred(MIB));
1799   }
1800
1801   // Build the new SUBri to adjust SP for integer callee-save spill area 2.
1802   emitSPUpdate(isARM, MBB, MBBI, dl, TII, -GPRCS2Size);
1803
1804   // Build the new SUBri to adjust SP for FP callee-save spill area.
1805   movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, ARM::t2STRi12, 2, STI);
1806   emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRCSSize);
1807
1808   // Determine starting offsets of spill areas.
1809   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
1810   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
1811   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
1812   if (HasFP)
1813     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
1814                                 NumBytes);
1815   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1816   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1817   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
1818
1819   movePastCSLoadStoreOps(MBB, MBBI, ARM::VSTRD, 0, 3, STI);
1820   NumBytes = DPRCSOffset;
1821   if (NumBytes) {
1822     // Adjust SP after all the callee-save spills.
1823     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
1824     if (HasFP)
1825       AFI->setShouldRestoreSPFromFP(true);
1826   }
1827
1828   if (STI.isTargetELF() && hasFP(MF)) {
1829     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
1830                              AFI->getFramePtrSpillOffset());
1831     AFI->setShouldRestoreSPFromFP(true);
1832   }
1833
1834   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1835   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1836   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
1837
1838   // If we need dynamic stack realignment, do it here.
1839   if (needsStackRealignment(MF)) {
1840     unsigned MaxAlign = MFI->getMaxAlignment();
1841     assert (!AFI->isThumb1OnlyFunction());
1842     if (!AFI->isThumbFunction()) {
1843       // Emit bic sp, sp, MaxAlign
1844       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
1845                                           TII.get(ARM::BICri), ARM::SP)
1846                                   .addReg(ARM::SP, RegState::Kill)
1847                                   .addImm(MaxAlign-1)));
1848     } else {
1849       // We cannot use sp as source/dest register here, thus we're emitting the
1850       // following sequence:
1851       // mov r4, sp
1852       // bic r4, r4, MaxAlign
1853       // mov sp, r4
1854       // FIXME: It will be better just to find spare register here.
1855       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
1856         .addReg(ARM::SP, RegState::Kill);
1857       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
1858                                           TII.get(ARM::t2BICri), ARM::R4)
1859                                   .addReg(ARM::R4, RegState::Kill)
1860                                   .addImm(MaxAlign-1)));
1861       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
1862         .addReg(ARM::R4, RegState::Kill);
1863     }
1864
1865     AFI->setShouldRestoreSPFromFP(true);
1866   }
1867
1868   // If the frame has variable sized objects then the epilogue must restore
1869   // the sp from fp.
1870   if (!AFI->shouldRestoreSPFromFP() && MFI->hasVarSizedObjects())
1871     AFI->setShouldRestoreSPFromFP(true);
1872 }
1873
1874 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
1875   for (unsigned i = 0; CSRegs[i]; ++i)
1876     if (Reg == CSRegs[i])
1877       return true;
1878   return false;
1879 }
1880
1881 static bool isCSRestore(MachineInstr *MI,
1882                         const ARMBaseInstrInfo &TII,
1883                         const unsigned *CSRegs) {
1884   return ((MI->getOpcode() == (int)ARM::VLDRD ||
1885            MI->getOpcode() == (int)ARM::LDR ||
1886            MI->getOpcode() == (int)ARM::t2LDRi12) &&
1887           MI->getOperand(1).isFI() &&
1888           isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
1889 }
1890
1891 void ARMBaseRegisterInfo::
1892 emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const {
1893   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1894   assert(MBBI->getDesc().isReturn() &&
1895          "Can only insert epilog into returning blocks");
1896   unsigned RetOpcode = MBBI->getOpcode();
1897   DebugLoc dl = MBBI->getDebugLoc();
1898   MachineFrameInfo *MFI = MF.getFrameInfo();
1899   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1900   assert(!AFI->isThumb1OnlyFunction() &&
1901          "This emitEpilogue does not support Thumb1!");
1902   bool isARM = !AFI->isThumbFunction();
1903
1904   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1905   int NumBytes = (int)MFI->getStackSize();
1906
1907   if (!AFI->hasStackFrame()) {
1908     if (NumBytes != 0)
1909       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
1910   } else {
1911     // Unwind MBBI to point to first LDR / VLDRD.
1912     const unsigned *CSRegs = getCalleeSavedRegs();
1913     if (MBBI != MBB.begin()) {
1914       do
1915         --MBBI;
1916       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
1917       if (!isCSRestore(MBBI, TII, CSRegs))
1918         ++MBBI;
1919     }
1920
1921     // Move SP to start of FP callee save spill area.
1922     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
1923                  AFI->getGPRCalleeSavedArea2Size() +
1924                  AFI->getDPRCalleeSavedAreaSize());
1925
1926     // Reset SP based on frame pointer only if the stack frame extends beyond
1927     // frame pointer stack slot or target is ELF and the function has FP.
1928     if (AFI->shouldRestoreSPFromFP()) {
1929       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1930       if (NumBytes) {
1931         if (isARM)
1932           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
1933                                   ARMCC::AL, 0, TII);
1934         else
1935           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
1936                                  ARMCC::AL, 0, TII);
1937       } else {
1938         // Thumb2 or ARM.
1939         if (isARM)
1940           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
1941             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1942         else
1943           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
1944             .addReg(FramePtr);
1945       }
1946     } else if (NumBytes)
1947       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
1948
1949     // Move SP to start of integer callee save spill area 2.
1950     movePastCSLoadStoreOps(MBB, MBBI, ARM::VLDRD, 0, 3, STI);
1951     emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedAreaSize());
1952
1953     // Move SP to start of integer callee save spill area 1.
1954     movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, ARM::t2LDRi12, 2, STI);
1955     emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getGPRCalleeSavedArea2Size());
1956
1957     // Move SP to SP upon entry to the function.
1958     movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, ARM::t2LDRi12, 1, STI);
1959     emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getGPRCalleeSavedArea1Size());
1960   }
1961
1962   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
1963       RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
1964     // Tail call return: adjust the stack pointer and jump to callee.
1965     MBBI = prior(MBB.end());
1966     MachineOperand &JumpTarget = MBBI->getOperand(0);
1967
1968     // Jump to label or value in register.
1969     if (RetOpcode == ARM::TCRETURNdi) {
1970       BuildMI(MBB, MBBI, dl, 
1971             TII.get(STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)).
1972         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1973                          JumpTarget.getTargetFlags());
1974     } else if (RetOpcode == ARM::TCRETURNdiND) {
1975       BuildMI(MBB, MBBI, dl,
1976             TII.get(STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND)).
1977         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1978                          JumpTarget.getTargetFlags());
1979     } else if (RetOpcode == ARM::TCRETURNri) {
1980       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
1981         addReg(JumpTarget.getReg(), RegState::Kill);
1982     } else if (RetOpcode == ARM::TCRETURNriND) {
1983       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
1984         addReg(JumpTarget.getReg(), RegState::Kill);
1985     } 
1986
1987     MachineInstr *NewMI = prior(MBBI);
1988     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
1989       NewMI->addOperand(MBBI->getOperand(i));
1990
1991     // Delete the pseudo instruction TCRETURN.
1992     MBB.erase(MBBI);
1993   }
1994
1995   if (VARegSaveSize)
1996     emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
1997 }
1998
1999 #include "ARMGenRegisterInfo.inc"