ExecutionDepsFix.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. //===- ExecutionDepsFix.cpp - Fix execution dependecy issues ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains the execution dependency fix pass.
  11. //
  12. // Some X86 SSE instructions like mov, and, or, xor are available in different
  13. // variants for different operand types. These variant instructions are
  14. // equivalent, but on Nehalem and newer cpus there is extra latency
  15. // transferring data between integer and floating point domains. ARM cores
  16. // have similar issues when they are configured with both VFP and NEON
  17. // pipelines.
  18. //
  19. // This pass changes the variant instructions to minimize domain crossings.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/CodeGen/Passes.h"
  23. #include "llvm/ADT/PostOrderIterator.h"
  24. #include "llvm/ADT/iterator_range.h"
  25. #include "llvm/CodeGen/LivePhysRegs.h"
  26. #include "llvm/CodeGen/MachineFunctionPass.h"
  27. #include "llvm/CodeGen/MachineRegisterInfo.h"
  28. #include "llvm/Support/Allocator.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include "llvm/Target/TargetInstrInfo.h"
  32. #include "llvm/Target/TargetSubtargetInfo.h"
  33. using namespace llvm;
  34. #define DEBUG_TYPE "execution-fix"
  35. /// A DomainValue is a bit like LiveIntervals' ValNo, but it also keeps track
  36. /// of execution domains.
  37. ///
  38. /// An open DomainValue represents a set of instructions that can still switch
  39. /// execution domain. Multiple registers may refer to the same open
  40. /// DomainValue - they will eventually be collapsed to the same execution
  41. /// domain.
  42. ///
  43. /// A collapsed DomainValue represents a single register that has been forced
  44. /// into one of more execution domains. There is a separate collapsed
  45. /// DomainValue for each register, but it may contain multiple execution
  46. /// domains. A register value is initially created in a single execution
  47. /// domain, but if we were forced to pay the penalty of a domain crossing, we
  48. /// keep track of the fact that the register is now available in multiple
  49. /// domains.
  50. namespace {
  51. struct DomainValue {
  52. // Basic reference counting.
  53. unsigned Refs;
  54. // Bitmask of available domains. For an open DomainValue, it is the still
  55. // possible domains for collapsing. For a collapsed DomainValue it is the
  56. // domains where the register is available for free.
  57. unsigned AvailableDomains;
  58. // Pointer to the next DomainValue in a chain. When two DomainValues are
  59. // merged, Victim.Next is set to point to Victor, so old DomainValue
  60. // references can be updated by following the chain.
  61. DomainValue *Next;
  62. // Twiddleable instructions using or defining these registers.
  63. SmallVector<MachineInstr*, 8> Instrs;
  64. // A collapsed DomainValue has no instructions to twiddle - it simply keeps
  65. // track of the domains where the registers are already available.
  66. bool isCollapsed() const { return Instrs.empty(); }
  67. // Is domain available?
  68. bool hasDomain(unsigned domain) const {
  69. assert(domain <
  70. static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
  71. "undefined behavior");
  72. return AvailableDomains & (1u << domain);
  73. }
  74. // Mark domain as available.
  75. void addDomain(unsigned domain) {
  76. AvailableDomains |= 1u << domain;
  77. }
  78. // Restrict to a single domain available.
  79. void setSingleDomain(unsigned domain) {
  80. AvailableDomains = 1u << domain;
  81. }
  82. // Return bitmask of domains that are available and in mask.
  83. unsigned getCommonDomains(unsigned mask) const {
  84. return AvailableDomains & mask;
  85. }
  86. // First domain available.
  87. unsigned getFirstDomain() const {
  88. return countTrailingZeros(AvailableDomains);
  89. }
  90. DomainValue() : Refs(0) { clear(); }
  91. // Clear this DomainValue and point to next which has all its data.
  92. void clear() {
  93. AvailableDomains = 0;
  94. Next = nullptr;
  95. Instrs.clear();
  96. }
  97. };
  98. }
  99. namespace {
  100. /// Information about a live register.
  101. struct LiveReg {
  102. /// Value currently in this register, or NULL when no value is being tracked.
  103. /// This counts as a DomainValue reference.
  104. DomainValue *Value;
  105. /// Instruction that defined this register, relative to the beginning of the
  106. /// current basic block. When a LiveReg is used to represent a live-out
  107. /// register, this value is relative to the end of the basic block, so it
  108. /// will be a negative number.
  109. int Def;
  110. };
  111. } // anonymous namespace
  112. namespace {
  113. class ExeDepsFix : public MachineFunctionPass {
  114. static char ID;
  115. SpecificBumpPtrAllocator<DomainValue> Allocator;
  116. SmallVector<DomainValue*,16> Avail;
  117. const TargetRegisterClass *const RC;
  118. MachineFunction *MF;
  119. const TargetInstrInfo *TII;
  120. const TargetRegisterInfo *TRI;
  121. std::vector<SmallVector<int, 1>> AliasMap;
  122. const unsigned NumRegs;
  123. LiveReg *LiveRegs;
  124. typedef DenseMap<MachineBasicBlock*, LiveReg*> LiveOutMap;
  125. LiveOutMap LiveOuts;
  126. /// List of undefined register reads in this block in forward order.
  127. std::vector<std::pair<MachineInstr*, unsigned> > UndefReads;
  128. /// Storage for register unit liveness.
  129. LivePhysRegs LiveRegSet;
  130. /// Current instruction number.
  131. /// The first instruction in each basic block is 0.
  132. int CurInstr;
  133. /// True when the current block has a predecessor that hasn't been visited
  134. /// yet.
  135. bool SeenUnknownBackEdge;
  136. public:
  137. ExeDepsFix(const TargetRegisterClass *rc)
  138. : MachineFunctionPass(ID), RC(rc), NumRegs(RC->getNumRegs()) {}
  139. void getAnalysisUsage(AnalysisUsage &AU) const override {
  140. AU.setPreservesAll();
  141. MachineFunctionPass::getAnalysisUsage(AU);
  142. }
  143. bool runOnMachineFunction(MachineFunction &MF) override;
  144. MachineFunctionProperties getRequiredProperties() const override {
  145. return MachineFunctionProperties().set(
  146. MachineFunctionProperties::Property::AllVRegsAllocated);
  147. }
  148. const char *getPassName() const override {
  149. return "Execution dependency fix";
  150. }
  151. private:
  152. iterator_range<SmallVectorImpl<int>::const_iterator>
  153. regIndices(unsigned Reg) const;
  154. // DomainValue allocation.
  155. DomainValue *alloc(int domain = -1);
  156. DomainValue *retain(DomainValue *DV) {
  157. if (DV) ++DV->Refs;
  158. return DV;
  159. }
  160. void release(DomainValue*);
  161. DomainValue *resolve(DomainValue*&);
  162. // LiveRegs manipulations.
  163. void setLiveReg(int rx, DomainValue *DV);
  164. void kill(int rx);
  165. void force(int rx, unsigned domain);
  166. void collapse(DomainValue *dv, unsigned domain);
  167. bool merge(DomainValue *A, DomainValue *B);
  168. void enterBasicBlock(MachineBasicBlock*);
  169. void leaveBasicBlock(MachineBasicBlock*);
  170. void visitInstr(MachineInstr*);
  171. void processDefs(MachineInstr*, bool Kill);
  172. void visitSoftInstr(MachineInstr*, unsigned mask);
  173. void visitHardInstr(MachineInstr*, unsigned domain);
  174. bool shouldBreakDependence(MachineInstr*, unsigned OpIdx, unsigned Pref);
  175. void processUndefReads(MachineBasicBlock*);
  176. };
  177. }
  178. char ExeDepsFix::ID = 0;
  179. /// Translate TRI register number to a list of indices into our smaller tables
  180. /// of interesting registers.
  181. iterator_range<SmallVectorImpl<int>::const_iterator>
  182. ExeDepsFix::regIndices(unsigned Reg) const {
  183. assert(Reg < AliasMap.size() && "Invalid register");
  184. const auto &Entry = AliasMap[Reg];
  185. return make_range(Entry.begin(), Entry.end());
  186. }
  187. DomainValue *ExeDepsFix::alloc(int domain) {
  188. DomainValue *dv = Avail.empty() ?
  189. new(Allocator.Allocate()) DomainValue :
  190. Avail.pop_back_val();
  191. if (domain >= 0)
  192. dv->addDomain(domain);
  193. assert(dv->Refs == 0 && "Reference count wasn't cleared");
  194. assert(!dv->Next && "Chained DomainValue shouldn't have been recycled");
  195. return dv;
  196. }
  197. /// Release a reference to DV. When the last reference is released,
  198. /// collapse if needed.
  199. void ExeDepsFix::release(DomainValue *DV) {
  200. while (DV) {
  201. assert(DV->Refs && "Bad DomainValue");
  202. if (--DV->Refs)
  203. return;
  204. // There are no more DV references. Collapse any contained instructions.
  205. if (DV->AvailableDomains && !DV->isCollapsed())
  206. collapse(DV, DV->getFirstDomain());
  207. DomainValue *Next = DV->Next;
  208. DV->clear();
  209. Avail.push_back(DV);
  210. // Also release the next DomainValue in the chain.
  211. DV = Next;
  212. }
  213. }
  214. /// Follow the chain of dead DomainValues until a live DomainValue is reached.
  215. /// Update the referenced pointer when necessary.
  216. DomainValue *ExeDepsFix::resolve(DomainValue *&DVRef) {
  217. DomainValue *DV = DVRef;
  218. if (!DV || !DV->Next)
  219. return DV;
  220. // DV has a chain. Find the end.
  221. do DV = DV->Next;
  222. while (DV->Next);
  223. // Update DVRef to point to DV.
  224. retain(DV);
  225. release(DVRef);
  226. DVRef = DV;
  227. return DV;
  228. }
  229. /// Set LiveRegs[rx] = dv, updating reference counts.
  230. void ExeDepsFix::setLiveReg(int rx, DomainValue *dv) {
  231. assert(unsigned(rx) < NumRegs && "Invalid index");
  232. assert(LiveRegs && "Must enter basic block first.");
  233. if (LiveRegs[rx].Value == dv)
  234. return;
  235. if (LiveRegs[rx].Value)
  236. release(LiveRegs[rx].Value);
  237. LiveRegs[rx].Value = retain(dv);
  238. }
  239. // Kill register rx, recycle or collapse any DomainValue.
  240. void ExeDepsFix::kill(int rx) {
  241. assert(unsigned(rx) < NumRegs && "Invalid index");
  242. assert(LiveRegs && "Must enter basic block first.");
  243. if (!LiveRegs[rx].Value)
  244. return;
  245. release(LiveRegs[rx].Value);
  246. LiveRegs[rx].Value = nullptr;
  247. }
  248. /// Force register rx into domain.
  249. void ExeDepsFix::force(int rx, unsigned domain) {
  250. assert(unsigned(rx) < NumRegs && "Invalid index");
  251. assert(LiveRegs && "Must enter basic block first.");
  252. if (DomainValue *dv = LiveRegs[rx].Value) {
  253. if (dv->isCollapsed())
  254. dv->addDomain(domain);
  255. else if (dv->hasDomain(domain))
  256. collapse(dv, domain);
  257. else {
  258. // This is an incompatible open DomainValue. Collapse it to whatever and
  259. // force the new value into domain. This costs a domain crossing.
  260. collapse(dv, dv->getFirstDomain());
  261. assert(LiveRegs[rx].Value && "Not live after collapse?");
  262. LiveRegs[rx].Value->addDomain(domain);
  263. }
  264. } else {
  265. // Set up basic collapsed DomainValue.
  266. setLiveReg(rx, alloc(domain));
  267. }
  268. }
  269. /// Collapse open DomainValue into given domain. If there are multiple
  270. /// registers using dv, they each get a unique collapsed DomainValue.
  271. void ExeDepsFix::collapse(DomainValue *dv, unsigned domain) {
  272. assert(dv->hasDomain(domain) && "Cannot collapse");
  273. // Collapse all the instructions.
  274. while (!dv->Instrs.empty())
  275. TII->setExecutionDomain(dv->Instrs.pop_back_val(), domain);
  276. dv->setSingleDomain(domain);
  277. // If there are multiple users, give them new, unique DomainValues.
  278. if (LiveRegs && dv->Refs > 1)
  279. for (unsigned rx = 0; rx != NumRegs; ++rx)
  280. if (LiveRegs[rx].Value == dv)
  281. setLiveReg(rx, alloc(domain));
  282. }
  283. /// All instructions and registers in B are moved to A, and B is released.
  284. bool ExeDepsFix::merge(DomainValue *A, DomainValue *B) {
  285. assert(!A->isCollapsed() && "Cannot merge into collapsed");
  286. assert(!B->isCollapsed() && "Cannot merge from collapsed");
  287. if (A == B)
  288. return true;
  289. // Restrict to the domains that A and B have in common.
  290. unsigned common = A->getCommonDomains(B->AvailableDomains);
  291. if (!common)
  292. return false;
  293. A->AvailableDomains = common;
  294. A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
  295. // Clear the old DomainValue so we won't try to swizzle instructions twice.
  296. B->clear();
  297. // All uses of B are referred to A.
  298. B->Next = retain(A);
  299. for (unsigned rx = 0; rx != NumRegs; ++rx) {
  300. assert(LiveRegs && "no space allocated for live registers");
  301. if (LiveRegs[rx].Value == B)
  302. setLiveReg(rx, A);
  303. }
  304. return true;
  305. }
  306. /// Set up LiveRegs by merging predecessor live-out values.
  307. void ExeDepsFix::enterBasicBlock(MachineBasicBlock *MBB) {
  308. // Detect back-edges from predecessors we haven't processed yet.
  309. SeenUnknownBackEdge = false;
  310. // Reset instruction counter in each basic block.
  311. CurInstr = 0;
  312. // Set up UndefReads to track undefined register reads.
  313. UndefReads.clear();
  314. LiveRegSet.clear();
  315. // Set up LiveRegs to represent registers entering MBB.
  316. if (!LiveRegs)
  317. LiveRegs = new LiveReg[NumRegs];
  318. // Default values are 'nothing happened a long time ago'.
  319. for (unsigned rx = 0; rx != NumRegs; ++rx) {
  320. LiveRegs[rx].Value = nullptr;
  321. LiveRegs[rx].Def = -(1 << 20);
  322. }
  323. // This is the entry block.
  324. if (MBB->pred_empty()) {
  325. for (const auto &LI : MBB->liveins()) {
  326. for (int rx : regIndices(LI.PhysReg)) {
  327. // Treat function live-ins as if they were defined just before the first
  328. // instruction. Usually, function arguments are set up immediately
  329. // before the call.
  330. LiveRegs[rx].Def = -1;
  331. }
  332. }
  333. DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": entry\n");
  334. return;
  335. }
  336. // Try to coalesce live-out registers from predecessors.
  337. for (MachineBasicBlock::const_pred_iterator pi = MBB->pred_begin(),
  338. pe = MBB->pred_end(); pi != pe; ++pi) {
  339. LiveOutMap::const_iterator fi = LiveOuts.find(*pi);
  340. if (fi == LiveOuts.end()) {
  341. SeenUnknownBackEdge = true;
  342. continue;
  343. }
  344. assert(fi->second && "Can't have NULL entries");
  345. for (unsigned rx = 0; rx != NumRegs; ++rx) {
  346. // Use the most recent predecessor def for each register.
  347. LiveRegs[rx].Def = std::max(LiveRegs[rx].Def, fi->second[rx].Def);
  348. DomainValue *pdv = resolve(fi->second[rx].Value);
  349. if (!pdv)
  350. continue;
  351. if (!LiveRegs[rx].Value) {
  352. setLiveReg(rx, pdv);
  353. continue;
  354. }
  355. // We have a live DomainValue from more than one predecessor.
  356. if (LiveRegs[rx].Value->isCollapsed()) {
  357. // We are already collapsed, but predecessor is not. Force it.
  358. unsigned Domain = LiveRegs[rx].Value->getFirstDomain();
  359. if (!pdv->isCollapsed() && pdv->hasDomain(Domain))
  360. collapse(pdv, Domain);
  361. continue;
  362. }
  363. // Currently open, merge in predecessor.
  364. if (!pdv->isCollapsed())
  365. merge(LiveRegs[rx].Value, pdv);
  366. else
  367. force(rx, pdv->getFirstDomain());
  368. }
  369. }
  370. DEBUG(dbgs() << "BB#" << MBB->getNumber()
  371. << (SeenUnknownBackEdge ? ": incomplete\n" : ": all preds known\n"));
  372. }
  373. void ExeDepsFix::leaveBasicBlock(MachineBasicBlock *MBB) {
  374. assert(LiveRegs && "Must enter basic block first.");
  375. // Save live registers at end of MBB - used by enterBasicBlock().
  376. // Also use LiveOuts as a visited set to detect back-edges.
  377. bool First = LiveOuts.insert(std::make_pair(MBB, LiveRegs)).second;
  378. if (First) {
  379. // LiveRegs was inserted in LiveOuts. Adjust all defs to be relative to
  380. // the end of this block instead of the beginning.
  381. for (unsigned i = 0, e = NumRegs; i != e; ++i)
  382. LiveRegs[i].Def -= CurInstr;
  383. } else {
  384. // Insertion failed, this must be the second pass.
  385. // Release all the DomainValues instead of keeping them.
  386. for (unsigned i = 0, e = NumRegs; i != e; ++i)
  387. release(LiveRegs[i].Value);
  388. delete[] LiveRegs;
  389. }
  390. LiveRegs = nullptr;
  391. }
  392. void ExeDepsFix::visitInstr(MachineInstr *MI) {
  393. if (MI->isDebugValue())
  394. return;
  395. // Update instructions with explicit execution domains.
  396. std::pair<uint16_t, uint16_t> DomP = TII->getExecutionDomain(MI);
  397. if (DomP.first) {
  398. if (DomP.second)
  399. visitSoftInstr(MI, DomP.second);
  400. else
  401. visitHardInstr(MI, DomP.first);
  402. }
  403. // Process defs to track register ages, and kill values clobbered by generic
  404. // instructions.
  405. processDefs(MI, !DomP.first);
  406. }
  407. /// \brief Return true to if it makes sense to break dependence on a partial def
  408. /// or undef use.
  409. bool ExeDepsFix::shouldBreakDependence(MachineInstr *MI, unsigned OpIdx,
  410. unsigned Pref) {
  411. unsigned reg = MI->getOperand(OpIdx).getReg();
  412. for (int rx : regIndices(reg)) {
  413. unsigned Clearance = CurInstr - LiveRegs[rx].Def;
  414. DEBUG(dbgs() << "Clearance: " << Clearance << ", want " << Pref);
  415. if (Pref > Clearance) {
  416. DEBUG(dbgs() << ": Break dependency.\n");
  417. continue;
  418. }
  419. // The current clearance seems OK, but we may be ignoring a def from a
  420. // back-edge.
  421. if (!SeenUnknownBackEdge || Pref <= unsigned(CurInstr)) {
  422. DEBUG(dbgs() << ": OK .\n");
  423. return false;
  424. }
  425. // A def from an unprocessed back-edge may make us break this dependency.
  426. DEBUG(dbgs() << ": Wait for back-edge to resolve.\n");
  427. return false;
  428. }
  429. return true;
  430. }
  431. // Update def-ages for registers defined by MI.
  432. // If Kill is set, also kill off DomainValues clobbered by the defs.
  433. //
  434. // Also break dependencies on partial defs and undef uses.
  435. void ExeDepsFix::processDefs(MachineInstr *MI, bool Kill) {
  436. assert(!MI->isDebugValue() && "Won't process debug values");
  437. // Break dependence on undef uses. Do this before updating LiveRegs below.
  438. unsigned OpNum;
  439. unsigned Pref = TII->getUndefRegClearance(MI, OpNum, TRI);
  440. if (Pref) {
  441. if (shouldBreakDependence(MI, OpNum, Pref))
  442. UndefReads.push_back(std::make_pair(MI, OpNum));
  443. }
  444. const MCInstrDesc &MCID = MI->getDesc();
  445. for (unsigned i = 0,
  446. e = MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
  447. i != e; ++i) {
  448. MachineOperand &MO = MI->getOperand(i);
  449. if (!MO.isReg())
  450. continue;
  451. if (MO.isImplicit())
  452. break;
  453. if (MO.isUse())
  454. continue;
  455. for (int rx : regIndices(MO.getReg())) {
  456. // This instruction explicitly defines rx.
  457. DEBUG(dbgs() << TRI->getName(RC->getRegister(rx)) << ":\t" << CurInstr
  458. << '\t' << *MI);
  459. // Check clearance before partial register updates.
  460. // Call breakDependence before setting LiveRegs[rx].Def.
  461. unsigned Pref = TII->getPartialRegUpdateClearance(MI, i, TRI);
  462. if (Pref && shouldBreakDependence(MI, i, Pref))
  463. TII->breakPartialRegDependency(MI, i, TRI);
  464. // How many instructions since rx was last written?
  465. LiveRegs[rx].Def = CurInstr;
  466. // Kill off domains redefined by generic instructions.
  467. if (Kill)
  468. kill(rx);
  469. }
  470. }
  471. ++CurInstr;
  472. }
  473. /// \break Break false dependencies on undefined register reads.
  474. ///
  475. /// Walk the block backward computing precise liveness. This is expensive, so we
  476. /// only do it on demand. Note that the occurrence of undefined register reads
  477. /// that should be broken is very rare, but when they occur we may have many in
  478. /// a single block.
  479. void ExeDepsFix::processUndefReads(MachineBasicBlock *MBB) {
  480. if (UndefReads.empty())
  481. return;
  482. // Collect this block's live out register units.
  483. LiveRegSet.init(TRI);
  484. // We do not need to care about pristine registers as they are just preserved
  485. // but not actually used in the function.
  486. LiveRegSet.addLiveOutsNoPristines(*MBB);
  487. MachineInstr *UndefMI = UndefReads.back().first;
  488. unsigned OpIdx = UndefReads.back().second;
  489. for (MachineInstr &I : make_range(MBB->rbegin(), MBB->rend())) {
  490. // Update liveness, including the current instruction's defs.
  491. LiveRegSet.stepBackward(I);
  492. if (UndefMI == &I) {
  493. if (!LiveRegSet.contains(UndefMI->getOperand(OpIdx).getReg()))
  494. TII->breakPartialRegDependency(UndefMI, OpIdx, TRI);
  495. UndefReads.pop_back();
  496. if (UndefReads.empty())
  497. return;
  498. UndefMI = UndefReads.back().first;
  499. OpIdx = UndefReads.back().second;
  500. }
  501. }
  502. }
  503. // A hard instruction only works in one domain. All input registers will be
  504. // forced into that domain.
  505. void ExeDepsFix::visitHardInstr(MachineInstr *mi, unsigned domain) {
  506. // Collapse all uses.
  507. for (unsigned i = mi->getDesc().getNumDefs(),
  508. e = mi->getDesc().getNumOperands(); i != e; ++i) {
  509. MachineOperand &mo = mi->getOperand(i);
  510. if (!mo.isReg()) continue;
  511. for (int rx : regIndices(mo.getReg())) {
  512. force(rx, domain);
  513. }
  514. }
  515. // Kill all defs and force them.
  516. for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
  517. MachineOperand &mo = mi->getOperand(i);
  518. if (!mo.isReg()) continue;
  519. for (int rx : regIndices(mo.getReg())) {
  520. kill(rx);
  521. force(rx, domain);
  522. }
  523. }
  524. }
  525. // A soft instruction can be changed to work in other domains given by mask.
  526. void ExeDepsFix::visitSoftInstr(MachineInstr *mi, unsigned mask) {
  527. // Bitmask of available domains for this instruction after taking collapsed
  528. // operands into account.
  529. unsigned available = mask;
  530. // Scan the explicit use operands for incoming domains.
  531. SmallVector<int, 4> used;
  532. if (LiveRegs)
  533. for (unsigned i = mi->getDesc().getNumDefs(),
  534. e = mi->getDesc().getNumOperands(); i != e; ++i) {
  535. MachineOperand &mo = mi->getOperand(i);
  536. if (!mo.isReg()) continue;
  537. for (int rx : regIndices(mo.getReg())) {
  538. DomainValue *dv = LiveRegs[rx].Value;
  539. if (dv == nullptr)
  540. continue;
  541. // Bitmask of domains that dv and available have in common.
  542. unsigned common = dv->getCommonDomains(available);
  543. // Is it possible to use this collapsed register for free?
  544. if (dv->isCollapsed()) {
  545. // Restrict available domains to the ones in common with the operand.
  546. // If there are no common domains, we must pay the cross-domain
  547. // penalty for this operand.
  548. if (common) available = common;
  549. } else if (common)
  550. // Open DomainValue is compatible, save it for merging.
  551. used.push_back(rx);
  552. else
  553. // Open DomainValue is not compatible with instruction. It is useless
  554. // now.
  555. kill(rx);
  556. }
  557. }
  558. // If the collapsed operands force a single domain, propagate the collapse.
  559. if (isPowerOf2_32(available)) {
  560. unsigned domain = countTrailingZeros(available);
  561. TII->setExecutionDomain(mi, domain);
  562. visitHardInstr(mi, domain);
  563. return;
  564. }
  565. // Kill off any remaining uses that don't match available, and build a list of
  566. // incoming DomainValues that we want to merge.
  567. SmallVector<LiveReg, 4> Regs;
  568. for (SmallVectorImpl<int>::iterator i=used.begin(), e=used.end(); i!=e; ++i) {
  569. int rx = *i;
  570. assert(LiveRegs && "no space allocated for live registers");
  571. const LiveReg &LR = LiveRegs[rx];
  572. // This useless DomainValue could have been missed above.
  573. if (!LR.Value->getCommonDomains(available)) {
  574. kill(rx);
  575. continue;
  576. }
  577. // Sorted insertion.
  578. bool Inserted = false;
  579. for (SmallVectorImpl<LiveReg>::iterator i = Regs.begin(), e = Regs.end();
  580. i != e && !Inserted; ++i) {
  581. if (LR.Def < i->Def) {
  582. Inserted = true;
  583. Regs.insert(i, LR);
  584. }
  585. }
  586. if (!Inserted)
  587. Regs.push_back(LR);
  588. }
  589. // doms are now sorted in order of appearance. Try to merge them all, giving
  590. // priority to the latest ones.
  591. DomainValue *dv = nullptr;
  592. while (!Regs.empty()) {
  593. if (!dv) {
  594. dv = Regs.pop_back_val().Value;
  595. // Force the first dv to match the current instruction.
  596. dv->AvailableDomains = dv->getCommonDomains(available);
  597. assert(dv->AvailableDomains && "Domain should have been filtered");
  598. continue;
  599. }
  600. DomainValue *Latest = Regs.pop_back_val().Value;
  601. // Skip already merged values.
  602. if (Latest == dv || Latest->Next)
  603. continue;
  604. if (merge(dv, Latest))
  605. continue;
  606. // If latest didn't merge, it is useless now. Kill all registers using it.
  607. for (int i : used) {
  608. assert(LiveRegs && "no space allocated for live registers");
  609. if (LiveRegs[i].Value == Latest)
  610. kill(i);
  611. }
  612. }
  613. // dv is the DomainValue we are going to use for this instruction.
  614. if (!dv) {
  615. dv = alloc();
  616. dv->AvailableDomains = available;
  617. }
  618. dv->Instrs.push_back(mi);
  619. // Finally set all defs and non-collapsed uses to dv. We must iterate through
  620. // all the operators, including imp-def ones.
  621. for (MachineInstr::mop_iterator ii = mi->operands_begin(),
  622. ee = mi->operands_end();
  623. ii != ee; ++ii) {
  624. MachineOperand &mo = *ii;
  625. if (!mo.isReg()) continue;
  626. for (int rx : regIndices(mo.getReg())) {
  627. if (!LiveRegs[rx].Value || (mo.isDef() && LiveRegs[rx].Value != dv)) {
  628. kill(rx);
  629. setLiveReg(rx, dv);
  630. }
  631. }
  632. }
  633. }
  634. bool ExeDepsFix::runOnMachineFunction(MachineFunction &mf) {
  635. MF = &mf;
  636. TII = MF->getSubtarget().getInstrInfo();
  637. TRI = MF->getSubtarget().getRegisterInfo();
  638. LiveRegs = nullptr;
  639. assert(NumRegs == RC->getNumRegs() && "Bad regclass");
  640. DEBUG(dbgs() << "********** FIX EXECUTION DEPENDENCIES: "
  641. << TRI->getRegClassName(RC) << " **********\n");
  642. // If no relevant registers are used in the function, we can skip it
  643. // completely.
  644. bool anyregs = false;
  645. const MachineRegisterInfo &MRI = mf.getRegInfo();
  646. for (unsigned Reg : *RC) {
  647. if (MRI.isPhysRegUsed(Reg)) {
  648. anyregs = true;
  649. break;
  650. }
  651. }
  652. if (!anyregs) return false;
  653. // Initialize the AliasMap on the first use.
  654. if (AliasMap.empty()) {
  655. // Given a PhysReg, AliasMap[PhysReg] returns a list of indices into RC and
  656. // therefore the LiveRegs array.
  657. AliasMap.resize(TRI->getNumRegs());
  658. for (unsigned i = 0, e = RC->getNumRegs(); i != e; ++i)
  659. for (MCRegAliasIterator AI(RC->getRegister(i), TRI, true);
  660. AI.isValid(); ++AI)
  661. AliasMap[*AI].push_back(i);
  662. }
  663. MachineBasicBlock *Entry = &*MF->begin();
  664. ReversePostOrderTraversal<MachineBasicBlock*> RPOT(Entry);
  665. SmallVector<MachineBasicBlock*, 16> Loops;
  666. for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
  667. MBBI = RPOT.begin(), MBBE = RPOT.end(); MBBI != MBBE; ++MBBI) {
  668. MachineBasicBlock *MBB = *MBBI;
  669. enterBasicBlock(MBB);
  670. if (SeenUnknownBackEdge)
  671. Loops.push_back(MBB);
  672. for (MachineInstr &MI : *MBB)
  673. visitInstr(&MI);
  674. processUndefReads(MBB);
  675. leaveBasicBlock(MBB);
  676. }
  677. // Visit all the loop blocks again in order to merge DomainValues from
  678. // back-edges.
  679. for (MachineBasicBlock *MBB : Loops) {
  680. enterBasicBlock(MBB);
  681. for (MachineInstr &MI : *MBB)
  682. if (!MI.isDebugValue())
  683. processDefs(&MI, false);
  684. processUndefReads(MBB);
  685. leaveBasicBlock(MBB);
  686. }
  687. // Clear the LiveOuts vectors and collapse any remaining DomainValues.
  688. for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
  689. MBBI = RPOT.begin(), MBBE = RPOT.end(); MBBI != MBBE; ++MBBI) {
  690. LiveOutMap::const_iterator FI = LiveOuts.find(*MBBI);
  691. if (FI == LiveOuts.end() || !FI->second)
  692. continue;
  693. for (unsigned i = 0, e = NumRegs; i != e; ++i)
  694. if (FI->second[i].Value)
  695. release(FI->second[i].Value);
  696. delete[] FI->second;
  697. }
  698. LiveOuts.clear();
  699. UndefReads.clear();
  700. Avail.clear();
  701. Allocator.DestroyAll();
  702. return false;
  703. }
  704. FunctionPass *
  705. llvm::createExecutionDependencyFixPass(const TargetRegisterClass *RC) {
  706. return new ExeDepsFix(RC);
  707. }