AArch64RedundantCopyElimination.cpp 17 KB

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