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