AggressiveAntiDepBreaker.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. //===- AggressiveAntiDepBreaker.cpp - Anti-dep breaker --------------------===//
  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 file implements the AggressiveAntiDepBreaker class, which
  10. // implements register anti-dependence breaking during post-RA
  11. // scheduling. It attempts to break all anti-dependencies within a
  12. // block.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "AggressiveAntiDepBreaker.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/iterator_range.h"
  20. #include "llvm/CodeGen/MachineBasicBlock.h"
  21. #include "llvm/CodeGen/MachineFrameInfo.h"
  22. #include "llvm/CodeGen/MachineFunction.h"
  23. #include "llvm/CodeGen/MachineInstr.h"
  24. #include "llvm/CodeGen/MachineOperand.h"
  25. #include "llvm/CodeGen/MachineRegisterInfo.h"
  26. #include "llvm/CodeGen/RegisterClassInfo.h"
  27. #include "llvm/CodeGen/ScheduleDAG.h"
  28. #include "llvm/CodeGen/TargetInstrInfo.h"
  29. #include "llvm/CodeGen/TargetRegisterInfo.h"
  30. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  31. #include "llvm/MC/MCInstrDesc.h"
  32. #include "llvm/MC/MCRegisterInfo.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/MachineValueType.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <cassert>
  38. #include <map>
  39. #include <set>
  40. #include <utility>
  41. #include <vector>
  42. using namespace llvm;
  43. #define DEBUG_TYPE "post-RA-sched"
  44. // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
  45. static cl::opt<int>
  46. DebugDiv("agg-antidep-debugdiv",
  47. cl::desc("Debug control for aggressive anti-dep breaker"),
  48. cl::init(0), cl::Hidden);
  49. static cl::opt<int>
  50. DebugMod("agg-antidep-debugmod",
  51. cl::desc("Debug control for aggressive anti-dep breaker"),
  52. cl::init(0), cl::Hidden);
  53. AggressiveAntiDepState::AggressiveAntiDepState(const unsigned TargetRegs,
  54. MachineBasicBlock *BB)
  55. : NumTargetRegs(TargetRegs), GroupNodes(TargetRegs, 0),
  56. GroupNodeIndices(TargetRegs, 0), KillIndices(TargetRegs, 0),
  57. DefIndices(TargetRegs, 0) {
  58. const unsigned BBSize = BB->size();
  59. for (unsigned i = 0; i < NumTargetRegs; ++i) {
  60. // Initialize all registers to be in their own group. Initially we
  61. // assign the register to the same-indexed GroupNode.
  62. GroupNodeIndices[i] = i;
  63. // Initialize the indices to indicate that no registers are live.
  64. KillIndices[i] = ~0u;
  65. DefIndices[i] = BBSize;
  66. }
  67. }
  68. unsigned AggressiveAntiDepState::GetGroup(unsigned Reg) {
  69. unsigned Node = GroupNodeIndices[Reg];
  70. while (GroupNodes[Node] != Node)
  71. Node = GroupNodes[Node];
  72. return Node;
  73. }
  74. void AggressiveAntiDepState::GetGroupRegs(
  75. unsigned Group,
  76. std::vector<unsigned> &Regs,
  77. std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
  78. {
  79. for (unsigned Reg = 0; Reg != NumTargetRegs; ++Reg) {
  80. if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
  81. Regs.push_back(Reg);
  82. }
  83. }
  84. unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2) {
  85. assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
  86. assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
  87. // find group for each register
  88. unsigned Group1 = GetGroup(Reg1);
  89. unsigned Group2 = GetGroup(Reg2);
  90. // if either group is 0, then that must become the parent
  91. unsigned Parent = (Group1 == 0) ? Group1 : Group2;
  92. unsigned Other = (Parent == Group1) ? Group2 : Group1;
  93. GroupNodes.at(Other) = Parent;
  94. return Parent;
  95. }
  96. unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg) {
  97. // Create a new GroupNode for Reg. Reg's existing GroupNode must
  98. // stay as is because there could be other GroupNodes referring to
  99. // it.
  100. unsigned idx = GroupNodes.size();
  101. GroupNodes.push_back(idx);
  102. GroupNodeIndices[Reg] = idx;
  103. return idx;
  104. }
  105. bool AggressiveAntiDepState::IsLive(unsigned Reg) {
  106. // KillIndex must be defined and DefIndex not defined for a register
  107. // to be live.
  108. return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
  109. }
  110. AggressiveAntiDepBreaker::AggressiveAntiDepBreaker(
  111. MachineFunction &MFi, const RegisterClassInfo &RCI,
  112. TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
  113. : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
  114. TII(MF.getSubtarget().getInstrInfo()),
  115. TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI) {
  116. /* Collect a bitset of all registers that are only broken if they
  117. are on the critical path. */
  118. for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
  119. BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
  120. if (CriticalPathSet.none())
  121. CriticalPathSet = CPSet;
  122. else
  123. CriticalPathSet |= CPSet;
  124. }
  125. LLVM_DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
  126. LLVM_DEBUG(for (unsigned r
  127. : CriticalPathSet.set_bits()) dbgs()
  128. << " " << printReg(r, TRI));
  129. LLVM_DEBUG(dbgs() << '\n');
  130. }
  131. AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
  132. delete State;
  133. }
  134. void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
  135. assert(!State);
  136. State = new AggressiveAntiDepState(TRI->getNumRegs(), BB);
  137. bool IsReturnBlock = BB->isReturnBlock();
  138. std::vector<unsigned> &KillIndices = State->GetKillIndices();
  139. std::vector<unsigned> &DefIndices = State->GetDefIndices();
  140. // Examine the live-in regs of all successors.
  141. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  142. SE = BB->succ_end(); SI != SE; ++SI)
  143. for (const auto &LI : (*SI)->liveins()) {
  144. for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {
  145. unsigned Reg = *AI;
  146. State->UnionGroups(Reg, 0);
  147. KillIndices[Reg] = BB->size();
  148. DefIndices[Reg] = ~0u;
  149. }
  150. }
  151. // Mark live-out callee-saved registers. In a return block this is
  152. // all callee-saved registers. In non-return this is any
  153. // callee-saved register that is not saved in the prolog.
  154. const MachineFrameInfo &MFI = MF.getFrameInfo();
  155. BitVector Pristine = MFI.getPristineRegs(MF);
  156. for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I;
  157. ++I) {
  158. unsigned Reg = *I;
  159. if (!IsReturnBlock && !Pristine.test(Reg))
  160. continue;
  161. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
  162. unsigned AliasReg = *AI;
  163. State->UnionGroups(AliasReg, 0);
  164. KillIndices[AliasReg] = BB->size();
  165. DefIndices[AliasReg] = ~0u;
  166. }
  167. }
  168. }
  169. void AggressiveAntiDepBreaker::FinishBlock() {
  170. delete State;
  171. State = nullptr;
  172. }
  173. void AggressiveAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count,
  174. unsigned InsertPosIndex) {
  175. assert(Count < InsertPosIndex && "Instruction index out of expected range!");
  176. std::set<unsigned> PassthruRegs;
  177. GetPassthruRegs(MI, PassthruRegs);
  178. PrescanInstruction(MI, Count, PassthruRegs);
  179. ScanInstruction(MI, Count);
  180. LLVM_DEBUG(dbgs() << "Observe: ");
  181. LLVM_DEBUG(MI.dump());
  182. LLVM_DEBUG(dbgs() << "\tRegs:");
  183. std::vector<unsigned> &DefIndices = State->GetDefIndices();
  184. for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
  185. // If Reg is current live, then mark that it can't be renamed as
  186. // we don't know the extent of its live-range anymore (now that it
  187. // has been scheduled). If it is not live but was defined in the
  188. // previous schedule region, then set its def index to the most
  189. // conservative location (i.e. the beginning of the previous
  190. // schedule region).
  191. if (State->IsLive(Reg)) {
  192. LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs()
  193. << " " << printReg(Reg, TRI) << "=g" << State->GetGroup(Reg)
  194. << "->g0(region live-out)");
  195. State->UnionGroups(Reg, 0);
  196. } else if ((DefIndices[Reg] < InsertPosIndex)
  197. && (DefIndices[Reg] >= Count)) {
  198. DefIndices[Reg] = Count;
  199. }
  200. }
  201. LLVM_DEBUG(dbgs() << '\n');
  202. }
  203. bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr &MI,
  204. MachineOperand &MO) {
  205. if (!MO.isReg() || !MO.isImplicit())
  206. return false;
  207. Register Reg = MO.getReg();
  208. if (Reg == 0)
  209. return false;
  210. MachineOperand *Op = nullptr;
  211. if (MO.isDef())
  212. Op = MI.findRegisterUseOperand(Reg, true);
  213. else
  214. Op = MI.findRegisterDefOperand(Reg);
  215. return(Op && Op->isImplicit());
  216. }
  217. void AggressiveAntiDepBreaker::GetPassthruRegs(
  218. MachineInstr &MI, std::set<unsigned> &PassthruRegs) {
  219. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  220. MachineOperand &MO = MI.getOperand(i);
  221. if (!MO.isReg()) continue;
  222. if ((MO.isDef() && MI.isRegTiedToUseOperand(i)) ||
  223. IsImplicitDefUse(MI, MO)) {
  224. const Register Reg = MO.getReg();
  225. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  226. SubRegs.isValid(); ++SubRegs)
  227. PassthruRegs.insert(*SubRegs);
  228. }
  229. }
  230. }
  231. /// AntiDepEdges - Return in Edges the anti- and output- dependencies
  232. /// in SU that we want to consider for breaking.
  233. static void AntiDepEdges(const SUnit *SU, std::vector<const SDep *> &Edges) {
  234. SmallSet<unsigned, 4> RegSet;
  235. for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
  236. P != PE; ++P) {
  237. if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
  238. if (RegSet.insert(P->getReg()).second)
  239. Edges.push_back(&*P);
  240. }
  241. }
  242. }
  243. /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
  244. /// critical path.
  245. static const SUnit *CriticalPathStep(const SUnit *SU) {
  246. const SDep *Next = nullptr;
  247. unsigned NextDepth = 0;
  248. // Find the predecessor edge with the greatest depth.
  249. if (SU) {
  250. for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
  251. P != PE; ++P) {
  252. const SUnit *PredSU = P->getSUnit();
  253. unsigned PredLatency = P->getLatency();
  254. unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
  255. // In the case of a latency tie, prefer an anti-dependency edge over
  256. // other types of edges.
  257. if (NextDepth < PredTotalLatency ||
  258. (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
  259. NextDepth = PredTotalLatency;
  260. Next = &*P;
  261. }
  262. }
  263. }
  264. return (Next) ? Next->getSUnit() : nullptr;
  265. }
  266. void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
  267. const char *tag,
  268. const char *header,
  269. const char *footer) {
  270. std::vector<unsigned> &KillIndices = State->GetKillIndices();
  271. std::vector<unsigned> &DefIndices = State->GetDefIndices();
  272. std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
  273. RegRefs = State->GetRegRefs();
  274. // FIXME: We must leave subregisters of live super registers as live, so that
  275. // we don't clear out the register tracking information for subregisters of
  276. // super registers we're still tracking (and with which we're unioning
  277. // subregister definitions).
  278. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  279. if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI)) {
  280. LLVM_DEBUG(if (!header && footer) dbgs() << footer);
  281. return;
  282. }
  283. if (!State->IsLive(Reg)) {
  284. KillIndices[Reg] = KillIdx;
  285. DefIndices[Reg] = ~0u;
  286. RegRefs.erase(Reg);
  287. State->LeaveGroup(Reg);
  288. LLVM_DEBUG(if (header) {
  289. dbgs() << header << printReg(Reg, TRI);
  290. header = nullptr;
  291. });
  292. LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << tag);
  293. // Repeat for subregisters. Note that we only do this if the superregister
  294. // was not live because otherwise, regardless whether we have an explicit
  295. // use of the subregister, the subregister's contents are needed for the
  296. // uses of the superregister.
  297. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  298. unsigned SubregReg = *SubRegs;
  299. if (!State->IsLive(SubregReg)) {
  300. KillIndices[SubregReg] = KillIdx;
  301. DefIndices[SubregReg] = ~0u;
  302. RegRefs.erase(SubregReg);
  303. State->LeaveGroup(SubregReg);
  304. LLVM_DEBUG(if (header) {
  305. dbgs() << header << printReg(Reg, TRI);
  306. header = nullptr;
  307. });
  308. LLVM_DEBUG(dbgs() << " " << printReg(SubregReg, TRI) << "->g"
  309. << State->GetGroup(SubregReg) << tag);
  310. }
  311. }
  312. }
  313. LLVM_DEBUG(if (!header && footer) dbgs() << footer);
  314. }
  315. void AggressiveAntiDepBreaker::PrescanInstruction(
  316. MachineInstr &MI, unsigned Count, std::set<unsigned> &PassthruRegs) {
  317. std::vector<unsigned> &DefIndices = State->GetDefIndices();
  318. std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
  319. RegRefs = State->GetRegRefs();
  320. // Handle dead defs by simulating a last-use of the register just
  321. // after the def. A dead def can occur because the def is truly
  322. // dead, or because only a subregister is live at the def. If we
  323. // don't do this the dead def will be incorrectly merged into the
  324. // previous def.
  325. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  326. MachineOperand &MO = MI.getOperand(i);
  327. if (!MO.isReg() || !MO.isDef()) continue;
  328. Register Reg = MO.getReg();
  329. if (Reg == 0) continue;
  330. HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
  331. }
  332. LLVM_DEBUG(dbgs() << "\tDef Groups:");
  333. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  334. MachineOperand &MO = MI.getOperand(i);
  335. if (!MO.isReg() || !MO.isDef()) continue;
  336. Register Reg = MO.getReg();
  337. if (Reg == 0) continue;
  338. LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI) << "=g"
  339. << State->GetGroup(Reg));
  340. // If MI's defs have a special allocation requirement, don't allow
  341. // any def registers to be changed. Also assume all registers
  342. // defined in a call must not be changed (ABI). Inline assembly may
  343. // reference either system calls or the register directly. Skip it until we
  344. // can tell user specified registers from compiler-specified.
  345. if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI) ||
  346. MI.isInlineAsm()) {
  347. LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
  348. State->UnionGroups(Reg, 0);
  349. }
  350. // Any aliased that are live at this point are completely or
  351. // partially defined here, so group those aliases with Reg.
  352. for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
  353. unsigned AliasReg = *AI;
  354. if (State->IsLive(AliasReg)) {
  355. State->UnionGroups(Reg, AliasReg);
  356. LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << "(via "
  357. << printReg(AliasReg, TRI) << ")");
  358. }
  359. }
  360. // Note register reference...
  361. const TargetRegisterClass *RC = nullptr;
  362. if (i < MI.getDesc().getNumOperands())
  363. RC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
  364. AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
  365. RegRefs.insert(std::make_pair(Reg, RR));
  366. }
  367. LLVM_DEBUG(dbgs() << '\n');
  368. // Scan the register defs for this instruction and update
  369. // live-ranges.
  370. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  371. MachineOperand &MO = MI.getOperand(i);
  372. if (!MO.isReg() || !MO.isDef()) continue;
  373. Register Reg = MO.getReg();
  374. if (Reg == 0) continue;
  375. // Ignore KILLs and passthru registers for liveness...
  376. if (MI.isKill() || (PassthruRegs.count(Reg) != 0))
  377. continue;
  378. // Update def for Reg and aliases.
  379. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
  380. // We need to be careful here not to define already-live super registers.
  381. // If the super register is already live, then this definition is not
  382. // a definition of the whole super register (just a partial insertion
  383. // into it). Earlier subregister definitions (which we've not yet visited
  384. // because we're iterating bottom-up) need to be linked to the same group
  385. // as this definition.
  386. if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI))
  387. continue;
  388. DefIndices[*AI] = Count;
  389. }
  390. }
  391. }
  392. void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr &MI,
  393. unsigned Count) {
  394. LLVM_DEBUG(dbgs() << "\tUse Groups:");
  395. std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
  396. RegRefs = State->GetRegRefs();
  397. // If MI's uses have special allocation requirement, don't allow
  398. // any use registers to be changed. Also assume all registers
  399. // used in a call must not be changed (ABI).
  400. // Inline Assembly register uses also cannot be safely changed.
  401. // FIXME: The issue with predicated instruction is more complex. We are being
  402. // conservatively here because the kill markers cannot be trusted after
  403. // if-conversion:
  404. // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
  405. // ...
  406. // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
  407. // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
  408. // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
  409. //
  410. // The first R6 kill is not really a kill since it's killed by a predicated
  411. // instruction which may not be executed. The second R6 def may or may not
  412. // re-define R6 so it's not safe to change it since the last R6 use cannot be
  413. // changed.
  414. bool Special = MI.isCall() || MI.hasExtraSrcRegAllocReq() ||
  415. TII->isPredicated(MI) || MI.isInlineAsm();
  416. // Scan the register uses for this instruction and update
  417. // live-ranges, groups and RegRefs.
  418. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  419. MachineOperand &MO = MI.getOperand(i);
  420. if (!MO.isReg() || !MO.isUse()) continue;
  421. Register Reg = MO.getReg();
  422. if (Reg == 0) continue;
  423. LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI) << "=g"
  424. << State->GetGroup(Reg));
  425. // It wasn't previously live but now it is, this is a kill. Forget
  426. // the previous live-range information and start a new live-range
  427. // for the register.
  428. HandleLastUse(Reg, Count, "(last-use)");
  429. if (Special) {
  430. LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
  431. State->UnionGroups(Reg, 0);
  432. }
  433. // Note register reference...
  434. const TargetRegisterClass *RC = nullptr;
  435. if (i < MI.getDesc().getNumOperands())
  436. RC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
  437. AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
  438. RegRefs.insert(std::make_pair(Reg, RR));
  439. }
  440. LLVM_DEBUG(dbgs() << '\n');
  441. // Form a group of all defs and uses of a KILL instruction to ensure
  442. // that all registers are renamed as a group.
  443. if (MI.isKill()) {
  444. LLVM_DEBUG(dbgs() << "\tKill Group:");
  445. unsigned FirstReg = 0;
  446. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  447. MachineOperand &MO = MI.getOperand(i);
  448. if (!MO.isReg()) continue;
  449. Register Reg = MO.getReg();
  450. if (Reg == 0) continue;
  451. if (FirstReg != 0) {
  452. LLVM_DEBUG(dbgs() << "=" << printReg(Reg, TRI));
  453. State->UnionGroups(FirstReg, Reg);
  454. } else {
  455. LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
  456. FirstReg = Reg;
  457. }
  458. }
  459. LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(FirstReg) << '\n');
  460. }
  461. }
  462. BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
  463. BitVector BV(TRI->getNumRegs(), false);
  464. bool first = true;
  465. // Check all references that need rewriting for Reg. For each, use
  466. // the corresponding register class to narrow the set of registers
  467. // that are appropriate for renaming.
  468. for (const auto &Q : make_range(State->GetRegRefs().equal_range(Reg))) {
  469. const TargetRegisterClass *RC = Q.second.RC;
  470. if (!RC) continue;
  471. BitVector RCBV = TRI->getAllocatableSet(MF, RC);
  472. if (first) {
  473. BV |= RCBV;
  474. first = false;
  475. } else {
  476. BV &= RCBV;
  477. }
  478. LLVM_DEBUG(dbgs() << " " << TRI->getRegClassName(RC));
  479. }
  480. return BV;
  481. }
  482. bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
  483. unsigned AntiDepGroupIndex,
  484. RenameOrderType& RenameOrder,
  485. std::map<unsigned, unsigned> &RenameMap) {
  486. std::vector<unsigned> &KillIndices = State->GetKillIndices();
  487. std::vector<unsigned> &DefIndices = State->GetDefIndices();
  488. std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
  489. RegRefs = State->GetRegRefs();
  490. // Collect all referenced registers in the same group as
  491. // AntiDepReg. These all need to be renamed together if we are to
  492. // break the anti-dependence.
  493. std::vector<unsigned> Regs;
  494. State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
  495. assert(!Regs.empty() && "Empty register group!");
  496. if (Regs.empty())
  497. return false;
  498. // Find the "superest" register in the group. At the same time,
  499. // collect the BitVector of registers that can be used to rename
  500. // each register.
  501. LLVM_DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
  502. << ":\n");
  503. std::map<unsigned, BitVector> RenameRegisterMap;
  504. unsigned SuperReg = 0;
  505. for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
  506. unsigned Reg = Regs[i];
  507. if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
  508. SuperReg = Reg;
  509. // If Reg has any references, then collect possible rename regs
  510. if (RegRefs.count(Reg) > 0) {
  511. LLVM_DEBUG(dbgs() << "\t\t" << printReg(Reg, TRI) << ":");
  512. BitVector &BV = RenameRegisterMap[Reg];
  513. assert(BV.empty());
  514. BV = GetRenameRegisters(Reg);
  515. LLVM_DEBUG({
  516. dbgs() << " ::";
  517. for (unsigned r : BV.set_bits())
  518. dbgs() << " " << printReg(r, TRI);
  519. dbgs() << "\n";
  520. });
  521. }
  522. }
  523. // All group registers should be a subreg of SuperReg.
  524. for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
  525. unsigned Reg = Regs[i];
  526. if (Reg == SuperReg) continue;
  527. bool IsSub = TRI->isSubRegister(SuperReg, Reg);
  528. // FIXME: remove this once PR18663 has been properly fixed. For now,
  529. // return a conservative answer:
  530. // assert(IsSub && "Expecting group subregister");
  531. if (!IsSub)
  532. return false;
  533. }
  534. #ifndef NDEBUG
  535. // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
  536. if (DebugDiv > 0) {
  537. static int renamecnt = 0;
  538. if (renamecnt++ % DebugDiv != DebugMod)
  539. return false;
  540. dbgs() << "*** Performing rename " << printReg(SuperReg, TRI)
  541. << " for debug ***\n";
  542. }
  543. #endif
  544. // Check each possible rename register for SuperReg in round-robin
  545. // order. If that register is available, and the corresponding
  546. // registers are available for the other group subregisters, then we
  547. // can use those registers to rename.
  548. // FIXME: Using getMinimalPhysRegClass is very conservative. We should
  549. // check every use of the register and find the largest register class
  550. // that can be used in all of them.
  551. const TargetRegisterClass *SuperRC =
  552. TRI->getMinimalPhysRegClass(SuperReg, MVT::Other);
  553. ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(SuperRC);
  554. if (Order.empty()) {
  555. LLVM_DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
  556. return false;
  557. }
  558. LLVM_DEBUG(dbgs() << "\tFind Registers:");
  559. RenameOrder.insert(RenameOrderType::value_type(SuperRC, Order.size()));
  560. unsigned OrigR = RenameOrder[SuperRC];
  561. unsigned EndR = ((OrigR == Order.size()) ? 0 : OrigR);
  562. unsigned R = OrigR;
  563. do {
  564. if (R == 0) R = Order.size();
  565. --R;
  566. const unsigned NewSuperReg = Order[R];
  567. // Don't consider non-allocatable registers
  568. if (!MRI.isAllocatable(NewSuperReg)) continue;
  569. // Don't replace a register with itself.
  570. if (NewSuperReg == SuperReg) continue;
  571. LLVM_DEBUG(dbgs() << " [" << printReg(NewSuperReg, TRI) << ':');
  572. RenameMap.clear();
  573. // For each referenced group register (which must be a SuperReg or
  574. // a subregister of SuperReg), find the corresponding subregister
  575. // of NewSuperReg and make sure it is free to be renamed.
  576. for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
  577. unsigned Reg = Regs[i];
  578. unsigned NewReg = 0;
  579. if (Reg == SuperReg) {
  580. NewReg = NewSuperReg;
  581. } else {
  582. unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
  583. if (NewSubRegIdx != 0)
  584. NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
  585. }
  586. LLVM_DEBUG(dbgs() << " " << printReg(NewReg, TRI));
  587. // Check if Reg can be renamed to NewReg.
  588. if (!RenameRegisterMap[Reg].test(NewReg)) {
  589. LLVM_DEBUG(dbgs() << "(no rename)");
  590. goto next_super_reg;
  591. }
  592. // If NewReg is dead and NewReg's most recent def is not before
  593. // Regs's kill, it's safe to replace Reg with NewReg. We
  594. // must also check all aliases of NewReg, because we can't define a
  595. // register when any sub or super is already live.
  596. if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
  597. LLVM_DEBUG(dbgs() << "(live)");
  598. goto next_super_reg;
  599. } else {
  600. bool found = false;
  601. for (MCRegAliasIterator AI(NewReg, TRI, false); AI.isValid(); ++AI) {
  602. unsigned AliasReg = *AI;
  603. if (State->IsLive(AliasReg) ||
  604. (KillIndices[Reg] > DefIndices[AliasReg])) {
  605. LLVM_DEBUG(dbgs()
  606. << "(alias " << printReg(AliasReg, TRI) << " live)");
  607. found = true;
  608. break;
  609. }
  610. }
  611. if (found)
  612. goto next_super_reg;
  613. }
  614. // We cannot rename 'Reg' to 'NewReg' if one of the uses of 'Reg' also
  615. // defines 'NewReg' via an early-clobber operand.
  616. for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
  617. MachineInstr *UseMI = Q.second.Operand->getParent();
  618. int Idx = UseMI->findRegisterDefOperandIdx(NewReg, false, true, TRI);
  619. if (Idx == -1)
  620. continue;
  621. if (UseMI->getOperand(Idx).isEarlyClobber()) {
  622. LLVM_DEBUG(dbgs() << "(ec)");
  623. goto next_super_reg;
  624. }
  625. }
  626. // Also, we cannot rename 'Reg' to 'NewReg' if the instruction defining
  627. // 'Reg' is an early-clobber define and that instruction also uses
  628. // 'NewReg'.
  629. for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
  630. if (!Q.second.Operand->isDef() || !Q.second.Operand->isEarlyClobber())
  631. continue;
  632. MachineInstr *DefMI = Q.second.Operand->getParent();
  633. if (DefMI->readsRegister(NewReg, TRI)) {
  634. LLVM_DEBUG(dbgs() << "(ec)");
  635. goto next_super_reg;
  636. }
  637. }
  638. // Record that 'Reg' can be renamed to 'NewReg'.
  639. RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
  640. }
  641. // If we fall-out here, then every register in the group can be
  642. // renamed, as recorded in RenameMap.
  643. RenameOrder.erase(SuperRC);
  644. RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
  645. LLVM_DEBUG(dbgs() << "]\n");
  646. return true;
  647. next_super_reg:
  648. LLVM_DEBUG(dbgs() << ']');
  649. } while (R != EndR);
  650. LLVM_DEBUG(dbgs() << '\n');
  651. // No registers are free and available!
  652. return false;
  653. }
  654. /// BreakAntiDependencies - Identifiy anti-dependencies within the
  655. /// ScheduleDAG and break them by renaming registers.
  656. unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
  657. const std::vector<SUnit> &SUnits,
  658. MachineBasicBlock::iterator Begin,
  659. MachineBasicBlock::iterator End,
  660. unsigned InsertPosIndex,
  661. DbgValueVector &DbgValues) {
  662. std::vector<unsigned> &KillIndices = State->GetKillIndices();
  663. std::vector<unsigned> &DefIndices = State->GetDefIndices();
  664. std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
  665. RegRefs = State->GetRegRefs();
  666. // The code below assumes that there is at least one instruction,
  667. // so just duck out immediately if the block is empty.
  668. if (SUnits.empty()) return 0;
  669. // For each regclass the next register to use for renaming.
  670. RenameOrderType RenameOrder;
  671. // ...need a map from MI to SUnit.
  672. std::map<MachineInstr *, const SUnit *> MISUnitMap;
  673. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  674. const SUnit *SU = &SUnits[i];
  675. MISUnitMap.insert(std::pair<MachineInstr *, const SUnit *>(SU->getInstr(),
  676. SU));
  677. }
  678. // Track progress along the critical path through the SUnit graph as
  679. // we walk the instructions. This is needed for regclasses that only
  680. // break critical-path anti-dependencies.
  681. const SUnit *CriticalPathSU = nullptr;
  682. MachineInstr *CriticalPathMI = nullptr;
  683. if (CriticalPathSet.any()) {
  684. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  685. const SUnit *SU = &SUnits[i];
  686. if (!CriticalPathSU ||
  687. ((SU->getDepth() + SU->Latency) >
  688. (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
  689. CriticalPathSU = SU;
  690. }
  691. }
  692. CriticalPathMI = CriticalPathSU->getInstr();
  693. }
  694. #ifndef NDEBUG
  695. LLVM_DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
  696. LLVM_DEBUG(dbgs() << "Available regs:");
  697. for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
  698. if (!State->IsLive(Reg))
  699. LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
  700. }
  701. LLVM_DEBUG(dbgs() << '\n');
  702. #endif
  703. BitVector RegAliases(TRI->getNumRegs());
  704. // Attempt to break anti-dependence edges. Walk the instructions
  705. // from the bottom up, tracking information about liveness as we go
  706. // to help determine which registers are available.
  707. unsigned Broken = 0;
  708. unsigned Count = InsertPosIndex - 1;
  709. for (MachineBasicBlock::iterator I = End, E = Begin;
  710. I != E; --Count) {
  711. MachineInstr &MI = *--I;
  712. if (MI.isDebugInstr())
  713. continue;
  714. LLVM_DEBUG(dbgs() << "Anti: ");
  715. LLVM_DEBUG(MI.dump());
  716. std::set<unsigned> PassthruRegs;
  717. GetPassthruRegs(MI, PassthruRegs);
  718. // Process the defs in MI...
  719. PrescanInstruction(MI, Count, PassthruRegs);
  720. // The dependence edges that represent anti- and output-
  721. // dependencies that are candidates for breaking.
  722. std::vector<const SDep *> Edges;
  723. const SUnit *PathSU = MISUnitMap[&MI];
  724. AntiDepEdges(PathSU, Edges);
  725. // If MI is not on the critical path, then we don't rename
  726. // registers in the CriticalPathSet.
  727. BitVector *ExcludeRegs = nullptr;
  728. if (&MI == CriticalPathMI) {
  729. CriticalPathSU = CriticalPathStep(CriticalPathSU);
  730. CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : nullptr;
  731. } else if (CriticalPathSet.any()) {
  732. ExcludeRegs = &CriticalPathSet;
  733. }
  734. // Ignore KILL instructions (they form a group in ScanInstruction
  735. // but don't cause any anti-dependence breaking themselves)
  736. if (!MI.isKill()) {
  737. // Attempt to break each anti-dependency...
  738. for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
  739. const SDep *Edge = Edges[i];
  740. SUnit *NextSU = Edge->getSUnit();
  741. if ((Edge->getKind() != SDep::Anti) &&
  742. (Edge->getKind() != SDep::Output)) continue;
  743. unsigned AntiDepReg = Edge->getReg();
  744. LLVM_DEBUG(dbgs() << "\tAntidep reg: " << printReg(AntiDepReg, TRI));
  745. assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
  746. if (!MRI.isAllocatable(AntiDepReg)) {
  747. // Don't break anti-dependencies on non-allocatable registers.
  748. LLVM_DEBUG(dbgs() << " (non-allocatable)\n");
  749. continue;
  750. } else if (ExcludeRegs && ExcludeRegs->test(AntiDepReg)) {
  751. // Don't break anti-dependencies for critical path registers
  752. // if not on the critical path
  753. LLVM_DEBUG(dbgs() << " (not critical-path)\n");
  754. continue;
  755. } else if (PassthruRegs.count(AntiDepReg) != 0) {
  756. // If the anti-dep register liveness "passes-thru", then
  757. // don't try to change it. It will be changed along with
  758. // the use if required to break an earlier antidep.
  759. LLVM_DEBUG(dbgs() << " (passthru)\n");
  760. continue;
  761. } else {
  762. // No anti-dep breaking for implicit deps
  763. MachineOperand *AntiDepOp = MI.findRegisterDefOperand(AntiDepReg);
  764. assert(AntiDepOp && "Can't find index for defined register operand");
  765. if (!AntiDepOp || AntiDepOp->isImplicit()) {
  766. LLVM_DEBUG(dbgs() << " (implicit)\n");
  767. continue;
  768. }
  769. // If the SUnit has other dependencies on the SUnit that
  770. // it anti-depends on, don't bother breaking the
  771. // anti-dependency since those edges would prevent such
  772. // units from being scheduled past each other
  773. // regardless.
  774. //
  775. // Also, if there are dependencies on other SUnits with the
  776. // same register as the anti-dependency, don't attempt to
  777. // break it.
  778. for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
  779. PE = PathSU->Preds.end(); P != PE; ++P) {
  780. if (P->getSUnit() == NextSU ?
  781. (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
  782. (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
  783. AntiDepReg = 0;
  784. break;
  785. }
  786. }
  787. for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
  788. PE = PathSU->Preds.end(); P != PE; ++P) {
  789. if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
  790. (P->getKind() != SDep::Output)) {
  791. LLVM_DEBUG(dbgs() << " (real dependency)\n");
  792. AntiDepReg = 0;
  793. break;
  794. } else if ((P->getSUnit() != NextSU) &&
  795. (P->getKind() == SDep::Data) &&
  796. (P->getReg() == AntiDepReg)) {
  797. LLVM_DEBUG(dbgs() << " (other dependency)\n");
  798. AntiDepReg = 0;
  799. break;
  800. }
  801. }
  802. if (AntiDepReg == 0) continue;
  803. // If the definition of the anti-dependency register does not start
  804. // a new live range, bail out. This can happen if the anti-dep
  805. // register is a sub-register of another register whose live range
  806. // spans over PathSU. In such case, PathSU defines only a part of
  807. // the larger register.
  808. RegAliases.reset();
  809. for (MCRegAliasIterator AI(AntiDepReg, TRI, true); AI.isValid(); ++AI)
  810. RegAliases.set(*AI);
  811. for (SDep S : PathSU->Succs) {
  812. SDep::Kind K = S.getKind();
  813. if (K != SDep::Data && K != SDep::Output && K != SDep::Anti)
  814. continue;
  815. unsigned R = S.getReg();
  816. if (!RegAliases[R])
  817. continue;
  818. if (R == AntiDepReg || TRI->isSubRegister(AntiDepReg, R))
  819. continue;
  820. AntiDepReg = 0;
  821. break;
  822. }
  823. if (AntiDepReg == 0) continue;
  824. }
  825. assert(AntiDepReg != 0);
  826. if (AntiDepReg == 0) continue;
  827. // Determine AntiDepReg's register group.
  828. const unsigned GroupIndex = State->GetGroup(AntiDepReg);
  829. if (GroupIndex == 0) {
  830. LLVM_DEBUG(dbgs() << " (zero group)\n");
  831. continue;
  832. }
  833. LLVM_DEBUG(dbgs() << '\n');
  834. // Look for a suitable register to use to break the anti-dependence.
  835. std::map<unsigned, unsigned> RenameMap;
  836. if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
  837. LLVM_DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
  838. << printReg(AntiDepReg, TRI) << ":");
  839. // Handle each group register...
  840. for (std::map<unsigned, unsigned>::iterator
  841. S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
  842. unsigned CurrReg = S->first;
  843. unsigned NewReg = S->second;
  844. LLVM_DEBUG(dbgs() << " " << printReg(CurrReg, TRI) << "->"
  845. << printReg(NewReg, TRI) << "("
  846. << RegRefs.count(CurrReg) << " refs)");
  847. // Update the references to the old register CurrReg to
  848. // refer to the new register NewReg.
  849. for (const auto &Q : make_range(RegRefs.equal_range(CurrReg))) {
  850. Q.second.Operand->setReg(NewReg);
  851. // If the SU for the instruction being updated has debug
  852. // information related to the anti-dependency register, make
  853. // sure to update that as well.
  854. const SUnit *SU = MISUnitMap[Q.second.Operand->getParent()];
  855. if (!SU) continue;
  856. UpdateDbgValues(DbgValues, Q.second.Operand->getParent(),
  857. AntiDepReg, NewReg);
  858. }
  859. // We just went back in time and modified history; the
  860. // liveness information for CurrReg is now inconsistent. Set
  861. // the state as if it were dead.
  862. State->UnionGroups(NewReg, 0);
  863. RegRefs.erase(NewReg);
  864. DefIndices[NewReg] = DefIndices[CurrReg];
  865. KillIndices[NewReg] = KillIndices[CurrReg];
  866. State->UnionGroups(CurrReg, 0);
  867. RegRefs.erase(CurrReg);
  868. DefIndices[CurrReg] = KillIndices[CurrReg];
  869. KillIndices[CurrReg] = ~0u;
  870. assert(((KillIndices[CurrReg] == ~0u) !=
  871. (DefIndices[CurrReg] == ~0u)) &&
  872. "Kill and Def maps aren't consistent for AntiDepReg!");
  873. }
  874. ++Broken;
  875. LLVM_DEBUG(dbgs() << '\n');
  876. }
  877. }
  878. }
  879. ScanInstruction(MI, Count);
  880. }
  881. return Broken;
  882. }