GIMatchTree.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. //===- GIMatchTree.cpp - A decision tree to match GIMatchDag's ------------===//
  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 "GIMatchTree.h"
  9. #include "GIMatchDagPredicate.h"
  10. #include "../CodeGenInstruction.h"
  11. #include "llvm/Support/Debug.h"
  12. #include "llvm/Support/Format.h"
  13. #include "llvm/Support/ScopedPrinter.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. #include "llvm/TableGen/Error.h"
  16. #include "llvm/TableGen/Record.h"
  17. #define DEBUG_TYPE "gimatchtree"
  18. using namespace llvm;
  19. void GIMatchTree::writeDOTGraph(raw_ostream &OS) const {
  20. OS << "digraph \"matchtree\" {\n";
  21. writeDOTGraphNode(OS);
  22. OS << "}\n";
  23. }
  24. void GIMatchTree::writeDOTGraphNode(raw_ostream &OS) const {
  25. OS << format(" Node%p", this) << " [shape=record,label=\"{";
  26. if (Partitioner) {
  27. Partitioner->emitDescription(OS);
  28. OS << "|" << Partitioner->getNumPartitions() << " partitions|";
  29. } else
  30. OS << "No partitioner|";
  31. bool IsFullyTraversed = true;
  32. bool IsFullyTested = true;
  33. StringRef Separator = "";
  34. for (const auto &Leaf : PossibleLeaves) {
  35. OS << Separator << Leaf.getName();
  36. Separator = ",";
  37. if (!Leaf.isFullyTraversed())
  38. IsFullyTraversed = false;
  39. if (!Leaf.isFullyTested())
  40. IsFullyTested = false;
  41. }
  42. if (!Partitioner && !IsFullyTraversed)
  43. OS << "|Not fully traversed";
  44. if (!Partitioner && !IsFullyTested) {
  45. OS << "|Not fully tested";
  46. if (IsFullyTraversed) {
  47. for (const GIMatchTreeLeafInfo &Leaf : PossibleLeaves) {
  48. if (Leaf.isFullyTested())
  49. continue;
  50. OS << "\\n" << Leaf.getName() << ": " << &Leaf;
  51. for (const GIMatchDagPredicate *P : Leaf.untested_predicates())
  52. OS << *P;
  53. }
  54. }
  55. }
  56. OS << "}\"";
  57. if (!Partitioner &&
  58. (!IsFullyTraversed || !IsFullyTested || PossibleLeaves.size() > 1))
  59. OS << ",color=red";
  60. OS << "]\n";
  61. for (const auto &C : Children)
  62. C.writeDOTGraphNode(OS);
  63. writeDOTGraphEdges(OS);
  64. }
  65. void GIMatchTree::writeDOTGraphEdges(raw_ostream &OS) const {
  66. for (const auto &Child : enumerate(Children)) {
  67. OS << format(" Node%p", this) << " -> " << format("Node%p", &Child.value())
  68. << " [label=\"#" << Child.index() << " ";
  69. Partitioner->emitPartitionName(OS, Child.index());
  70. OS << "\"]\n";
  71. }
  72. }
  73. GIMatchTreeBuilderLeafInfo::GIMatchTreeBuilderLeafInfo(
  74. GIMatchTreeBuilder &Builder, StringRef Name, unsigned RootIdx,
  75. const GIMatchDag &MatchDag, void *Data)
  76. : Builder(Builder), Info(Name, RootIdx, Data), MatchDag(MatchDag),
  77. RemainingInstrNodes(BitVector(MatchDag.getNumInstrNodes(), true)),
  78. RemainingEdges(BitVector(MatchDag.getNumEdges(), true)),
  79. RemainingPredicates(BitVector(MatchDag.getNumPredicates(), true)),
  80. TraversableEdges(MatchDag.getNumEdges()),
  81. TestablePredicates(MatchDag.getNumPredicates()) {
  82. // Number all the predicates in this DAG
  83. for (auto &P : enumerate(MatchDag.predicates())) {
  84. PredicateIDs.insert(std::make_pair(P.value(), P.index()));
  85. }
  86. // Number all the predicate dependencies in this DAG and set up a bitvector
  87. // for each predicate indicating the unsatisfied dependencies.
  88. for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
  89. PredicateDepIDs.insert(std::make_pair(Dep.value(), Dep.index()));
  90. }
  91. UnsatisfiedPredDepsForPred.resize(MatchDag.getNumPredicates(),
  92. BitVector(PredicateDepIDs.size()));
  93. for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
  94. unsigned ID = PredicateIDs.lookup(Dep.value()->getPredicate());
  95. UnsatisfiedPredDepsForPred[ID].set(Dep.index());
  96. }
  97. }
  98. void GIMatchTreeBuilderLeafInfo::declareInstr(const GIMatchDagInstr *Instr, unsigned ID) {
  99. // Record the assignment of this instr to the given ID.
  100. auto InfoI = InstrNodeToInfo.insert(std::make_pair(
  101. Instr, GIMatchTreeInstrInfo(ID, Instr)));
  102. InstrIDToInfo.insert(std::make_pair(ID, &InfoI.first->second));
  103. if (Instr == nullptr)
  104. return;
  105. if (!Instr->getUserAssignedName().empty())
  106. Info.bindInstrVariable(Instr->getUserAssignedName(), ID);
  107. for (const auto &VarBinding : Instr->user_assigned_operand_names())
  108. Info.bindOperandVariable(VarBinding.second, ID, VarBinding.first);
  109. // Clear the bit indicating we haven't visited this instr.
  110. const auto &NodeI = find(MatchDag.instr_nodes(), Instr);
  111. assert(NodeI != MatchDag.instr_nodes_end() && "Instr isn't in this DAG");
  112. unsigned InstrIdx = MatchDag.getInstrNodeIdx(NodeI);
  113. RemainingInstrNodes.reset(InstrIdx);
  114. // When we declare an instruction, we don't expose any traversable edges just
  115. // yet. A partitioner has to check they exist and are registers before they
  116. // are traversable.
  117. // When we declare an instruction, we potentially activate some predicates.
  118. // Mark the dependencies that are now satisfied as a result of this
  119. // instruction and mark any predicates whose dependencies are fully
  120. // satisfied.
  121. for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
  122. if (Dep.value()->getRequiredMI() == Instr &&
  123. Dep.value()->getRequiredMO() == nullptr) {
  124. for (auto &DepsFor : enumerate(UnsatisfiedPredDepsForPred)) {
  125. DepsFor.value().reset(Dep.index());
  126. if (DepsFor.value().none())
  127. TestablePredicates.set(DepsFor.index());
  128. }
  129. }
  130. }
  131. }
  132. void GIMatchTreeBuilderLeafInfo::declareOperand(unsigned InstrID,
  133. unsigned OpIdx) {
  134. const GIMatchDagInstr *Instr = InstrIDToInfo.lookup(InstrID)->getInstrNode();
  135. OperandIDToInfo.insert(std::make_pair(
  136. std::make_pair(InstrID, OpIdx),
  137. GIMatchTreeOperandInfo(Instr, OpIdx)));
  138. // When an operand becomes reachable, we potentially activate some traversals.
  139. // Record the edges that can now be followed as a result of this
  140. // instruction.
  141. for (auto &E : enumerate(MatchDag.edges())) {
  142. if (E.value()->getFromMI() == Instr &&
  143. E.value()->getFromMO()->getIdx() == OpIdx) {
  144. TraversableEdges.set(E.index());
  145. }
  146. }
  147. // When an operand becomes reachable, we potentially activate some predicates.
  148. // Clear the dependencies that are now satisfied as a result of this
  149. // operand and activate any predicates whose dependencies are fully
  150. // satisfied.
  151. for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
  152. if (Dep.value()->getRequiredMI() == Instr && Dep.value()->getRequiredMO() &&
  153. Dep.value()->getRequiredMO()->getIdx() == OpIdx) {
  154. for (auto &DepsFor : enumerate(UnsatisfiedPredDepsForPred)) {
  155. DepsFor.value().reset(Dep.index());
  156. if (DepsFor.value().none())
  157. TestablePredicates.set(DepsFor.index());
  158. }
  159. }
  160. }
  161. }
  162. void GIMatchTreeBuilder::addPartitionersForInstr(unsigned InstrIdx) {
  163. // Find the partitioners that can be used now that this node is
  164. // uncovered. Our choices are:
  165. // - Test the opcode
  166. addPartitioner(std::make_unique<GIMatchTreeOpcodePartitioner>(InstrIdx));
  167. }
  168. void GIMatchTreeBuilder::addPartitionersForOperand(unsigned InstrID,
  169. unsigned OpIdx) {
  170. LLVM_DEBUG(dbgs() << "Add partitioners for Instrs[" << InstrID
  171. << "].getOperand(" << OpIdx << ")\n");
  172. addPartitioner(
  173. std::make_unique<GIMatchTreeVRegDefPartitioner>(InstrID, OpIdx));
  174. }
  175. void GIMatchTreeBuilder::filterRedundantPartitioners() {
  176. // TODO: Filter partitioners for facts that are already known
  177. // - If we know the opcode, we can elide the num operand check so long as
  178. // the instruction has a fixed number of operands.
  179. // - If we know an exact number of operands then we can elide further number
  180. // of operand checks.
  181. // - If the current min number of operands exceeds the one we want to check
  182. // then we can elide it.
  183. }
  184. void GIMatchTreeBuilder::evaluatePartitioners() {
  185. // Determine the partitioning the partitioner would produce
  186. for (auto &Partitioner : Partitioners) {
  187. LLVM_DEBUG(dbgs() << " Weighing up ";
  188. Partitioner->emitDescription(dbgs()); dbgs() << "\n");
  189. Partitioner->repartition(Leaves);
  190. LLVM_DEBUG(Partitioner->emitPartitionResults(dbgs()));
  191. }
  192. }
  193. void GIMatchTreeBuilder::runStep() {
  194. LLVM_DEBUG(dbgs() << "Building match tree node for " << TreeNode << "\n");
  195. LLVM_DEBUG(dbgs() << " Rules reachable at this node:\n");
  196. for (const auto &Leaf : Leaves) {
  197. LLVM_DEBUG(dbgs() << " " << Leaf.getName() << " (" << &Leaf.getInfo() << "\n");
  198. TreeNode->addPossibleLeaf(Leaf.getInfo(), Leaf.isFullyTraversed(),
  199. Leaf.isFullyTested());
  200. }
  201. LLVM_DEBUG(dbgs() << " Partitioners available at this node:\n");
  202. #ifndef NDEBUG
  203. for (const auto &Partitioner : Partitioners)
  204. LLVM_DEBUG(dbgs() << " "; Partitioner->emitDescription(dbgs());
  205. dbgs() << "\n");
  206. #endif // ifndef NDEBUG
  207. // Check for unreachable rules. Rules are unreachable if they are preceeded by
  208. // a fully tested rule.
  209. // Note: This is only true for the current algorithm, if we allow the
  210. // algorithm to compare equally valid rules then they will become
  211. // reachable.
  212. {
  213. auto FullyTestedLeafI = Leaves.end();
  214. for (auto LeafI = Leaves.begin(), LeafE = Leaves.end();
  215. LeafI != LeafE; ++LeafI) {
  216. if (LeafI->isFullyTraversed() && LeafI->isFullyTested())
  217. FullyTestedLeafI = LeafI;
  218. else if (FullyTestedLeafI != Leaves.end()) {
  219. PrintError("Leaf " + LeafI->getName() + " is unreachable");
  220. PrintNote("Leaf " + FullyTestedLeafI->getName() +
  221. " will have already matched");
  222. }
  223. }
  224. }
  225. LLVM_DEBUG(dbgs() << " Eliminating redundant partitioners:\n");
  226. filterRedundantPartitioners();
  227. LLVM_DEBUG(dbgs() << " Partitioners remaining:\n");
  228. #ifndef NDEBUG
  229. for (const auto &Partitioner : Partitioners)
  230. LLVM_DEBUG(dbgs() << " "; Partitioner->emitDescription(dbgs());
  231. dbgs() << "\n");
  232. #endif // ifndef NDEBUG
  233. if (Partitioners.empty()) {
  234. // Nothing left to do but check we really did identify a single rule.
  235. if (Leaves.size() > 1) {
  236. LLVM_DEBUG(dbgs() << "Leaf contains multiple rules, drop after the first "
  237. "fully tested rule\n");
  238. auto FirstFullyTested =
  239. llvm::find_if(Leaves, [](const GIMatchTreeBuilderLeafInfo &X) {
  240. return X.isFullyTraversed() && X.isFullyTested() &&
  241. !X.getMatchDag().hasPostMatchPredicate();
  242. });
  243. if (FirstFullyTested != Leaves.end())
  244. FirstFullyTested++;
  245. #ifndef NDEBUG
  246. for (auto &Leaf : make_range(Leaves.begin(), FirstFullyTested))
  247. LLVM_DEBUG(dbgs() << " Kept " << Leaf.getName() << "\n");
  248. for (const auto &Leaf : make_range(FirstFullyTested, Leaves.end()))
  249. LLVM_DEBUG(dbgs() << " Dropped " << Leaf.getName() << "\n");
  250. #endif // ifndef NDEBUG
  251. TreeNode->dropLeavesAfter(
  252. std::distance(Leaves.begin(), FirstFullyTested));
  253. }
  254. for (const auto &Leaf : Leaves) {
  255. if (!Leaf.isFullyTraversed()) {
  256. PrintError("Leaf " + Leaf.getName() + " is not fully traversed");
  257. PrintNote("This indicates a missing partitioner within tblgen");
  258. Leaf.dump(errs());
  259. for (unsigned InstrIdx : Leaf.untested_instrs())
  260. PrintNote("Instr " + llvm::to_string(*Leaf.getInstr(InstrIdx)));
  261. for (unsigned EdgeIdx : Leaf.untested_edges())
  262. PrintNote("Edge " + llvm::to_string(*Leaf.getEdge(EdgeIdx)));
  263. }
  264. }
  265. // Copy out information about untested predicates so the user of the tree
  266. // can deal with them.
  267. for (auto LeafPair : zip(Leaves, TreeNode->possible_leaves())) {
  268. const GIMatchTreeBuilderLeafInfo &BuilderLeaf = std::get<0>(LeafPair);
  269. GIMatchTreeLeafInfo &TreeLeaf = std::get<1>(LeafPair);
  270. if (!BuilderLeaf.isFullyTested())
  271. for (unsigned PredicateIdx : BuilderLeaf.untested_predicates())
  272. TreeLeaf.addUntestedPredicate(BuilderLeaf.getPredicate(PredicateIdx));
  273. }
  274. return;
  275. }
  276. LLVM_DEBUG(dbgs() << " Weighing up partitioners:\n");
  277. evaluatePartitioners();
  278. // Select the best partitioner by its ability to partition
  279. // - Prefer partitioners that don't distinguish between partitions. This
  280. // is to fail early on decisions that must go a single way.
  281. auto PartitionerI = std::max_element(
  282. Partitioners.begin(), Partitioners.end(),
  283. [](const std::unique_ptr<GIMatchTreePartitioner> &A,
  284. const std::unique_ptr<GIMatchTreePartitioner> &B) {
  285. // We generally want partitioners that subdivide the
  286. // ruleset as much as possible since these take fewer
  287. // checks to converge on a particular rule. However,
  288. // it's important to note that one leaf can end up in
  289. // multiple partitions if the check isn't mutually
  290. // exclusive (e.g. getVRegDef() vs isReg()).
  291. // We therefore minimize average leaves per partition.
  292. return (double)A->getNumLeavesWithDupes() / A->getNumPartitions() >
  293. (double)B->getNumLeavesWithDupes() / B->getNumPartitions();
  294. });
  295. // Select a partitioner and partition the ruleset
  296. // Note that it's possible for a single rule to end up in multiple
  297. // partitions. For example, an opcode test on a rule without an opcode
  298. // predicate will result in it being passed to all partitions.
  299. std::unique_ptr<GIMatchTreePartitioner> Partitioner = std::move(*PartitionerI);
  300. Partitioners.erase(PartitionerI);
  301. LLVM_DEBUG(dbgs() << " Selected partitioner: ";
  302. Partitioner->emitDescription(dbgs()); dbgs() << "\n");
  303. assert(Partitioner->getNumPartitions() > 0 &&
  304. "Must always partition into at least one partition");
  305. TreeNode->setNumChildren(Partitioner->getNumPartitions());
  306. for (auto &C : enumerate(TreeNode->children())) {
  307. SubtreeBuilders.emplace_back(&C.value(), NextInstrID);
  308. Partitioner->applyForPartition(C.index(), *this, SubtreeBuilders.back());
  309. }
  310. TreeNode->setPartitioner(std::move(Partitioner));
  311. // Recurse into the subtree builders. Each one must get a copy of the
  312. // remaining partitioners as each path has to check everything.
  313. for (auto &SubtreeBuilder : SubtreeBuilders) {
  314. for (const auto &Partitioner : Partitioners)
  315. SubtreeBuilder.addPartitioner(Partitioner->clone());
  316. SubtreeBuilder.runStep();
  317. }
  318. }
  319. std::unique_ptr<GIMatchTree> GIMatchTreeBuilder::run() {
  320. unsigned NewInstrID = allocInstrID();
  321. // Start by recording the root instruction as instr #0 and set up the initial
  322. // partitioners.
  323. for (auto &Leaf : Leaves) {
  324. LLVM_DEBUG(Leaf.getMatchDag().writeDOTGraph(dbgs(), Leaf.getName()));
  325. GIMatchDagInstr *Root =
  326. *(Leaf.getMatchDag().roots().begin() + Leaf.getRootIdx());
  327. Leaf.declareInstr(Root, NewInstrID);
  328. }
  329. addPartitionersForInstr(NewInstrID);
  330. std::unique_ptr<GIMatchTree> TreeRoot = std::make_unique<GIMatchTree>();
  331. TreeNode = TreeRoot.get();
  332. runStep();
  333. return TreeRoot;
  334. }
  335. void GIMatchTreeOpcodePartitioner::emitPartitionName(raw_ostream &OS, unsigned Idx) const {
  336. if (PartitionToInstr[Idx] == nullptr) {
  337. OS << "* or nullptr";
  338. return;
  339. }
  340. OS << PartitionToInstr[Idx]->Namespace
  341. << "::" << PartitionToInstr[Idx]->TheDef->getName();
  342. }
  343. void GIMatchTreeOpcodePartitioner::repartition(
  344. GIMatchTreeBuilder::LeafVec &Leaves) {
  345. Partitions.clear();
  346. InstrToPartition.clear();
  347. PartitionToInstr.clear();
  348. TestedPredicates.clear();
  349. for (const auto &Leaf : enumerate(Leaves)) {
  350. bool AllOpcodes = true;
  351. GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
  352. BitVector TestedPredicatesForLeaf(
  353. Leaf.value().getMatchDag().getNumPredicates());
  354. // If the instruction isn't declared then we don't care about it. Ignore
  355. // it for now and add it to all partitions later once we know what
  356. // partitions we have.
  357. if (!InstrInfo) {
  358. LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
  359. << " doesn't care about Instr[" << InstrID << "]\n");
  360. assert(TestedPredicatesForLeaf.size() == Leaf.value().getMatchDag().getNumPredicates());
  361. TestedPredicates.push_back(TestedPredicatesForLeaf);
  362. continue;
  363. }
  364. // If the opcode is available to test then any opcode predicates will have
  365. // been enabled too.
  366. for (unsigned PIdx : Leaf.value().TestablePredicates.set_bits()) {
  367. const auto &P = Leaf.value().getPredicate(PIdx);
  368. SmallVector<const CodeGenInstruction *, 1> OpcodesForThisPredicate;
  369. if (const auto *OpcodeP = dyn_cast<const GIMatchDagOpcodePredicate>(P)) {
  370. // We've found _an_ opcode predicate, but we don't know if it's
  371. // checking this instruction yet.
  372. bool IsThisPredicate = false;
  373. for (const auto &PDep : Leaf.value().getMatchDag().predicate_edges()) {
  374. if (PDep->getRequiredMI() == InstrInfo->getInstrNode() &&
  375. PDep->getRequiredMO() == nullptr && PDep->getPredicate() == P) {
  376. IsThisPredicate = true;
  377. break;
  378. }
  379. }
  380. if (!IsThisPredicate)
  381. continue;
  382. // If we get here twice then we've somehow ended up with two opcode
  383. // predicates for one instruction in the same DAG. That should be
  384. // impossible.
  385. assert(AllOpcodes && "Conflicting opcode predicates");
  386. const CodeGenInstruction *Expected = OpcodeP->getInstr();
  387. OpcodesForThisPredicate.push_back(Expected);
  388. }
  389. if (const auto *OpcodeP =
  390. dyn_cast<const GIMatchDagOneOfOpcodesPredicate>(P)) {
  391. // We've found _an_ oneof(opcodes) predicate, but we don't know if it's
  392. // checking this instruction yet.
  393. bool IsThisPredicate = false;
  394. for (const auto &PDep : Leaf.value().getMatchDag().predicate_edges()) {
  395. if (PDep->getRequiredMI() == InstrInfo->getInstrNode() &&
  396. PDep->getRequiredMO() == nullptr && PDep->getPredicate() == P) {
  397. IsThisPredicate = true;
  398. break;
  399. }
  400. }
  401. if (!IsThisPredicate)
  402. continue;
  403. // If we get here twice then we've somehow ended up with two opcode
  404. // predicates for one instruction in the same DAG. That should be
  405. // impossible.
  406. assert(AllOpcodes && "Conflicting opcode predicates");
  407. append_range(OpcodesForThisPredicate, OpcodeP->getInstrs());
  408. }
  409. for (const CodeGenInstruction *Expected : OpcodesForThisPredicate) {
  410. // Mark this predicate as one we're testing.
  411. TestedPredicatesForLeaf.set(PIdx);
  412. // Partitions must be numbered 0, 1, .., N but instructions don't meet
  413. // that requirement. Assign a partition number to each opcode if we
  414. // lack one ...
  415. auto Partition = InstrToPartition.find(Expected);
  416. if (Partition == InstrToPartition.end()) {
  417. BitVector Contents(Leaves.size());
  418. Partition = InstrToPartition
  419. .insert(std::make_pair(Expected, Partitions.size()))
  420. .first;
  421. PartitionToInstr.push_back(Expected);
  422. Partitions.insert(std::make_pair(Partitions.size(), Contents));
  423. }
  424. // ... and mark this leaf as being in that partition.
  425. Partitions.find(Partition->second)->second.set(Leaf.index());
  426. AllOpcodes = false;
  427. LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
  428. << " is in partition " << Partition->second << "\n");
  429. }
  430. // TODO: This is where we would handle multiple choices of opcode
  431. // the end result will be that this leaf ends up in multiple
  432. // partitions similarly to AllOpcodes.
  433. }
  434. // If we never check the opcode, add it to every partition.
  435. if (AllOpcodes) {
  436. // Add a partition for the default case if we don't already have one.
  437. if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
  438. PartitionToInstr.push_back(nullptr);
  439. BitVector Contents(Leaves.size());
  440. Partitions.insert(std::make_pair(Partitions.size(), Contents));
  441. }
  442. LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
  443. << " is in all partitions (opcode not checked)\n");
  444. for (auto &Partition : Partitions)
  445. Partition.second.set(Leaf.index());
  446. }
  447. assert(TestedPredicatesForLeaf.size() == Leaf.value().getMatchDag().getNumPredicates());
  448. TestedPredicates.push_back(TestedPredicatesForLeaf);
  449. }
  450. if (Partitions.size() == 0) {
  451. // Add a partition for the default case if we don't already have one.
  452. if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
  453. PartitionToInstr.push_back(nullptr);
  454. BitVector Contents(Leaves.size());
  455. Partitions.insert(std::make_pair(Partitions.size(), Contents));
  456. }
  457. }
  458. // Add any leaves that don't care about this instruction to all partitions.
  459. for (const auto &Leaf : enumerate(Leaves)) {
  460. GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
  461. if (!InstrInfo) {
  462. // Add a partition for the default case if we don't already have one.
  463. if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
  464. PartitionToInstr.push_back(nullptr);
  465. BitVector Contents(Leaves.size());
  466. Partitions.insert(std::make_pair(Partitions.size(), Contents));
  467. }
  468. for (auto &Partition : Partitions)
  469. Partition.second.set(Leaf.index());
  470. }
  471. }
  472. }
  473. void GIMatchTreeOpcodePartitioner::applyForPartition(
  474. unsigned PartitionIdx, GIMatchTreeBuilder &Builder, GIMatchTreeBuilder &SubBuilder) {
  475. LLVM_DEBUG(dbgs() << " Making partition " << PartitionIdx << "\n");
  476. const CodeGenInstruction *CGI = PartitionToInstr[PartitionIdx];
  477. BitVector PossibleLeaves = getPossibleLeavesForPartition(PartitionIdx);
  478. // Consume any predicates we handled.
  479. for (auto &EnumeratedLeaf : enumerate(Builder.getPossibleLeaves())) {
  480. if (!PossibleLeaves[EnumeratedLeaf.index()])
  481. continue;
  482. auto &Leaf = EnumeratedLeaf.value();
  483. const auto &TestedPredicatesForLeaf =
  484. TestedPredicates[EnumeratedLeaf.index()];
  485. for (unsigned PredIdx : TestedPredicatesForLeaf.set_bits()) {
  486. LLVM_DEBUG(dbgs() << " " << Leaf.getName() << " tested predicate #"
  487. << PredIdx << " of " << TestedPredicatesForLeaf.size()
  488. << " " << *Leaf.getPredicate(PredIdx) << "\n");
  489. Leaf.RemainingPredicates.reset(PredIdx);
  490. Leaf.TestablePredicates.reset(PredIdx);
  491. }
  492. SubBuilder.addLeaf(Leaf);
  493. }
  494. // Nothing to do, we don't know anything about this instruction as a result
  495. // of this partitioner.
  496. if (CGI == nullptr)
  497. return;
  498. GIMatchTreeBuilder::LeafVec &NewLeaves = SubBuilder.getPossibleLeaves();
  499. // Find all the operands we know to exist and are referenced. This will
  500. // usually be all the referenced operands but there are some cases where
  501. // instructions are variadic. Such operands must be handled by partitioners
  502. // that check the number of operands.
  503. BitVector ReferencedOperands(1);
  504. for (auto &Leaf : NewLeaves) {
  505. GIMatchTreeInstrInfo *InstrInfo = Leaf.getInstrInfo(InstrID);
  506. // Skip any leaves that don't care about this instruction.
  507. if (!InstrInfo)
  508. continue;
  509. const GIMatchDagInstr *Instr = InstrInfo->getInstrNode();
  510. for (auto &E : enumerate(Leaf.getMatchDag().edges())) {
  511. if (E.value()->getFromMI() == Instr &&
  512. E.value()->getFromMO()->getIdx() < CGI->Operands.size()) {
  513. ReferencedOperands.resize(E.value()->getFromMO()->getIdx() + 1);
  514. ReferencedOperands.set(E.value()->getFromMO()->getIdx());
  515. }
  516. }
  517. }
  518. for (auto &Leaf : NewLeaves) {
  519. for (unsigned OpIdx : ReferencedOperands.set_bits()) {
  520. Leaf.declareOperand(InstrID, OpIdx);
  521. }
  522. }
  523. for (unsigned OpIdx : ReferencedOperands.set_bits()) {
  524. SubBuilder.addPartitionersForOperand(InstrID, OpIdx);
  525. }
  526. }
  527. void GIMatchTreeOpcodePartitioner::emitPartitionResults(
  528. raw_ostream &OS) const {
  529. OS << "Partitioning by opcode would produce " << Partitions.size()
  530. << " partitions\n";
  531. for (const auto &Partition : InstrToPartition) {
  532. if (Partition.first == nullptr)
  533. OS << "Default: ";
  534. else
  535. OS << Partition.first->TheDef->getName() << ": ";
  536. StringRef Separator = "";
  537. for (unsigned I : Partitions.find(Partition.second)->second.set_bits()) {
  538. OS << Separator << I;
  539. Separator = ", ";
  540. }
  541. OS << "\n";
  542. }
  543. }
  544. void GIMatchTreeOpcodePartitioner::generatePartitionSelectorCode(
  545. raw_ostream &OS, StringRef Indent) const {
  546. // Make sure not to emit empty switch or switch with just default
  547. if (PartitionToInstr.size() == 1 && PartitionToInstr[0] == nullptr) {
  548. OS << Indent << "Partition = 0;\n";
  549. } else if (PartitionToInstr.size()) {
  550. OS << Indent << "Partition = -1;\n"
  551. << Indent << "switch (MIs[" << InstrID << "]->getOpcode()) {\n";
  552. for (const auto &EnumInstr : enumerate(PartitionToInstr)) {
  553. if (EnumInstr.value() == nullptr)
  554. OS << Indent << "default:";
  555. else
  556. OS << Indent << "case " << EnumInstr.value()->Namespace
  557. << "::" << EnumInstr.value()->TheDef->getName() << ":";
  558. OS << " Partition = " << EnumInstr.index() << "; break;\n";
  559. }
  560. OS << Indent << "}\n";
  561. }
  562. OS << Indent
  563. << "// Default case but without conflicting with potential default case "
  564. "in selection.\n"
  565. << Indent << "if (Partition == -1) return false;\n";
  566. }
  567. void GIMatchTreeVRegDefPartitioner::addToPartition(bool Result,
  568. unsigned LeafIdx) {
  569. auto I = ResultToPartition.find(Result);
  570. if (I == ResultToPartition.end()) {
  571. ResultToPartition.insert(std::make_pair(Result, PartitionToResult.size()));
  572. PartitionToResult.push_back(Result);
  573. }
  574. I = ResultToPartition.find(Result);
  575. auto P = Partitions.find(I->second);
  576. if (P == Partitions.end())
  577. P = Partitions.insert(std::make_pair(I->second, BitVector())).first;
  578. P->second.resize(LeafIdx + 1);
  579. P->second.set(LeafIdx);
  580. }
  581. void GIMatchTreeVRegDefPartitioner::repartition(
  582. GIMatchTreeBuilder::LeafVec &Leaves) {
  583. Partitions.clear();
  584. for (const auto &Leaf : enumerate(Leaves)) {
  585. GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
  586. BitVector TraversedEdgesForLeaf(Leaf.value().getMatchDag().getNumEdges());
  587. // If the instruction isn't declared then we don't care about it. Ignore
  588. // it for now and add it to all partitions later once we know what
  589. // partitions we have.
  590. if (!InstrInfo) {
  591. TraversedEdges.push_back(TraversedEdgesForLeaf);
  592. continue;
  593. }
  594. // If this node has an use -> def edge from this operand then this
  595. // instruction must be in partition 1 (isVRegDef()).
  596. bool WantsEdge = false;
  597. for (unsigned EIdx : Leaf.value().TraversableEdges.set_bits()) {
  598. const auto &E = Leaf.value().getEdge(EIdx);
  599. if (E->getFromMI() != InstrInfo->getInstrNode() ||
  600. E->getFromMO()->getIdx() != OpIdx || E->isDefToUse())
  601. continue;
  602. // We're looking at the right edge. This leaf wants a vreg def so we'll
  603. // put it in partition 1.
  604. addToPartition(true, Leaf.index());
  605. TraversedEdgesForLeaf.set(EIdx);
  606. WantsEdge = true;
  607. }
  608. bool isNotReg = false;
  609. if (!WantsEdge && isNotReg) {
  610. // If this leaf doesn't have an edge and we _don't_ want a register,
  611. // then add it to partition 0.
  612. addToPartition(false, Leaf.index());
  613. } else if (!WantsEdge) {
  614. // If this leaf doesn't have an edge and we don't know what we want,
  615. // then add it to partition 0 and 1.
  616. addToPartition(false, Leaf.index());
  617. addToPartition(true, Leaf.index());
  618. }
  619. TraversedEdges.push_back(TraversedEdgesForLeaf);
  620. }
  621. // Add any leaves that don't care about this instruction to all partitions.
  622. for (const auto &Leaf : enumerate(Leaves)) {
  623. GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
  624. if (!InstrInfo)
  625. for (auto &Partition : Partitions)
  626. Partition.second.set(Leaf.index());
  627. }
  628. }
  629. void GIMatchTreeVRegDefPartitioner::applyForPartition(
  630. unsigned PartitionIdx, GIMatchTreeBuilder &Builder,
  631. GIMatchTreeBuilder &SubBuilder) {
  632. BitVector PossibleLeaves = getPossibleLeavesForPartition(PartitionIdx);
  633. std::vector<BitVector> TraversedEdgesByNewLeaves;
  634. // Consume any edges we handled.
  635. for (auto &EnumeratedLeaf : enumerate(Builder.getPossibleLeaves())) {
  636. if (!PossibleLeaves[EnumeratedLeaf.index()])
  637. continue;
  638. auto &Leaf = EnumeratedLeaf.value();
  639. const auto &TraversedEdgesForLeaf = TraversedEdges[EnumeratedLeaf.index()];
  640. TraversedEdgesByNewLeaves.push_back(TraversedEdgesForLeaf);
  641. Leaf.RemainingEdges.reset(TraversedEdgesForLeaf);
  642. Leaf.TraversableEdges.reset(TraversedEdgesForLeaf);
  643. SubBuilder.addLeaf(Leaf);
  644. }
  645. // Nothing to do. The only thing we know is that it isn't a vreg-def.
  646. if (PartitionToResult[PartitionIdx] == false)
  647. return;
  648. NewInstrID = SubBuilder.allocInstrID();
  649. GIMatchTreeBuilder::LeafVec &NewLeaves = SubBuilder.getPossibleLeaves();
  650. for (const auto I : zip(NewLeaves, TraversedEdgesByNewLeaves)) {
  651. auto &Leaf = std::get<0>(I);
  652. auto &TraversedEdgesForLeaf = std::get<1>(I);
  653. GIMatchTreeInstrInfo *InstrInfo = Leaf.getInstrInfo(InstrID);
  654. // Skip any leaves that don't care about this instruction.
  655. if (!InstrInfo)
  656. continue;
  657. for (unsigned EIdx : TraversedEdgesForLeaf.set_bits()) {
  658. const GIMatchDagEdge *E = Leaf.getEdge(EIdx);
  659. Leaf.declareInstr(E->getToMI(), NewInstrID);
  660. }
  661. }
  662. SubBuilder.addPartitionersForInstr(NewInstrID);
  663. }
  664. void GIMatchTreeVRegDefPartitioner::emitPartitionResults(
  665. raw_ostream &OS) const {
  666. OS << "Partitioning by vreg-def would produce " << Partitions.size()
  667. << " partitions\n";
  668. for (const auto &Partition : Partitions) {
  669. OS << Partition.first << " (";
  670. emitPartitionName(OS, Partition.first);
  671. OS << "): ";
  672. StringRef Separator = "";
  673. for (unsigned I : Partition.second.set_bits()) {
  674. OS << Separator << I;
  675. Separator = ", ";
  676. }
  677. OS << "\n";
  678. }
  679. }
  680. void GIMatchTreeVRegDefPartitioner::generatePartitionSelectorCode(
  681. raw_ostream &OS, StringRef Indent) const {
  682. OS << Indent << "Partition = -1\n"
  683. << Indent << "if (MIs.size() <= NewInstrID) MIs.resize(NewInstrID + 1);\n"
  684. << Indent << "MIs[" << NewInstrID << "] = nullptr;\n"
  685. << Indent << "if (MIs[" << InstrID << "].getOperand(" << OpIdx
  686. << ").isReg()))\n"
  687. << Indent << " MIs[" << NewInstrID << "] = MRI.getVRegDef(MIs[" << InstrID
  688. << "].getOperand(" << OpIdx << ").getReg()));\n";
  689. for (const auto &Pair : ResultToPartition)
  690. OS << Indent << "if (MIs[" << NewInstrID << "] "
  691. << (Pair.first ? "==" : "!=")
  692. << " nullptr) Partition = " << Pair.second << ";\n";
  693. OS << Indent << "if (Partition == -1) return false;\n";
  694. }