ARMBaseRegisterInfo.cpp revision 36b56886974eae4f9c5ebc96befd3e7bfe5de338
1//===-- ARMBaseRegisterInfo.cpp - ARM Register Information ----------------===//
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 "ARMBaseRegisterInfo.h"
15#include "ARM.h"
16#include "ARMBaseInstrInfo.h"
17#include "ARMFrameLowering.h"
18#include "ARMMachineFunctionInfo.h"
19#include "ARMSubtarget.h"
20#include "MCTargetDesc/ARMAddressingModes.h"
21#include "llvm/ADT/BitVector.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineRegisterInfo.h"
28#include "llvm/CodeGen/RegisterScavenging.h"
29#include "llvm/CodeGen/VirtRegMap.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/raw_ostream.h"
37#include "llvm/Target/TargetFrameLowering.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetOptions.h"
40
41#define GET_REGINFO_TARGET_DESC
42#include "ARMGenRegisterInfo.inc"
43
44using namespace llvm;
45
46ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMSubtarget &sti)
47  : ARMGenRegisterInfo(ARM::LR, 0, 0, ARM::PC), STI(sti),
48    FramePtr((STI.isTargetMachO() || STI.isThumb()) ? ARM::R7 : ARM::R11),
49    BasePtr(ARM::R6) {
50}
51
52const uint16_t*
53ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
54  const uint16_t *RegList = (STI.isTargetIOS() && !STI.isAAPCS_ABI())
55                                ? CSR_iOS_SaveList
56                                : CSR_AAPCS_SaveList;
57
58  if (!MF) return RegList;
59
60  const Function *F = MF->getFunction();
61  if (F->getCallingConv() == CallingConv::GHC) {
62    // GHC set of callee saved regs is empty as all those regs are
63    // used for passing STG regs around
64    return CSR_NoRegs_SaveList;
65  } else if (F->hasFnAttribute("interrupt")) {
66    if (STI.isMClass()) {
67      // M-class CPUs have hardware which saves the registers needed to allow a
68      // function conforming to the AAPCS to function as a handler.
69      return CSR_AAPCS_SaveList;
70    } else if (F->getFnAttribute("interrupt").getValueAsString() == "FIQ") {
71      // Fast interrupt mode gives the handler a private copy of R8-R14, so less
72      // need to be saved to restore user-mode state.
73      return CSR_FIQ_SaveList;
74    } else {
75      // Generally only R13-R14 (i.e. SP, LR) are automatically preserved by
76      // exception handling.
77      return CSR_GenericInt_SaveList;
78    }
79  }
80
81  return RegList;
82}
83
84const uint32_t*
85ARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
86  if (CC == CallingConv::GHC)
87    // This is academic becase all GHC calls are (supposed to be) tail calls
88    return CSR_NoRegs_RegMask;
89  return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
90    ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
91}
92
93const uint32_t*
94ARMBaseRegisterInfo::getNoPreservedMask() const {
95  return CSR_NoRegs_RegMask;
96}
97
98const uint32_t*
99ARMBaseRegisterInfo::getThisReturnPreservedMask(CallingConv::ID CC) const {
100  // This should return a register mask that is the same as that returned by
101  // getCallPreservedMask but that additionally preserves the register used for
102  // the first i32 argument (which must also be the register used to return a
103  // single i32 return value)
104  //
105  // In case that the calling convention does not use the same register for
106  // both or otherwise does not want to enable this optimization, the function
107  // should return NULL
108  if (CC == CallingConv::GHC)
109    // This is academic becase all GHC calls are (supposed to be) tail calls
110    return NULL;
111  return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
112    ? CSR_iOS_ThisReturn_RegMask : CSR_AAPCS_ThisReturn_RegMask;
113}
114
115BitVector ARMBaseRegisterInfo::
116getReservedRegs(const MachineFunction &MF) const {
117  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
118
119  // FIXME: avoid re-calculating this every time.
120  BitVector Reserved(getNumRegs());
121  Reserved.set(ARM::SP);
122  Reserved.set(ARM::PC);
123  Reserved.set(ARM::FPSCR);
124  Reserved.set(ARM::APSR_NZCV);
125  if (TFI->hasFP(MF))
126    Reserved.set(FramePtr);
127  if (hasBasePointer(MF))
128    Reserved.set(BasePtr);
129  // Some targets reserve R9.
130  if (STI.isR9Reserved())
131    Reserved.set(ARM::R9);
132  // Reserve D16-D31 if the subtarget doesn't support them.
133  if (!STI.hasVFP3() || STI.hasD16()) {
134    assert(ARM::D31 == ARM::D16 + 15);
135    for (unsigned i = 0; i != 16; ++i)
136      Reserved.set(ARM::D16 + i);
137  }
138  const TargetRegisterClass *RC  = &ARM::GPRPairRegClass;
139  for(TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I!=E; ++I)
140    for (MCSubRegIterator SI(*I, this); SI.isValid(); ++SI)
141      if (Reserved.test(*SI)) Reserved.set(*I);
142
143  return Reserved;
144}
145
146const TargetRegisterClass*
147ARMBaseRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
148                                                                         const {
149  const TargetRegisterClass *Super = RC;
150  TargetRegisterClass::sc_iterator I = RC->getSuperClasses();
151  do {
152    switch (Super->getID()) {
153    case ARM::GPRRegClassID:
154    case ARM::SPRRegClassID:
155    case ARM::DPRRegClassID:
156    case ARM::QPRRegClassID:
157    case ARM::QQPRRegClassID:
158    case ARM::QQQQPRRegClassID:
159    case ARM::GPRPairRegClassID:
160      return Super;
161    }
162    Super = *I++;
163  } while (Super);
164  return RC;
165}
166
167const TargetRegisterClass *
168ARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
169                                                                         const {
170  return &ARM::GPRRegClass;
171}
172
173const TargetRegisterClass *
174ARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
175  if (RC == &ARM::CCRRegClass)
176    return 0;  // Can't copy CCR registers.
177  return RC;
178}
179
180unsigned
181ARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
182                                         MachineFunction &MF) const {
183  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
184
185  switch (RC->getID()) {
186  default:
187    return 0;
188  case ARM::tGPRRegClassID:
189    return TFI->hasFP(MF) ? 4 : 5;
190  case ARM::GPRRegClassID: {
191    unsigned FP = TFI->hasFP(MF) ? 1 : 0;
192    return 10 - FP - (STI.isR9Reserved() ? 1 : 0);
193  }
194  case ARM::SPRRegClassID:  // Currently not used as 'rep' register class.
195  case ARM::DPRRegClassID:
196    return 32 - 10;
197  }
198}
199
200// Get the other register in a GPRPair.
201static unsigned getPairedGPR(unsigned Reg, bool Odd, const MCRegisterInfo *RI) {
202  for (MCSuperRegIterator Supers(Reg, RI); Supers.isValid(); ++Supers)
203    if (ARM::GPRPairRegClass.contains(*Supers))
204      return RI->getSubReg(*Supers, Odd ? ARM::gsub_1 : ARM::gsub_0);
205  return 0;
206}
207
208// Resolve the RegPairEven / RegPairOdd register allocator hints.
209void
210ARMBaseRegisterInfo::getRegAllocationHints(unsigned VirtReg,
211                                           ArrayRef<MCPhysReg> Order,
212                                           SmallVectorImpl<MCPhysReg> &Hints,
213                                           const MachineFunction &MF,
214                                           const VirtRegMap *VRM) const {
215  const MachineRegisterInfo &MRI = MF.getRegInfo();
216  std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
217
218  unsigned Odd;
219  switch (Hint.first) {
220  case ARMRI::RegPairEven:
221    Odd = 0;
222    break;
223  case ARMRI::RegPairOdd:
224    Odd = 1;
225    break;
226  default:
227    TargetRegisterInfo::getRegAllocationHints(VirtReg, Order, Hints, MF, VRM);
228    return;
229  }
230
231  // This register should preferably be even (Odd == 0) or odd (Odd == 1).
232  // Check if the other part of the pair has already been assigned, and provide
233  // the paired register as the first hint.
234  unsigned PairedPhys = 0;
235  if (VRM && VRM->hasPhys(Hint.second)) {
236    PairedPhys = getPairedGPR(VRM->getPhys(Hint.second), Odd, this);
237    if (PairedPhys && MRI.isReserved(PairedPhys))
238      PairedPhys = 0;
239  }
240
241  // First prefer the paired physreg.
242  if (PairedPhys &&
243      std::find(Order.begin(), Order.end(), PairedPhys) != Order.end())
244    Hints.push_back(PairedPhys);
245
246  // Then prefer even or odd registers.
247  for (unsigned I = 0, E = Order.size(); I != E; ++I) {
248    unsigned Reg = Order[I];
249    if (Reg == PairedPhys || (getEncodingValue(Reg) & 1) != Odd)
250      continue;
251    // Don't provide hints that are paired to a reserved register.
252    unsigned Paired = getPairedGPR(Reg, !Odd, this);
253    if (!Paired || MRI.isReserved(Paired))
254      continue;
255    Hints.push_back(Reg);
256  }
257}
258
259void
260ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
261                                        MachineFunction &MF) const {
262  MachineRegisterInfo *MRI = &MF.getRegInfo();
263  std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
264  if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
265       Hint.first == (unsigned)ARMRI::RegPairEven) &&
266      TargetRegisterInfo::isVirtualRegister(Hint.second)) {
267    // If 'Reg' is one of the even / odd register pair and it's now changed
268    // (e.g. coalesced) into a different register. The other register of the
269    // pair allocation hint must be updated to reflect the relationship
270    // change.
271    unsigned OtherReg = Hint.second;
272    Hint = MRI->getRegAllocationHint(OtherReg);
273    if (Hint.second == Reg)
274      // Make sure the pair has not already divorced.
275      MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
276  }
277}
278
279bool
280ARMBaseRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
281  // CortexA9 has a Write-after-write hazard for NEON registers.
282  if (!STI.isLikeA9())
283    return false;
284
285  switch (RC->getID()) {
286  case ARM::DPRRegClassID:
287  case ARM::DPR_8RegClassID:
288  case ARM::DPR_VFP2RegClassID:
289  case ARM::QPRRegClassID:
290  case ARM::QPR_8RegClassID:
291  case ARM::QPR_VFP2RegClassID:
292  case ARM::SPRRegClassID:
293  case ARM::SPR_8RegClassID:
294    // Avoid reusing S, D, and Q registers.
295    // Don't increase register pressure for QQ and QQQQ.
296    return true;
297  default:
298    return false;
299  }
300}
301
302bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
303  const MachineFrameInfo *MFI = MF.getFrameInfo();
304  const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
305  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
306
307  // When outgoing call frames are so large that we adjust the stack pointer
308  // around the call, we can no longer use the stack pointer to reach the
309  // emergency spill slot.
310  if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
311    return true;
312
313  // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
314  // negative range for ldr/str (255), and thumb1 is positive offsets only.
315  // It's going to be better to use the SP or Base Pointer instead. When there
316  // are variable sized objects, we can't reference off of the SP, so we
317  // reserve a Base Pointer.
318  if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
319    // Conservatively estimate whether the negative offset from the frame
320    // pointer will be sufficient to reach. If a function has a smallish
321    // frame, it's less likely to have lots of spills and callee saved
322    // space, so it's all more likely to be within range of the frame pointer.
323    // If it's wrong, the scavenger will still enable access to work, it just
324    // won't be optimal.
325    if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
326      return false;
327    return true;
328  }
329
330  return false;
331}
332
333bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
334  const MachineRegisterInfo *MRI = &MF.getRegInfo();
335  const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
336  // We can't realign the stack if:
337  // 1. Dynamic stack realignment is explicitly disabled,
338  // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
339  // 3. There are VLAs in the function and the base pointer is disabled.
340  if (MF.getFunction()->hasFnAttribute("no-realign-stack"))
341    return false;
342  if (AFI->isThumb1OnlyFunction())
343    return false;
344  // Stack realignment requires a frame pointer.  If we already started
345  // register allocation with frame pointer elimination, it is too late now.
346  if (!MRI->canReserveReg(FramePtr))
347    return false;
348  // We may also need a base pointer if there are dynamic allocas or stack
349  // pointer adjustments around calls.
350  if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
351    return true;
352  // A base pointer is required and allowed.  Check that it isn't too late to
353  // reserve it.
354  return MRI->canReserveReg(BasePtr);
355}
356
357bool ARMBaseRegisterInfo::
358needsStackRealignment(const MachineFunction &MF) const {
359  const MachineFrameInfo *MFI = MF.getFrameInfo();
360  const Function *F = MF.getFunction();
361  unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
362  bool requiresRealignment =
363    ((MFI->getMaxAlignment() > StackAlign) ||
364     F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
365                                     Attribute::StackAlignment));
366
367  return requiresRealignment && canRealignStack(MF);
368}
369
370bool ARMBaseRegisterInfo::
371cannotEliminateFrame(const MachineFunction &MF) const {
372  const MachineFrameInfo *MFI = MF.getFrameInfo();
373  if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
374    return true;
375  return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
376    || needsStackRealignment(MF);
377}
378
379unsigned
380ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
381  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
382
383  if (TFI->hasFP(MF))
384    return FramePtr;
385  return ARM::SP;
386}
387
388/// emitLoadConstPool - Emits a load from constpool to materialize the
389/// specified immediate.
390void ARMBaseRegisterInfo::
391emitLoadConstPool(MachineBasicBlock &MBB,
392                  MachineBasicBlock::iterator &MBBI,
393                  DebugLoc dl,
394                  unsigned DestReg, unsigned SubIdx, int Val,
395                  ARMCC::CondCodes Pred,
396                  unsigned PredReg, unsigned MIFlags) const {
397  MachineFunction &MF = *MBB.getParent();
398  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
399  MachineConstantPool *ConstantPool = MF.getConstantPool();
400  const Constant *C =
401        ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
402  unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
403
404  BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
405    .addReg(DestReg, getDefRegState(true), SubIdx)
406    .addConstantPoolIndex(Idx)
407    .addImm(0).addImm(Pred).addReg(PredReg)
408    .setMIFlags(MIFlags);
409}
410
411bool ARMBaseRegisterInfo::mayOverrideLocalAssignment() const {
412  // The native linux build hits a downstream codegen bug when this is enabled.
413  return STI.isTargetDarwin();
414}
415
416bool ARMBaseRegisterInfo::
417requiresRegisterScavenging(const MachineFunction &MF) const {
418  return true;
419}
420
421bool ARMBaseRegisterInfo::
422trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
423  return true;
424}
425
426bool ARMBaseRegisterInfo::
427requiresFrameIndexScavenging(const MachineFunction &MF) const {
428  return true;
429}
430
431bool ARMBaseRegisterInfo::
432requiresVirtualBaseRegisters(const MachineFunction &MF) const {
433  return true;
434}
435
436int64_t ARMBaseRegisterInfo::
437getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
438  const MCInstrDesc &Desc = MI->getDesc();
439  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
440  int64_t InstrOffs = 0;
441  int Scale = 1;
442  unsigned ImmIdx = 0;
443  switch (AddrMode) {
444  case ARMII::AddrModeT2_i8:
445  case ARMII::AddrModeT2_i12:
446  case ARMII::AddrMode_i12:
447    InstrOffs = MI->getOperand(Idx+1).getImm();
448    Scale = 1;
449    break;
450  case ARMII::AddrMode5: {
451    // VFP address mode.
452    const MachineOperand &OffOp = MI->getOperand(Idx+1);
453    InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
454    if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
455      InstrOffs = -InstrOffs;
456    Scale = 4;
457    break;
458  }
459  case ARMII::AddrMode2: {
460    ImmIdx = Idx+2;
461    InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
462    if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
463      InstrOffs = -InstrOffs;
464    break;
465  }
466  case ARMII::AddrMode3: {
467    ImmIdx = Idx+2;
468    InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
469    if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
470      InstrOffs = -InstrOffs;
471    break;
472  }
473  case ARMII::AddrModeT1_s: {
474    ImmIdx = Idx+1;
475    InstrOffs = MI->getOperand(ImmIdx).getImm();
476    Scale = 4;
477    break;
478  }
479  default:
480    llvm_unreachable("Unsupported addressing mode!");
481  }
482
483  return InstrOffs * Scale;
484}
485
486/// needsFrameBaseReg - Returns true if the instruction's frame index
487/// reference would be better served by a base register other than FP
488/// or SP. Used by LocalStackFrameAllocation to determine which frame index
489/// references it should create new base registers for.
490bool ARMBaseRegisterInfo::
491needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
492  for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
493    assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
494  }
495
496  // It's the load/store FI references that cause issues, as it can be difficult
497  // to materialize the offset if it won't fit in the literal field. Estimate
498  // based on the size of the local frame and some conservative assumptions
499  // about the rest of the stack frame (note, this is pre-regalloc, so
500  // we don't know everything for certain yet) whether this offset is likely
501  // to be out of range of the immediate. Return true if so.
502
503  // We only generate virtual base registers for loads and stores, so
504  // return false for everything else.
505  unsigned Opc = MI->getOpcode();
506  switch (Opc) {
507  case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
508  case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
509  case ARM::t2LDRi12: case ARM::t2LDRi8:
510  case ARM::t2STRi12: case ARM::t2STRi8:
511  case ARM::VLDRS: case ARM::VLDRD:
512  case ARM::VSTRS: case ARM::VSTRD:
513  case ARM::tSTRspi: case ARM::tLDRspi:
514    break;
515  default:
516    return false;
517  }
518
519  // Without a virtual base register, if the function has variable sized
520  // objects, all fixed-size local references will be via the frame pointer,
521  // Approximate the offset and see if it's legal for the instruction.
522  // Note that the incoming offset is based on the SP value at function entry,
523  // so it'll be negative.
524  MachineFunction &MF = *MI->getParent()->getParent();
525  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
526  MachineFrameInfo *MFI = MF.getFrameInfo();
527  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
528
529  // Estimate an offset from the frame pointer.
530  // Conservatively assume all callee-saved registers get pushed. R4-R6
531  // will be earlier than the FP, so we ignore those.
532  // R7, LR
533  int64_t FPOffset = Offset - 8;
534  // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
535  if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
536    FPOffset -= 80;
537  // Estimate an offset from the stack pointer.
538  // The incoming offset is relating to the SP at the start of the function,
539  // but when we access the local it'll be relative to the SP after local
540  // allocation, so adjust our SP-relative offset by that allocation size.
541  Offset = -Offset;
542  Offset += MFI->getLocalFrameSize();
543  // Assume that we'll have at least some spill slots allocated.
544  // FIXME: This is a total SWAG number. We should run some statistics
545  //        and pick a real one.
546  Offset += 128; // 128 bytes of spill slots
547
548  // If there is a frame pointer, try using it.
549  // The FP is only available if there is no dynamic realignment. We
550  // don't know for sure yet whether we'll need that, so we guess based
551  // on whether there are any local variables that would trigger it.
552  unsigned StackAlign = TFI->getStackAlignment();
553  if (TFI->hasFP(MF) &&
554      !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
555    if (isFrameOffsetLegal(MI, FPOffset))
556      return false;
557  }
558  // If we can reference via the stack pointer, try that.
559  // FIXME: This (and the code that resolves the references) can be improved
560  //        to only disallow SP relative references in the live range of
561  //        the VLA(s). In practice, it's unclear how much difference that
562  //        would make, but it may be worth doing.
563  if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
564    return false;
565
566  // The offset likely isn't legal, we want to allocate a virtual base register.
567  return true;
568}
569
570/// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
571/// be a pointer to FrameIdx at the beginning of the basic block.
572void ARMBaseRegisterInfo::
573materializeFrameBaseRegister(MachineBasicBlock *MBB,
574                             unsigned BaseReg, int FrameIdx,
575                             int64_t Offset) const {
576  ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
577  unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
578    (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
579
580  MachineBasicBlock::iterator Ins = MBB->begin();
581  DebugLoc DL;                  // Defaults to "unknown"
582  if (Ins != MBB->end())
583    DL = Ins->getDebugLoc();
584
585  const MachineFunction &MF = *MBB->getParent();
586  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
587  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
588  const MCInstrDesc &MCID = TII.get(ADDriOpc);
589  MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
590
591  MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
592    .addFrameIndex(FrameIdx).addImm(Offset));
593
594  if (!AFI->isThumb1OnlyFunction())
595    AddDefaultCC(MIB);
596}
597
598void ARMBaseRegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
599                                            int64_t Offset) const {
600  MachineBasicBlock &MBB = *MI.getParent();
601  MachineFunction &MF = *MBB.getParent();
602  const ARMBaseInstrInfo &TII =
603    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
604  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
605  int Off = Offset; // ARM doesn't need the general 64-bit offsets
606  unsigned i = 0;
607
608  assert(!AFI->isThumb1OnlyFunction() &&
609         "This resolveFrameIndex does not support Thumb1!");
610
611  while (!MI.getOperand(i).isFI()) {
612    ++i;
613    assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
614  }
615  bool Done = false;
616  if (!AFI->isThumbFunction())
617    Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
618  else {
619    assert(AFI->isThumb2Function());
620    Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
621  }
622  assert (Done && "Unable to resolve frame index!");
623  (void)Done;
624}
625
626bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
627                                             int64_t Offset) const {
628  const MCInstrDesc &Desc = MI->getDesc();
629  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
630  unsigned i = 0;
631
632  while (!MI->getOperand(i).isFI()) {
633    ++i;
634    assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
635  }
636
637  // AddrMode4 and AddrMode6 cannot handle any offset.
638  if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
639    return Offset == 0;
640
641  unsigned NumBits = 0;
642  unsigned Scale = 1;
643  bool isSigned = true;
644  switch (AddrMode) {
645  case ARMII::AddrModeT2_i8:
646  case ARMII::AddrModeT2_i12:
647    // i8 supports only negative, and i12 supports only positive, so
648    // based on Offset sign, consider the appropriate instruction
649    Scale = 1;
650    if (Offset < 0) {
651      NumBits = 8;
652      Offset = -Offset;
653    } else {
654      NumBits = 12;
655    }
656    break;
657  case ARMII::AddrMode5:
658    // VFP address mode.
659    NumBits = 8;
660    Scale = 4;
661    break;
662  case ARMII::AddrMode_i12:
663  case ARMII::AddrMode2:
664    NumBits = 12;
665    break;
666  case ARMII::AddrMode3:
667    NumBits = 8;
668    break;
669  case ARMII::AddrModeT1_s:
670    NumBits = 5;
671    Scale = 4;
672    isSigned = false;
673    break;
674  default:
675    llvm_unreachable("Unsupported addressing mode!");
676  }
677
678  Offset += getFrameIndexInstrOffset(MI, i);
679  // Make sure the offset is encodable for instructions that scale the
680  // immediate.
681  if ((Offset & (Scale-1)) != 0)
682    return false;
683
684  if (isSigned && Offset < 0)
685    Offset = -Offset;
686
687  unsigned Mask = (1 << NumBits) - 1;
688  if ((unsigned)Offset <= Mask * Scale)
689    return true;
690
691  return false;
692}
693
694void
695ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
696                                         int SPAdj, unsigned FIOperandNum,
697                                         RegScavenger *RS) const {
698  MachineInstr &MI = *II;
699  MachineBasicBlock &MBB = *MI.getParent();
700  MachineFunction &MF = *MBB.getParent();
701  const ARMBaseInstrInfo &TII =
702    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
703  const ARMFrameLowering *TFI =
704    static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
705  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
706  assert(!AFI->isThumb1OnlyFunction() &&
707         "This eliminateFrameIndex does not support Thumb1!");
708  int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
709  unsigned FrameReg;
710
711  int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
712
713  // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
714  // call frame setup/destroy instructions have already been eliminated.  That
715  // means the stack pointer cannot be used to access the emergency spill slot
716  // when !hasReservedCallFrame().
717#ifndef NDEBUG
718  if (RS && FrameReg == ARM::SP && RS->isScavengingFrameIndex(FrameIndex)){
719    assert(TFI->hasReservedCallFrame(MF) &&
720           "Cannot use SP to access the emergency spill slot in "
721           "functions without a reserved call frame");
722    assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
723           "Cannot use SP to access the emergency spill slot in "
724           "functions with variable sized frame objects");
725  }
726#endif // NDEBUG
727
728  assert(!MI.isDebugValue() && "DBG_VALUEs should be handled in target-independent code");
729
730  // Modify MI as necessary to handle as much of 'Offset' as possible
731  bool Done = false;
732  if (!AFI->isThumbFunction())
733    Done = rewriteARMFrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
734  else {
735    assert(AFI->isThumb2Function());
736    Done = rewriteT2FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
737  }
738  if (Done)
739    return;
740
741  // If we get here, the immediate doesn't fit into the instruction.  We folded
742  // as much as possible above, handle the rest, providing a register that is
743  // SP+LargeImm.
744  assert((Offset ||
745          (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
746          (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
747         "This code isn't needed if offset already handled!");
748
749  unsigned ScratchReg = 0;
750  int PIdx = MI.findFirstPredOperandIdx();
751  ARMCC::CondCodes Pred = (PIdx == -1)
752    ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
753  unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
754  if (Offset == 0)
755    // Must be addrmode4/6.
756    MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false, false, false);
757  else {
758    ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
759    if (!AFI->isThumbFunction())
760      emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
761                              Offset, Pred, PredReg, TII);
762    else {
763      assert(AFI->isThumb2Function());
764      emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
765                             Offset, Pred, PredReg, TII);
766    }
767    // Update the original instruction to use the scratch register.
768    MI.getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false,true);
769  }
770}
771