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