MachineCSE.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. //===- MachineCSE.cpp - Machine Common Subexpression Elimination 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 pass performs global common subexpression elimination on machine
  10. // instructions using a scoped hash table based value numbering scheme. It
  11. // must be run while the machine function is still in SSA form.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/ScopedHashTable.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Analysis/CFG.h"
  22. #include "llvm/CodeGen/MachineBasicBlock.h"
  23. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  24. #include "llvm/CodeGen/MachineDominators.h"
  25. #include "llvm/CodeGen/MachineFunction.h"
  26. #include "llvm/CodeGen/MachineFunctionPass.h"
  27. #include "llvm/CodeGen/MachineInstr.h"
  28. #include "llvm/CodeGen/MachineOperand.h"
  29. #include "llvm/CodeGen/MachineRegisterInfo.h"
  30. #include "llvm/CodeGen/Passes.h"
  31. #include "llvm/CodeGen/TargetInstrInfo.h"
  32. #include "llvm/CodeGen/TargetOpcodes.h"
  33. #include "llvm/CodeGen/TargetRegisterInfo.h"
  34. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  35. #include "llvm/InitializePasses.h"
  36. #include "llvm/MC/MCInstrDesc.h"
  37. #include "llvm/MC/MCRegister.h"
  38. #include "llvm/MC/MCRegisterInfo.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/Allocator.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Support/RecyclingAllocator.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include <cassert>
  45. #include <iterator>
  46. #include <utility>
  47. #include <vector>
  48. using namespace llvm;
  49. #define DEBUG_TYPE "machine-cse"
  50. STATISTIC(NumCoalesces, "Number of copies coalesced");
  51. STATISTIC(NumCSEs, "Number of common subexpression eliminated");
  52. STATISTIC(NumPREs, "Number of partial redundant expression"
  53. " transformed to fully redundant");
  54. STATISTIC(NumPhysCSEs,
  55. "Number of physreg referencing common subexpr eliminated");
  56. STATISTIC(NumCrossBBCSEs,
  57. "Number of cross-MBB physreg referencing CS eliminated");
  58. STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
  59. namespace {
  60. class MachineCSE : public MachineFunctionPass {
  61. const TargetInstrInfo *TII;
  62. const TargetRegisterInfo *TRI;
  63. AliasAnalysis *AA;
  64. MachineDominatorTree *DT;
  65. MachineRegisterInfo *MRI;
  66. MachineBlockFrequencyInfo *MBFI;
  67. public:
  68. static char ID; // Pass identification
  69. MachineCSE() : MachineFunctionPass(ID) {
  70. initializeMachineCSEPass(*PassRegistry::getPassRegistry());
  71. }
  72. bool runOnMachineFunction(MachineFunction &MF) override;
  73. void getAnalysisUsage(AnalysisUsage &AU) const override {
  74. AU.setPreservesCFG();
  75. MachineFunctionPass::getAnalysisUsage(AU);
  76. AU.addRequired<AAResultsWrapperPass>();
  77. AU.addPreservedID(MachineLoopInfoID);
  78. AU.addRequired<MachineDominatorTree>();
  79. AU.addPreserved<MachineDominatorTree>();
  80. AU.addRequired<MachineBlockFrequencyInfo>();
  81. AU.addPreserved<MachineBlockFrequencyInfo>();
  82. }
  83. void releaseMemory() override {
  84. ScopeMap.clear();
  85. PREMap.clear();
  86. Exps.clear();
  87. }
  88. private:
  89. using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
  90. ScopedHashTableVal<MachineInstr *, unsigned>>;
  91. using ScopedHTType =
  92. ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait,
  93. AllocatorTy>;
  94. using ScopeType = ScopedHTType::ScopeTy;
  95. using PhysDefVector = SmallVector<std::pair<unsigned, unsigned>, 2>;
  96. unsigned LookAheadLimit = 0;
  97. DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap;
  98. DenseMap<MachineInstr *, MachineBasicBlock *, MachineInstrExpressionTrait>
  99. PREMap;
  100. ScopedHTType VNT;
  101. SmallVector<MachineInstr *, 64> Exps;
  102. unsigned CurrVN = 0;
  103. bool PerformTrivialCopyPropagation(MachineInstr *MI,
  104. MachineBasicBlock *MBB);
  105. bool isPhysDefTriviallyDead(MCRegister Reg,
  106. MachineBasicBlock::const_iterator I,
  107. MachineBasicBlock::const_iterator E) const;
  108. bool hasLivePhysRegDefUses(const MachineInstr *MI,
  109. const MachineBasicBlock *MBB,
  110. SmallSet<MCRegister, 8> &PhysRefs,
  111. PhysDefVector &PhysDefs, bool &PhysUseDef) const;
  112. bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
  113. SmallSet<MCRegister, 8> &PhysRefs,
  114. PhysDefVector &PhysDefs, bool &NonLocal) const;
  115. bool isCSECandidate(MachineInstr *MI);
  116. bool isProfitableToCSE(Register CSReg, Register Reg,
  117. MachineBasicBlock *CSBB, MachineInstr *MI);
  118. void EnterScope(MachineBasicBlock *MBB);
  119. void ExitScope(MachineBasicBlock *MBB);
  120. bool ProcessBlockCSE(MachineBasicBlock *MBB);
  121. void ExitScopeIfDone(MachineDomTreeNode *Node,
  122. DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren);
  123. bool PerformCSE(MachineDomTreeNode *Node);
  124. bool isPRECandidate(MachineInstr *MI);
  125. bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *MBB);
  126. bool PerformSimplePRE(MachineDominatorTree *DT);
  127. /// Heuristics to see if it's profitable to move common computations of MBB
  128. /// and MBB1 to CandidateBB.
  129. bool isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
  130. MachineBasicBlock *MBB,
  131. MachineBasicBlock *MBB1);
  132. };
  133. } // end anonymous namespace
  134. char MachineCSE::ID = 0;
  135. char &llvm::MachineCSEID = MachineCSE::ID;
  136. INITIALIZE_PASS_BEGIN(MachineCSE, DEBUG_TYPE,
  137. "Machine Common Subexpression Elimination", false, false)
  138. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  139. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  140. INITIALIZE_PASS_END(MachineCSE, DEBUG_TYPE,
  141. "Machine Common Subexpression Elimination", false, false)
  142. /// The source register of a COPY machine instruction can be propagated to all
  143. /// its users, and this propagation could increase the probability of finding
  144. /// common subexpressions. If the COPY has only one user, the COPY itself can
  145. /// be removed.
  146. bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI,
  147. MachineBasicBlock *MBB) {
  148. bool Changed = false;
  149. for (MachineOperand &MO : MI->operands()) {
  150. if (!MO.isReg() || !MO.isUse())
  151. continue;
  152. Register Reg = MO.getReg();
  153. if (!Register::isVirtualRegister(Reg))
  154. continue;
  155. bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
  156. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  157. if (!DefMI->isCopy())
  158. continue;
  159. Register SrcReg = DefMI->getOperand(1).getReg();
  160. if (!Register::isVirtualRegister(SrcReg))
  161. continue;
  162. if (DefMI->getOperand(0).getSubReg())
  163. continue;
  164. // FIXME: We should trivially coalesce subregister copies to expose CSE
  165. // opportunities on instructions with truncated operands (see
  166. // cse-add-with-overflow.ll). This can be done here as follows:
  167. // if (SrcSubReg)
  168. // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC,
  169. // SrcSubReg);
  170. // MO.substVirtReg(SrcReg, SrcSubReg, *TRI);
  171. //
  172. // The 2-addr pass has been updated to handle coalesced subregs. However,
  173. // some machine-specific code still can't handle it.
  174. // To handle it properly we also need a way find a constrained subregister
  175. // class given a super-reg class and subreg index.
  176. if (DefMI->getOperand(1).getSubReg())
  177. continue;
  178. if (!MRI->constrainRegAttrs(SrcReg, Reg))
  179. continue;
  180. LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
  181. LLVM_DEBUG(dbgs() << "*** to: " << *MI);
  182. // Propagate SrcReg of copies to MI.
  183. MO.setReg(SrcReg);
  184. MRI->clearKillFlags(SrcReg);
  185. // Coalesce single use copies.
  186. if (OnlyOneUse) {
  187. // If (and only if) we've eliminated all uses of the copy, also
  188. // copy-propagate to any debug-users of MI, or they'll be left using
  189. // an undefined value.
  190. DefMI->changeDebugValuesDefReg(SrcReg);
  191. DefMI->eraseFromParent();
  192. ++NumCoalesces;
  193. }
  194. Changed = true;
  195. }
  196. return Changed;
  197. }
  198. bool MachineCSE::isPhysDefTriviallyDead(
  199. MCRegister Reg, MachineBasicBlock::const_iterator I,
  200. MachineBasicBlock::const_iterator E) const {
  201. unsigned LookAheadLeft = LookAheadLimit;
  202. while (LookAheadLeft) {
  203. // Skip over dbg_value's.
  204. I = skipDebugInstructionsForward(I, E);
  205. if (I == E)
  206. // Reached end of block, we don't know if register is dead or not.
  207. return false;
  208. bool SeenDef = false;
  209. for (const MachineOperand &MO : I->operands()) {
  210. if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
  211. SeenDef = true;
  212. if (!MO.isReg() || !MO.getReg())
  213. continue;
  214. if (!TRI->regsOverlap(MO.getReg(), Reg))
  215. continue;
  216. if (MO.isUse())
  217. // Found a use!
  218. return false;
  219. SeenDef = true;
  220. }
  221. if (SeenDef)
  222. // See a def of Reg (or an alias) before encountering any use, it's
  223. // trivially dead.
  224. return true;
  225. --LookAheadLeft;
  226. ++I;
  227. }
  228. return false;
  229. }
  230. static bool isCallerPreservedOrConstPhysReg(MCRegister Reg,
  231. const MachineFunction &MF,
  232. const TargetRegisterInfo &TRI) {
  233. // MachineRegisterInfo::isConstantPhysReg directly called by
  234. // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the
  235. // reserved registers to be frozen. That doesn't cause a problem post-ISel as
  236. // most (if not all) targets freeze reserved registers right after ISel.
  237. //
  238. // It does cause issues mid-GlobalISel, however, hence the additional
  239. // reservedRegsFrozen check.
  240. const MachineRegisterInfo &MRI = MF.getRegInfo();
  241. return TRI.isCallerPreservedPhysReg(Reg, MF) ||
  242. (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg));
  243. }
  244. /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
  245. /// physical registers (except for dead defs of physical registers). It also
  246. /// returns the physical register def by reference if it's the only one and the
  247. /// instruction does not uses a physical register.
  248. bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
  249. const MachineBasicBlock *MBB,
  250. SmallSet<MCRegister, 8> &PhysRefs,
  251. PhysDefVector &PhysDefs,
  252. bool &PhysUseDef) const {
  253. // First, add all uses to PhysRefs.
  254. for (const MachineOperand &MO : MI->operands()) {
  255. if (!MO.isReg() || MO.isDef())
  256. continue;
  257. Register Reg = MO.getReg();
  258. if (!Reg)
  259. continue;
  260. if (Register::isVirtualRegister(Reg))
  261. continue;
  262. // Reading either caller preserved or constant physregs is ok.
  263. if (!isCallerPreservedOrConstPhysReg(Reg.asMCReg(), *MI->getMF(), *TRI))
  264. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  265. PhysRefs.insert(*AI);
  266. }
  267. // Next, collect all defs into PhysDefs. If any is already in PhysRefs
  268. // (which currently contains only uses), set the PhysUseDef flag.
  269. PhysUseDef = false;
  270. MachineBasicBlock::const_iterator I = MI; I = std::next(I);
  271. for (const auto &MOP : llvm::enumerate(MI->operands())) {
  272. const MachineOperand &MO = MOP.value();
  273. if (!MO.isReg() || !MO.isDef())
  274. continue;
  275. Register Reg = MO.getReg();
  276. if (!Reg)
  277. continue;
  278. if (Register::isVirtualRegister(Reg))
  279. continue;
  280. // Check against PhysRefs even if the def is "dead".
  281. if (PhysRefs.count(Reg.asMCReg()))
  282. PhysUseDef = true;
  283. // If the def is dead, it's ok. But the def may not marked "dead". That's
  284. // common since this pass is run before livevariables. We can scan
  285. // forward a few instructions and check if it is obviously dead.
  286. if (!MO.isDead() && !isPhysDefTriviallyDead(Reg.asMCReg(), I, MBB->end()))
  287. PhysDefs.push_back(std::make_pair(MOP.index(), Reg));
  288. }
  289. // Finally, add all defs to PhysRefs as well.
  290. for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i)
  291. for (MCRegAliasIterator AI(PhysDefs[i].second, TRI, true); AI.isValid();
  292. ++AI)
  293. PhysRefs.insert(*AI);
  294. return !PhysRefs.empty();
  295. }
  296. bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
  297. SmallSet<MCRegister, 8> &PhysRefs,
  298. PhysDefVector &PhysDefs,
  299. bool &NonLocal) const {
  300. // For now conservatively returns false if the common subexpression is
  301. // not in the same basic block as the given instruction. The only exception
  302. // is if the common subexpression is in the sole predecessor block.
  303. const MachineBasicBlock *MBB = MI->getParent();
  304. const MachineBasicBlock *CSMBB = CSMI->getParent();
  305. bool CrossMBB = false;
  306. if (CSMBB != MBB) {
  307. if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
  308. return false;
  309. for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
  310. if (MRI->isAllocatable(PhysDefs[i].second) ||
  311. MRI->isReserved(PhysDefs[i].second))
  312. // Avoid extending live range of physical registers if they are
  313. //allocatable or reserved.
  314. return false;
  315. }
  316. CrossMBB = true;
  317. }
  318. MachineBasicBlock::const_iterator I = CSMI; I = std::next(I);
  319. MachineBasicBlock::const_iterator E = MI;
  320. MachineBasicBlock::const_iterator EE = CSMBB->end();
  321. unsigned LookAheadLeft = LookAheadLimit;
  322. while (LookAheadLeft) {
  323. // Skip over dbg_value's.
  324. while (I != E && I != EE && I->isDebugInstr())
  325. ++I;
  326. if (I == EE) {
  327. assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
  328. (void)CrossMBB;
  329. CrossMBB = false;
  330. NonLocal = true;
  331. I = MBB->begin();
  332. EE = MBB->end();
  333. continue;
  334. }
  335. if (I == E)
  336. return true;
  337. for (const MachineOperand &MO : I->operands()) {
  338. // RegMasks go on instructions like calls that clobber lots of physregs.
  339. // Don't attempt to CSE across such an instruction.
  340. if (MO.isRegMask())
  341. return false;
  342. if (!MO.isReg() || !MO.isDef())
  343. continue;
  344. Register MOReg = MO.getReg();
  345. if (Register::isVirtualRegister(MOReg))
  346. continue;
  347. if (PhysRefs.count(MOReg.asMCReg()))
  348. return false;
  349. }
  350. --LookAheadLeft;
  351. ++I;
  352. }
  353. return false;
  354. }
  355. bool MachineCSE::isCSECandidate(MachineInstr *MI) {
  356. if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() ||
  357. MI->isInlineAsm() || MI->isDebugInstr())
  358. return false;
  359. // Ignore copies.
  360. if (MI->isCopyLike())
  361. return false;
  362. // Ignore stuff that we obviously can't move.
  363. if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
  364. MI->mayRaiseFPException() || MI->hasUnmodeledSideEffects())
  365. return false;
  366. if (MI->mayLoad()) {
  367. // Okay, this instruction does a load. As a refinement, we allow the target
  368. // to decide whether the loaded value is actually a constant. If so, we can
  369. // actually use it as a load.
  370. if (!MI->isDereferenceableInvariantLoad(AA))
  371. // FIXME: we should be able to hoist loads with no other side effects if
  372. // there are no other instructions which can change memory in this loop.
  373. // This is a trivial form of alias analysis.
  374. return false;
  375. }
  376. // Ignore stack guard loads, otherwise the register that holds CSEed value may
  377. // be spilled and get loaded back with corrupted data.
  378. if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
  379. return false;
  380. return true;
  381. }
  382. /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
  383. /// common expression that defines Reg. CSBB is basic block where CSReg is
  384. /// defined.
  385. bool MachineCSE::isProfitableToCSE(Register CSReg, Register Reg,
  386. MachineBasicBlock *CSBB, MachineInstr *MI) {
  387. // FIXME: Heuristics that works around the lack the live range splitting.
  388. // If CSReg is used at all uses of Reg, CSE should not increase register
  389. // pressure of CSReg.
  390. bool MayIncreasePressure = true;
  391. if (Register::isVirtualRegister(CSReg) && Register::isVirtualRegister(Reg)) {
  392. MayIncreasePressure = false;
  393. SmallPtrSet<MachineInstr*, 8> CSUses;
  394. for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
  395. CSUses.insert(&MI);
  396. }
  397. for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
  398. if (!CSUses.count(&MI)) {
  399. MayIncreasePressure = true;
  400. break;
  401. }
  402. }
  403. }
  404. if (!MayIncreasePressure) return true;
  405. // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
  406. // an immediate predecessor. We don't want to increase register pressure and
  407. // end up causing other computation to be spilled.
  408. if (TII->isAsCheapAsAMove(*MI)) {
  409. MachineBasicBlock *BB = MI->getParent();
  410. if (CSBB != BB && !CSBB->isSuccessor(BB))
  411. return false;
  412. }
  413. // Heuristics #2: If the expression doesn't not use a vr and the only use
  414. // of the redundant computation are copies, do not cse.
  415. bool HasVRegUse = false;
  416. for (const MachineOperand &MO : MI->operands()) {
  417. if (MO.isReg() && MO.isUse() && Register::isVirtualRegister(MO.getReg())) {
  418. HasVRegUse = true;
  419. break;
  420. }
  421. }
  422. if (!HasVRegUse) {
  423. bool HasNonCopyUse = false;
  424. for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
  425. // Ignore copies.
  426. if (!MI.isCopyLike()) {
  427. HasNonCopyUse = true;
  428. break;
  429. }
  430. }
  431. if (!HasNonCopyUse)
  432. return false;
  433. }
  434. // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
  435. // it unless the defined value is already used in the BB of the new use.
  436. bool HasPHI = false;
  437. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) {
  438. HasPHI |= UseMI.isPHI();
  439. if (UseMI.getParent() == MI->getParent())
  440. return true;
  441. }
  442. return !HasPHI;
  443. }
  444. void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
  445. LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
  446. ScopeType *Scope = new ScopeType(VNT);
  447. ScopeMap[MBB] = Scope;
  448. }
  449. void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
  450. LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
  451. DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
  452. assert(SI != ScopeMap.end());
  453. delete SI->second;
  454. ScopeMap.erase(SI);
  455. }
  456. bool MachineCSE::ProcessBlockCSE(MachineBasicBlock *MBB) {
  457. bool Changed = false;
  458. SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
  459. SmallVector<unsigned, 2> ImplicitDefsToUpdate;
  460. SmallVector<unsigned, 2> ImplicitDefs;
  461. for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
  462. if (!isCSECandidate(&MI))
  463. continue;
  464. bool FoundCSE = VNT.count(&MI);
  465. if (!FoundCSE) {
  466. // Using trivial copy propagation to find more CSE opportunities.
  467. if (PerformTrivialCopyPropagation(&MI, MBB)) {
  468. Changed = true;
  469. // After coalescing MI itself may become a copy.
  470. if (MI.isCopyLike())
  471. continue;
  472. // Try again to see if CSE is possible.
  473. FoundCSE = VNT.count(&MI);
  474. }
  475. }
  476. // Commute commutable instructions.
  477. bool Commuted = false;
  478. if (!FoundCSE && MI.isCommutable()) {
  479. if (MachineInstr *NewMI = TII->commuteInstruction(MI)) {
  480. Commuted = true;
  481. FoundCSE = VNT.count(NewMI);
  482. if (NewMI != &MI) {
  483. // New instruction. It doesn't need to be kept.
  484. NewMI->eraseFromParent();
  485. Changed = true;
  486. } else if (!FoundCSE)
  487. // MI was changed but it didn't help, commute it back!
  488. (void)TII->commuteInstruction(MI);
  489. }
  490. }
  491. // If the instruction defines physical registers and the values *may* be
  492. // used, then it's not safe to replace it with a common subexpression.
  493. // It's also not safe if the instruction uses physical registers.
  494. bool CrossMBBPhysDef = false;
  495. SmallSet<MCRegister, 8> PhysRefs;
  496. PhysDefVector PhysDefs;
  497. bool PhysUseDef = false;
  498. if (FoundCSE &&
  499. hasLivePhysRegDefUses(&MI, MBB, PhysRefs, PhysDefs, PhysUseDef)) {
  500. FoundCSE = false;
  501. // ... Unless the CS is local or is in the sole predecessor block
  502. // and it also defines the physical register which is not clobbered
  503. // in between and the physical register uses were not clobbered.
  504. // This can never be the case if the instruction both uses and
  505. // defines the same physical register, which was detected above.
  506. if (!PhysUseDef) {
  507. unsigned CSVN = VNT.lookup(&MI);
  508. MachineInstr *CSMI = Exps[CSVN];
  509. if (PhysRegDefsReach(CSMI, &MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
  510. FoundCSE = true;
  511. }
  512. }
  513. if (!FoundCSE) {
  514. VNT.insert(&MI, CurrVN++);
  515. Exps.push_back(&MI);
  516. continue;
  517. }
  518. // Found a common subexpression, eliminate it.
  519. unsigned CSVN = VNT.lookup(&MI);
  520. MachineInstr *CSMI = Exps[CSVN];
  521. LLVM_DEBUG(dbgs() << "Examining: " << MI);
  522. LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
  523. // Prevent CSE-ing non-local convergent instructions.
  524. // LLVM's current definition of `isConvergent` does not necessarily prove
  525. // that non-local CSE is illegal. The following check extends the definition
  526. // of `isConvergent` to assume a convergent instruction is dependent not
  527. // only on additional conditions, but also on fewer conditions. LLVM does
  528. // not have a MachineInstr attribute which expresses this extended
  529. // definition, so it's necessary to use `isConvergent` to prevent illegally
  530. // CSE-ing the subset of `isConvergent` instructions which do fall into this
  531. // extended definition.
  532. if (MI.isConvergent() && MI.getParent() != CSMI->getParent()) {
  533. LLVM_DEBUG(dbgs() << "*** Convergent MI and subexpression exist in "
  534. "different BBs, avoid CSE!\n");
  535. VNT.insert(&MI, CurrVN++);
  536. Exps.push_back(&MI);
  537. continue;
  538. }
  539. // Check if it's profitable to perform this CSE.
  540. bool DoCSE = true;
  541. unsigned NumDefs = MI.getNumDefs();
  542. for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
  543. MachineOperand &MO = MI.getOperand(i);
  544. if (!MO.isReg() || !MO.isDef())
  545. continue;
  546. Register OldReg = MO.getReg();
  547. Register NewReg = CSMI->getOperand(i).getReg();
  548. // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
  549. // we should make sure it is not dead at CSMI.
  550. if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
  551. ImplicitDefsToUpdate.push_back(i);
  552. // Keep track of implicit defs of CSMI and MI, to clear possibly
  553. // made-redundant kill flags.
  554. if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
  555. ImplicitDefs.push_back(OldReg);
  556. if (OldReg == NewReg) {
  557. --NumDefs;
  558. continue;
  559. }
  560. assert(Register::isVirtualRegister(OldReg) &&
  561. Register::isVirtualRegister(NewReg) &&
  562. "Do not CSE physical register defs!");
  563. if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), &MI)) {
  564. LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
  565. DoCSE = false;
  566. break;
  567. }
  568. // Don't perform CSE if the result of the new instruction cannot exist
  569. // within the constraints (register class, bank, or low-level type) of
  570. // the old instruction.
  571. if (!MRI->constrainRegAttrs(NewReg, OldReg)) {
  572. LLVM_DEBUG(
  573. dbgs() << "*** Not the same register constraints, avoid CSE!\n");
  574. DoCSE = false;
  575. break;
  576. }
  577. CSEPairs.push_back(std::make_pair(OldReg, NewReg));
  578. --NumDefs;
  579. }
  580. // Actually perform the elimination.
  581. if (DoCSE) {
  582. for (const std::pair<unsigned, unsigned> &CSEPair : CSEPairs) {
  583. unsigned OldReg = CSEPair.first;
  584. unsigned NewReg = CSEPair.second;
  585. // OldReg may have been unused but is used now, clear the Dead flag
  586. MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
  587. assert(Def != nullptr && "CSEd register has no unique definition?");
  588. Def->clearRegisterDeads(NewReg);
  589. // Replace with NewReg and clear kill flags which may be wrong now.
  590. MRI->replaceRegWith(OldReg, NewReg);
  591. MRI->clearKillFlags(NewReg);
  592. }
  593. // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
  594. // we should make sure it is not dead at CSMI.
  595. for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
  596. CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
  597. for (const auto &PhysDef : PhysDefs)
  598. if (!MI.getOperand(PhysDef.first).isDead())
  599. CSMI->getOperand(PhysDef.first).setIsDead(false);
  600. // Go through implicit defs of CSMI and MI, and clear the kill flags on
  601. // their uses in all the instructions between CSMI and MI.
  602. // We might have made some of the kill flags redundant, consider:
  603. // subs ... implicit-def %nzcv <- CSMI
  604. // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore
  605. // subs ... implicit-def %nzcv <- MI, to be eliminated
  606. // csinc ... implicit killed %nzcv
  607. // Since we eliminated MI, and reused a register imp-def'd by CSMI
  608. // (here %nzcv), that register, if it was killed before MI, should have
  609. // that kill flag removed, because it's lifetime was extended.
  610. if (CSMI->getParent() == MI.getParent()) {
  611. for (MachineBasicBlock::iterator II = CSMI, IE = &MI; II != IE; ++II)
  612. for (auto ImplicitDef : ImplicitDefs)
  613. if (MachineOperand *MO = II->findRegisterUseOperand(
  614. ImplicitDef, /*isKill=*/true, TRI))
  615. MO->setIsKill(false);
  616. } else {
  617. // If the instructions aren't in the same BB, bail out and clear the
  618. // kill flag on all uses of the imp-def'd register.
  619. for (auto ImplicitDef : ImplicitDefs)
  620. MRI->clearKillFlags(ImplicitDef);
  621. }
  622. if (CrossMBBPhysDef) {
  623. // Add physical register defs now coming in from a predecessor to MBB
  624. // livein list.
  625. while (!PhysDefs.empty()) {
  626. auto LiveIn = PhysDefs.pop_back_val();
  627. if (!MBB->isLiveIn(LiveIn.second))
  628. MBB->addLiveIn(LiveIn.second);
  629. }
  630. ++NumCrossBBCSEs;
  631. }
  632. MI.eraseFromParent();
  633. ++NumCSEs;
  634. if (!PhysRefs.empty())
  635. ++NumPhysCSEs;
  636. if (Commuted)
  637. ++NumCommutes;
  638. Changed = true;
  639. } else {
  640. VNT.insert(&MI, CurrVN++);
  641. Exps.push_back(&MI);
  642. }
  643. CSEPairs.clear();
  644. ImplicitDefsToUpdate.clear();
  645. ImplicitDefs.clear();
  646. }
  647. return Changed;
  648. }
  649. /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
  650. /// dominator tree node if its a leaf or all of its children are done. Walk
  651. /// up the dominator tree to destroy ancestors which are now done.
  652. void
  653. MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
  654. DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) {
  655. if (OpenChildren[Node])
  656. return;
  657. // Pop scope.
  658. ExitScope(Node->getBlock());
  659. // Now traverse upwards to pop ancestors whose offsprings are all done.
  660. while (MachineDomTreeNode *Parent = Node->getIDom()) {
  661. unsigned Left = --OpenChildren[Parent];
  662. if (Left != 0)
  663. break;
  664. ExitScope(Parent->getBlock());
  665. Node = Parent;
  666. }
  667. }
  668. bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
  669. SmallVector<MachineDomTreeNode*, 32> Scopes;
  670. SmallVector<MachineDomTreeNode*, 8> WorkList;
  671. DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
  672. CurrVN = 0;
  673. // Perform a DFS walk to determine the order of visit.
  674. WorkList.push_back(Node);
  675. do {
  676. Node = WorkList.pop_back_val();
  677. Scopes.push_back(Node);
  678. OpenChildren[Node] = Node->getNumChildren();
  679. append_range(WorkList, Node->children());
  680. } while (!WorkList.empty());
  681. // Now perform CSE.
  682. bool Changed = false;
  683. for (MachineDomTreeNode *Node : Scopes) {
  684. MachineBasicBlock *MBB = Node->getBlock();
  685. EnterScope(MBB);
  686. Changed |= ProcessBlockCSE(MBB);
  687. // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
  688. ExitScopeIfDone(Node, OpenChildren);
  689. }
  690. return Changed;
  691. }
  692. // We use stronger checks for PRE candidate rather than for CSE ones to embrace
  693. // checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps
  694. // to exclude instrs created by PRE that won't be CSEed later.
  695. bool MachineCSE::isPRECandidate(MachineInstr *MI) {
  696. if (!isCSECandidate(MI) ||
  697. MI->isNotDuplicable() ||
  698. MI->mayLoad() ||
  699. MI->isAsCheapAsAMove() ||
  700. MI->getNumDefs() != 1 ||
  701. MI->getNumExplicitDefs() != 1)
  702. return false;
  703. for (const auto &def : MI->defs())
  704. if (!Register::isVirtualRegister(def.getReg()))
  705. return false;
  706. for (const auto &use : MI->uses())
  707. if (use.isReg() && !Register::isVirtualRegister(use.getReg()))
  708. return false;
  709. return true;
  710. }
  711. bool MachineCSE::ProcessBlockPRE(MachineDominatorTree *DT,
  712. MachineBasicBlock *MBB) {
  713. bool Changed = false;
  714. for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
  715. if (!isPRECandidate(&MI))
  716. continue;
  717. if (!PREMap.count(&MI)) {
  718. PREMap[&MI] = MBB;
  719. continue;
  720. }
  721. auto MBB1 = PREMap[&MI];
  722. assert(
  723. !DT->properlyDominates(MBB, MBB1) &&
  724. "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
  725. auto CMBB = DT->findNearestCommonDominator(MBB, MBB1);
  726. if (!CMBB->isLegalToHoistInto())
  727. continue;
  728. if (!isProfitableToHoistInto(CMBB, MBB, MBB1))
  729. continue;
  730. // Two instrs are partial redundant if their basic blocks are reachable
  731. // from one to another but one doesn't dominate another.
  732. if (CMBB != MBB1) {
  733. auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock();
  734. if (BB != nullptr && BB1 != nullptr &&
  735. (isPotentiallyReachable(BB1, BB) ||
  736. isPotentiallyReachable(BB, BB1))) {
  737. // The following check extends the definition of `isConvergent` to
  738. // assume a convergent instruction is dependent not only on additional
  739. // conditions, but also on fewer conditions. LLVM does not have a
  740. // MachineInstr attribute which expresses this extended definition, so
  741. // it's necessary to use `isConvergent` to prevent illegally PRE-ing the
  742. // subset of `isConvergent` instructions which do fall into this
  743. // extended definition.
  744. if (MI.isConvergent() && CMBB != MBB)
  745. continue;
  746. assert(MI.getOperand(0).isDef() &&
  747. "First operand of instr with one explicit def must be this def");
  748. Register VReg = MI.getOperand(0).getReg();
  749. Register NewReg = MRI->cloneVirtualRegister(VReg);
  750. if (!isProfitableToCSE(NewReg, VReg, CMBB, &MI))
  751. continue;
  752. MachineInstr &NewMI =
  753. TII->duplicate(*CMBB, CMBB->getFirstTerminator(), MI);
  754. // When hoisting, make sure we don't carry the debug location of
  755. // the original instruction, as that's not correct and can cause
  756. // unexpected jumps when debugging optimized code.
  757. auto EmptyDL = DebugLoc();
  758. NewMI.setDebugLoc(EmptyDL);
  759. NewMI.getOperand(0).setReg(NewReg);
  760. PREMap[&MI] = CMBB;
  761. ++NumPREs;
  762. Changed = true;
  763. }
  764. }
  765. }
  766. return Changed;
  767. }
  768. // This simple PRE (partial redundancy elimination) pass doesn't actually
  769. // eliminate partial redundancy but transforms it to full redundancy,
  770. // anticipating that the next CSE step will eliminate this created redundancy.
  771. // If CSE doesn't eliminate this, than created instruction will remain dead
  772. // and eliminated later by Remove Dead Machine Instructions pass.
  773. bool MachineCSE::PerformSimplePRE(MachineDominatorTree *DT) {
  774. SmallVector<MachineDomTreeNode *, 32> BBs;
  775. PREMap.clear();
  776. bool Changed = false;
  777. BBs.push_back(DT->getRootNode());
  778. do {
  779. auto Node = BBs.pop_back_val();
  780. append_range(BBs, Node->children());
  781. MachineBasicBlock *MBB = Node->getBlock();
  782. Changed |= ProcessBlockPRE(DT, MBB);
  783. } while (!BBs.empty());
  784. return Changed;
  785. }
  786. bool MachineCSE::isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
  787. MachineBasicBlock *MBB,
  788. MachineBasicBlock *MBB1) {
  789. if (CandidateBB->getParent()->getFunction().hasMinSize())
  790. return true;
  791. assert(DT->dominates(CandidateBB, MBB) && "CandidateBB should dominate MBB");
  792. assert(DT->dominates(CandidateBB, MBB1) &&
  793. "CandidateBB should dominate MBB1");
  794. return MBFI->getBlockFreq(CandidateBB) <=
  795. MBFI->getBlockFreq(MBB) + MBFI->getBlockFreq(MBB1);
  796. }
  797. bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
  798. if (skipFunction(MF.getFunction()))
  799. return false;
  800. TII = MF.getSubtarget().getInstrInfo();
  801. TRI = MF.getSubtarget().getRegisterInfo();
  802. MRI = &MF.getRegInfo();
  803. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  804. DT = &getAnalysis<MachineDominatorTree>();
  805. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  806. LookAheadLimit = TII->getMachineCSELookAheadLimit();
  807. bool ChangedPRE, ChangedCSE;
  808. ChangedPRE = PerformSimplePRE(DT);
  809. ChangedCSE = PerformCSE(DT->getRootNode());
  810. return ChangedPRE || ChangedCSE;
  811. }