AArch64RedundantCopyElimination.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. //=- AArch64RedundantCopyElimination.cpp - Remove useless copy for AArch64 -=//
  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. // This pass removes unnecessary copies/moves in BBs based on a dominating
  8. // condition.
  9. //
  10. // We handle three cases:
  11. // 1. For BBs that are targets of CBZ/CBNZ instructions, we know the value of
  12. // the CBZ/CBNZ source register is zero on the taken/not-taken path. For
  13. // instance, the copy instruction in the code below can be removed because
  14. // the CBZW jumps to %bb.2 when w0 is zero.
  15. //
  16. // %bb.1:
  17. // cbz w0, .LBB0_2
  18. // .LBB0_2:
  19. // mov w0, wzr ; <-- redundant
  20. //
  21. // 2. If the flag setting instruction defines a register other than WZR/XZR, we
  22. // can remove a zero copy in some cases.
  23. //
  24. // %bb.0:
  25. // subs w0, w1, w2
  26. // str w0, [x1]
  27. // b.ne .LBB0_2
  28. // %bb.1:
  29. // mov w0, wzr ; <-- redundant
  30. // str w0, [x2]
  31. // .LBB0_2
  32. //
  33. // 3. Finally, if the flag setting instruction is a comparison against a
  34. // constant (i.e., ADDS[W|X]ri, SUBS[W|X]ri), we can remove a mov immediate
  35. // in some cases.
  36. //
  37. // %bb.0:
  38. // subs xzr, x0, #1
  39. // b.eq .LBB0_1
  40. // .LBB0_1:
  41. // orr x0, xzr, #0x1 ; <-- redundant
  42. //
  43. // This pass should be run after register allocation.
  44. //
  45. // FIXME: This could also be extended to check the whole dominance subtree below
  46. // the comparison if the compile time regression is acceptable.
  47. //
  48. // FIXME: Add support for handling CCMP instructions.
  49. // FIXME: If the known register value is zero, we should be able to rewrite uses
  50. // to use WZR/XZR directly in some cases.
  51. //===----------------------------------------------------------------------===//
  52. #include "AArch64.h"
  53. #include "llvm/ADT/SetVector.h"
  54. #include "llvm/ADT/Statistic.h"
  55. #include "llvm/ADT/iterator_range.h"
  56. #include "llvm/CodeGen/LiveRegUnits.h"
  57. #include "llvm/CodeGen/MachineFunctionPass.h"
  58. #include "llvm/CodeGen/MachineRegisterInfo.h"
  59. #include "llvm/Support/Debug.h"
  60. using namespace llvm;
  61. #define DEBUG_TYPE "aarch64-copyelim"
  62. STATISTIC(NumCopiesRemoved, "Number of copies removed.");
  63. namespace {
  64. class AArch64RedundantCopyElimination : public MachineFunctionPass {
  65. const MachineRegisterInfo *MRI;
  66. const TargetRegisterInfo *TRI;
  67. // DomBBClobberedRegs is used when computing known values in the dominating
  68. // BB.
  69. LiveRegUnits DomBBClobberedRegs, DomBBUsedRegs;
  70. // OptBBClobberedRegs is used when optimizing away redundant copies/moves.
  71. LiveRegUnits OptBBClobberedRegs, OptBBUsedRegs;
  72. public:
  73. static char ID;
  74. AArch64RedundantCopyElimination() : MachineFunctionPass(ID) {
  75. initializeAArch64RedundantCopyEliminationPass(
  76. *PassRegistry::getPassRegistry());
  77. }
  78. struct RegImm {
  79. MCPhysReg Reg;
  80. int32_t Imm;
  81. RegImm(MCPhysReg Reg, int32_t Imm) : Reg(Reg), Imm(Imm) {}
  82. };
  83. bool knownRegValInBlock(MachineInstr &CondBr, MachineBasicBlock *MBB,
  84. SmallVectorImpl<RegImm> &KnownRegs,
  85. MachineBasicBlock::iterator &FirstUse);
  86. bool optimizeBlock(MachineBasicBlock *MBB);
  87. bool runOnMachineFunction(MachineFunction &MF) override;
  88. MachineFunctionProperties getRequiredProperties() const override {
  89. return MachineFunctionProperties().set(
  90. MachineFunctionProperties::Property::NoVRegs);
  91. }
  92. StringRef getPassName() const override {
  93. return "AArch64 Redundant Copy Elimination";
  94. }
  95. };
  96. char AArch64RedundantCopyElimination::ID = 0;
  97. }
  98. INITIALIZE_PASS(AArch64RedundantCopyElimination, "aarch64-copyelim",
  99. "AArch64 redundant copy elimination pass", false, false)
  100. /// It's possible to determine the value of a register based on a dominating
  101. /// condition. To do so, this function checks to see if the basic block \p MBB
  102. /// is the target of a conditional branch \p CondBr with an equality comparison.
  103. /// If the branch is a CBZ/CBNZ, we know the value of its source operand is zero
  104. /// in \p MBB for some cases. Otherwise, we find and inspect the NZCV setting
  105. /// instruction (e.g., SUBS, ADDS). If this instruction defines a register
  106. /// other than WZR/XZR, we know the value of the destination register is zero in
  107. /// \p MMB for some cases. In addition, if the NZCV setting instruction is
  108. /// comparing against a constant we know the other source register is equal to
  109. /// the constant in \p MBB for some cases. If we find any constant values, push
  110. /// a physical register and constant value pair onto the KnownRegs vector and
  111. /// return true. Otherwise, return false if no known values were found.
  112. bool AArch64RedundantCopyElimination::knownRegValInBlock(
  113. MachineInstr &CondBr, MachineBasicBlock *MBB,
  114. SmallVectorImpl<RegImm> &KnownRegs, MachineBasicBlock::iterator &FirstUse) {
  115. unsigned Opc = CondBr.getOpcode();
  116. // Check if the current basic block is the target block to which the
  117. // CBZ/CBNZ instruction jumps when its Wt/Xt is zero.
  118. if (((Opc == AArch64::CBZW || Opc == AArch64::CBZX) &&
  119. MBB == CondBr.getOperand(1).getMBB()) ||
  120. ((Opc == AArch64::CBNZW || Opc == AArch64::CBNZX) &&
  121. MBB != CondBr.getOperand(1).getMBB())) {
  122. FirstUse = CondBr;
  123. KnownRegs.push_back(RegImm(CondBr.getOperand(0).getReg(), 0));
  124. return true;
  125. }
  126. // Otherwise, must be a conditional branch.
  127. if (Opc != AArch64::Bcc)
  128. return false;
  129. // Must be an equality check (i.e., == or !=).
  130. AArch64CC::CondCode CC = (AArch64CC::CondCode)CondBr.getOperand(0).getImm();
  131. if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
  132. return false;
  133. MachineBasicBlock *BrTarget = CondBr.getOperand(1).getMBB();
  134. if ((CC == AArch64CC::EQ && BrTarget != MBB) ||
  135. (CC == AArch64CC::NE && BrTarget == MBB))
  136. return false;
  137. // Stop if we get to the beginning of PredMBB.
  138. MachineBasicBlock *PredMBB = *MBB->pred_begin();
  139. assert(PredMBB == CondBr.getParent() &&
  140. "Conditional branch not in predecessor block!");
  141. if (CondBr == PredMBB->begin())
  142. return false;
  143. // Registers clobbered in PredMBB between CondBr instruction and current
  144. // instruction being checked in loop.
  145. DomBBClobberedRegs.clear();
  146. DomBBUsedRegs.clear();
  147. // Find compare instruction that sets NZCV used by CondBr.
  148. MachineBasicBlock::reverse_iterator RIt = CondBr.getReverseIterator();
  149. for (MachineInstr &PredI : make_range(std::next(RIt), PredMBB->rend())) {
  150. bool IsCMN = false;
  151. switch (PredI.getOpcode()) {
  152. default:
  153. break;
  154. // CMN is an alias for ADDS with a dead destination register.
  155. case AArch64::ADDSWri:
  156. case AArch64::ADDSXri:
  157. IsCMN = true;
  158. [[fallthrough]];
  159. // CMP is an alias for SUBS with a dead destination register.
  160. case AArch64::SUBSWri:
  161. case AArch64::SUBSXri: {
  162. // Sometimes the first operand is a FrameIndex. Bail if tht happens.
  163. if (!PredI.getOperand(1).isReg())
  164. return false;
  165. MCPhysReg DstReg = PredI.getOperand(0).getReg();
  166. MCPhysReg SrcReg = PredI.getOperand(1).getReg();
  167. bool Res = false;
  168. // If we're comparing against a non-symbolic immediate and the source
  169. // register of the compare is not modified (including a self-clobbering
  170. // compare) between the compare and conditional branch we known the value
  171. // of the 1st source operand.
  172. if (PredI.getOperand(2).isImm() && DomBBClobberedRegs.available(SrcReg) &&
  173. SrcReg != DstReg) {
  174. // We've found the instruction that sets NZCV.
  175. int32_t KnownImm = PredI.getOperand(2).getImm();
  176. int32_t Shift = PredI.getOperand(3).getImm();
  177. KnownImm <<= Shift;
  178. if (IsCMN)
  179. KnownImm = -KnownImm;
  180. FirstUse = PredI;
  181. KnownRegs.push_back(RegImm(SrcReg, KnownImm));
  182. Res = true;
  183. }
  184. // If this instructions defines something other than WZR/XZR, we know it's
  185. // result is zero in some cases.
  186. if (DstReg == AArch64::WZR || DstReg == AArch64::XZR)
  187. return Res;
  188. // The destination register must not be modified between the NZCV setting
  189. // instruction and the conditional branch.
  190. if (!DomBBClobberedRegs.available(DstReg))
  191. return Res;
  192. FirstUse = PredI;
  193. KnownRegs.push_back(RegImm(DstReg, 0));
  194. return true;
  195. }
  196. // Look for NZCV setting instructions that define something other than
  197. // WZR/XZR.
  198. case AArch64::ADCSWr:
  199. case AArch64::ADCSXr:
  200. case AArch64::ADDSWrr:
  201. case AArch64::ADDSWrs:
  202. case AArch64::ADDSWrx:
  203. case AArch64::ADDSXrr:
  204. case AArch64::ADDSXrs:
  205. case AArch64::ADDSXrx:
  206. case AArch64::ADDSXrx64:
  207. case AArch64::ANDSWri:
  208. case AArch64::ANDSWrr:
  209. case AArch64::ANDSWrs:
  210. case AArch64::ANDSXri:
  211. case AArch64::ANDSXrr:
  212. case AArch64::ANDSXrs:
  213. case AArch64::BICSWrr:
  214. case AArch64::BICSWrs:
  215. case AArch64::BICSXrs:
  216. case AArch64::BICSXrr:
  217. case AArch64::SBCSWr:
  218. case AArch64::SBCSXr:
  219. case AArch64::SUBSWrr:
  220. case AArch64::SUBSWrs:
  221. case AArch64::SUBSWrx:
  222. case AArch64::SUBSXrr:
  223. case AArch64::SUBSXrs:
  224. case AArch64::SUBSXrx:
  225. case AArch64::SUBSXrx64: {
  226. MCPhysReg DstReg = PredI.getOperand(0).getReg();
  227. if (DstReg == AArch64::WZR || DstReg == AArch64::XZR)
  228. return false;
  229. // The destination register of the NZCV setting instruction must not be
  230. // modified before the conditional branch.
  231. if (!DomBBClobberedRegs.available(DstReg))
  232. return false;
  233. // We've found the instruction that sets NZCV whose DstReg == 0.
  234. FirstUse = PredI;
  235. KnownRegs.push_back(RegImm(DstReg, 0));
  236. return true;
  237. }
  238. }
  239. // Bail if we see an instruction that defines NZCV that we don't handle.
  240. if (PredI.definesRegister(AArch64::NZCV))
  241. return false;
  242. // Track clobbered and used registers.
  243. LiveRegUnits::accumulateUsedDefed(PredI, DomBBClobberedRegs, DomBBUsedRegs,
  244. TRI);
  245. }
  246. return false;
  247. }
  248. bool AArch64RedundantCopyElimination::optimizeBlock(MachineBasicBlock *MBB) {
  249. // Check if the current basic block has a single predecessor.
  250. if (MBB->pred_size() != 1)
  251. return false;
  252. // Check if the predecessor has two successors, implying the block ends in a
  253. // conditional branch.
  254. MachineBasicBlock *PredMBB = *MBB->pred_begin();
  255. if (PredMBB->succ_size() != 2)
  256. return false;
  257. MachineBasicBlock::iterator CondBr = PredMBB->getLastNonDebugInstr();
  258. if (CondBr == PredMBB->end())
  259. return false;
  260. // Keep track of the earliest point in the PredMBB block where kill markers
  261. // need to be removed if a COPY is removed.
  262. MachineBasicBlock::iterator FirstUse;
  263. // After calling knownRegValInBlock, FirstUse will either point to a CBZ/CBNZ
  264. // or a compare (i.e., SUBS). In the latter case, we must take care when
  265. // updating FirstUse when scanning for COPY instructions. In particular, if
  266. // there's a COPY in between the compare and branch the COPY should not
  267. // update FirstUse.
  268. bool SeenFirstUse = false;
  269. // Registers that contain a known value at the start of MBB.
  270. SmallVector<RegImm, 4> KnownRegs;
  271. MachineBasicBlock::iterator Itr = std::next(CondBr);
  272. do {
  273. --Itr;
  274. if (!knownRegValInBlock(*Itr, MBB, KnownRegs, FirstUse))
  275. continue;
  276. // Reset the clobbered and used register units.
  277. OptBBClobberedRegs.clear();
  278. OptBBUsedRegs.clear();
  279. // Look backward in PredMBB for COPYs from the known reg to find other
  280. // registers that are known to be a constant value.
  281. for (auto PredI = Itr;; --PredI) {
  282. if (FirstUse == PredI)
  283. SeenFirstUse = true;
  284. if (PredI->isCopy()) {
  285. MCPhysReg CopyDstReg = PredI->getOperand(0).getReg();
  286. MCPhysReg CopySrcReg = PredI->getOperand(1).getReg();
  287. for (auto &KnownReg : KnownRegs) {
  288. if (!OptBBClobberedRegs.available(KnownReg.Reg))
  289. continue;
  290. // If we have X = COPY Y, and Y is known to be zero, then now X is
  291. // known to be zero.
  292. if (CopySrcReg == KnownReg.Reg &&
  293. OptBBClobberedRegs.available(CopyDstReg)) {
  294. KnownRegs.push_back(RegImm(CopyDstReg, KnownReg.Imm));
  295. if (SeenFirstUse)
  296. FirstUse = PredI;
  297. break;
  298. }
  299. // If we have X = COPY Y, and X is known to be zero, then now Y is
  300. // known to be zero.
  301. if (CopyDstReg == KnownReg.Reg &&
  302. OptBBClobberedRegs.available(CopySrcReg)) {
  303. KnownRegs.push_back(RegImm(CopySrcReg, KnownReg.Imm));
  304. if (SeenFirstUse)
  305. FirstUse = PredI;
  306. break;
  307. }
  308. }
  309. }
  310. // Stop if we get to the beginning of PredMBB.
  311. if (PredI == PredMBB->begin())
  312. break;
  313. LiveRegUnits::accumulateUsedDefed(*PredI, OptBBClobberedRegs,
  314. OptBBUsedRegs, TRI);
  315. // Stop if all of the known-zero regs have been clobbered.
  316. if (all_of(KnownRegs, [&](RegImm KnownReg) {
  317. return !OptBBClobberedRegs.available(KnownReg.Reg);
  318. }))
  319. break;
  320. }
  321. break;
  322. } while (Itr != PredMBB->begin() && Itr->isTerminator());
  323. // We've not found a registers with a known value, time to bail out.
  324. if (KnownRegs.empty())
  325. return false;
  326. bool Changed = false;
  327. // UsedKnownRegs is the set of KnownRegs that have had uses added to MBB.
  328. SmallSetVector<unsigned, 4> UsedKnownRegs;
  329. MachineBasicBlock::iterator LastChange = MBB->begin();
  330. // Remove redundant copy/move instructions unless KnownReg is modified.
  331. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) {
  332. MachineInstr *MI = &*I;
  333. ++I;
  334. bool RemovedMI = false;
  335. bool IsCopy = MI->isCopy();
  336. bool IsMoveImm = MI->isMoveImmediate();
  337. if (IsCopy || IsMoveImm) {
  338. Register DefReg = MI->getOperand(0).getReg();
  339. Register SrcReg = IsCopy ? MI->getOperand(1).getReg() : Register();
  340. int64_t SrcImm = IsMoveImm ? MI->getOperand(1).getImm() : 0;
  341. if (!MRI->isReserved(DefReg) &&
  342. ((IsCopy && (SrcReg == AArch64::XZR || SrcReg == AArch64::WZR)) ||
  343. IsMoveImm)) {
  344. for (RegImm &KnownReg : KnownRegs) {
  345. if (KnownReg.Reg != DefReg &&
  346. !TRI->isSuperRegister(DefReg, KnownReg.Reg))
  347. continue;
  348. // For a copy, the known value must be a zero.
  349. if (IsCopy && KnownReg.Imm != 0)
  350. continue;
  351. if (IsMoveImm) {
  352. // For a move immediate, the known immediate must match the source
  353. // immediate.
  354. if (KnownReg.Imm != SrcImm)
  355. continue;
  356. // Don't remove a move immediate that implicitly defines the upper
  357. // bits when only the lower 32 bits are known.
  358. MCPhysReg CmpReg = KnownReg.Reg;
  359. if (any_of(MI->implicit_operands(), [CmpReg](MachineOperand &O) {
  360. return !O.isDead() && O.isReg() && O.isDef() &&
  361. O.getReg() != CmpReg;
  362. }))
  363. continue;
  364. // Don't remove a move immediate that implicitly defines the upper
  365. // bits as different.
  366. if (TRI->isSuperRegister(DefReg, KnownReg.Reg) && KnownReg.Imm < 0)
  367. continue;
  368. }
  369. if (IsCopy)
  370. LLVM_DEBUG(dbgs() << "Remove redundant Copy : " << *MI);
  371. else
  372. LLVM_DEBUG(dbgs() << "Remove redundant Move : " << *MI);
  373. MI->eraseFromParent();
  374. Changed = true;
  375. LastChange = I;
  376. NumCopiesRemoved++;
  377. UsedKnownRegs.insert(KnownReg.Reg);
  378. RemovedMI = true;
  379. break;
  380. }
  381. }
  382. }
  383. // Skip to the next instruction if we removed the COPY/MovImm.
  384. if (RemovedMI)
  385. continue;
  386. // Remove any regs the MI clobbers from the KnownConstRegs set.
  387. for (unsigned RI = 0; RI < KnownRegs.size();)
  388. if (MI->modifiesRegister(KnownRegs[RI].Reg, TRI)) {
  389. std::swap(KnownRegs[RI], KnownRegs[KnownRegs.size() - 1]);
  390. KnownRegs.pop_back();
  391. // Don't increment RI since we need to now check the swapped-in
  392. // KnownRegs[RI].
  393. } else {
  394. ++RI;
  395. }
  396. // Continue until the KnownRegs set is empty.
  397. if (KnownRegs.empty())
  398. break;
  399. }
  400. if (!Changed)
  401. return false;
  402. // Add newly used regs to the block's live-in list if they aren't there
  403. // already.
  404. for (MCPhysReg KnownReg : UsedKnownRegs)
  405. if (!MBB->isLiveIn(KnownReg))
  406. MBB->addLiveIn(KnownReg);
  407. // Clear kills in the range where changes were made. This is conservative,
  408. // but should be okay since kill markers are being phased out.
  409. LLVM_DEBUG(dbgs() << "Clearing kill flags.\n\tFirstUse: " << *FirstUse
  410. << "\tLastChange: " << *LastChange);
  411. for (MachineInstr &MMI : make_range(FirstUse, PredMBB->end()))
  412. MMI.clearKillInfo();
  413. for (MachineInstr &MMI : make_range(MBB->begin(), LastChange))
  414. MMI.clearKillInfo();
  415. return true;
  416. }
  417. bool AArch64RedundantCopyElimination::runOnMachineFunction(
  418. MachineFunction &MF) {
  419. if (skipFunction(MF.getFunction()))
  420. return false;
  421. TRI = MF.getSubtarget().getRegisterInfo();
  422. MRI = &MF.getRegInfo();
  423. // Resize the clobbered and used register unit trackers. We do this once per
  424. // function.
  425. DomBBClobberedRegs.init(*TRI);
  426. DomBBUsedRegs.init(*TRI);
  427. OptBBClobberedRegs.init(*TRI);
  428. OptBBUsedRegs.init(*TRI);
  429. bool Changed = false;
  430. for (MachineBasicBlock &MBB : MF)
  431. Changed |= optimizeBlock(&MBB);
  432. return Changed;
  433. }
  434. FunctionPass *llvm::createAArch64RedundantCopyEliminationPass() {
  435. return new AArch64RedundantCopyElimination();
  436. }