ExecutionDomainFix.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. //===- ExecutionDomainFix.cpp - Fix execution domain issues ----*- 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/CodeGen/ExecutionDomainFix.h"
  9. #include "llvm/CodeGen/MachineRegisterInfo.h"
  10. #include "llvm/CodeGen/TargetInstrInfo.h"
  11. using namespace llvm;
  12. #define DEBUG_TYPE "execution-deps-fix"
  13. iterator_range<SmallVectorImpl<int>::const_iterator>
  14. ExecutionDomainFix::regIndices(unsigned Reg) const {
  15. assert(Reg < AliasMap.size() && "Invalid register");
  16. const auto &Entry = AliasMap[Reg];
  17. return make_range(Entry.begin(), Entry.end());
  18. }
  19. DomainValue *ExecutionDomainFix::alloc(int domain) {
  20. DomainValue *dv = Avail.empty() ? new (Allocator.Allocate()) DomainValue
  21. : Avail.pop_back_val();
  22. if (domain >= 0)
  23. dv->addDomain(domain);
  24. assert(dv->Refs == 0 && "Reference count wasn't cleared");
  25. assert(!dv->Next && "Chained DomainValue shouldn't have been recycled");
  26. return dv;
  27. }
  28. void ExecutionDomainFix::release(DomainValue *DV) {
  29. while (DV) {
  30. assert(DV->Refs && "Bad DomainValue");
  31. if (--DV->Refs)
  32. return;
  33. // There are no more DV references. Collapse any contained instructions.
  34. if (DV->AvailableDomains && !DV->isCollapsed())
  35. collapse(DV, DV->getFirstDomain());
  36. DomainValue *Next = DV->Next;
  37. DV->clear();
  38. Avail.push_back(DV);
  39. // Also release the next DomainValue in the chain.
  40. DV = Next;
  41. }
  42. }
  43. DomainValue *ExecutionDomainFix::resolve(DomainValue *&DVRef) {
  44. DomainValue *DV = DVRef;
  45. if (!DV || !DV->Next)
  46. return DV;
  47. // DV has a chain. Find the end.
  48. do
  49. DV = DV->Next;
  50. while (DV->Next);
  51. // Update DVRef to point to DV.
  52. retain(DV);
  53. release(DVRef);
  54. DVRef = DV;
  55. return DV;
  56. }
  57. void ExecutionDomainFix::setLiveReg(int rx, DomainValue *dv) {
  58. assert(unsigned(rx) < NumRegs && "Invalid index");
  59. assert(!LiveRegs.empty() && "Must enter basic block first.");
  60. if (LiveRegs[rx] == dv)
  61. return;
  62. if (LiveRegs[rx])
  63. release(LiveRegs[rx]);
  64. LiveRegs[rx] = retain(dv);
  65. }
  66. void ExecutionDomainFix::kill(int rx) {
  67. assert(unsigned(rx) < NumRegs && "Invalid index");
  68. assert(!LiveRegs.empty() && "Must enter basic block first.");
  69. if (!LiveRegs[rx])
  70. return;
  71. release(LiveRegs[rx]);
  72. LiveRegs[rx] = nullptr;
  73. }
  74. void ExecutionDomainFix::force(int rx, unsigned domain) {
  75. assert(unsigned(rx) < NumRegs && "Invalid index");
  76. assert(!LiveRegs.empty() && "Must enter basic block first.");
  77. if (DomainValue *dv = LiveRegs[rx]) {
  78. if (dv->isCollapsed())
  79. dv->addDomain(domain);
  80. else if (dv->hasDomain(domain))
  81. collapse(dv, domain);
  82. else {
  83. // This is an incompatible open DomainValue. Collapse it to whatever and
  84. // force the new value into domain. This costs a domain crossing.
  85. collapse(dv, dv->getFirstDomain());
  86. assert(LiveRegs[rx] && "Not live after collapse?");
  87. LiveRegs[rx]->addDomain(domain);
  88. }
  89. } else {
  90. // Set up basic collapsed DomainValue.
  91. setLiveReg(rx, alloc(domain));
  92. }
  93. }
  94. void ExecutionDomainFix::collapse(DomainValue *dv, unsigned domain) {
  95. assert(dv->hasDomain(domain) && "Cannot collapse");
  96. // Collapse all the instructions.
  97. while (!dv->Instrs.empty())
  98. TII->setExecutionDomain(*dv->Instrs.pop_back_val(), domain);
  99. dv->setSingleDomain(domain);
  100. // If there are multiple users, give them new, unique DomainValues.
  101. if (!LiveRegs.empty() && dv->Refs > 1)
  102. for (unsigned rx = 0; rx != NumRegs; ++rx)
  103. if (LiveRegs[rx] == dv)
  104. setLiveReg(rx, alloc(domain));
  105. }
  106. bool ExecutionDomainFix::merge(DomainValue *A, DomainValue *B) {
  107. assert(!A->isCollapsed() && "Cannot merge into collapsed");
  108. assert(!B->isCollapsed() && "Cannot merge from collapsed");
  109. if (A == B)
  110. return true;
  111. // Restrict to the domains that A and B have in common.
  112. unsigned common = A->getCommonDomains(B->AvailableDomains);
  113. if (!common)
  114. return false;
  115. A->AvailableDomains = common;
  116. A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
  117. // Clear the old DomainValue so we won't try to swizzle instructions twice.
  118. B->clear();
  119. // All uses of B are referred to A.
  120. B->Next = retain(A);
  121. for (unsigned rx = 0; rx != NumRegs; ++rx) {
  122. assert(!LiveRegs.empty() && "no space allocated for live registers");
  123. if (LiveRegs[rx] == B)
  124. setLiveReg(rx, A);
  125. }
  126. return true;
  127. }
  128. void ExecutionDomainFix::enterBasicBlock(
  129. const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
  130. MachineBasicBlock *MBB = TraversedMBB.MBB;
  131. // Set up LiveRegs to represent registers entering MBB.
  132. // Set default domain values to 'no domain' (nullptr)
  133. if (LiveRegs.empty())
  134. LiveRegs.assign(NumRegs, nullptr);
  135. // This is the entry block.
  136. if (MBB->pred_empty()) {
  137. LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
  138. return;
  139. }
  140. // Try to coalesce live-out registers from predecessors.
  141. for (MachineBasicBlock *pred : MBB->predecessors()) {
  142. assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
  143. "Should have pre-allocated MBBInfos for all MBBs");
  144. LiveRegsDVInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
  145. // Incoming is null if this is a backedge from a BB
  146. // we haven't processed yet
  147. if (Incoming.empty())
  148. continue;
  149. for (unsigned rx = 0; rx != NumRegs; ++rx) {
  150. DomainValue *pdv = resolve(Incoming[rx]);
  151. if (!pdv)
  152. continue;
  153. if (!LiveRegs[rx]) {
  154. setLiveReg(rx, pdv);
  155. continue;
  156. }
  157. // We have a live DomainValue from more than one predecessor.
  158. if (LiveRegs[rx]->isCollapsed()) {
  159. // We are already collapsed, but predecessor is not. Force it.
  160. unsigned Domain = LiveRegs[rx]->getFirstDomain();
  161. if (!pdv->isCollapsed() && pdv->hasDomain(Domain))
  162. collapse(pdv, Domain);
  163. continue;
  164. }
  165. // Currently open, merge in predecessor.
  166. if (!pdv->isCollapsed())
  167. merge(LiveRegs[rx], pdv);
  168. else
  169. force(rx, pdv->getFirstDomain());
  170. }
  171. }
  172. LLVM_DEBUG(dbgs() << printMBBReference(*MBB)
  173. << (!TraversedMBB.IsDone ? ": incomplete\n"
  174. : ": all preds known\n"));
  175. }
  176. void ExecutionDomainFix::leaveBasicBlock(
  177. const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
  178. assert(!LiveRegs.empty() && "Must enter basic block first.");
  179. unsigned MBBNumber = TraversedMBB.MBB->getNumber();
  180. assert(MBBNumber < MBBOutRegsInfos.size() &&
  181. "Unexpected basic block number.");
  182. // Save register clearances at end of MBB - used by enterBasicBlock().
  183. for (DomainValue *OldLiveReg : MBBOutRegsInfos[MBBNumber]) {
  184. release(OldLiveReg);
  185. }
  186. MBBOutRegsInfos[MBBNumber] = LiveRegs;
  187. LiveRegs.clear();
  188. }
  189. bool ExecutionDomainFix::visitInstr(MachineInstr *MI) {
  190. // Update instructions with explicit execution domains.
  191. std::pair<uint16_t, uint16_t> DomP = TII->getExecutionDomain(*MI);
  192. if (DomP.first) {
  193. if (DomP.second)
  194. visitSoftInstr(MI, DomP.second);
  195. else
  196. visitHardInstr(MI, DomP.first);
  197. }
  198. return !DomP.first;
  199. }
  200. void ExecutionDomainFix::processDefs(MachineInstr *MI, bool Kill) {
  201. assert(!MI->isDebugInstr() && "Won't process debug values");
  202. const MCInstrDesc &MCID = MI->getDesc();
  203. for (unsigned i = 0,
  204. e = MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
  205. i != e; ++i) {
  206. MachineOperand &MO = MI->getOperand(i);
  207. if (!MO.isReg())
  208. continue;
  209. if (MO.isUse())
  210. continue;
  211. for (int rx : regIndices(MO.getReg())) {
  212. // This instruction explicitly defines rx.
  213. LLVM_DEBUG(dbgs() << printReg(RC->getRegister(rx), TRI) << ":\t" << *MI);
  214. // Kill off domains redefined by generic instructions.
  215. if (Kill)
  216. kill(rx);
  217. }
  218. }
  219. }
  220. void ExecutionDomainFix::visitHardInstr(MachineInstr *mi, unsigned domain) {
  221. // Collapse all uses.
  222. for (unsigned i = mi->getDesc().getNumDefs(),
  223. e = mi->getDesc().getNumOperands();
  224. i != e; ++i) {
  225. MachineOperand &mo = mi->getOperand(i);
  226. if (!mo.isReg())
  227. continue;
  228. for (int rx : regIndices(mo.getReg())) {
  229. force(rx, domain);
  230. }
  231. }
  232. // Kill all defs and force them.
  233. for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
  234. MachineOperand &mo = mi->getOperand(i);
  235. if (!mo.isReg())
  236. continue;
  237. for (int rx : regIndices(mo.getReg())) {
  238. kill(rx);
  239. force(rx, domain);
  240. }
  241. }
  242. }
  243. void ExecutionDomainFix::visitSoftInstr(MachineInstr *mi, unsigned mask) {
  244. // Bitmask of available domains for this instruction after taking collapsed
  245. // operands into account.
  246. unsigned available = mask;
  247. // Scan the explicit use operands for incoming domains.
  248. SmallVector<int, 4> used;
  249. if (!LiveRegs.empty())
  250. for (unsigned i = mi->getDesc().getNumDefs(),
  251. e = mi->getDesc().getNumOperands();
  252. i != e; ++i) {
  253. MachineOperand &mo = mi->getOperand(i);
  254. if (!mo.isReg())
  255. continue;
  256. for (int rx : regIndices(mo.getReg())) {
  257. DomainValue *dv = LiveRegs[rx];
  258. if (dv == nullptr)
  259. continue;
  260. // Bitmask of domains that dv and available have in common.
  261. unsigned common = dv->getCommonDomains(available);
  262. // Is it possible to use this collapsed register for free?
  263. if (dv->isCollapsed()) {
  264. // Restrict available domains to the ones in common with the operand.
  265. // If there are no common domains, we must pay the cross-domain
  266. // penalty for this operand.
  267. if (common)
  268. available = common;
  269. } else if (common)
  270. // Open DomainValue is compatible, save it for merging.
  271. used.push_back(rx);
  272. else
  273. // Open DomainValue is not compatible with instruction. It is useless
  274. // now.
  275. kill(rx);
  276. }
  277. }
  278. // If the collapsed operands force a single domain, propagate the collapse.
  279. if (isPowerOf2_32(available)) {
  280. unsigned domain = countTrailingZeros(available);
  281. TII->setExecutionDomain(*mi, domain);
  282. visitHardInstr(mi, domain);
  283. return;
  284. }
  285. // Kill off any remaining uses that don't match available, and build a list of
  286. // incoming DomainValues that we want to merge.
  287. SmallVector<int, 4> Regs;
  288. for (int rx : used) {
  289. assert(!LiveRegs.empty() && "no space allocated for live registers");
  290. DomainValue *&LR = LiveRegs[rx];
  291. // This useless DomainValue could have been missed above.
  292. if (!LR->getCommonDomains(available)) {
  293. kill(rx);
  294. continue;
  295. }
  296. // Sorted insertion.
  297. // Enables giving priority to the latest domains during merging.
  298. const int Def = RDA->getReachingDef(mi, RC->getRegister(rx));
  299. auto I = partition_point(Regs, [&](int I) {
  300. return RDA->getReachingDef(mi, RC->getRegister(I)) <= Def;
  301. });
  302. Regs.insert(I, rx);
  303. }
  304. // doms are now sorted in order of appearance. Try to merge them all, giving
  305. // priority to the latest ones.
  306. DomainValue *dv = nullptr;
  307. while (!Regs.empty()) {
  308. if (!dv) {
  309. dv = LiveRegs[Regs.pop_back_val()];
  310. // Force the first dv to match the current instruction.
  311. dv->AvailableDomains = dv->getCommonDomains(available);
  312. assert(dv->AvailableDomains && "Domain should have been filtered");
  313. continue;
  314. }
  315. DomainValue *Latest = LiveRegs[Regs.pop_back_val()];
  316. // Skip already merged values.
  317. if (Latest == dv || Latest->Next)
  318. continue;
  319. if (merge(dv, Latest))
  320. continue;
  321. // If latest didn't merge, it is useless now. Kill all registers using it.
  322. for (int i : used) {
  323. assert(!LiveRegs.empty() && "no space allocated for live registers");
  324. if (LiveRegs[i] == Latest)
  325. kill(i);
  326. }
  327. }
  328. // dv is the DomainValue we are going to use for this instruction.
  329. if (!dv) {
  330. dv = alloc();
  331. dv->AvailableDomains = available;
  332. }
  333. dv->Instrs.push_back(mi);
  334. // Finally set all defs and non-collapsed uses to dv. We must iterate through
  335. // all the operators, including imp-def ones.
  336. for (MachineOperand &mo : mi->operands()) {
  337. if (!mo.isReg())
  338. continue;
  339. for (int rx : regIndices(mo.getReg())) {
  340. if (!LiveRegs[rx] || (mo.isDef() && LiveRegs[rx] != dv)) {
  341. kill(rx);
  342. setLiveReg(rx, dv);
  343. }
  344. }
  345. }
  346. }
  347. void ExecutionDomainFix::processBasicBlock(
  348. const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
  349. enterBasicBlock(TraversedMBB);
  350. // If this block is not done, it makes little sense to make any decisions
  351. // based on clearance information. We need to make a second pass anyway,
  352. // and by then we'll have better information, so we can avoid doing the work
  353. // to try and break dependencies now.
  354. for (MachineInstr &MI : *TraversedMBB.MBB) {
  355. if (!MI.isDebugInstr()) {
  356. bool Kill = false;
  357. if (TraversedMBB.PrimaryPass)
  358. Kill = visitInstr(&MI);
  359. processDefs(&MI, Kill);
  360. }
  361. }
  362. leaveBasicBlock(TraversedMBB);
  363. }
  364. bool ExecutionDomainFix::runOnMachineFunction(MachineFunction &mf) {
  365. if (skipFunction(mf.getFunction()))
  366. return false;
  367. MF = &mf;
  368. TII = MF->getSubtarget().getInstrInfo();
  369. TRI = MF->getSubtarget().getRegisterInfo();
  370. LiveRegs.clear();
  371. assert(NumRegs == RC->getNumRegs() && "Bad regclass");
  372. LLVM_DEBUG(dbgs() << "********** FIX EXECUTION DOMAIN: "
  373. << TRI->getRegClassName(RC) << " **********\n");
  374. // If no relevant registers are used in the function, we can skip it
  375. // completely.
  376. bool anyregs = false;
  377. const MachineRegisterInfo &MRI = mf.getRegInfo();
  378. for (unsigned Reg : *RC) {
  379. if (MRI.isPhysRegUsed(Reg)) {
  380. anyregs = true;
  381. break;
  382. }
  383. }
  384. if (!anyregs)
  385. return false;
  386. RDA = &getAnalysis<ReachingDefAnalysis>();
  387. // Initialize the AliasMap on the first use.
  388. if (AliasMap.empty()) {
  389. // Given a PhysReg, AliasMap[PhysReg] returns a list of indices into RC and
  390. // therefore the LiveRegs array.
  391. AliasMap.resize(TRI->getNumRegs());
  392. for (unsigned i = 0, e = RC->getNumRegs(); i != e; ++i)
  393. for (MCRegAliasIterator AI(RC->getRegister(i), TRI, true); AI.isValid();
  394. ++AI)
  395. AliasMap[*AI].push_back(i);
  396. }
  397. // Initialize the MBBOutRegsInfos
  398. MBBOutRegsInfos.resize(mf.getNumBlockIDs());
  399. // Traverse the basic blocks.
  400. LoopTraversal Traversal;
  401. LoopTraversal::TraversalOrder TraversedMBBOrder = Traversal.traverse(mf);
  402. for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder) {
  403. processBasicBlock(TraversedMBB);
  404. }
  405. for (LiveRegsDVInfo OutLiveRegs : MBBOutRegsInfos) {
  406. for (DomainValue *OutLiveReg : OutLiveRegs) {
  407. if (OutLiveReg)
  408. release(OutLiveReg);
  409. }
  410. }
  411. MBBOutRegsInfos.clear();
  412. Avail.clear();
  413. Allocator.DestroyAll();
  414. return false;
  415. }