MachineCSE.cpp 34 KB

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