MachineCopyPropagation.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
  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 is an extremely simple MachineInstr-level copy propagation pass.
  10. //
  11. // This pass forwards the source of COPYs to the users of their destinations
  12. // when doing so is legal. For example:
  13. //
  14. // %reg1 = COPY %reg0
  15. // ...
  16. // ... = OP %reg1
  17. //
  18. // If
  19. // - %reg0 has not been clobbered by the time of the use of %reg1
  20. // - the register class constraints are satisfied
  21. // - the COPY def is the only value that reaches OP
  22. // then this pass replaces the above with:
  23. //
  24. // %reg1 = COPY %reg0
  25. // ...
  26. // ... = OP %reg0
  27. //
  28. // This pass also removes some redundant COPYs. For example:
  29. //
  30. // %R1 = COPY %R0
  31. // ... // No clobber of %R1
  32. // %R0 = COPY %R1 <<< Removed
  33. //
  34. // or
  35. //
  36. // %R1 = COPY %R0
  37. // ... // No clobber of %R0
  38. // %R1 = COPY %R0 <<< Removed
  39. //
  40. //===----------------------------------------------------------------------===//
  41. #include "llvm/ADT/DenseMap.h"
  42. #include "llvm/ADT/STLExtras.h"
  43. #include "llvm/ADT/SetVector.h"
  44. #include "llvm/ADT/SmallVector.h"
  45. #include "llvm/ADT/Statistic.h"
  46. #include "llvm/ADT/iterator_range.h"
  47. #include "llvm/CodeGen/MachineBasicBlock.h"
  48. #include "llvm/CodeGen/MachineFunction.h"
  49. #include "llvm/CodeGen/MachineFunctionPass.h"
  50. #include "llvm/CodeGen/MachineInstr.h"
  51. #include "llvm/CodeGen/MachineOperand.h"
  52. #include "llvm/CodeGen/MachineRegisterInfo.h"
  53. #include "llvm/CodeGen/TargetInstrInfo.h"
  54. #include "llvm/CodeGen/TargetRegisterInfo.h"
  55. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  56. #include "llvm/MC/MCRegisterInfo.h"
  57. #include "llvm/Pass.h"
  58. #include "llvm/Support/Debug.h"
  59. #include "llvm/Support/DebugCounter.h"
  60. #include "llvm/Support/raw_ostream.h"
  61. #include <cassert>
  62. #include <iterator>
  63. using namespace llvm;
  64. #define DEBUG_TYPE "machine-cp"
  65. STATISTIC(NumDeletes, "Number of dead copies deleted");
  66. STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
  67. DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
  68. "Controls which register COPYs are forwarded");
  69. namespace {
  70. class CopyTracker {
  71. struct CopyInfo {
  72. MachineInstr *MI;
  73. SmallVector<unsigned, 4> DefRegs;
  74. bool Avail;
  75. };
  76. DenseMap<unsigned, CopyInfo> Copies;
  77. public:
  78. /// Mark all of the given registers and their subregisters as unavailable for
  79. /// copying.
  80. void markRegsUnavailable(ArrayRef<unsigned> Regs,
  81. const TargetRegisterInfo &TRI) {
  82. for (unsigned Reg : Regs) {
  83. // Source of copy is no longer available for propagation.
  84. for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
  85. auto CI = Copies.find(*RUI);
  86. if (CI != Copies.end())
  87. CI->second.Avail = false;
  88. }
  89. }
  90. }
  91. /// Clobber a single register, removing it from the tracker's copy maps.
  92. void clobberRegister(unsigned Reg, const TargetRegisterInfo &TRI) {
  93. for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
  94. auto I = Copies.find(*RUI);
  95. if (I != Copies.end()) {
  96. // When we clobber the source of a copy, we need to clobber everything
  97. // it defined.
  98. markRegsUnavailable(I->second.DefRegs, TRI);
  99. // When we clobber the destination of a copy, we need to clobber the
  100. // whole register it defined.
  101. if (MachineInstr *MI = I->second.MI)
  102. markRegsUnavailable({MI->getOperand(0).getReg()}, TRI);
  103. // Now we can erase the copy.
  104. Copies.erase(I);
  105. }
  106. }
  107. }
  108. /// Add this copy's registers into the tracker's copy maps.
  109. void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI) {
  110. assert(MI->isCopy() && "Tracking non-copy?");
  111. Register Def = MI->getOperand(0).getReg();
  112. Register Src = MI->getOperand(1).getReg();
  113. // Remember Def is defined by the copy.
  114. for (MCRegUnitIterator RUI(Def, &TRI); RUI.isValid(); ++RUI)
  115. Copies[*RUI] = {MI, {}, true};
  116. // Remember source that's copied to Def. Once it's clobbered, then
  117. // it's no longer available for copy propagation.
  118. for (MCRegUnitIterator RUI(Src, &TRI); RUI.isValid(); ++RUI) {
  119. auto I = Copies.insert({*RUI, {nullptr, {}, false}});
  120. auto &Copy = I.first->second;
  121. if (!is_contained(Copy.DefRegs, Def))
  122. Copy.DefRegs.push_back(Def);
  123. }
  124. }
  125. bool hasAnyCopies() {
  126. return !Copies.empty();
  127. }
  128. MachineInstr *findCopyForUnit(unsigned RegUnit, const TargetRegisterInfo &TRI,
  129. bool MustBeAvailable = false) {
  130. auto CI = Copies.find(RegUnit);
  131. if (CI == Copies.end())
  132. return nullptr;
  133. if (MustBeAvailable && !CI->second.Avail)
  134. return nullptr;
  135. return CI->second.MI;
  136. }
  137. MachineInstr *findAvailCopy(MachineInstr &DestCopy, unsigned Reg,
  138. const TargetRegisterInfo &TRI) {
  139. // We check the first RegUnit here, since we'll only be interested in the
  140. // copy if it copies the entire register anyway.
  141. MCRegUnitIterator RUI(Reg, &TRI);
  142. MachineInstr *AvailCopy =
  143. findCopyForUnit(*RUI, TRI, /*MustBeAvailable=*/true);
  144. if (!AvailCopy ||
  145. !TRI.isSubRegisterEq(AvailCopy->getOperand(0).getReg(), Reg))
  146. return nullptr;
  147. // Check that the available copy isn't clobbered by any regmasks between
  148. // itself and the destination.
  149. Register AvailSrc = AvailCopy->getOperand(1).getReg();
  150. Register AvailDef = AvailCopy->getOperand(0).getReg();
  151. for (const MachineInstr &MI :
  152. make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
  153. for (const MachineOperand &MO : MI.operands())
  154. if (MO.isRegMask())
  155. if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
  156. return nullptr;
  157. return AvailCopy;
  158. }
  159. void clear() {
  160. Copies.clear();
  161. }
  162. };
  163. class MachineCopyPropagation : public MachineFunctionPass {
  164. const TargetRegisterInfo *TRI;
  165. const TargetInstrInfo *TII;
  166. const MachineRegisterInfo *MRI;
  167. public:
  168. static char ID; // Pass identification, replacement for typeid
  169. MachineCopyPropagation() : MachineFunctionPass(ID) {
  170. initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
  171. }
  172. void getAnalysisUsage(AnalysisUsage &AU) const override {
  173. AU.setPreservesCFG();
  174. MachineFunctionPass::getAnalysisUsage(AU);
  175. }
  176. bool runOnMachineFunction(MachineFunction &MF) override;
  177. MachineFunctionProperties getRequiredProperties() const override {
  178. return MachineFunctionProperties().set(
  179. MachineFunctionProperties::Property::NoVRegs);
  180. }
  181. private:
  182. typedef enum { DebugUse = false, RegularUse = true } DebugType;
  183. void ClobberRegister(unsigned Reg);
  184. void ReadRegister(unsigned Reg, MachineInstr &Reader,
  185. DebugType DT);
  186. void CopyPropagateBlock(MachineBasicBlock &MBB);
  187. bool eraseIfRedundant(MachineInstr &Copy, unsigned Src, unsigned Def);
  188. void forwardUses(MachineInstr &MI);
  189. bool isForwardableRegClassCopy(const MachineInstr &Copy,
  190. const MachineInstr &UseI, unsigned UseIdx);
  191. bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
  192. /// Candidates for deletion.
  193. SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
  194. /// Multimap tracking debug users in current BB
  195. DenseMap<MachineInstr*, SmallVector<MachineInstr*, 2>> CopyDbgUsers;
  196. CopyTracker Tracker;
  197. bool Changed;
  198. };
  199. } // end anonymous namespace
  200. char MachineCopyPropagation::ID = 0;
  201. char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
  202. INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
  203. "Machine Copy Propagation Pass", false, false)
  204. void MachineCopyPropagation::ReadRegister(unsigned Reg, MachineInstr &Reader,
  205. DebugType DT) {
  206. // If 'Reg' is defined by a copy, the copy is no longer a candidate
  207. // for elimination. If a copy is "read" by a debug user, record the user
  208. // for propagation.
  209. for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) {
  210. if (MachineInstr *Copy = Tracker.findCopyForUnit(*RUI, *TRI)) {
  211. if (DT == RegularUse) {
  212. LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
  213. MaybeDeadCopies.remove(Copy);
  214. } else {
  215. CopyDbgUsers[Copy].push_back(&Reader);
  216. }
  217. }
  218. }
  219. }
  220. /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
  221. /// This fact may have been obscured by sub register usage or may not be true at
  222. /// all even though Src and Def are subregisters of the registers used in
  223. /// PreviousCopy. e.g.
  224. /// isNopCopy("ecx = COPY eax", AX, CX) == true
  225. /// isNopCopy("ecx = COPY eax", AH, CL) == false
  226. static bool isNopCopy(const MachineInstr &PreviousCopy, unsigned Src,
  227. unsigned Def, const TargetRegisterInfo *TRI) {
  228. Register PreviousSrc = PreviousCopy.getOperand(1).getReg();
  229. Register PreviousDef = PreviousCopy.getOperand(0).getReg();
  230. if (Src == PreviousSrc) {
  231. assert(Def == PreviousDef);
  232. return true;
  233. }
  234. if (!TRI->isSubRegister(PreviousSrc, Src))
  235. return false;
  236. unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
  237. return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
  238. }
  239. /// Remove instruction \p Copy if there exists a previous copy that copies the
  240. /// register \p Src to the register \p Def; This may happen indirectly by
  241. /// copying the super registers.
  242. bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy, unsigned Src,
  243. unsigned Def) {
  244. // Avoid eliminating a copy from/to a reserved registers as we cannot predict
  245. // the value (Example: The sparc zero register is writable but stays zero).
  246. if (MRI->isReserved(Src) || MRI->isReserved(Def))
  247. return false;
  248. // Search for an existing copy.
  249. MachineInstr *PrevCopy = Tracker.findAvailCopy(Copy, Def, *TRI);
  250. if (!PrevCopy)
  251. return false;
  252. // Check that the existing copy uses the correct sub registers.
  253. if (PrevCopy->getOperand(0).isDead())
  254. return false;
  255. if (!isNopCopy(*PrevCopy, Src, Def, TRI))
  256. return false;
  257. LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
  258. // Copy was redundantly redefining either Src or Def. Remove earlier kill
  259. // flags between Copy and PrevCopy because the value will be reused now.
  260. assert(Copy.isCopy());
  261. Register CopyDef = Copy.getOperand(0).getReg();
  262. assert(CopyDef == Src || CopyDef == Def);
  263. for (MachineInstr &MI :
  264. make_range(PrevCopy->getIterator(), Copy.getIterator()))
  265. MI.clearRegisterKills(CopyDef, TRI);
  266. Copy.eraseFromParent();
  267. Changed = true;
  268. ++NumDeletes;
  269. return true;
  270. }
  271. /// Decide whether we should forward the source of \param Copy to its use in
  272. /// \param UseI based on the physical register class constraints of the opcode
  273. /// and avoiding introducing more cross-class COPYs.
  274. bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
  275. const MachineInstr &UseI,
  276. unsigned UseIdx) {
  277. Register CopySrcReg = Copy.getOperand(1).getReg();
  278. // If the new register meets the opcode register constraints, then allow
  279. // forwarding.
  280. if (const TargetRegisterClass *URC =
  281. UseI.getRegClassConstraint(UseIdx, TII, TRI))
  282. return URC->contains(CopySrcReg);
  283. if (!UseI.isCopy())
  284. return false;
  285. /// COPYs don't have register class constraints, so if the user instruction
  286. /// is a COPY, we just try to avoid introducing additional cross-class
  287. /// COPYs. For example:
  288. ///
  289. /// RegClassA = COPY RegClassB // Copy parameter
  290. /// ...
  291. /// RegClassB = COPY RegClassA // UseI parameter
  292. ///
  293. /// which after forwarding becomes
  294. ///
  295. /// RegClassA = COPY RegClassB
  296. /// ...
  297. /// RegClassB = COPY RegClassB
  298. ///
  299. /// so we have reduced the number of cross-class COPYs and potentially
  300. /// introduced a nop COPY that can be removed.
  301. const TargetRegisterClass *UseDstRC =
  302. TRI->getMinimalPhysRegClass(UseI.getOperand(0).getReg());
  303. const TargetRegisterClass *SuperRC = UseDstRC;
  304. for (TargetRegisterClass::sc_iterator SuperRCI = UseDstRC->getSuperClasses();
  305. SuperRC; SuperRC = *SuperRCI++)
  306. if (SuperRC->contains(CopySrcReg))
  307. return true;
  308. return false;
  309. }
  310. /// Check that \p MI does not have implicit uses that overlap with it's \p Use
  311. /// operand (the register being replaced), since these can sometimes be
  312. /// implicitly tied to other operands. For example, on AMDGPU:
  313. ///
  314. /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
  315. ///
  316. /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
  317. /// way of knowing we need to update the latter when updating the former.
  318. bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
  319. const MachineOperand &Use) {
  320. for (const MachineOperand &MIUse : MI.uses())
  321. if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
  322. MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
  323. return true;
  324. return false;
  325. }
  326. /// Look for available copies whose destination register is used by \p MI and
  327. /// replace the use in \p MI with the copy's source register.
  328. void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
  329. if (!Tracker.hasAnyCopies())
  330. return;
  331. // Look for non-tied explicit vreg uses that have an active COPY
  332. // instruction that defines the physical register allocated to them.
  333. // Replace the vreg with the source of the active COPY.
  334. for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
  335. ++OpIdx) {
  336. MachineOperand &MOUse = MI.getOperand(OpIdx);
  337. // Don't forward into undef use operands since doing so can cause problems
  338. // with the machine verifier, since it doesn't treat undef reads as reads,
  339. // so we can end up with a live range that ends on an undef read, leading to
  340. // an error that the live range doesn't end on a read of the live range
  341. // register.
  342. if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
  343. MOUse.isImplicit())
  344. continue;
  345. if (!MOUse.getReg())
  346. continue;
  347. // Check that the register is marked 'renamable' so we know it is safe to
  348. // rename it without violating any constraints that aren't expressed in the
  349. // IR (e.g. ABI or opcode requirements).
  350. if (!MOUse.isRenamable())
  351. continue;
  352. MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg(), *TRI);
  353. if (!Copy)
  354. continue;
  355. Register CopyDstReg = Copy->getOperand(0).getReg();
  356. const MachineOperand &CopySrc = Copy->getOperand(1);
  357. Register CopySrcReg = CopySrc.getReg();
  358. // FIXME: Don't handle partial uses of wider COPYs yet.
  359. if (MOUse.getReg() != CopyDstReg) {
  360. LLVM_DEBUG(
  361. dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n "
  362. << MI);
  363. continue;
  364. }
  365. // Don't forward COPYs of reserved regs unless they are constant.
  366. if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
  367. continue;
  368. if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
  369. continue;
  370. if (hasImplicitOverlap(MI, MOUse))
  371. continue;
  372. if (!DebugCounter::shouldExecute(FwdCounter)) {
  373. LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
  374. << MI);
  375. continue;
  376. }
  377. LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
  378. << "\n with " << printReg(CopySrcReg, TRI)
  379. << "\n in " << MI << " from " << *Copy);
  380. MOUse.setReg(CopySrcReg);
  381. if (!CopySrc.isRenamable())
  382. MOUse.setIsRenamable(false);
  383. LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
  384. // Clear kill markers that may have been invalidated.
  385. for (MachineInstr &KMI :
  386. make_range(Copy->getIterator(), std::next(MI.getIterator())))
  387. KMI.clearRegisterKills(CopySrcReg, TRI);
  388. ++NumCopyForwards;
  389. Changed = true;
  390. }
  391. }
  392. void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
  393. LLVM_DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
  394. for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
  395. MachineInstr *MI = &*I;
  396. ++I;
  397. // Analyze copies (which don't overlap themselves).
  398. if (MI->isCopy() && !TRI->regsOverlap(MI->getOperand(0).getReg(),
  399. MI->getOperand(1).getReg())) {
  400. Register Def = MI->getOperand(0).getReg();
  401. Register Src = MI->getOperand(1).getReg();
  402. assert(!Register::isVirtualRegister(Def) &&
  403. !Register::isVirtualRegister(Src) &&
  404. "MachineCopyPropagation should be run after register allocation!");
  405. // The two copies cancel out and the source of the first copy
  406. // hasn't been overridden, eliminate the second one. e.g.
  407. // %ecx = COPY %eax
  408. // ... nothing clobbered eax.
  409. // %eax = COPY %ecx
  410. // =>
  411. // %ecx = COPY %eax
  412. //
  413. // or
  414. //
  415. // %ecx = COPY %eax
  416. // ... nothing clobbered eax.
  417. // %ecx = COPY %eax
  418. // =>
  419. // %ecx = COPY %eax
  420. if (eraseIfRedundant(*MI, Def, Src) || eraseIfRedundant(*MI, Src, Def))
  421. continue;
  422. forwardUses(*MI);
  423. // Src may have been changed by forwardUses()
  424. Src = MI->getOperand(1).getReg();
  425. // If Src is defined by a previous copy, the previous copy cannot be
  426. // eliminated.
  427. ReadRegister(Src, *MI, RegularUse);
  428. for (const MachineOperand &MO : MI->implicit_operands()) {
  429. if (!MO.isReg() || !MO.readsReg())
  430. continue;
  431. Register Reg = MO.getReg();
  432. if (!Reg)
  433. continue;
  434. ReadRegister(Reg, *MI, RegularUse);
  435. }
  436. LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
  437. // Copy is now a candidate for deletion.
  438. if (!MRI->isReserved(Def))
  439. MaybeDeadCopies.insert(MI);
  440. // If 'Def' is previously source of another copy, then this earlier copy's
  441. // source is no longer available. e.g.
  442. // %xmm9 = copy %xmm2
  443. // ...
  444. // %xmm2 = copy %xmm0
  445. // ...
  446. // %xmm2 = copy %xmm9
  447. Tracker.clobberRegister(Def, *TRI);
  448. for (const MachineOperand &MO : MI->implicit_operands()) {
  449. if (!MO.isReg() || !MO.isDef())
  450. continue;
  451. Register Reg = MO.getReg();
  452. if (!Reg)
  453. continue;
  454. Tracker.clobberRegister(Reg, *TRI);
  455. }
  456. Tracker.trackCopy(MI, *TRI);
  457. continue;
  458. }
  459. // Clobber any earlyclobber regs first.
  460. for (const MachineOperand &MO : MI->operands())
  461. if (MO.isReg() && MO.isEarlyClobber()) {
  462. Register Reg = MO.getReg();
  463. // If we have a tied earlyclobber, that means it is also read by this
  464. // instruction, so we need to make sure we don't remove it as dead
  465. // later.
  466. if (MO.isTied())
  467. ReadRegister(Reg, *MI, RegularUse);
  468. Tracker.clobberRegister(Reg, *TRI);
  469. }
  470. forwardUses(*MI);
  471. // Not a copy.
  472. SmallVector<unsigned, 2> Defs;
  473. const MachineOperand *RegMask = nullptr;
  474. for (const MachineOperand &MO : MI->operands()) {
  475. if (MO.isRegMask())
  476. RegMask = &MO;
  477. if (!MO.isReg())
  478. continue;
  479. Register Reg = MO.getReg();
  480. if (!Reg)
  481. continue;
  482. assert(!Register::isVirtualRegister(Reg) &&
  483. "MachineCopyPropagation should be run after register allocation!");
  484. if (MO.isDef() && !MO.isEarlyClobber()) {
  485. Defs.push_back(Reg);
  486. continue;
  487. } else if (MO.readsReg())
  488. ReadRegister(Reg, *MI, MO.isDebug() ? DebugUse : RegularUse);
  489. }
  490. // The instruction has a register mask operand which means that it clobbers
  491. // a large set of registers. Treat clobbered registers the same way as
  492. // defined registers.
  493. if (RegMask) {
  494. // Erase any MaybeDeadCopies whose destination register is clobbered.
  495. for (SmallSetVector<MachineInstr *, 8>::iterator DI =
  496. MaybeDeadCopies.begin();
  497. DI != MaybeDeadCopies.end();) {
  498. MachineInstr *MaybeDead = *DI;
  499. Register Reg = MaybeDead->getOperand(0).getReg();
  500. assert(!MRI->isReserved(Reg));
  501. if (!RegMask->clobbersPhysReg(Reg)) {
  502. ++DI;
  503. continue;
  504. }
  505. LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
  506. MaybeDead->dump());
  507. // Make sure we invalidate any entries in the copy maps before erasing
  508. // the instruction.
  509. Tracker.clobberRegister(Reg, *TRI);
  510. // erase() will return the next valid iterator pointing to the next
  511. // element after the erased one.
  512. DI = MaybeDeadCopies.erase(DI);
  513. MaybeDead->eraseFromParent();
  514. Changed = true;
  515. ++NumDeletes;
  516. }
  517. }
  518. // Any previous copy definition or reading the Defs is no longer available.
  519. for (unsigned Reg : Defs)
  520. Tracker.clobberRegister(Reg, *TRI);
  521. }
  522. // If MBB doesn't have successors, delete the copies whose defs are not used.
  523. // If MBB does have successors, then conservative assume the defs are live-out
  524. // since we don't want to trust live-in lists.
  525. if (MBB.succ_empty()) {
  526. for (MachineInstr *MaybeDead : MaybeDeadCopies) {
  527. LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
  528. MaybeDead->dump());
  529. assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
  530. // Update matching debug values, if any.
  531. assert(MaybeDead->isCopy());
  532. unsigned SrcReg = MaybeDead->getOperand(1).getReg();
  533. MRI->updateDbgUsersToReg(SrcReg, CopyDbgUsers[MaybeDead]);
  534. MaybeDead->eraseFromParent();
  535. Changed = true;
  536. ++NumDeletes;
  537. }
  538. }
  539. MaybeDeadCopies.clear();
  540. CopyDbgUsers.clear();
  541. Tracker.clear();
  542. }
  543. bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
  544. if (skipFunction(MF.getFunction()))
  545. return false;
  546. Changed = false;
  547. TRI = MF.getSubtarget().getRegisterInfo();
  548. TII = MF.getSubtarget().getInstrInfo();
  549. MRI = &MF.getRegInfo();
  550. for (MachineBasicBlock &MBB : MF)
  551. CopyPropagateBlock(MBB);
  552. return Changed;
  553. }