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