ARMBaseRegisterInfo.cpp 36 KB

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