ReachingDefAnalysis.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. //===---- ReachingDefAnalysis.cpp - Reaching Def Analysis ---*- C++ -*-----===//
  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. #include "llvm/ADT/SmallSet.h"
  9. #include "llvm/ADT/SetOperations.h"
  10. #include "llvm/CodeGen/LivePhysRegs.h"
  11. #include "llvm/CodeGen/ReachingDefAnalysis.h"
  12. #include "llvm/CodeGen/TargetRegisterInfo.h"
  13. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  14. #include "llvm/Support/Debug.h"
  15. using namespace llvm;
  16. #define DEBUG_TYPE "reaching-deps-analysis"
  17. char ReachingDefAnalysis::ID = 0;
  18. INITIALIZE_PASS(ReachingDefAnalysis, DEBUG_TYPE, "ReachingDefAnalysis", false,
  19. true)
  20. static bool isValidReg(const MachineOperand &MO) {
  21. return MO.isReg() && MO.getReg();
  22. }
  23. static bool isValidRegUse(const MachineOperand &MO) {
  24. return isValidReg(MO) && MO.isUse();
  25. }
  26. static bool isValidRegUseOf(const MachineOperand &MO, MCRegister PhysReg,
  27. const TargetRegisterInfo *TRI) {
  28. if (!isValidRegUse(MO))
  29. return false;
  30. if (MO.getReg() == PhysReg)
  31. return true;
  32. for (MCRegAliasIterator R(PhysReg, TRI, false); R.isValid(); ++R)
  33. if (MO.getReg() == *R)
  34. return true;
  35. return false;
  36. }
  37. static bool isValidRegDef(const MachineOperand &MO) {
  38. return isValidReg(MO) && MO.isDef();
  39. }
  40. static bool isValidRegDefOf(const MachineOperand &MO, MCRegister PhysReg,
  41. const TargetRegisterInfo *TRI) {
  42. if (!isValidRegDef(MO))
  43. return false;
  44. if (MO.getReg() == PhysReg)
  45. return true;
  46. for (MCRegAliasIterator R(PhysReg, TRI, false); R.isValid(); ++R)
  47. if (MO.getReg() == *R)
  48. return true;
  49. return false;
  50. }
  51. void ReachingDefAnalysis::enterBasicBlock(MachineBasicBlock *MBB) {
  52. unsigned MBBNumber = MBB->getNumber();
  53. assert(MBBNumber < MBBReachingDefs.size() &&
  54. "Unexpected basic block number.");
  55. MBBReachingDefs[MBBNumber].resize(NumRegUnits);
  56. // Reset instruction counter in each basic block.
  57. CurInstr = 0;
  58. // Set up LiveRegs to represent registers entering MBB.
  59. // Default values are 'nothing happened a long time ago'.
  60. if (LiveRegs.empty())
  61. LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
  62. // This is the entry block.
  63. if (MBB->pred_empty()) {
  64. for (const auto &LI : MBB->liveins()) {
  65. for (MCRegUnitIterator Unit(LI.PhysReg, TRI); Unit.isValid(); ++Unit) {
  66. // Treat function live-ins as if they were defined just before the first
  67. // instruction. Usually, function arguments are set up immediately
  68. // before the call.
  69. if (LiveRegs[*Unit] != -1) {
  70. LiveRegs[*Unit] = -1;
  71. MBBReachingDefs[MBBNumber][*Unit].push_back(-1);
  72. }
  73. }
  74. }
  75. LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
  76. return;
  77. }
  78. // Try to coalesce live-out registers from predecessors.
  79. for (MachineBasicBlock *pred : MBB->predecessors()) {
  80. assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
  81. "Should have pre-allocated MBBInfos for all MBBs");
  82. const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
  83. // Incoming is null if this is a backedge from a BB
  84. // we haven't processed yet
  85. if (Incoming.empty())
  86. continue;
  87. // Find the most recent reaching definition from a predecessor.
  88. for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
  89. LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
  90. }
  91. // Insert the most recent reaching definition we found.
  92. for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
  93. if (LiveRegs[Unit] != ReachingDefDefaultVal)
  94. MBBReachingDefs[MBBNumber][Unit].push_back(LiveRegs[Unit]);
  95. }
  96. void ReachingDefAnalysis::leaveBasicBlock(MachineBasicBlock *MBB) {
  97. assert(!LiveRegs.empty() && "Must enter basic block first.");
  98. unsigned MBBNumber = MBB->getNumber();
  99. assert(MBBNumber < MBBOutRegsInfos.size() &&
  100. "Unexpected basic block number.");
  101. // Save register clearances at end of MBB - used by enterBasicBlock().
  102. MBBOutRegsInfos[MBBNumber] = LiveRegs;
  103. // While processing the basic block, we kept `Def` relative to the start
  104. // of the basic block for convenience. However, future use of this information
  105. // only cares about the clearance from the end of the block, so adjust
  106. // everything to be relative to the end of the basic block.
  107. for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
  108. if (OutLiveReg != ReachingDefDefaultVal)
  109. OutLiveReg -= CurInstr;
  110. LiveRegs.clear();
  111. }
  112. void ReachingDefAnalysis::processDefs(MachineInstr *MI) {
  113. assert(!MI->isDebugInstr() && "Won't process debug instructions");
  114. unsigned MBBNumber = MI->getParent()->getNumber();
  115. assert(MBBNumber < MBBReachingDefs.size() &&
  116. "Unexpected basic block number.");
  117. for (auto &MO : MI->operands()) {
  118. if (!isValidRegDef(MO))
  119. continue;
  120. for (MCRegUnitIterator Unit(MO.getReg().asMCReg(), TRI); Unit.isValid();
  121. ++Unit) {
  122. // This instruction explicitly defines the current reg unit.
  123. LLVM_DEBUG(dbgs() << printRegUnit(*Unit, TRI) << ":\t" << CurInstr
  124. << '\t' << *MI);
  125. // How many instructions since this reg unit was last written?
  126. if (LiveRegs[*Unit] != CurInstr) {
  127. LiveRegs[*Unit] = CurInstr;
  128. MBBReachingDefs[MBBNumber][*Unit].push_back(CurInstr);
  129. }
  130. }
  131. }
  132. InstIds[MI] = CurInstr;
  133. ++CurInstr;
  134. }
  135. void ReachingDefAnalysis::reprocessBasicBlock(MachineBasicBlock *MBB) {
  136. unsigned MBBNumber = MBB->getNumber();
  137. assert(MBBNumber < MBBReachingDefs.size() &&
  138. "Unexpected basic block number.");
  139. // Count number of non-debug instructions for end of block adjustment.
  140. auto NonDbgInsts =
  141. instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end());
  142. int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
  143. // When reprocessing a block, the only thing we need to do is check whether
  144. // there is now a more recent incoming reaching definition from a predecessor.
  145. for (MachineBasicBlock *pred : MBB->predecessors()) {
  146. assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
  147. "Should have pre-allocated MBBInfos for all MBBs");
  148. const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
  149. // Incoming may be empty for dead predecessors.
  150. if (Incoming.empty())
  151. continue;
  152. for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
  153. int Def = Incoming[Unit];
  154. if (Def == ReachingDefDefaultVal)
  155. continue;
  156. auto Start = MBBReachingDefs[MBBNumber][Unit].begin();
  157. if (Start != MBBReachingDefs[MBBNumber][Unit].end() && *Start < 0) {
  158. if (*Start >= Def)
  159. continue;
  160. // Update existing reaching def from predecessor to a more recent one.
  161. *Start = Def;
  162. } else {
  163. // Insert new reaching def from predecessor.
  164. MBBReachingDefs[MBBNumber][Unit].insert(Start, Def);
  165. }
  166. // Update reaching def at end of of BB. Keep in mind that these are
  167. // adjusted relative to the end of the basic block.
  168. if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
  169. MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
  170. }
  171. }
  172. }
  173. void ReachingDefAnalysis::processBasicBlock(
  174. const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
  175. MachineBasicBlock *MBB = TraversedMBB.MBB;
  176. LLVM_DEBUG(dbgs() << printMBBReference(*MBB)
  177. << (!TraversedMBB.IsDone ? ": incomplete\n"
  178. : ": all preds known\n"));
  179. if (!TraversedMBB.PrimaryPass) {
  180. // Reprocess MBB that is part of a loop.
  181. reprocessBasicBlock(MBB);
  182. return;
  183. }
  184. enterBasicBlock(MBB);
  185. for (MachineInstr &MI :
  186. instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end()))
  187. processDefs(&MI);
  188. leaveBasicBlock(MBB);
  189. }
  190. bool ReachingDefAnalysis::runOnMachineFunction(MachineFunction &mf) {
  191. MF = &mf;
  192. TRI = MF->getSubtarget().getRegisterInfo();
  193. LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
  194. init();
  195. traverse();
  196. return false;
  197. }
  198. void ReachingDefAnalysis::releaseMemory() {
  199. // Clear the internal vectors.
  200. MBBOutRegsInfos.clear();
  201. MBBReachingDefs.clear();
  202. InstIds.clear();
  203. LiveRegs.clear();
  204. }
  205. void ReachingDefAnalysis::reset() {
  206. releaseMemory();
  207. init();
  208. traverse();
  209. }
  210. void ReachingDefAnalysis::init() {
  211. NumRegUnits = TRI->getNumRegUnits();
  212. MBBReachingDefs.resize(MF->getNumBlockIDs());
  213. // Initialize the MBBOutRegsInfos
  214. MBBOutRegsInfos.resize(MF->getNumBlockIDs());
  215. LoopTraversal Traversal;
  216. TraversedMBBOrder = Traversal.traverse(*MF);
  217. }
  218. void ReachingDefAnalysis::traverse() {
  219. // Traverse the basic blocks.
  220. for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
  221. processBasicBlock(TraversedMBB);
  222. #ifndef NDEBUG
  223. // Make sure reaching defs are sorted and unique.
  224. for (MBBDefsInfo &MBBDefs : MBBReachingDefs) {
  225. for (MBBRegUnitDefs &RegUnitDefs : MBBDefs) {
  226. int LastDef = ReachingDefDefaultVal;
  227. for (int Def : RegUnitDefs) {
  228. assert(Def > LastDef && "Defs must be sorted and unique");
  229. LastDef = Def;
  230. }
  231. }
  232. }
  233. #endif
  234. }
  235. int ReachingDefAnalysis::getReachingDef(MachineInstr *MI,
  236. MCRegister PhysReg) const {
  237. assert(InstIds.count(MI) && "Unexpected machine instuction.");
  238. int InstId = InstIds.lookup(MI);
  239. int DefRes = ReachingDefDefaultVal;
  240. unsigned MBBNumber = MI->getParent()->getNumber();
  241. assert(MBBNumber < MBBReachingDefs.size() &&
  242. "Unexpected basic block number.");
  243. int LatestDef = ReachingDefDefaultVal;
  244. for (MCRegUnitIterator Unit(PhysReg, TRI); Unit.isValid(); ++Unit) {
  245. for (int Def : MBBReachingDefs[MBBNumber][*Unit]) {
  246. if (Def >= InstId)
  247. break;
  248. DefRes = Def;
  249. }
  250. LatestDef = std::max(LatestDef, DefRes);
  251. }
  252. return LatestDef;
  253. }
  254. MachineInstr *
  255. ReachingDefAnalysis::getReachingLocalMIDef(MachineInstr *MI,
  256. MCRegister PhysReg) const {
  257. return hasLocalDefBefore(MI, PhysReg)
  258. ? getInstFromId(MI->getParent(), getReachingDef(MI, PhysReg))
  259. : nullptr;
  260. }
  261. bool ReachingDefAnalysis::hasSameReachingDef(MachineInstr *A, MachineInstr *B,
  262. MCRegister PhysReg) const {
  263. MachineBasicBlock *ParentA = A->getParent();
  264. MachineBasicBlock *ParentB = B->getParent();
  265. if (ParentA != ParentB)
  266. return false;
  267. return getReachingDef(A, PhysReg) == getReachingDef(B, PhysReg);
  268. }
  269. MachineInstr *ReachingDefAnalysis::getInstFromId(MachineBasicBlock *MBB,
  270. int InstId) const {
  271. assert(static_cast<size_t>(MBB->getNumber()) < MBBReachingDefs.size() &&
  272. "Unexpected basic block number.");
  273. assert(InstId < static_cast<int>(MBB->size()) &&
  274. "Unexpected instruction id.");
  275. if (InstId < 0)
  276. return nullptr;
  277. for (auto &MI : *MBB) {
  278. auto F = InstIds.find(&MI);
  279. if (F != InstIds.end() && F->second == InstId)
  280. return &MI;
  281. }
  282. return nullptr;
  283. }
  284. int ReachingDefAnalysis::getClearance(MachineInstr *MI,
  285. MCRegister PhysReg) const {
  286. assert(InstIds.count(MI) && "Unexpected machine instuction.");
  287. return InstIds.lookup(MI) - getReachingDef(MI, PhysReg);
  288. }
  289. bool ReachingDefAnalysis::hasLocalDefBefore(MachineInstr *MI,
  290. MCRegister PhysReg) const {
  291. return getReachingDef(MI, PhysReg) >= 0;
  292. }
  293. void ReachingDefAnalysis::getReachingLocalUses(MachineInstr *Def,
  294. MCRegister PhysReg,
  295. InstSet &Uses) const {
  296. MachineBasicBlock *MBB = Def->getParent();
  297. MachineBasicBlock::iterator MI = MachineBasicBlock::iterator(Def);
  298. while (++MI != MBB->end()) {
  299. if (MI->isDebugInstr())
  300. continue;
  301. // If/when we find a new reaching def, we know that there's no more uses
  302. // of 'Def'.
  303. if (getReachingLocalMIDef(&*MI, PhysReg) != Def)
  304. return;
  305. for (auto &MO : MI->operands()) {
  306. if (!isValidRegUseOf(MO, PhysReg, TRI))
  307. continue;
  308. Uses.insert(&*MI);
  309. if (MO.isKill())
  310. return;
  311. }
  312. }
  313. }
  314. bool ReachingDefAnalysis::getLiveInUses(MachineBasicBlock *MBB,
  315. MCRegister PhysReg,
  316. InstSet &Uses) const {
  317. for (MachineInstr &MI :
  318. instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
  319. for (auto &MO : MI.operands()) {
  320. if (!isValidRegUseOf(MO, PhysReg, TRI))
  321. continue;
  322. if (getReachingDef(&MI, PhysReg) >= 0)
  323. return false;
  324. Uses.insert(&MI);
  325. }
  326. }
  327. auto Last = MBB->getLastNonDebugInstr();
  328. if (Last == MBB->end())
  329. return true;
  330. return isReachingDefLiveOut(&*Last, PhysReg);
  331. }
  332. void ReachingDefAnalysis::getGlobalUses(MachineInstr *MI, MCRegister PhysReg,
  333. InstSet &Uses) const {
  334. MachineBasicBlock *MBB = MI->getParent();
  335. // Collect the uses that each def touches within the block.
  336. getReachingLocalUses(MI, PhysReg, Uses);
  337. // Handle live-out values.
  338. if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), PhysReg)) {
  339. if (LiveOut != MI)
  340. return;
  341. SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
  342. SmallPtrSet<MachineBasicBlock*, 4>Visited;
  343. while (!ToVisit.empty()) {
  344. MachineBasicBlock *MBB = ToVisit.pop_back_val();
  345. if (Visited.count(MBB) || !MBB->isLiveIn(PhysReg))
  346. continue;
  347. if (getLiveInUses(MBB, PhysReg, Uses))
  348. llvm::append_range(ToVisit, MBB->successors());
  349. Visited.insert(MBB);
  350. }
  351. }
  352. }
  353. void ReachingDefAnalysis::getGlobalReachingDefs(MachineInstr *MI,
  354. MCRegister PhysReg,
  355. InstSet &Defs) const {
  356. if (auto *Def = getUniqueReachingMIDef(MI, PhysReg)) {
  357. Defs.insert(Def);
  358. return;
  359. }
  360. for (auto *MBB : MI->getParent()->predecessors())
  361. getLiveOuts(MBB, PhysReg, Defs);
  362. }
  363. void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
  364. MCRegister PhysReg, InstSet &Defs) const {
  365. SmallPtrSet<MachineBasicBlock*, 2> VisitedBBs;
  366. getLiveOuts(MBB, PhysReg, Defs, VisitedBBs);
  367. }
  368. void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
  369. MCRegister PhysReg, InstSet &Defs,
  370. BlockSet &VisitedBBs) const {
  371. if (VisitedBBs.count(MBB))
  372. return;
  373. VisitedBBs.insert(MBB);
  374. LivePhysRegs LiveRegs(*TRI);
  375. LiveRegs.addLiveOuts(*MBB);
  376. if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
  377. return;
  378. if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
  379. Defs.insert(Def);
  380. else
  381. for (auto *Pred : MBB->predecessors())
  382. getLiveOuts(Pred, PhysReg, Defs, VisitedBBs);
  383. }
  384. MachineInstr *
  385. ReachingDefAnalysis::getUniqueReachingMIDef(MachineInstr *MI,
  386. MCRegister PhysReg) const {
  387. // If there's a local def before MI, return it.
  388. MachineInstr *LocalDef = getReachingLocalMIDef(MI, PhysReg);
  389. if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
  390. return LocalDef;
  391. SmallPtrSet<MachineInstr*, 2> Incoming;
  392. MachineBasicBlock *Parent = MI->getParent();
  393. for (auto *Pred : Parent->predecessors())
  394. getLiveOuts(Pred, PhysReg, Incoming);
  395. // Check that we have a single incoming value and that it does not
  396. // come from the same block as MI - since it would mean that the def
  397. // is executed after MI.
  398. if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
  399. return *Incoming.begin();
  400. return nullptr;
  401. }
  402. MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
  403. unsigned Idx) const {
  404. assert(MI->getOperand(Idx).isReg() && "Expected register operand");
  405. return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
  406. }
  407. MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
  408. MachineOperand &MO) const {
  409. assert(MO.isReg() && "Expected register operand");
  410. return getUniqueReachingMIDef(MI, MO.getReg());
  411. }
  412. bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
  413. MCRegister PhysReg) const {
  414. MachineBasicBlock *MBB = MI->getParent();
  415. LivePhysRegs LiveRegs(*TRI);
  416. LiveRegs.addLiveOuts(*MBB);
  417. // Yes if the register is live out of the basic block.
  418. if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
  419. return true;
  420. // Walk backwards through the block to see if the register is live at some
  421. // point.
  422. for (MachineInstr &Last :
  423. instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
  424. LiveRegs.stepBackward(Last);
  425. if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
  426. return InstIds.lookup(&Last) > InstIds.lookup(MI);
  427. }
  428. return false;
  429. }
  430. bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr *MI,
  431. MCRegister PhysReg) const {
  432. MachineBasicBlock *MBB = MI->getParent();
  433. auto Last = MBB->getLastNonDebugInstr();
  434. if (Last != MBB->end() &&
  435. getReachingDef(MI, PhysReg) != getReachingDef(&*Last, PhysReg))
  436. return true;
  437. if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
  438. return Def == getReachingLocalMIDef(MI, PhysReg);
  439. return false;
  440. }
  441. bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
  442. MCRegister PhysReg) const {
  443. MachineBasicBlock *MBB = MI->getParent();
  444. LivePhysRegs LiveRegs(*TRI);
  445. LiveRegs.addLiveOuts(*MBB);
  446. if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
  447. return false;
  448. auto Last = MBB->getLastNonDebugInstr();
  449. int Def = getReachingDef(MI, PhysReg);
  450. if (Last != MBB->end() && getReachingDef(&*Last, PhysReg) != Def)
  451. return false;
  452. // Finally check that the last instruction doesn't redefine the register.
  453. for (auto &MO : Last->operands())
  454. if (isValidRegDefOf(MO, PhysReg, TRI))
  455. return false;
  456. return true;
  457. }
  458. MachineInstr *
  459. ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
  460. MCRegister PhysReg) const {
  461. LivePhysRegs LiveRegs(*TRI);
  462. LiveRegs.addLiveOuts(*MBB);
  463. if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
  464. return nullptr;
  465. auto Last = MBB->getLastNonDebugInstr();
  466. if (Last == MBB->end())
  467. return nullptr;
  468. int Def = getReachingDef(&*Last, PhysReg);
  469. for (auto &MO : Last->operands())
  470. if (isValidRegDefOf(MO, PhysReg, TRI))
  471. return &*Last;
  472. return Def < 0 ? nullptr : getInstFromId(MBB, Def);
  473. }
  474. static bool mayHaveSideEffects(MachineInstr &MI) {
  475. return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
  476. MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
  477. MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
  478. }
  479. // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
  480. // not define a register that is used by any instructions, after and including,
  481. // 'To'. These instructions also must not redefine any of Froms operands.
  482. template<typename Iterator>
  483. bool ReachingDefAnalysis::isSafeToMove(MachineInstr *From,
  484. MachineInstr *To) const {
  485. if (From->getParent() != To->getParent() || From == To)
  486. return false;
  487. SmallSet<int, 2> Defs;
  488. // First check that From would compute the same value if moved.
  489. for (auto &MO : From->operands()) {
  490. if (!isValidReg(MO))
  491. continue;
  492. if (MO.isDef())
  493. Defs.insert(MO.getReg());
  494. else if (!hasSameReachingDef(From, To, MO.getReg()))
  495. return false;
  496. }
  497. // Now walk checking that the rest of the instructions will compute the same
  498. // value and that we're not overwriting anything. Don't move the instruction
  499. // past any memory, control-flow or other ambiguous instructions.
  500. for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
  501. if (mayHaveSideEffects(*I))
  502. return false;
  503. for (auto &MO : I->operands())
  504. if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
  505. return false;
  506. }
  507. return true;
  508. }
  509. bool ReachingDefAnalysis::isSafeToMoveForwards(MachineInstr *From,
  510. MachineInstr *To) const {
  511. using Iterator = MachineBasicBlock::iterator;
  512. // Walk forwards until we find the instruction.
  513. for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
  514. if (&*I == To)
  515. return isSafeToMove<Iterator>(From, To);
  516. return false;
  517. }
  518. bool ReachingDefAnalysis::isSafeToMoveBackwards(MachineInstr *From,
  519. MachineInstr *To) const {
  520. using Iterator = MachineBasicBlock::reverse_iterator;
  521. // Walk backwards until we find the instruction.
  522. for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
  523. if (&*I == To)
  524. return isSafeToMove<Iterator>(From, To);
  525. return false;
  526. }
  527. bool ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI,
  528. InstSet &ToRemove) const {
  529. SmallPtrSet<MachineInstr*, 1> Ignore;
  530. SmallPtrSet<MachineInstr*, 2> Visited;
  531. return isSafeToRemove(MI, Visited, ToRemove, Ignore);
  532. }
  533. bool
  534. ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &ToRemove,
  535. InstSet &Ignore) const {
  536. SmallPtrSet<MachineInstr*, 2> Visited;
  537. return isSafeToRemove(MI, Visited, ToRemove, Ignore);
  538. }
  539. bool
  540. ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
  541. InstSet &ToRemove, InstSet &Ignore) const {
  542. if (Visited.count(MI) || Ignore.count(MI))
  543. return true;
  544. else if (mayHaveSideEffects(*MI)) {
  545. // Unless told to ignore the instruction, don't remove anything which has
  546. // side effects.
  547. return false;
  548. }
  549. Visited.insert(MI);
  550. for (auto &MO : MI->operands()) {
  551. if (!isValidRegDef(MO))
  552. continue;
  553. SmallPtrSet<MachineInstr*, 4> Uses;
  554. getGlobalUses(MI, MO.getReg(), Uses);
  555. for (auto I : Uses) {
  556. if (Ignore.count(I) || ToRemove.count(I))
  557. continue;
  558. if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
  559. return false;
  560. }
  561. }
  562. ToRemove.insert(MI);
  563. return true;
  564. }
  565. void ReachingDefAnalysis::collectKilledOperands(MachineInstr *MI,
  566. InstSet &Dead) const {
  567. Dead.insert(MI);
  568. auto IsDead = [this, &Dead](MachineInstr *Def, MCRegister PhysReg) {
  569. if (mayHaveSideEffects(*Def))
  570. return false;
  571. unsigned LiveDefs = 0;
  572. for (auto &MO : Def->operands()) {
  573. if (!isValidRegDef(MO))
  574. continue;
  575. if (!MO.isDead())
  576. ++LiveDefs;
  577. }
  578. if (LiveDefs > 1)
  579. return false;
  580. SmallPtrSet<MachineInstr*, 4> Uses;
  581. getGlobalUses(Def, PhysReg, Uses);
  582. return llvm::set_is_subset(Uses, Dead);
  583. };
  584. for (auto &MO : MI->operands()) {
  585. if (!isValidRegUse(MO))
  586. continue;
  587. if (MachineInstr *Def = getMIOperand(MI, MO))
  588. if (IsDead(Def, MO.getReg()))
  589. collectKilledOperands(Def, Dead);
  590. }
  591. }
  592. bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI,
  593. MCRegister PhysReg) const {
  594. SmallPtrSet<MachineInstr*, 1> Ignore;
  595. return isSafeToDefRegAt(MI, PhysReg, Ignore);
  596. }
  597. bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, MCRegister PhysReg,
  598. InstSet &Ignore) const {
  599. // Check for any uses of the register after MI.
  600. if (isRegUsedAfter(MI, PhysReg)) {
  601. if (auto *Def = getReachingLocalMIDef(MI, PhysReg)) {
  602. SmallPtrSet<MachineInstr*, 2> Uses;
  603. getGlobalUses(Def, PhysReg, Uses);
  604. if (!llvm::set_is_subset(Uses, Ignore))
  605. return false;
  606. } else
  607. return false;
  608. }
  609. MachineBasicBlock *MBB = MI->getParent();
  610. // Check for any defs after MI.
  611. if (isRegDefinedAfter(MI, PhysReg)) {
  612. auto I = MachineBasicBlock::iterator(MI);
  613. for (auto E = MBB->end(); I != E; ++I) {
  614. if (Ignore.count(&*I))
  615. continue;
  616. for (auto &MO : I->operands())
  617. if (isValidRegDefOf(MO, PhysReg, TRI))
  618. return false;
  619. }
  620. }
  621. return true;
  622. }