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