MachineCopyPropagation.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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. // or
  41. //
  42. // $R0 = OP ...
  43. // ... // No read/clobber of $R0 and $R1
  44. // $R1 = COPY $R0 // $R0 is killed
  45. // Replace $R0 with $R1 and remove the COPY
  46. // $R1 = OP ...
  47. // ...
  48. //
  49. //===----------------------------------------------------------------------===//
  50. #include "llvm/ADT/DenseMap.h"
  51. #include "llvm/ADT/STLExtras.h"
  52. #include "llvm/ADT/SetVector.h"
  53. #include "llvm/ADT/SmallSet.h"
  54. #include "llvm/ADT/SmallVector.h"
  55. #include "llvm/ADT/Statistic.h"
  56. #include "llvm/ADT/iterator_range.h"
  57. #include "llvm/CodeGen/MachineBasicBlock.h"
  58. #include "llvm/CodeGen/MachineFunction.h"
  59. #include "llvm/CodeGen/MachineFunctionPass.h"
  60. #include "llvm/CodeGen/MachineInstr.h"
  61. #include "llvm/CodeGen/MachineOperand.h"
  62. #include "llvm/CodeGen/MachineRegisterInfo.h"
  63. #include "llvm/CodeGen/TargetInstrInfo.h"
  64. #include "llvm/CodeGen/TargetRegisterInfo.h"
  65. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  66. #include "llvm/InitializePasses.h"
  67. #include "llvm/MC/MCRegisterInfo.h"
  68. #include "llvm/Pass.h"
  69. #include "llvm/Support/Debug.h"
  70. #include "llvm/Support/DebugCounter.h"
  71. #include "llvm/Support/raw_ostream.h"
  72. #include <cassert>
  73. #include <iterator>
  74. using namespace llvm;
  75. #define DEBUG_TYPE "machine-cp"
  76. STATISTIC(NumDeletes, "Number of dead copies deleted");
  77. STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
  78. STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated");
  79. DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
  80. "Controls which register COPYs are forwarded");
  81. static cl::opt<bool> MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false),
  82. cl::Hidden);
  83. namespace {
  84. static std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI,
  85. const TargetInstrInfo &TII,
  86. bool UseCopyInstr) {
  87. if (UseCopyInstr)
  88. return TII.isCopyInstr(MI);
  89. if (MI.isCopy())
  90. return std::optional<DestSourcePair>(
  91. DestSourcePair{MI.getOperand(0), MI.getOperand(1)});
  92. return std::nullopt;
  93. }
  94. class CopyTracker {
  95. struct CopyInfo {
  96. MachineInstr *MI;
  97. SmallVector<MCRegister, 4> DefRegs;
  98. bool Avail;
  99. };
  100. DenseMap<MCRegister, CopyInfo> Copies;
  101. public:
  102. /// Mark all of the given registers and their subregisters as unavailable for
  103. /// copying.
  104. void markRegsUnavailable(ArrayRef<MCRegister> Regs,
  105. const TargetRegisterInfo &TRI) {
  106. for (MCRegister Reg : Regs) {
  107. // Source of copy is no longer available for propagation.
  108. for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
  109. auto CI = Copies.find(*RUI);
  110. if (CI != Copies.end())
  111. CI->second.Avail = false;
  112. }
  113. }
  114. }
  115. /// Remove register from copy maps.
  116. void invalidateRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
  117. const TargetInstrInfo &TII, bool UseCopyInstr) {
  118. // Since Reg might be a subreg of some registers, only invalidate Reg is not
  119. // enough. We have to find the COPY defines Reg or registers defined by Reg
  120. // and invalidate all of them.
  121. SmallSet<MCRegister, 8> RegsToInvalidate;
  122. RegsToInvalidate.insert(Reg);
  123. for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
  124. auto I = Copies.find(*RUI);
  125. if (I != Copies.end()) {
  126. if (MachineInstr *MI = I->second.MI) {
  127. std::optional<DestSourcePair> CopyOperands =
  128. isCopyInstr(*MI, TII, UseCopyInstr);
  129. assert(CopyOperands && "Expect copy");
  130. RegsToInvalidate.insert(
  131. CopyOperands->Destination->getReg().asMCReg());
  132. RegsToInvalidate.insert(CopyOperands->Source->getReg().asMCReg());
  133. }
  134. RegsToInvalidate.insert(I->second.DefRegs.begin(),
  135. I->second.DefRegs.end());
  136. }
  137. }
  138. for (MCRegister InvalidReg : RegsToInvalidate)
  139. for (MCRegUnitIterator RUI(InvalidReg, &TRI); RUI.isValid(); ++RUI)
  140. Copies.erase(*RUI);
  141. }
  142. /// Clobber a single register, removing it from the tracker's copy maps.
  143. void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
  144. const TargetInstrInfo &TII, bool UseCopyInstr) {
  145. for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
  146. auto I = Copies.find(*RUI);
  147. if (I != Copies.end()) {
  148. // When we clobber the source of a copy, we need to clobber everything
  149. // it defined.
  150. markRegsUnavailable(I->second.DefRegs, TRI);
  151. // When we clobber the destination of a copy, we need to clobber the
  152. // whole register it defined.
  153. if (MachineInstr *MI = I->second.MI) {
  154. std::optional<DestSourcePair> CopyOperands =
  155. isCopyInstr(*MI, TII, UseCopyInstr);
  156. markRegsUnavailable({CopyOperands->Destination->getReg().asMCReg()},
  157. TRI);
  158. }
  159. // Now we can erase the copy.
  160. Copies.erase(I);
  161. }
  162. }
  163. }
  164. /// Add this copy's registers into the tracker's copy maps.
  165. void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI,
  166. const TargetInstrInfo &TII, bool UseCopyInstr) {
  167. std::optional<DestSourcePair> CopyOperands =
  168. isCopyInstr(*MI, TII, UseCopyInstr);
  169. assert(CopyOperands && "Tracking non-copy?");
  170. MCRegister Src = CopyOperands->Source->getReg().asMCReg();
  171. MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
  172. // Remember Def is defined by the copy.
  173. for (MCRegUnitIterator RUI(Def, &TRI); RUI.isValid(); ++RUI)
  174. Copies[*RUI] = {MI, {}, true};
  175. // Remember source that's copied to Def. Once it's clobbered, then
  176. // it's no longer available for copy propagation.
  177. for (MCRegUnitIterator RUI(Src, &TRI); RUI.isValid(); ++RUI) {
  178. auto I = Copies.insert({*RUI, {nullptr, {}, false}});
  179. auto &Copy = I.first->second;
  180. if (!is_contained(Copy.DefRegs, Def))
  181. Copy.DefRegs.push_back(Def);
  182. }
  183. }
  184. bool hasAnyCopies() {
  185. return !Copies.empty();
  186. }
  187. MachineInstr *findCopyForUnit(MCRegister RegUnit,
  188. const TargetRegisterInfo &TRI,
  189. bool MustBeAvailable = false) {
  190. auto CI = Copies.find(RegUnit);
  191. if (CI == Copies.end())
  192. return nullptr;
  193. if (MustBeAvailable && !CI->second.Avail)
  194. return nullptr;
  195. return CI->second.MI;
  196. }
  197. MachineInstr *findCopyDefViaUnit(MCRegister RegUnit,
  198. const TargetRegisterInfo &TRI) {
  199. auto CI = Copies.find(RegUnit);
  200. if (CI == Copies.end())
  201. return nullptr;
  202. if (CI->second.DefRegs.size() != 1)
  203. return nullptr;
  204. MCRegUnitIterator RUI(CI->second.DefRegs[0], &TRI);
  205. return findCopyForUnit(*RUI, TRI, true);
  206. }
  207. MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg,
  208. const TargetRegisterInfo &TRI,
  209. const TargetInstrInfo &TII,
  210. bool UseCopyInstr) {
  211. MCRegUnitIterator RUI(Reg, &TRI);
  212. MachineInstr *AvailCopy = findCopyDefViaUnit(*RUI, TRI);
  213. if (!AvailCopy)
  214. return nullptr;
  215. std::optional<DestSourcePair> CopyOperands =
  216. isCopyInstr(*AvailCopy, TII, UseCopyInstr);
  217. Register AvailSrc = CopyOperands->Source->getReg();
  218. Register AvailDef = CopyOperands->Destination->getReg();
  219. if (!TRI.isSubRegisterEq(AvailSrc, Reg))
  220. return nullptr;
  221. for (const MachineInstr &MI :
  222. make_range(AvailCopy->getReverseIterator(), I.getReverseIterator()))
  223. for (const MachineOperand &MO : MI.operands())
  224. if (MO.isRegMask())
  225. // FIXME: Shall we simultaneously invalidate AvailSrc or AvailDef?
  226. if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
  227. return nullptr;
  228. return AvailCopy;
  229. }
  230. MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister Reg,
  231. const TargetRegisterInfo &TRI,
  232. const TargetInstrInfo &TII, bool UseCopyInstr) {
  233. // We check the first RegUnit here, since we'll only be interested in the
  234. // copy if it copies the entire register anyway.
  235. MCRegUnitIterator RUI(Reg, &TRI);
  236. MachineInstr *AvailCopy =
  237. findCopyForUnit(*RUI, TRI, /*MustBeAvailable=*/true);
  238. if (!AvailCopy)
  239. return nullptr;
  240. std::optional<DestSourcePair> CopyOperands =
  241. isCopyInstr(*AvailCopy, TII, UseCopyInstr);
  242. Register AvailSrc = CopyOperands->Source->getReg();
  243. Register AvailDef = CopyOperands->Destination->getReg();
  244. if (!TRI.isSubRegisterEq(AvailDef, Reg))
  245. return nullptr;
  246. // Check that the available copy isn't clobbered by any regmasks between
  247. // itself and the destination.
  248. for (const MachineInstr &MI :
  249. make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
  250. for (const MachineOperand &MO : MI.operands())
  251. if (MO.isRegMask())
  252. if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
  253. return nullptr;
  254. return AvailCopy;
  255. }
  256. void clear() {
  257. Copies.clear();
  258. }
  259. };
  260. class MachineCopyPropagation : public MachineFunctionPass {
  261. const TargetRegisterInfo *TRI;
  262. const TargetInstrInfo *TII;
  263. const MachineRegisterInfo *MRI;
  264. // Return true if this is a copy instruction and false otherwise.
  265. bool UseCopyInstr;
  266. public:
  267. static char ID; // Pass identification, replacement for typeid
  268. MachineCopyPropagation(bool CopyInstr = false)
  269. : MachineFunctionPass(ID), UseCopyInstr(CopyInstr || MCPUseCopyInstr) {
  270. initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
  271. }
  272. void getAnalysisUsage(AnalysisUsage &AU) const override {
  273. AU.setPreservesCFG();
  274. MachineFunctionPass::getAnalysisUsage(AU);
  275. }
  276. bool runOnMachineFunction(MachineFunction &MF) override;
  277. MachineFunctionProperties getRequiredProperties() const override {
  278. return MachineFunctionProperties().set(
  279. MachineFunctionProperties::Property::NoVRegs);
  280. }
  281. private:
  282. typedef enum { DebugUse = false, RegularUse = true } DebugType;
  283. void ReadRegister(MCRegister Reg, MachineInstr &Reader, DebugType DT);
  284. void ForwardCopyPropagateBlock(MachineBasicBlock &MBB);
  285. void BackwardCopyPropagateBlock(MachineBasicBlock &MBB);
  286. bool eraseIfRedundant(MachineInstr &Copy, MCRegister Src, MCRegister Def);
  287. void forwardUses(MachineInstr &MI);
  288. void propagateDefs(MachineInstr &MI);
  289. bool isForwardableRegClassCopy(const MachineInstr &Copy,
  290. const MachineInstr &UseI, unsigned UseIdx);
  291. bool isBackwardPropagatableRegClassCopy(const MachineInstr &Copy,
  292. const MachineInstr &UseI,
  293. unsigned UseIdx);
  294. bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
  295. bool hasOverlappingMultipleDef(const MachineInstr &MI,
  296. const MachineOperand &MODef, Register Def);
  297. /// Candidates for deletion.
  298. SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
  299. /// Multimap tracking debug users in current BB
  300. DenseMap<MachineInstr *, SmallSet<MachineInstr *, 2>> CopyDbgUsers;
  301. CopyTracker Tracker;
  302. bool Changed;
  303. };
  304. } // end anonymous namespace
  305. char MachineCopyPropagation::ID = 0;
  306. char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
  307. INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
  308. "Machine Copy Propagation Pass", false, false)
  309. void MachineCopyPropagation::ReadRegister(MCRegister Reg, MachineInstr &Reader,
  310. DebugType DT) {
  311. // If 'Reg' is defined by a copy, the copy is no longer a candidate
  312. // for elimination. If a copy is "read" by a debug user, record the user
  313. // for propagation.
  314. for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) {
  315. if (MachineInstr *Copy = Tracker.findCopyForUnit(*RUI, *TRI)) {
  316. if (DT == RegularUse) {
  317. LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
  318. MaybeDeadCopies.remove(Copy);
  319. } else {
  320. CopyDbgUsers[Copy].insert(&Reader);
  321. }
  322. }
  323. }
  324. }
  325. /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
  326. /// This fact may have been obscured by sub register usage or may not be true at
  327. /// all even though Src and Def are subregisters of the registers used in
  328. /// PreviousCopy. e.g.
  329. /// isNopCopy("ecx = COPY eax", AX, CX) == true
  330. /// isNopCopy("ecx = COPY eax", AH, CL) == false
  331. static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src,
  332. MCRegister Def, const TargetRegisterInfo *TRI,
  333. const TargetInstrInfo *TII, bool UseCopyInstr) {
  334. std::optional<DestSourcePair> CopyOperands =
  335. isCopyInstr(PreviousCopy, *TII, UseCopyInstr);
  336. MCRegister PreviousSrc = CopyOperands->Source->getReg().asMCReg();
  337. MCRegister PreviousDef = CopyOperands->Destination->getReg().asMCReg();
  338. if (Src == PreviousSrc && Def == PreviousDef)
  339. return true;
  340. if (!TRI->isSubRegister(PreviousSrc, Src))
  341. return false;
  342. unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
  343. return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
  344. }
  345. /// Remove instruction \p Copy if there exists a previous copy that copies the
  346. /// register \p Src to the register \p Def; This may happen indirectly by
  347. /// copying the super registers.
  348. bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy,
  349. MCRegister Src, MCRegister Def) {
  350. // Avoid eliminating a copy from/to a reserved registers as we cannot predict
  351. // the value (Example: The sparc zero register is writable but stays zero).
  352. if (MRI->isReserved(Src) || MRI->isReserved(Def))
  353. return false;
  354. // Search for an existing copy.
  355. MachineInstr *PrevCopy =
  356. Tracker.findAvailCopy(Copy, Def, *TRI, *TII, UseCopyInstr);
  357. if (!PrevCopy)
  358. return false;
  359. auto PrevCopyOperands = isCopyInstr(*PrevCopy, *TII, UseCopyInstr);
  360. // Check that the existing copy uses the correct sub registers.
  361. if (PrevCopyOperands->Destination->isDead())
  362. return false;
  363. if (!isNopCopy(*PrevCopy, Src, Def, TRI, TII, UseCopyInstr))
  364. return false;
  365. LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
  366. // Copy was redundantly redefining either Src or Def. Remove earlier kill
  367. // flags between Copy and PrevCopy because the value will be reused now.
  368. std::optional<DestSourcePair> CopyOperands =
  369. isCopyInstr(Copy, *TII, UseCopyInstr);
  370. assert(CopyOperands);
  371. Register CopyDef = CopyOperands->Destination->getReg();
  372. assert(CopyDef == Src || CopyDef == Def);
  373. for (MachineInstr &MI :
  374. make_range(PrevCopy->getIterator(), Copy.getIterator()))
  375. MI.clearRegisterKills(CopyDef, TRI);
  376. Copy.eraseFromParent();
  377. Changed = true;
  378. ++NumDeletes;
  379. return true;
  380. }
  381. bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy(
  382. const MachineInstr &Copy, const MachineInstr &UseI, unsigned UseIdx) {
  383. std::optional<DestSourcePair> CopyOperands =
  384. isCopyInstr(Copy, *TII, UseCopyInstr);
  385. Register Def = CopyOperands->Destination->getReg();
  386. if (const TargetRegisterClass *URC =
  387. UseI.getRegClassConstraint(UseIdx, TII, TRI))
  388. return URC->contains(Def);
  389. // We don't process further if UseI is a COPY, since forward copy propagation
  390. // should handle that.
  391. return false;
  392. }
  393. /// Decide whether we should forward the source of \param Copy to its use in
  394. /// \param UseI based on the physical register class constraints of the opcode
  395. /// and avoiding introducing more cross-class COPYs.
  396. bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
  397. const MachineInstr &UseI,
  398. unsigned UseIdx) {
  399. std::optional<DestSourcePair> CopyOperands =
  400. isCopyInstr(Copy, *TII, UseCopyInstr);
  401. Register CopySrcReg = CopyOperands->Source->getReg();
  402. // If the new register meets the opcode register constraints, then allow
  403. // forwarding.
  404. if (const TargetRegisterClass *URC =
  405. UseI.getRegClassConstraint(UseIdx, TII, TRI))
  406. return URC->contains(CopySrcReg);
  407. auto UseICopyOperands = isCopyInstr(UseI, *TII, UseCopyInstr);
  408. if (!UseICopyOperands)
  409. return false;
  410. /// COPYs don't have register class constraints, so if the user instruction
  411. /// is a COPY, we just try to avoid introducing additional cross-class
  412. /// COPYs. For example:
  413. ///
  414. /// RegClassA = COPY RegClassB // Copy parameter
  415. /// ...
  416. /// RegClassB = COPY RegClassA // UseI parameter
  417. ///
  418. /// which after forwarding becomes
  419. ///
  420. /// RegClassA = COPY RegClassB
  421. /// ...
  422. /// RegClassB = COPY RegClassB
  423. ///
  424. /// so we have reduced the number of cross-class COPYs and potentially
  425. /// introduced a nop COPY that can be removed.
  426. // Allow forwarding if src and dst belong to any common class, so long as they
  427. // don't belong to any (possibly smaller) common class that requires copies to
  428. // go via a different class.
  429. Register UseDstReg = UseICopyOperands->Destination->getReg();
  430. bool Found = false;
  431. bool IsCrossClass = false;
  432. for (const TargetRegisterClass *RC : TRI->regclasses()) {
  433. if (RC->contains(CopySrcReg) && RC->contains(UseDstReg)) {
  434. Found = true;
  435. if (TRI->getCrossCopyRegClass(RC) != RC) {
  436. IsCrossClass = true;
  437. break;
  438. }
  439. }
  440. }
  441. if (!Found)
  442. return false;
  443. if (!IsCrossClass)
  444. return true;
  445. // The forwarded copy would be cross-class. Only do this if the original copy
  446. // was also cross-class.
  447. Register CopyDstReg = CopyOperands->Destination->getReg();
  448. for (const TargetRegisterClass *RC : TRI->regclasses()) {
  449. if (RC->contains(CopySrcReg) && RC->contains(CopyDstReg) &&
  450. TRI->getCrossCopyRegClass(RC) != RC)
  451. return true;
  452. }
  453. return false;
  454. }
  455. /// Check that \p MI does not have implicit uses that overlap with it's \p Use
  456. /// operand (the register being replaced), since these can sometimes be
  457. /// implicitly tied to other operands. For example, on AMDGPU:
  458. ///
  459. /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
  460. ///
  461. /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
  462. /// way of knowing we need to update the latter when updating the former.
  463. bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
  464. const MachineOperand &Use) {
  465. for (const MachineOperand &MIUse : MI.uses())
  466. if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
  467. MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
  468. return true;
  469. return false;
  470. }
  471. /// For an MI that has multiple definitions, check whether \p MI has
  472. /// a definition that overlaps with another of its definitions.
  473. /// For example, on ARM: umull r9, r9, lr, r0
  474. /// The umull instruction is unpredictable unless RdHi and RdLo are different.
  475. bool MachineCopyPropagation::hasOverlappingMultipleDef(
  476. const MachineInstr &MI, const MachineOperand &MODef, Register Def) {
  477. for (const MachineOperand &MIDef : MI.defs()) {
  478. if ((&MIDef != &MODef) && MIDef.isReg() &&
  479. TRI->regsOverlap(Def, MIDef.getReg()))
  480. return true;
  481. }
  482. return false;
  483. }
  484. /// Look for available copies whose destination register is used by \p MI and
  485. /// replace the use in \p MI with the copy's source register.
  486. void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
  487. if (!Tracker.hasAnyCopies())
  488. return;
  489. // Look for non-tied explicit vreg uses that have an active COPY
  490. // instruction that defines the physical register allocated to them.
  491. // Replace the vreg with the source of the active COPY.
  492. for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
  493. ++OpIdx) {
  494. MachineOperand &MOUse = MI.getOperand(OpIdx);
  495. // Don't forward into undef use operands since doing so can cause problems
  496. // with the machine verifier, since it doesn't treat undef reads as reads,
  497. // so we can end up with a live range that ends on an undef read, leading to
  498. // an error that the live range doesn't end on a read of the live range
  499. // register.
  500. if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
  501. MOUse.isImplicit())
  502. continue;
  503. if (!MOUse.getReg())
  504. continue;
  505. // Check that the register is marked 'renamable' so we know it is safe to
  506. // rename it without violating any constraints that aren't expressed in the
  507. // IR (e.g. ABI or opcode requirements).
  508. if (!MOUse.isRenamable())
  509. continue;
  510. MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg().asMCReg(),
  511. *TRI, *TII, UseCopyInstr);
  512. if (!Copy)
  513. continue;
  514. std::optional<DestSourcePair> CopyOperands =
  515. isCopyInstr(*Copy, *TII, UseCopyInstr);
  516. Register CopyDstReg = CopyOperands->Destination->getReg();
  517. const MachineOperand &CopySrc = *CopyOperands->Source;
  518. Register CopySrcReg = CopySrc.getReg();
  519. // FIXME: Don't handle partial uses of wider COPYs yet.
  520. if (MOUse.getReg() != CopyDstReg) {
  521. LLVM_DEBUG(
  522. dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n "
  523. << MI);
  524. continue;
  525. }
  526. // Don't forward COPYs of reserved regs unless they are constant.
  527. if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
  528. continue;
  529. if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
  530. continue;
  531. if (hasImplicitOverlap(MI, MOUse))
  532. continue;
  533. // Check that the instruction is not a copy that partially overwrites the
  534. // original copy source that we are about to use. The tracker mechanism
  535. // cannot cope with that.
  536. if (isCopyInstr(MI, *TII, UseCopyInstr) &&
  537. MI.modifiesRegister(CopySrcReg, TRI) &&
  538. !MI.definesRegister(CopySrcReg)) {
  539. LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI);
  540. continue;
  541. }
  542. if (!DebugCounter::shouldExecute(FwdCounter)) {
  543. LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
  544. << MI);
  545. continue;
  546. }
  547. LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
  548. << "\n with " << printReg(CopySrcReg, TRI)
  549. << "\n in " << MI << " from " << *Copy);
  550. MOUse.setReg(CopySrcReg);
  551. if (!CopySrc.isRenamable())
  552. MOUse.setIsRenamable(false);
  553. MOUse.setIsUndef(CopySrc.isUndef());
  554. LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
  555. // Clear kill markers that may have been invalidated.
  556. for (MachineInstr &KMI :
  557. make_range(Copy->getIterator(), std::next(MI.getIterator())))
  558. KMI.clearRegisterKills(CopySrcReg, TRI);
  559. ++NumCopyForwards;
  560. Changed = true;
  561. }
  562. }
  563. void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) {
  564. LLVM_DEBUG(dbgs() << "MCP: ForwardCopyPropagateBlock " << MBB.getName()
  565. << "\n");
  566. for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
  567. // Analyze copies (which don't overlap themselves).
  568. std::optional<DestSourcePair> CopyOperands =
  569. isCopyInstr(MI, *TII, UseCopyInstr);
  570. if (CopyOperands) {
  571. Register RegSrc = CopyOperands->Source->getReg();
  572. Register RegDef = CopyOperands->Destination->getReg();
  573. if (!TRI->regsOverlap(RegDef, RegSrc)) {
  574. assert(RegDef.isPhysical() && RegSrc.isPhysical() &&
  575. "MachineCopyPropagation should be run after register allocation!");
  576. MCRegister Def = RegDef.asMCReg();
  577. MCRegister Src = RegSrc.asMCReg();
  578. // The two copies cancel out and the source of the first copy
  579. // hasn't been overridden, eliminate the second one. e.g.
  580. // %ecx = COPY %eax
  581. // ... nothing clobbered eax.
  582. // %eax = COPY %ecx
  583. // =>
  584. // %ecx = COPY %eax
  585. //
  586. // or
  587. //
  588. // %ecx = COPY %eax
  589. // ... nothing clobbered eax.
  590. // %ecx = COPY %eax
  591. // =>
  592. // %ecx = COPY %eax
  593. if (eraseIfRedundant(MI, Def, Src) || eraseIfRedundant(MI, Src, Def))
  594. continue;
  595. forwardUses(MI);
  596. // Src may have been changed by forwardUses()
  597. CopyOperands = isCopyInstr(MI, *TII, UseCopyInstr);
  598. Src = CopyOperands->Source->getReg().asMCReg();
  599. // If Src is defined by a previous copy, the previous copy cannot be
  600. // eliminated.
  601. ReadRegister(Src, MI, RegularUse);
  602. for (const MachineOperand &MO : MI.implicit_operands()) {
  603. if (!MO.isReg() || !MO.readsReg())
  604. continue;
  605. MCRegister Reg = MO.getReg().asMCReg();
  606. if (!Reg)
  607. continue;
  608. ReadRegister(Reg, MI, RegularUse);
  609. }
  610. LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI.dump());
  611. // Copy is now a candidate for deletion.
  612. if (!MRI->isReserved(Def))
  613. MaybeDeadCopies.insert(&MI);
  614. // If 'Def' is previously source of another copy, then this earlier copy's
  615. // source is no longer available. e.g.
  616. // %xmm9 = copy %xmm2
  617. // ...
  618. // %xmm2 = copy %xmm0
  619. // ...
  620. // %xmm2 = copy %xmm9
  621. Tracker.clobberRegister(Def, *TRI, *TII, UseCopyInstr);
  622. for (const MachineOperand &MO : MI.implicit_operands()) {
  623. if (!MO.isReg() || !MO.isDef())
  624. continue;
  625. MCRegister Reg = MO.getReg().asMCReg();
  626. if (!Reg)
  627. continue;
  628. Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
  629. }
  630. Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
  631. continue;
  632. }
  633. }
  634. // Clobber any earlyclobber regs first.
  635. for (const MachineOperand &MO : MI.operands())
  636. if (MO.isReg() && MO.isEarlyClobber()) {
  637. MCRegister Reg = MO.getReg().asMCReg();
  638. // If we have a tied earlyclobber, that means it is also read by this
  639. // instruction, so we need to make sure we don't remove it as dead
  640. // later.
  641. if (MO.isTied())
  642. ReadRegister(Reg, MI, RegularUse);
  643. Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
  644. }
  645. forwardUses(MI);
  646. // Not a copy.
  647. SmallVector<Register, 2> Defs;
  648. const MachineOperand *RegMask = nullptr;
  649. for (const MachineOperand &MO : MI.operands()) {
  650. if (MO.isRegMask())
  651. RegMask = &MO;
  652. if (!MO.isReg())
  653. continue;
  654. Register Reg = MO.getReg();
  655. if (!Reg)
  656. continue;
  657. assert(!Reg.isVirtual() &&
  658. "MachineCopyPropagation should be run after register allocation!");
  659. if (MO.isDef() && !MO.isEarlyClobber()) {
  660. Defs.push_back(Reg.asMCReg());
  661. continue;
  662. } else if (MO.readsReg())
  663. ReadRegister(Reg.asMCReg(), MI, MO.isDebug() ? DebugUse : RegularUse);
  664. }
  665. // The instruction has a register mask operand which means that it clobbers
  666. // a large set of registers. Treat clobbered registers the same way as
  667. // defined registers.
  668. if (RegMask) {
  669. // Erase any MaybeDeadCopies whose destination register is clobbered.
  670. for (SmallSetVector<MachineInstr *, 8>::iterator DI =
  671. MaybeDeadCopies.begin();
  672. DI != MaybeDeadCopies.end();) {
  673. MachineInstr *MaybeDead = *DI;
  674. std::optional<DestSourcePair> CopyOperands =
  675. isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
  676. MCRegister Reg = CopyOperands->Destination->getReg().asMCReg();
  677. assert(!MRI->isReserved(Reg));
  678. if (!RegMask->clobbersPhysReg(Reg)) {
  679. ++DI;
  680. continue;
  681. }
  682. LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
  683. MaybeDead->dump());
  684. // Make sure we invalidate any entries in the copy maps before erasing
  685. // the instruction.
  686. Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
  687. // erase() will return the next valid iterator pointing to the next
  688. // element after the erased one.
  689. DI = MaybeDeadCopies.erase(DI);
  690. MaybeDead->eraseFromParent();
  691. Changed = true;
  692. ++NumDeletes;
  693. }
  694. }
  695. // Any previous copy definition or reading the Defs is no longer available.
  696. for (MCRegister Reg : Defs)
  697. Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
  698. }
  699. // If MBB doesn't have successors, delete the copies whose defs are not used.
  700. // If MBB does have successors, then conservative assume the defs are live-out
  701. // since we don't want to trust live-in lists.
  702. if (MBB.succ_empty()) {
  703. for (MachineInstr *MaybeDead : MaybeDeadCopies) {
  704. LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
  705. MaybeDead->dump());
  706. std::optional<DestSourcePair> CopyOperands =
  707. isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
  708. assert(CopyOperands);
  709. Register SrcReg = CopyOperands->Source->getReg();
  710. Register DestReg = CopyOperands->Destination->getReg();
  711. assert(!MRI->isReserved(DestReg));
  712. // Update matching debug values, if any.
  713. SmallVector<MachineInstr *> MaybeDeadDbgUsers(
  714. CopyDbgUsers[MaybeDead].begin(), CopyDbgUsers[MaybeDead].end());
  715. MRI->updateDbgUsersToReg(DestReg.asMCReg(), SrcReg.asMCReg(),
  716. MaybeDeadDbgUsers);
  717. MaybeDead->eraseFromParent();
  718. Changed = true;
  719. ++NumDeletes;
  720. }
  721. }
  722. MaybeDeadCopies.clear();
  723. CopyDbgUsers.clear();
  724. Tracker.clear();
  725. }
  726. static bool isBackwardPropagatableCopy(MachineInstr &MI,
  727. const MachineRegisterInfo &MRI,
  728. const TargetInstrInfo &TII,
  729. bool UseCopyInstr) {
  730. std::optional<DestSourcePair> CopyOperands =
  731. isCopyInstr(MI, TII, UseCopyInstr);
  732. assert(CopyOperands && "MI is expected to be a COPY");
  733. Register Def = CopyOperands->Destination->getReg();
  734. Register Src = CopyOperands->Source->getReg();
  735. if (!Def || !Src)
  736. return false;
  737. if (MRI.isReserved(Def) || MRI.isReserved(Src))
  738. return false;
  739. return CopyOperands->Source->isRenamable() && CopyOperands->Source->isKill();
  740. }
  741. void MachineCopyPropagation::propagateDefs(MachineInstr &MI) {
  742. if (!Tracker.hasAnyCopies())
  743. return;
  744. for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx != OpEnd;
  745. ++OpIdx) {
  746. MachineOperand &MODef = MI.getOperand(OpIdx);
  747. if (!MODef.isReg() || MODef.isUse())
  748. continue;
  749. // Ignore non-trivial cases.
  750. if (MODef.isTied() || MODef.isUndef() || MODef.isImplicit())
  751. continue;
  752. if (!MODef.getReg())
  753. continue;
  754. // We only handle if the register comes from a vreg.
  755. if (!MODef.isRenamable())
  756. continue;
  757. MachineInstr *Copy = Tracker.findAvailBackwardCopy(
  758. MI, MODef.getReg().asMCReg(), *TRI, *TII, UseCopyInstr);
  759. if (!Copy)
  760. continue;
  761. std::optional<DestSourcePair> CopyOperands =
  762. isCopyInstr(*Copy, *TII, UseCopyInstr);
  763. Register Def = CopyOperands->Destination->getReg();
  764. Register Src = CopyOperands->Source->getReg();
  765. if (MODef.getReg() != Src)
  766. continue;
  767. if (!isBackwardPropagatableRegClassCopy(*Copy, MI, OpIdx))
  768. continue;
  769. if (hasImplicitOverlap(MI, MODef))
  770. continue;
  771. if (hasOverlappingMultipleDef(MI, MODef, Def))
  772. continue;
  773. LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MODef.getReg(), TRI)
  774. << "\n with " << printReg(Def, TRI) << "\n in "
  775. << MI << " from " << *Copy);
  776. MODef.setReg(Def);
  777. MODef.setIsRenamable(CopyOperands->Destination->isRenamable());
  778. LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
  779. MaybeDeadCopies.insert(Copy);
  780. Changed = true;
  781. ++NumCopyBackwardPropagated;
  782. }
  783. }
  784. void MachineCopyPropagation::BackwardCopyPropagateBlock(
  785. MachineBasicBlock &MBB) {
  786. LLVM_DEBUG(dbgs() << "MCP: BackwardCopyPropagateBlock " << MBB.getName()
  787. << "\n");
  788. for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(MBB))) {
  789. // Ignore non-trivial COPYs.
  790. std::optional<DestSourcePair> CopyOperands =
  791. isCopyInstr(MI, *TII, UseCopyInstr);
  792. if (CopyOperands && MI.getNumOperands() == 2) {
  793. Register DefReg = CopyOperands->Destination->getReg();
  794. Register SrcReg = CopyOperands->Source->getReg();
  795. if (!TRI->regsOverlap(DefReg, SrcReg)) {
  796. MCRegister Def = DefReg.asMCReg();
  797. MCRegister Src = SrcReg.asMCReg();
  798. // Unlike forward cp, we don't invoke propagateDefs here,
  799. // just let forward cp do COPY-to-COPY propagation.
  800. if (isBackwardPropagatableCopy(MI, *MRI, *TII, UseCopyInstr)) {
  801. Tracker.invalidateRegister(Src, *TRI, *TII, UseCopyInstr);
  802. Tracker.invalidateRegister(Def, *TRI, *TII, UseCopyInstr);
  803. Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
  804. continue;
  805. }
  806. }
  807. }
  808. // Invalidate any earlyclobber regs first.
  809. for (const MachineOperand &MO : MI.operands())
  810. if (MO.isReg() && MO.isEarlyClobber()) {
  811. MCRegister Reg = MO.getReg().asMCReg();
  812. if (!Reg)
  813. continue;
  814. Tracker.invalidateRegister(Reg, *TRI, *TII, UseCopyInstr);
  815. }
  816. propagateDefs(MI);
  817. for (const MachineOperand &MO : MI.operands()) {
  818. if (!MO.isReg())
  819. continue;
  820. if (!MO.getReg())
  821. continue;
  822. if (MO.isDef())
  823. Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
  824. UseCopyInstr);
  825. if (MO.readsReg()) {
  826. if (MO.isDebug()) {
  827. // Check if the register in the debug instruction is utilized
  828. // in a copy instruction, so we can update the debug info if the
  829. // register is changed.
  830. for (MCRegUnitIterator RUI(MO.getReg().asMCReg(), TRI); RUI.isValid();
  831. ++RUI) {
  832. if (auto *Copy = Tracker.findCopyDefViaUnit(*RUI, *TRI)) {
  833. CopyDbgUsers[Copy].insert(&MI);
  834. }
  835. }
  836. } else {
  837. Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
  838. UseCopyInstr);
  839. }
  840. }
  841. }
  842. }
  843. for (auto *Copy : MaybeDeadCopies) {
  844. std::optional<DestSourcePair> CopyOperands =
  845. isCopyInstr(*Copy, *TII, UseCopyInstr);
  846. Register Src = CopyOperands->Source->getReg();
  847. Register Def = CopyOperands->Destination->getReg();
  848. SmallVector<MachineInstr *> MaybeDeadDbgUsers(CopyDbgUsers[Copy].begin(),
  849. CopyDbgUsers[Copy].end());
  850. MRI->updateDbgUsersToReg(Src.asMCReg(), Def.asMCReg(), MaybeDeadDbgUsers);
  851. Copy->eraseFromParent();
  852. ++NumDeletes;
  853. }
  854. MaybeDeadCopies.clear();
  855. CopyDbgUsers.clear();
  856. Tracker.clear();
  857. }
  858. bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
  859. if (skipFunction(MF.getFunction()))
  860. return false;
  861. Changed = false;
  862. TRI = MF.getSubtarget().getRegisterInfo();
  863. TII = MF.getSubtarget().getInstrInfo();
  864. MRI = &MF.getRegInfo();
  865. for (MachineBasicBlock &MBB : MF) {
  866. BackwardCopyPropagateBlock(MBB);
  867. ForwardCopyPropagateBlock(MBB);
  868. }
  869. return Changed;
  870. }
  871. MachineFunctionPass *
  872. llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) {
  873. return new MachineCopyPropagation(UseCopyInstr);
  874. }