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