MachineCSE.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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 (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
  462. MachineInstr *MI = &*I;
  463. ++I;
  464. if (!isCSECandidate(MI))
  465. continue;
  466. bool FoundCSE = VNT.count(MI);
  467. if (!FoundCSE) {
  468. // Using trivial copy propagation to find more CSE opportunities.
  469. if (PerformTrivialCopyPropagation(MI, MBB)) {
  470. Changed = true;
  471. // After coalescing MI itself may become a copy.
  472. if (MI->isCopyLike())
  473. continue;
  474. // Try again to see if CSE is possible.
  475. FoundCSE = VNT.count(MI);
  476. }
  477. }
  478. // Commute commutable instructions.
  479. bool Commuted = false;
  480. if (!FoundCSE && MI->isCommutable()) {
  481. if (MachineInstr *NewMI = TII->commuteInstruction(*MI)) {
  482. Commuted = true;
  483. FoundCSE = VNT.count(NewMI);
  484. if (NewMI != MI) {
  485. // New instruction. It doesn't need to be kept.
  486. NewMI->eraseFromParent();
  487. Changed = true;
  488. } else if (!FoundCSE)
  489. // MI was changed but it didn't help, commute it back!
  490. (void)TII->commuteInstruction(*MI);
  491. }
  492. }
  493. // If the instruction defines physical registers and the values *may* be
  494. // used, then it's not safe to replace it with a common subexpression.
  495. // It's also not safe if the instruction uses physical registers.
  496. bool CrossMBBPhysDef = false;
  497. SmallSet<MCRegister, 8> PhysRefs;
  498. PhysDefVector PhysDefs;
  499. bool PhysUseDef = false;
  500. if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs,
  501. PhysDefs, PhysUseDef)) {
  502. FoundCSE = false;
  503. // ... Unless the CS is local or is in the sole predecessor block
  504. // and it also defines the physical register which is not clobbered
  505. // in between and the physical register uses were not clobbered.
  506. // This can never be the case if the instruction both uses and
  507. // defines the same physical register, which was detected above.
  508. if (!PhysUseDef) {
  509. unsigned CSVN = VNT.lookup(MI);
  510. MachineInstr *CSMI = Exps[CSVN];
  511. if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
  512. FoundCSE = true;
  513. }
  514. }
  515. if (!FoundCSE) {
  516. VNT.insert(MI, CurrVN++);
  517. Exps.push_back(MI);
  518. continue;
  519. }
  520. // Found a common subexpression, eliminate it.
  521. unsigned CSVN = VNT.lookup(MI);
  522. MachineInstr *CSMI = Exps[CSVN];
  523. LLVM_DEBUG(dbgs() << "Examining: " << *MI);
  524. LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
  525. // Check if it's profitable to perform this CSE.
  526. bool DoCSE = true;
  527. unsigned NumDefs = MI->getNumDefs();
  528. for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
  529. MachineOperand &MO = MI->getOperand(i);
  530. if (!MO.isReg() || !MO.isDef())
  531. continue;
  532. Register OldReg = MO.getReg();
  533. Register NewReg = CSMI->getOperand(i).getReg();
  534. // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
  535. // we should make sure it is not dead at CSMI.
  536. if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
  537. ImplicitDefsToUpdate.push_back(i);
  538. // Keep track of implicit defs of CSMI and MI, to clear possibly
  539. // made-redundant kill flags.
  540. if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
  541. ImplicitDefs.push_back(OldReg);
  542. if (OldReg == NewReg) {
  543. --NumDefs;
  544. continue;
  545. }
  546. assert(Register::isVirtualRegister(OldReg) &&
  547. Register::isVirtualRegister(NewReg) &&
  548. "Do not CSE physical register defs!");
  549. if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), MI)) {
  550. LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
  551. DoCSE = false;
  552. break;
  553. }
  554. // Don't perform CSE if the result of the new instruction cannot exist
  555. // within the constraints (register class, bank, or low-level type) of
  556. // the old instruction.
  557. if (!MRI->constrainRegAttrs(NewReg, OldReg)) {
  558. LLVM_DEBUG(
  559. dbgs() << "*** Not the same register constraints, avoid CSE!\n");
  560. DoCSE = false;
  561. break;
  562. }
  563. CSEPairs.push_back(std::make_pair(OldReg, NewReg));
  564. --NumDefs;
  565. }
  566. // Actually perform the elimination.
  567. if (DoCSE) {
  568. for (const std::pair<unsigned, unsigned> &CSEPair : CSEPairs) {
  569. unsigned OldReg = CSEPair.first;
  570. unsigned NewReg = CSEPair.second;
  571. // OldReg may have been unused but is used now, clear the Dead flag
  572. MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
  573. assert(Def != nullptr && "CSEd register has no unique definition?");
  574. Def->clearRegisterDeads(NewReg);
  575. // Replace with NewReg and clear kill flags which may be wrong now.
  576. MRI->replaceRegWith(OldReg, NewReg);
  577. MRI->clearKillFlags(NewReg);
  578. }
  579. // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
  580. // we should make sure it is not dead at CSMI.
  581. for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
  582. CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
  583. for (const auto &PhysDef : PhysDefs)
  584. if (!MI->getOperand(PhysDef.first).isDead())
  585. CSMI->getOperand(PhysDef.first).setIsDead(false);
  586. // Go through implicit defs of CSMI and MI, and clear the kill flags on
  587. // their uses in all the instructions between CSMI and MI.
  588. // We might have made some of the kill flags redundant, consider:
  589. // subs ... implicit-def %nzcv <- CSMI
  590. // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore
  591. // subs ... implicit-def %nzcv <- MI, to be eliminated
  592. // csinc ... implicit killed %nzcv
  593. // Since we eliminated MI, and reused a register imp-def'd by CSMI
  594. // (here %nzcv), that register, if it was killed before MI, should have
  595. // that kill flag removed, because it's lifetime was extended.
  596. if (CSMI->getParent() == MI->getParent()) {
  597. for (MachineBasicBlock::iterator II = CSMI, IE = MI; II != IE; ++II)
  598. for (auto ImplicitDef : ImplicitDefs)
  599. if (MachineOperand *MO = II->findRegisterUseOperand(
  600. ImplicitDef, /*isKill=*/true, TRI))
  601. MO->setIsKill(false);
  602. } else {
  603. // If the instructions aren't in the same BB, bail out and clear the
  604. // kill flag on all uses of the imp-def'd register.
  605. for (auto ImplicitDef : ImplicitDefs)
  606. MRI->clearKillFlags(ImplicitDef);
  607. }
  608. if (CrossMBBPhysDef) {
  609. // Add physical register defs now coming in from a predecessor to MBB
  610. // livein list.
  611. while (!PhysDefs.empty()) {
  612. auto LiveIn = PhysDefs.pop_back_val();
  613. if (!MBB->isLiveIn(LiveIn.second))
  614. MBB->addLiveIn(LiveIn.second);
  615. }
  616. ++NumCrossBBCSEs;
  617. }
  618. MI->eraseFromParent();
  619. ++NumCSEs;
  620. if (!PhysRefs.empty())
  621. ++NumPhysCSEs;
  622. if (Commuted)
  623. ++NumCommutes;
  624. Changed = true;
  625. } else {
  626. VNT.insert(MI, CurrVN++);
  627. Exps.push_back(MI);
  628. }
  629. CSEPairs.clear();
  630. ImplicitDefsToUpdate.clear();
  631. ImplicitDefs.clear();
  632. }
  633. return Changed;
  634. }
  635. /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
  636. /// dominator tree node if its a leaf or all of its children are done. Walk
  637. /// up the dominator tree to destroy ancestors which are now done.
  638. void
  639. MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
  640. DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) {
  641. if (OpenChildren[Node])
  642. return;
  643. // Pop scope.
  644. ExitScope(Node->getBlock());
  645. // Now traverse upwards to pop ancestors whose offsprings are all done.
  646. while (MachineDomTreeNode *Parent = Node->getIDom()) {
  647. unsigned Left = --OpenChildren[Parent];
  648. if (Left != 0)
  649. break;
  650. ExitScope(Parent->getBlock());
  651. Node = Parent;
  652. }
  653. }
  654. bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
  655. SmallVector<MachineDomTreeNode*, 32> Scopes;
  656. SmallVector<MachineDomTreeNode*, 8> WorkList;
  657. DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
  658. CurrVN = 0;
  659. // Perform a DFS walk to determine the order of visit.
  660. WorkList.push_back(Node);
  661. do {
  662. Node = WorkList.pop_back_val();
  663. Scopes.push_back(Node);
  664. OpenChildren[Node] = Node->getNumChildren();
  665. append_range(WorkList, Node->children());
  666. } while (!WorkList.empty());
  667. // Now perform CSE.
  668. bool Changed = false;
  669. for (MachineDomTreeNode *Node : Scopes) {
  670. MachineBasicBlock *MBB = Node->getBlock();
  671. EnterScope(MBB);
  672. Changed |= ProcessBlockCSE(MBB);
  673. // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
  674. ExitScopeIfDone(Node, OpenChildren);
  675. }
  676. return Changed;
  677. }
  678. // We use stronger checks for PRE candidate rather than for CSE ones to embrace
  679. // checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps
  680. // to exclude instrs created by PRE that won't be CSEed later.
  681. bool MachineCSE::isPRECandidate(MachineInstr *MI) {
  682. if (!isCSECandidate(MI) ||
  683. MI->isNotDuplicable() ||
  684. MI->mayLoad() ||
  685. MI->isAsCheapAsAMove() ||
  686. MI->getNumDefs() != 1 ||
  687. MI->getNumExplicitDefs() != 1)
  688. return false;
  689. for (const auto &def : MI->defs())
  690. if (!Register::isVirtualRegister(def.getReg()))
  691. return false;
  692. for (const auto &use : MI->uses())
  693. if (use.isReg() && !Register::isVirtualRegister(use.getReg()))
  694. return false;
  695. return true;
  696. }
  697. bool MachineCSE::ProcessBlockPRE(MachineDominatorTree *DT,
  698. MachineBasicBlock *MBB) {
  699. bool Changed = false;
  700. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) {
  701. MachineInstr *MI = &*I;
  702. ++I;
  703. if (!isPRECandidate(MI))
  704. continue;
  705. if (!PREMap.count(MI)) {
  706. PREMap[MI] = MBB;
  707. continue;
  708. }
  709. auto MBB1 = PREMap[MI];
  710. assert(
  711. !DT->properlyDominates(MBB, MBB1) &&
  712. "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
  713. auto CMBB = DT->findNearestCommonDominator(MBB, MBB1);
  714. if (!CMBB->isLegalToHoistInto())
  715. continue;
  716. if (!isProfitableToHoistInto(CMBB, MBB, MBB1))
  717. continue;
  718. // Two instrs are partial redundant if their basic blocks are reachable
  719. // from one to another but one doesn't dominate another.
  720. if (CMBB != MBB1) {
  721. auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock();
  722. if (BB != nullptr && BB1 != nullptr &&
  723. (isPotentiallyReachable(BB1, BB) ||
  724. isPotentiallyReachable(BB, BB1))) {
  725. assert(MI->getOperand(0).isDef() &&
  726. "First operand of instr with one explicit def must be this def");
  727. Register VReg = MI->getOperand(0).getReg();
  728. Register NewReg = MRI->cloneVirtualRegister(VReg);
  729. if (!isProfitableToCSE(NewReg, VReg, CMBB, MI))
  730. continue;
  731. MachineInstr &NewMI =
  732. TII->duplicate(*CMBB, CMBB->getFirstTerminator(), *MI);
  733. // When hoisting, make sure we don't carry the debug location of
  734. // the original instruction, as that's not correct and can cause
  735. // unexpected jumps when debugging optimized code.
  736. auto EmptyDL = DebugLoc();
  737. NewMI.setDebugLoc(EmptyDL);
  738. NewMI.getOperand(0).setReg(NewReg);
  739. PREMap[MI] = CMBB;
  740. ++NumPREs;
  741. Changed = true;
  742. }
  743. }
  744. }
  745. return Changed;
  746. }
  747. // This simple PRE (partial redundancy elimination) pass doesn't actually
  748. // eliminate partial redundancy but transforms it to full redundancy,
  749. // anticipating that the next CSE step will eliminate this created redundancy.
  750. // If CSE doesn't eliminate this, than created instruction will remain dead
  751. // and eliminated later by Remove Dead Machine Instructions pass.
  752. bool MachineCSE::PerformSimplePRE(MachineDominatorTree *DT) {
  753. SmallVector<MachineDomTreeNode *, 32> BBs;
  754. PREMap.clear();
  755. bool Changed = false;
  756. BBs.push_back(DT->getRootNode());
  757. do {
  758. auto Node = BBs.pop_back_val();
  759. append_range(BBs, Node->children());
  760. MachineBasicBlock *MBB = Node->getBlock();
  761. Changed |= ProcessBlockPRE(DT, MBB);
  762. } while (!BBs.empty());
  763. return Changed;
  764. }
  765. bool MachineCSE::isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
  766. MachineBasicBlock *MBB,
  767. MachineBasicBlock *MBB1) {
  768. if (CandidateBB->getParent()->getFunction().hasMinSize())
  769. return true;
  770. assert(DT->dominates(CandidateBB, MBB) && "CandidateBB should dominate MBB");
  771. assert(DT->dominates(CandidateBB, MBB1) &&
  772. "CandidateBB should dominate MBB1");
  773. return MBFI->getBlockFreq(CandidateBB) <=
  774. MBFI->getBlockFreq(MBB) + MBFI->getBlockFreq(MBB1);
  775. }
  776. bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
  777. if (skipFunction(MF.getFunction()))
  778. return false;
  779. TII = MF.getSubtarget().getInstrInfo();
  780. TRI = MF.getSubtarget().getRegisterInfo();
  781. MRI = &MF.getRegInfo();
  782. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  783. DT = &getAnalysis<MachineDominatorTree>();
  784. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  785. LookAheadLimit = TII->getMachineCSELookAheadLimit();
  786. bool ChangedPRE, ChangedCSE;
  787. ChangedPRE = PerformSimplePRE(DT);
  788. ChangedCSE = PerformCSE(DT->getRootNode());
  789. return ChangedPRE || ChangedCSE;
  790. }