Thumb1FrameLowering.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. //===- Thumb1FrameLowering.cpp - Thumb1 Frame 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 Thumb1 implementation of TargetFrameLowering class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "Thumb1FrameLowering.h"
  13. #include "ARMBaseInstrInfo.h"
  14. #include "ARMBaseRegisterInfo.h"
  15. #include "ARMMachineFunctionInfo.h"
  16. #include "ARMSubtarget.h"
  17. #include "Thumb1InstrInfo.h"
  18. #include "ThumbRegisterInfo.h"
  19. #include "Utils/ARMBaseInfo.h"
  20. #include "llvm/ADT/BitVector.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/CodeGen/LivePhysRegs.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.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/MachineModuleInfo.h"
  30. #include "llvm/CodeGen/MachineOperand.h"
  31. #include "llvm/CodeGen/MachineRegisterInfo.h"
  32. #include "llvm/CodeGen/TargetInstrInfo.h"
  33. #include "llvm/CodeGen/TargetOpcodes.h"
  34. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  35. #include "llvm/IR/DebugLoc.h"
  36. #include "llvm/MC/MCContext.h"
  37. #include "llvm/MC/MCDwarf.h"
  38. #include "llvm/MC/MCRegisterInfo.h"
  39. #include "llvm/Support/Compiler.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/MathExtras.h"
  42. #include <bitset>
  43. #include <cassert>
  44. #include <iterator>
  45. #include <vector>
  46. using namespace llvm;
  47. Thumb1FrameLowering::Thumb1FrameLowering(const ARMSubtarget &sti)
  48. : ARMFrameLowering(sti) {}
  49. bool Thumb1FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const{
  50. const MachineFrameInfo &MFI = MF.getFrameInfo();
  51. unsigned CFSize = MFI.getMaxCallFrameSize();
  52. // It's not always a good idea to include the call frame as part of the
  53. // stack frame. ARM (especially Thumb) has small immediate offset to
  54. // address the stack frame. So a large call frame can cause poor codegen
  55. // and may even makes it impossible to scavenge a register.
  56. if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
  57. return false;
  58. return !MFI.hasVarSizedObjects();
  59. }
  60. static void
  61. emitPrologueEpilogueSPUpdate(MachineBasicBlock &MBB,
  62. MachineBasicBlock::iterator &MBBI,
  63. const TargetInstrInfo &TII, const DebugLoc &dl,
  64. const ThumbRegisterInfo &MRI, int NumBytes,
  65. unsigned ScratchReg, unsigned MIFlags) {
  66. // If it would take more than three instructions to adjust the stack pointer
  67. // using tADDspi/tSUBspi, load an immediate instead.
  68. if (std::abs(NumBytes) > 508 * 3) {
  69. // We use a different codepath here from the normal
  70. // emitThumbRegPlusImmediate so we don't have to deal with register
  71. // scavenging. (Scavenging could try to use the emergency spill slot
  72. // before we've actually finished setting up the stack.)
  73. if (ScratchReg == ARM::NoRegister)
  74. report_fatal_error("Failed to emit Thumb1 stack adjustment");
  75. MachineFunction &MF = *MBB.getParent();
  76. const ARMSubtarget &ST = MF.getSubtarget<ARMSubtarget>();
  77. if (ST.genExecuteOnly()) {
  78. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ScratchReg)
  79. .addImm(NumBytes).setMIFlags(MIFlags);
  80. } else {
  81. MRI.emitLoadConstPool(MBB, MBBI, dl, ScratchReg, 0, NumBytes, ARMCC::AL,
  82. 0, MIFlags);
  83. }
  84. BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDhirr), ARM::SP)
  85. .addReg(ARM::SP)
  86. .addReg(ScratchReg, RegState::Kill)
  87. .add(predOps(ARMCC::AL))
  88. .setMIFlags(MIFlags);
  89. return;
  90. }
  91. // FIXME: This is assuming the heuristics in emitThumbRegPlusImmediate
  92. // won't change.
  93. emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
  94. MRI, MIFlags);
  95. }
  96. static void emitCallSPUpdate(MachineBasicBlock &MBB,
  97. MachineBasicBlock::iterator &MBBI,
  98. const TargetInstrInfo &TII, const DebugLoc &dl,
  99. const ThumbRegisterInfo &MRI, int NumBytes,
  100. unsigned MIFlags = MachineInstr::NoFlags) {
  101. emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
  102. MRI, MIFlags);
  103. }
  104. MachineBasicBlock::iterator Thumb1FrameLowering::
  105. eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
  106. MachineBasicBlock::iterator I) const {
  107. const Thumb1InstrInfo &TII =
  108. *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
  109. const ThumbRegisterInfo *RegInfo =
  110. static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
  111. if (!hasReservedCallFrame(MF)) {
  112. // If we have alloca, convert as follows:
  113. // ADJCALLSTACKDOWN -> sub, sp, sp, amount
  114. // ADJCALLSTACKUP -> add, sp, sp, amount
  115. MachineInstr &Old = *I;
  116. DebugLoc dl = Old.getDebugLoc();
  117. unsigned Amount = TII.getFrameSize(Old);
  118. if (Amount != 0) {
  119. // We need to keep the stack aligned properly. To do this, we round the
  120. // amount of space needed for the outgoing arguments up to the next
  121. // alignment boundary.
  122. Amount = alignTo(Amount, getStackAlign());
  123. // Replace the pseudo instruction with a new instruction...
  124. unsigned Opc = Old.getOpcode();
  125. if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
  126. emitCallSPUpdate(MBB, I, TII, dl, *RegInfo, -Amount);
  127. } else {
  128. assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
  129. emitCallSPUpdate(MBB, I, TII, dl, *RegInfo, Amount);
  130. }
  131. }
  132. }
  133. return MBB.erase(I);
  134. }
  135. void Thumb1FrameLowering::emitPrologue(MachineFunction &MF,
  136. MachineBasicBlock &MBB) const {
  137. MachineBasicBlock::iterator MBBI = MBB.begin();
  138. MachineFrameInfo &MFI = MF.getFrameInfo();
  139. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  140. MachineModuleInfo &MMI = MF.getMMI();
  141. const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
  142. const ThumbRegisterInfo *RegInfo =
  143. static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
  144. const Thumb1InstrInfo &TII =
  145. *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
  146. unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
  147. unsigned NumBytes = MFI.getStackSize();
  148. assert(NumBytes >= ArgRegsSaveSize &&
  149. "ArgRegsSaveSize is included in NumBytes");
  150. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  151. // Debug location must be unknown since the first debug location is used
  152. // to determine the end of the prologue.
  153. DebugLoc dl;
  154. Register FramePtr = RegInfo->getFrameRegister(MF);
  155. Register BasePtr = RegInfo->getBaseRegister();
  156. int CFAOffset = 0;
  157. // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
  158. NumBytes = (NumBytes + 3) & ~3;
  159. MFI.setStackSize(NumBytes);
  160. // Determine the sizes of each callee-save spill areas and record which frame
  161. // belongs to which callee-save spill areas.
  162. unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
  163. int FramePtrSpillFI = 0;
  164. if (ArgRegsSaveSize) {
  165. emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -ArgRegsSaveSize,
  166. ARM::NoRegister, MachineInstr::FrameSetup);
  167. CFAOffset += ArgRegsSaveSize;
  168. unsigned CFIIndex =
  169. MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset));
  170. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  171. .addCFIIndex(CFIIndex)
  172. .setMIFlags(MachineInstr::FrameSetup);
  173. }
  174. if (!AFI->hasStackFrame()) {
  175. if (NumBytes - ArgRegsSaveSize != 0) {
  176. emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo,
  177. -(NumBytes - ArgRegsSaveSize),
  178. ARM::NoRegister, MachineInstr::FrameSetup);
  179. CFAOffset += NumBytes - ArgRegsSaveSize;
  180. unsigned CFIIndex = MF.addFrameInst(
  181. MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset));
  182. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  183. .addCFIIndex(CFIIndex)
  184. .setMIFlags(MachineInstr::FrameSetup);
  185. }
  186. return;
  187. }
  188. for (const CalleeSavedInfo &I : CSI) {
  189. Register Reg = I.getReg();
  190. int FI = I.getFrameIdx();
  191. switch (Reg) {
  192. case ARM::R8:
  193. case ARM::R9:
  194. case ARM::R10:
  195. case ARM::R11:
  196. if (STI.splitFramePushPop(MF)) {
  197. GPRCS2Size += 4;
  198. break;
  199. }
  200. LLVM_FALLTHROUGH;
  201. case ARM::R4:
  202. case ARM::R5:
  203. case ARM::R6:
  204. case ARM::R7:
  205. case ARM::LR:
  206. if (Reg == FramePtr)
  207. FramePtrSpillFI = FI;
  208. GPRCS1Size += 4;
  209. break;
  210. default:
  211. DPRCSSize += 8;
  212. }
  213. }
  214. if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
  215. ++MBBI;
  216. }
  217. // Determine starting offsets of spill areas.
  218. unsigned DPRCSOffset = NumBytes - ArgRegsSaveSize - (GPRCS1Size + GPRCS2Size + DPRCSSize);
  219. unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
  220. unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
  221. bool HasFP = hasFP(MF);
  222. if (HasFP)
  223. AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
  224. NumBytes);
  225. AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
  226. AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
  227. AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
  228. NumBytes = DPRCSOffset;
  229. int FramePtrOffsetInBlock = 0;
  230. unsigned adjustedGPRCS1Size = GPRCS1Size;
  231. if (GPRCS1Size > 0 && GPRCS2Size == 0 &&
  232. tryFoldSPUpdateIntoPushPop(STI, MF, &*std::prev(MBBI), NumBytes)) {
  233. FramePtrOffsetInBlock = NumBytes;
  234. adjustedGPRCS1Size += NumBytes;
  235. NumBytes = 0;
  236. }
  237. if (adjustedGPRCS1Size) {
  238. CFAOffset += adjustedGPRCS1Size;
  239. unsigned CFIIndex =
  240. MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset));
  241. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  242. .addCFIIndex(CFIIndex)
  243. .setMIFlags(MachineInstr::FrameSetup);
  244. }
  245. for (const CalleeSavedInfo &I : CSI) {
  246. Register Reg = I.getReg();
  247. int FI = I.getFrameIdx();
  248. switch (Reg) {
  249. case ARM::R8:
  250. case ARM::R9:
  251. case ARM::R10:
  252. case ARM::R11:
  253. case ARM::R12:
  254. if (STI.splitFramePushPop(MF))
  255. break;
  256. LLVM_FALLTHROUGH;
  257. case ARM::R0:
  258. case ARM::R1:
  259. case ARM::R2:
  260. case ARM::R3:
  261. case ARM::R4:
  262. case ARM::R5:
  263. case ARM::R6:
  264. case ARM::R7:
  265. case ARM::LR:
  266. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  267. nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
  268. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  269. .addCFIIndex(CFIIndex)
  270. .setMIFlags(MachineInstr::FrameSetup);
  271. break;
  272. }
  273. }
  274. // Adjust FP so it point to the stack slot that contains the previous FP.
  275. if (HasFP) {
  276. FramePtrOffsetInBlock +=
  277. MFI.getObjectOffset(FramePtrSpillFI) + GPRCS1Size + ArgRegsSaveSize;
  278. BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
  279. .addReg(ARM::SP)
  280. .addImm(FramePtrOffsetInBlock / 4)
  281. .setMIFlags(MachineInstr::FrameSetup)
  282. .add(predOps(ARMCC::AL));
  283. if(FramePtrOffsetInBlock) {
  284. CFAOffset -= FramePtrOffsetInBlock;
  285. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
  286. nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
  287. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  288. .addCFIIndex(CFIIndex)
  289. .setMIFlags(MachineInstr::FrameSetup);
  290. } else {
  291. unsigned CFIIndex =
  292. MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
  293. nullptr, MRI->getDwarfRegNum(FramePtr, true)));
  294. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  295. .addCFIIndex(CFIIndex)
  296. .setMIFlags(MachineInstr::FrameSetup);
  297. }
  298. if (NumBytes > 508)
  299. // If offset is > 508 then sp cannot be adjusted in a single instruction,
  300. // try restoring from fp instead.
  301. AFI->setShouldRestoreSPFromFP(true);
  302. }
  303. // Skip past the spilling of r8-r11, which could consist of multiple tPUSH
  304. // and tMOVr instructions. We don't need to add any call frame information
  305. // in-between these instructions, because they do not modify the high
  306. // registers.
  307. while (true) {
  308. MachineBasicBlock::iterator OldMBBI = MBBI;
  309. // Skip a run of tMOVr instructions
  310. while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tMOVr)
  311. MBBI++;
  312. if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
  313. MBBI++;
  314. } else {
  315. // We have reached an instruction which is not a push, so the previous
  316. // run of tMOVr instructions (which may have been empty) was not part of
  317. // the prologue. Reset MBBI back to the last PUSH of the prologue.
  318. MBBI = OldMBBI;
  319. break;
  320. }
  321. }
  322. // Emit call frame information for the callee-saved high registers.
  323. for (auto &I : CSI) {
  324. Register Reg = I.getReg();
  325. int FI = I.getFrameIdx();
  326. switch (Reg) {
  327. case ARM::R8:
  328. case ARM::R9:
  329. case ARM::R10:
  330. case ARM::R11:
  331. case ARM::R12: {
  332. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  333. nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
  334. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  335. .addCFIIndex(CFIIndex)
  336. .setMIFlags(MachineInstr::FrameSetup);
  337. break;
  338. }
  339. default:
  340. break;
  341. }
  342. }
  343. if (NumBytes) {
  344. // Insert it after all the callee-save spills.
  345. //
  346. // For a large stack frame, we might need a scratch register to store
  347. // the size of the frame. We know all callee-save registers are free
  348. // at this point in the prologue, so pick one.
  349. unsigned ScratchRegister = ARM::NoRegister;
  350. for (auto &I : CSI) {
  351. Register Reg = I.getReg();
  352. if (isARMLowRegister(Reg) && !(HasFP && Reg == FramePtr)) {
  353. ScratchRegister = Reg;
  354. break;
  355. }
  356. }
  357. emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
  358. ScratchRegister, MachineInstr::FrameSetup);
  359. if (!HasFP) {
  360. CFAOffset += NumBytes;
  361. unsigned CFIIndex = MF.addFrameInst(
  362. MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset));
  363. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  364. .addCFIIndex(CFIIndex)
  365. .setMIFlags(MachineInstr::FrameSetup);
  366. }
  367. }
  368. if (STI.isTargetELF() && HasFP)
  369. MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
  370. AFI->getFramePtrSpillOffset());
  371. AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
  372. AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
  373. AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
  374. if (RegInfo->hasStackRealignment(MF)) {
  375. const unsigned NrBitsToZero = Log2(MFI.getMaxAlign());
  376. // Emit the following sequence, using R4 as a temporary, since we cannot use
  377. // SP as a source or destination register for the shifts:
  378. // mov r4, sp
  379. // lsrs r4, r4, #NrBitsToZero
  380. // lsls r4, r4, #NrBitsToZero
  381. // mov sp, r4
  382. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
  383. .addReg(ARM::SP, RegState::Kill)
  384. .add(predOps(ARMCC::AL));
  385. BuildMI(MBB, MBBI, dl, TII.get(ARM::tLSRri), ARM::R4)
  386. .addDef(ARM::CPSR)
  387. .addReg(ARM::R4, RegState::Kill)
  388. .addImm(NrBitsToZero)
  389. .add(predOps(ARMCC::AL));
  390. BuildMI(MBB, MBBI, dl, TII.get(ARM::tLSLri), ARM::R4)
  391. .addDef(ARM::CPSR)
  392. .addReg(ARM::R4, RegState::Kill)
  393. .addImm(NrBitsToZero)
  394. .add(predOps(ARMCC::AL));
  395. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  396. .addReg(ARM::R4, RegState::Kill)
  397. .add(predOps(ARMCC::AL));
  398. AFI->setShouldRestoreSPFromFP(true);
  399. }
  400. // If we need a base pointer, set it up here. It's whatever the value
  401. // of the stack pointer is at this point. Any variable size objects
  402. // will be allocated after this, so we can still use the base pointer
  403. // to reference locals.
  404. if (RegInfo->hasBasePointer(MF))
  405. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
  406. .addReg(ARM::SP)
  407. .add(predOps(ARMCC::AL));
  408. // If the frame has variable sized objects then the epilogue must restore
  409. // the sp from fp. We can assume there's an FP here since hasFP already
  410. // checks for hasVarSizedObjects.
  411. if (MFI.hasVarSizedObjects())
  412. AFI->setShouldRestoreSPFromFP(true);
  413. // In some cases, virtual registers have been introduced, e.g. by uses of
  414. // emitThumbRegPlusImmInReg.
  415. MF.getProperties().reset(MachineFunctionProperties::Property::NoVRegs);
  416. }
  417. static bool isCSRestore(MachineInstr &MI, const MCPhysReg *CSRegs) {
  418. if (MI.getOpcode() == ARM::tLDRspi && MI.getOperand(1).isFI() &&
  419. isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs))
  420. return true;
  421. else if (MI.getOpcode() == ARM::tPOP) {
  422. return true;
  423. } else if (MI.getOpcode() == ARM::tMOVr) {
  424. Register Dst = MI.getOperand(0).getReg();
  425. Register Src = MI.getOperand(1).getReg();
  426. return ((ARM::tGPRRegClass.contains(Src) || Src == ARM::LR) &&
  427. ARM::hGPRRegClass.contains(Dst));
  428. }
  429. return false;
  430. }
  431. void Thumb1FrameLowering::emitEpilogue(MachineFunction &MF,
  432. MachineBasicBlock &MBB) const {
  433. MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
  434. DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
  435. MachineFrameInfo &MFI = MF.getFrameInfo();
  436. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  437. const ThumbRegisterInfo *RegInfo =
  438. static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
  439. const Thumb1InstrInfo &TII =
  440. *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
  441. unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
  442. int NumBytes = (int)MFI.getStackSize();
  443. assert((unsigned)NumBytes >= ArgRegsSaveSize &&
  444. "ArgRegsSaveSize is included in NumBytes");
  445. const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
  446. Register FramePtr = RegInfo->getFrameRegister(MF);
  447. if (!AFI->hasStackFrame()) {
  448. if (NumBytes - ArgRegsSaveSize != 0)
  449. emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo,
  450. NumBytes - ArgRegsSaveSize, ARM::NoRegister,
  451. MachineInstr::NoFlags);
  452. } else {
  453. // Unwind MBBI to point to first LDR / VLDRD.
  454. if (MBBI != MBB.begin()) {
  455. do
  456. --MBBI;
  457. while (MBBI != MBB.begin() && isCSRestore(*MBBI, CSRegs));
  458. if (!isCSRestore(*MBBI, CSRegs))
  459. ++MBBI;
  460. }
  461. // Move SP to start of FP callee save spill area.
  462. NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
  463. AFI->getGPRCalleeSavedArea2Size() +
  464. AFI->getDPRCalleeSavedAreaSize() +
  465. ArgRegsSaveSize);
  466. if (AFI->shouldRestoreSPFromFP()) {
  467. NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
  468. // Reset SP based on frame pointer only if the stack frame extends beyond
  469. // frame pointer stack slot, the target is ELF and the function has FP, or
  470. // the target uses var sized objects.
  471. if (NumBytes) {
  472. assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
  473. "No scratch register to restore SP from FP!");
  474. emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
  475. TII, *RegInfo);
  476. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  477. .addReg(ARM::R4)
  478. .add(predOps(ARMCC::AL));
  479. } else
  480. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  481. .addReg(FramePtr)
  482. .add(predOps(ARMCC::AL));
  483. } else {
  484. // For a large stack frame, we might need a scratch register to store
  485. // the size of the frame. We know all callee-save registers are free
  486. // at this point in the epilogue, so pick one.
  487. unsigned ScratchRegister = ARM::NoRegister;
  488. bool HasFP = hasFP(MF);
  489. for (auto &I : MFI.getCalleeSavedInfo()) {
  490. Register Reg = I.getReg();
  491. if (isARMLowRegister(Reg) && !(HasFP && Reg == FramePtr)) {
  492. ScratchRegister = Reg;
  493. break;
  494. }
  495. }
  496. if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET &&
  497. &MBB.front() != &*MBBI && std::prev(MBBI)->getOpcode() == ARM::tPOP) {
  498. MachineBasicBlock::iterator PMBBI = std::prev(MBBI);
  499. if (!tryFoldSPUpdateIntoPushPop(STI, MF, &*PMBBI, NumBytes))
  500. emitPrologueEpilogueSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes,
  501. ScratchRegister, MachineInstr::NoFlags);
  502. } else if (!tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
  503. emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes,
  504. ScratchRegister, MachineInstr::NoFlags);
  505. }
  506. }
  507. if (needPopSpecialFixUp(MF)) {
  508. bool Done = emitPopSpecialFixUp(MBB, /* DoIt */ true);
  509. (void)Done;
  510. assert(Done && "Emission of the special fixup failed!?");
  511. }
  512. }
  513. bool Thumb1FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
  514. if (!needPopSpecialFixUp(*MBB.getParent()))
  515. return true;
  516. MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
  517. return emitPopSpecialFixUp(*TmpMBB, /* DoIt */ false);
  518. }
  519. bool Thumb1FrameLowering::needPopSpecialFixUp(const MachineFunction &MF) const {
  520. ARMFunctionInfo *AFI =
  521. const_cast<MachineFunction *>(&MF)->getInfo<ARMFunctionInfo>();
  522. if (AFI->getArgRegsSaveSize())
  523. return true;
  524. // LR cannot be encoded with Thumb1, i.e., it requires a special fix-up.
  525. for (const CalleeSavedInfo &CSI : MF.getFrameInfo().getCalleeSavedInfo())
  526. if (CSI.getReg() == ARM::LR)
  527. return true;
  528. return false;
  529. }
  530. static void findTemporariesForLR(const BitVector &GPRsNoLRSP,
  531. const BitVector &PopFriendly,
  532. const LivePhysRegs &UsedRegs, unsigned &PopReg,
  533. unsigned &TmpReg, MachineRegisterInfo &MRI) {
  534. PopReg = TmpReg = 0;
  535. for (auto Reg : GPRsNoLRSP.set_bits()) {
  536. if (UsedRegs.available(MRI, Reg)) {
  537. // Remember the first pop-friendly register and exit.
  538. if (PopFriendly.test(Reg)) {
  539. PopReg = Reg;
  540. TmpReg = 0;
  541. break;
  542. }
  543. // Otherwise, remember that the register will be available to
  544. // save a pop-friendly register.
  545. TmpReg = Reg;
  546. }
  547. }
  548. }
  549. bool Thumb1FrameLowering::emitPopSpecialFixUp(MachineBasicBlock &MBB,
  550. bool DoIt) const {
  551. MachineFunction &MF = *MBB.getParent();
  552. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  553. unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
  554. const TargetInstrInfo &TII = *STI.getInstrInfo();
  555. const ThumbRegisterInfo *RegInfo =
  556. static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
  557. // If MBBI is a return instruction, or is a tPOP followed by a return
  558. // instruction in the successor BB, we may be able to directly restore
  559. // LR in the PC.
  560. // This is only possible with v5T ops (v4T can't change the Thumb bit via
  561. // a POP PC instruction), and only if we do not need to emit any SP update.
  562. // Otherwise, we need a temporary register to pop the value
  563. // and copy that value into LR.
  564. auto MBBI = MBB.getFirstTerminator();
  565. bool CanRestoreDirectly = STI.hasV5TOps() && !ArgRegsSaveSize;
  566. if (CanRestoreDirectly) {
  567. if (MBBI != MBB.end() && MBBI->getOpcode() != ARM::tB)
  568. CanRestoreDirectly = (MBBI->getOpcode() == ARM::tBX_RET ||
  569. MBBI->getOpcode() == ARM::tPOP_RET);
  570. else {
  571. auto MBBI_prev = MBBI;
  572. MBBI_prev--;
  573. assert(MBBI_prev->getOpcode() == ARM::tPOP);
  574. assert(MBB.succ_size() == 1);
  575. if ((*MBB.succ_begin())->begin()->getOpcode() == ARM::tBX_RET)
  576. MBBI = MBBI_prev; // Replace the final tPOP with a tPOP_RET.
  577. else
  578. CanRestoreDirectly = false;
  579. }
  580. }
  581. if (CanRestoreDirectly) {
  582. if (!DoIt || MBBI->getOpcode() == ARM::tPOP_RET)
  583. return true;
  584. MachineInstrBuilder MIB =
  585. BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP_RET))
  586. .add(predOps(ARMCC::AL));
  587. // Copy implicit ops and popped registers, if any.
  588. for (auto MO: MBBI->operands())
  589. if (MO.isReg() && (MO.isImplicit() || MO.isDef()))
  590. MIB.add(MO);
  591. MIB.addReg(ARM::PC, RegState::Define);
  592. // Erase the old instruction (tBX_RET or tPOP).
  593. MBB.erase(MBBI);
  594. return true;
  595. }
  596. // Look for a temporary register to use.
  597. // First, compute the liveness information.
  598. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  599. LivePhysRegs UsedRegs(TRI);
  600. UsedRegs.addLiveOuts(MBB);
  601. // The semantic of pristines changed recently and now,
  602. // the callee-saved registers that are touched in the function
  603. // are not part of the pristines set anymore.
  604. // Add those callee-saved now.
  605. const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
  606. for (unsigned i = 0; CSRegs[i]; ++i)
  607. UsedRegs.addReg(CSRegs[i]);
  608. DebugLoc dl = DebugLoc();
  609. if (MBBI != MBB.end()) {
  610. dl = MBBI->getDebugLoc();
  611. auto InstUpToMBBI = MBB.end();
  612. while (InstUpToMBBI != MBBI)
  613. // The pre-decrement is on purpose here.
  614. // We want to have the liveness right before MBBI.
  615. UsedRegs.stepBackward(*--InstUpToMBBI);
  616. }
  617. // Look for a register that can be directly use in the POP.
  618. unsigned PopReg = 0;
  619. // And some temporary register, just in case.
  620. unsigned TemporaryReg = 0;
  621. BitVector PopFriendly =
  622. TRI.getAllocatableSet(MF, TRI.getRegClass(ARM::tGPRRegClassID));
  623. // R7 may be used as a frame pointer, hence marked as not generally
  624. // allocatable, however there's no reason to not use it as a temporary for
  625. // restoring LR.
  626. if (STI.getFramePointerReg() == ARM::R7)
  627. PopFriendly.set(ARM::R7);
  628. assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
  629. // Rebuild the GPRs from the high registers because they are removed
  630. // form the GPR reg class for thumb1.
  631. BitVector GPRsNoLRSP =
  632. TRI.getAllocatableSet(MF, TRI.getRegClass(ARM::hGPRRegClassID));
  633. GPRsNoLRSP |= PopFriendly;
  634. GPRsNoLRSP.reset(ARM::LR);
  635. GPRsNoLRSP.reset(ARM::SP);
  636. GPRsNoLRSP.reset(ARM::PC);
  637. findTemporariesForLR(GPRsNoLRSP, PopFriendly, UsedRegs, PopReg, TemporaryReg,
  638. MF.getRegInfo());
  639. // If we couldn't find a pop-friendly register, try restoring LR before
  640. // popping the other callee-saved registers, so we could use one of them as a
  641. // temporary.
  642. bool UseLDRSP = false;
  643. if (!PopReg && MBBI != MBB.begin()) {
  644. auto PrevMBBI = MBBI;
  645. PrevMBBI--;
  646. if (PrevMBBI->getOpcode() == ARM::tPOP) {
  647. UsedRegs.stepBackward(*PrevMBBI);
  648. findTemporariesForLR(GPRsNoLRSP, PopFriendly, UsedRegs, PopReg,
  649. TemporaryReg, MF.getRegInfo());
  650. if (PopReg) {
  651. MBBI = PrevMBBI;
  652. UseLDRSP = true;
  653. }
  654. }
  655. }
  656. if (!DoIt && !PopReg && !TemporaryReg)
  657. return false;
  658. assert((PopReg || TemporaryReg) && "Cannot get LR");
  659. if (UseLDRSP) {
  660. assert(PopReg && "Do not know how to get LR");
  661. // Load the LR via LDR tmp, [SP, #off]
  662. BuildMI(MBB, MBBI, dl, TII.get(ARM::tLDRspi))
  663. .addReg(PopReg, RegState::Define)
  664. .addReg(ARM::SP)
  665. .addImm(MBBI->getNumExplicitOperands() - 2)
  666. .add(predOps(ARMCC::AL));
  667. // Move from the temporary register to the LR.
  668. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
  669. .addReg(ARM::LR, RegState::Define)
  670. .addReg(PopReg, RegState::Kill)
  671. .add(predOps(ARMCC::AL));
  672. // Advance past the pop instruction.
  673. MBBI++;
  674. // Increment the SP.
  675. emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo,
  676. ArgRegsSaveSize + 4, ARM::NoRegister,
  677. MachineInstr::NoFlags);
  678. return true;
  679. }
  680. if (TemporaryReg) {
  681. assert(!PopReg && "Unnecessary MOV is about to be inserted");
  682. PopReg = PopFriendly.find_first();
  683. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
  684. .addReg(TemporaryReg, RegState::Define)
  685. .addReg(PopReg, RegState::Kill)
  686. .add(predOps(ARMCC::AL));
  687. }
  688. if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPOP_RET) {
  689. // We couldn't use the direct restoration above, so
  690. // perform the opposite conversion: tPOP_RET to tPOP.
  691. MachineInstrBuilder MIB =
  692. BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP))
  693. .add(predOps(ARMCC::AL));
  694. bool Popped = false;
  695. for (auto MO: MBBI->operands())
  696. if (MO.isReg() && (MO.isImplicit() || MO.isDef()) &&
  697. MO.getReg() != ARM::PC) {
  698. MIB.add(MO);
  699. if (!MO.isImplicit())
  700. Popped = true;
  701. }
  702. // Is there anything left to pop?
  703. if (!Popped)
  704. MBB.erase(MIB.getInstr());
  705. // Erase the old instruction.
  706. MBB.erase(MBBI);
  707. MBBI = BuildMI(MBB, MBB.end(), dl, TII.get(ARM::tBX_RET))
  708. .add(predOps(ARMCC::AL));
  709. }
  710. assert(PopReg && "Do not know how to get LR");
  711. BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP))
  712. .add(predOps(ARMCC::AL))
  713. .addReg(PopReg, RegState::Define);
  714. emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize,
  715. ARM::NoRegister, MachineInstr::NoFlags);
  716. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
  717. .addReg(ARM::LR, RegState::Define)
  718. .addReg(PopReg, RegState::Kill)
  719. .add(predOps(ARMCC::AL));
  720. if (TemporaryReg)
  721. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
  722. .addReg(PopReg, RegState::Define)
  723. .addReg(TemporaryReg, RegState::Kill)
  724. .add(predOps(ARMCC::AL));
  725. return true;
  726. }
  727. using ARMRegSet = std::bitset<ARM::NUM_TARGET_REGS>;
  728. // Return the first iteraror after CurrentReg which is present in EnabledRegs,
  729. // or OrderEnd if no further registers are in that set. This does not advance
  730. // the iterator fiorst, so returns CurrentReg if it is in EnabledRegs.
  731. static const unsigned *findNextOrderedReg(const unsigned *CurrentReg,
  732. const ARMRegSet &EnabledRegs,
  733. const unsigned *OrderEnd) {
  734. while (CurrentReg != OrderEnd && !EnabledRegs[*CurrentReg])
  735. ++CurrentReg;
  736. return CurrentReg;
  737. }
  738. bool Thumb1FrameLowering::spillCalleeSavedRegisters(
  739. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  740. ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  741. if (CSI.empty())
  742. return false;
  743. DebugLoc DL;
  744. const TargetInstrInfo &TII = *STI.getInstrInfo();
  745. MachineFunction &MF = *MBB.getParent();
  746. const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
  747. MF.getSubtarget().getRegisterInfo());
  748. ARMRegSet LoRegsToSave; // r0-r7, lr
  749. ARMRegSet HiRegsToSave; // r8-r11
  750. ARMRegSet CopyRegs; // Registers which can be used after pushing
  751. // LoRegs for saving HiRegs.
  752. for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
  753. Register Reg = I.getReg();
  754. if (ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) {
  755. LoRegsToSave[Reg] = true;
  756. } else if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::LR) {
  757. HiRegsToSave[Reg] = true;
  758. } else {
  759. llvm_unreachable("callee-saved register of unexpected class");
  760. }
  761. if ((ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) &&
  762. !MF.getRegInfo().isLiveIn(Reg) &&
  763. !(hasFP(MF) && Reg == RegInfo->getFrameRegister(MF)))
  764. CopyRegs[Reg] = true;
  765. }
  766. // Unused argument registers can be used for the high register saving.
  767. for (unsigned ArgReg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3})
  768. if (!MF.getRegInfo().isLiveIn(ArgReg))
  769. CopyRegs[ArgReg] = true;
  770. // Push the low registers and lr
  771. const MachineRegisterInfo &MRI = MF.getRegInfo();
  772. if (!LoRegsToSave.none()) {
  773. MachineInstrBuilder MIB =
  774. BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH)).add(predOps(ARMCC::AL));
  775. for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6, ARM::R7, ARM::LR}) {
  776. if (LoRegsToSave[Reg]) {
  777. bool isKill = !MRI.isLiveIn(Reg);
  778. if (isKill && !MRI.isReserved(Reg))
  779. MBB.addLiveIn(Reg);
  780. MIB.addReg(Reg, getKillRegState(isKill));
  781. }
  782. }
  783. MIB.setMIFlags(MachineInstr::FrameSetup);
  784. }
  785. // Push the high registers. There are no store instructions that can access
  786. // these registers directly, so we have to move them to low registers, and
  787. // push them. This might take multiple pushes, as it is possible for there to
  788. // be fewer low registers available than high registers which need saving.
  789. // These are in reverse order so that in the case where we need to use
  790. // multiple PUSH instructions, the order of the registers on the stack still
  791. // matches the unwind info. They need to be swicthed back to ascending order
  792. // before adding to the PUSH instruction.
  793. static const unsigned AllCopyRegs[] = {ARM::LR, ARM::R7, ARM::R6,
  794. ARM::R5, ARM::R4, ARM::R3,
  795. ARM::R2, ARM::R1, ARM::R0};
  796. static const unsigned AllHighRegs[] = {ARM::R11, ARM::R10, ARM::R9, ARM::R8};
  797. const unsigned *AllCopyRegsEnd = std::end(AllCopyRegs);
  798. const unsigned *AllHighRegsEnd = std::end(AllHighRegs);
  799. // Find the first register to save.
  800. const unsigned *HiRegToSave = findNextOrderedReg(
  801. std::begin(AllHighRegs), HiRegsToSave, AllHighRegsEnd);
  802. while (HiRegToSave != AllHighRegsEnd) {
  803. // Find the first low register to use.
  804. const unsigned *CopyReg =
  805. findNextOrderedReg(std::begin(AllCopyRegs), CopyRegs, AllCopyRegsEnd);
  806. // Create the PUSH, but don't insert it yet (the MOVs need to come first).
  807. MachineInstrBuilder PushMIB = BuildMI(MF, DL, TII.get(ARM::tPUSH))
  808. .add(predOps(ARMCC::AL))
  809. .setMIFlags(MachineInstr::FrameSetup);
  810. SmallVector<unsigned, 4> RegsToPush;
  811. while (HiRegToSave != AllHighRegsEnd && CopyReg != AllCopyRegsEnd) {
  812. if (HiRegsToSave[*HiRegToSave]) {
  813. bool isKill = !MRI.isLiveIn(*HiRegToSave);
  814. if (isKill && !MRI.isReserved(*HiRegToSave))
  815. MBB.addLiveIn(*HiRegToSave);
  816. // Emit a MOV from the high reg to the low reg.
  817. BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
  818. .addReg(*CopyReg, RegState::Define)
  819. .addReg(*HiRegToSave, getKillRegState(isKill))
  820. .add(predOps(ARMCC::AL))
  821. .setMIFlags(MachineInstr::FrameSetup);
  822. // Record the register that must be added to the PUSH.
  823. RegsToPush.push_back(*CopyReg);
  824. CopyReg = findNextOrderedReg(++CopyReg, CopyRegs, AllCopyRegsEnd);
  825. HiRegToSave =
  826. findNextOrderedReg(++HiRegToSave, HiRegsToSave, AllHighRegsEnd);
  827. }
  828. }
  829. // Add the low registers to the PUSH, in ascending order.
  830. for (unsigned Reg : llvm::reverse(RegsToPush))
  831. PushMIB.addReg(Reg, RegState::Kill);
  832. // Insert the PUSH instruction after the MOVs.
  833. MBB.insert(MI, PushMIB);
  834. }
  835. return true;
  836. }
  837. bool Thumb1FrameLowering::restoreCalleeSavedRegisters(
  838. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  839. MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  840. if (CSI.empty())
  841. return false;
  842. MachineFunction &MF = *MBB.getParent();
  843. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  844. const TargetInstrInfo &TII = *STI.getInstrInfo();
  845. const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
  846. MF.getSubtarget().getRegisterInfo());
  847. bool isVarArg = AFI->getArgRegsSaveSize() > 0;
  848. DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
  849. ARMRegSet LoRegsToRestore;
  850. ARMRegSet HiRegsToRestore;
  851. // Low registers (r0-r7) which can be used to restore the high registers.
  852. ARMRegSet CopyRegs;
  853. for (CalleeSavedInfo I : CSI) {
  854. Register Reg = I.getReg();
  855. if (ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) {
  856. LoRegsToRestore[Reg] = true;
  857. } else if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::LR) {
  858. HiRegsToRestore[Reg] = true;
  859. } else {
  860. llvm_unreachable("callee-saved register of unexpected class");
  861. }
  862. // If this is a low register not used as the frame pointer, we may want to
  863. // use it for restoring the high registers.
  864. if ((ARM::tGPRRegClass.contains(Reg)) &&
  865. !(hasFP(MF) && Reg == RegInfo->getFrameRegister(MF)))
  866. CopyRegs[Reg] = true;
  867. }
  868. // If this is a return block, we may be able to use some unused return value
  869. // registers for restoring the high regs.
  870. auto Terminator = MBB.getFirstTerminator();
  871. if (Terminator != MBB.end() && Terminator->getOpcode() == ARM::tBX_RET) {
  872. CopyRegs[ARM::R0] = true;
  873. CopyRegs[ARM::R1] = true;
  874. CopyRegs[ARM::R2] = true;
  875. CopyRegs[ARM::R3] = true;
  876. for (auto Op : Terminator->implicit_operands()) {
  877. if (Op.isReg())
  878. CopyRegs[Op.getReg()] = false;
  879. }
  880. }
  881. static const unsigned AllCopyRegs[] = {ARM::R0, ARM::R1, ARM::R2, ARM::R3,
  882. ARM::R4, ARM::R5, ARM::R6, ARM::R7};
  883. static const unsigned AllHighRegs[] = {ARM::R8, ARM::R9, ARM::R10, ARM::R11};
  884. const unsigned *AllCopyRegsEnd = std::end(AllCopyRegs);
  885. const unsigned *AllHighRegsEnd = std::end(AllHighRegs);
  886. // Find the first register to restore.
  887. auto HiRegToRestore = findNextOrderedReg(std::begin(AllHighRegs),
  888. HiRegsToRestore, AllHighRegsEnd);
  889. while (HiRegToRestore != AllHighRegsEnd) {
  890. assert(!CopyRegs.none());
  891. // Find the first low register to use.
  892. auto CopyReg =
  893. findNextOrderedReg(std::begin(AllCopyRegs), CopyRegs, AllCopyRegsEnd);
  894. // Create the POP instruction.
  895. MachineInstrBuilder PopMIB =
  896. BuildMI(MBB, MI, DL, TII.get(ARM::tPOP)).add(predOps(ARMCC::AL));
  897. while (HiRegToRestore != AllHighRegsEnd && CopyReg != AllCopyRegsEnd) {
  898. // Add the low register to the POP.
  899. PopMIB.addReg(*CopyReg, RegState::Define);
  900. // Create the MOV from low to high register.
  901. BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
  902. .addReg(*HiRegToRestore, RegState::Define)
  903. .addReg(*CopyReg, RegState::Kill)
  904. .add(predOps(ARMCC::AL));
  905. CopyReg = findNextOrderedReg(++CopyReg, CopyRegs, AllCopyRegsEnd);
  906. HiRegToRestore =
  907. findNextOrderedReg(++HiRegToRestore, HiRegsToRestore, AllHighRegsEnd);
  908. }
  909. }
  910. MachineInstrBuilder MIB =
  911. BuildMI(MF, DL, TII.get(ARM::tPOP)).add(predOps(ARMCC::AL));
  912. bool NeedsPop = false;
  913. for (CalleeSavedInfo &Info : llvm::reverse(CSI)) {
  914. Register Reg = Info.getReg();
  915. // High registers (excluding lr) have already been dealt with
  916. if (!(ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR))
  917. continue;
  918. if (Reg == ARM::LR) {
  919. Info.setRestored(false);
  920. if (!MBB.succ_empty() ||
  921. MI->getOpcode() == ARM::TCRETURNdi ||
  922. MI->getOpcode() == ARM::TCRETURNri)
  923. // LR may only be popped into PC, as part of return sequence.
  924. // If this isn't the return sequence, we'll need emitPopSpecialFixUp
  925. // to restore LR the hard way.
  926. // FIXME: if we don't pass any stack arguments it would be actually
  927. // advantageous *and* correct to do the conversion to an ordinary call
  928. // instruction here.
  929. continue;
  930. // Special epilogue for vararg functions. See emitEpilogue
  931. if (isVarArg)
  932. continue;
  933. // ARMv4T requires BX, see emitEpilogue
  934. if (!STI.hasV5TOps())
  935. continue;
  936. // CMSE entry functions must return via BXNS, see emitEpilogue.
  937. if (AFI->isCmseNSEntryFunction())
  938. continue;
  939. // Pop LR into PC.
  940. Reg = ARM::PC;
  941. (*MIB).setDesc(TII.get(ARM::tPOP_RET));
  942. if (MI != MBB.end())
  943. MIB.copyImplicitOps(*MI);
  944. MI = MBB.erase(MI);
  945. }
  946. MIB.addReg(Reg, getDefRegState(true));
  947. NeedsPop = true;
  948. }
  949. // It's illegal to emit pop instruction without operands.
  950. if (NeedsPop)
  951. MBB.insert(MI, &*MIB);
  952. else
  953. MF.deleteMachineInstr(MIB);
  954. return true;
  955. }