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