1 //===- Predicate.cpp - Predicate class ------------------------------------===//
2 //
3 // Part of the MLIR 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 // Wrapper around predicates defined in TableGen.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/TableGen/Predicate.h"
14 #include "llvm/ADT/SetVector.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/FormatVariadic.h"
18 #include "llvm/TableGen/Error.h"
19 #include "llvm/TableGen/Record.h"
20 
21 using namespace mlir;
22 
23 // Construct a Predicate from a record.
24 tblgen::Pred::Pred(const llvm::Record *record) : def(record) {
25   assert(def->isSubClassOf("Pred") &&
26          "must be a subclass of TableGen 'Pred' class");
27 }
28 
29 // Construct a Predicate from an initializer.
30 tblgen::Pred::Pred(const llvm::Init *init) : def(nullptr) {
31   if (const auto *defInit = dyn_cast_or_null<llvm::DefInit>(init))
32     def = defInit->getDef();
33 }
34 
35 std::string tblgen::Pred::getCondition() const {
36   // Static dispatch to subclasses.
37   if (def->isSubClassOf("CombinedPred"))
38     return static_cast<const CombinedPred *>(this)->getConditionImpl();
39   if (def->isSubClassOf("CPred"))
40     return static_cast<const CPred *>(this)->getConditionImpl();
41   llvm_unreachable("Pred::getCondition must be overridden in subclasses");
42 }
43 
44 bool tblgen::Pred::isCombined() const {
45   return def && def->isSubClassOf("CombinedPred");
46 }
47 
48 ArrayRef<llvm::SMLoc> tblgen::Pred::getLoc() const { return def->getLoc(); }
49 
50 tblgen::CPred::CPred(const llvm::Record *record) : Pred(record) {
51   assert(def->isSubClassOf("CPred") &&
52          "must be a subclass of Tablegen 'CPred' class");
53 }
54 
55 tblgen::CPred::CPred(const llvm::Init *init) : Pred(init) {
56   assert((!def || def->isSubClassOf("CPred")) &&
57          "must be a subclass of Tablegen 'CPred' class");
58 }
59 
60 // Get condition of the C Predicate.
61 std::string tblgen::CPred::getConditionImpl() const {
62   assert(!isNull() && "null predicate does not have a condition");
63   return def->getValueAsString("predExpr");
64 }
65 
66 tblgen::CombinedPred::CombinedPred(const llvm::Record *record) : Pred(record) {
67   assert(def->isSubClassOf("CombinedPred") &&
68          "must be a subclass of Tablegen 'CombinedPred' class");
69 }
70 
71 tblgen::CombinedPred::CombinedPred(const llvm::Init *init) : Pred(init) {
72   assert((!def || def->isSubClassOf("CombinedPred")) &&
73          "must be a subclass of Tablegen 'CombinedPred' class");
74 }
75 
76 const llvm::Record *tblgen::CombinedPred::getCombinerDef() const {
77   assert(def->getValue("kind") && "CombinedPred must have a value 'kind'");
78   return def->getValueAsDef("kind");
79 }
80 
81 const std::vector<llvm::Record *> tblgen::CombinedPred::getChildren() const {
82   assert(def->getValue("children") &&
83          "CombinedPred must have a value 'children'");
84   return def->getValueAsListOfDefs("children");
85 }
86 
87 namespace {
88 // Kinds of nodes in a logical predicate tree.
89 enum class PredCombinerKind {
90   Leaf,
91   And,
92   Or,
93   Not,
94   SubstLeaves,
95   Concat,
96   // Special kinds that are used in simplification.
97   False,
98   True
99 };
100 
101 // A node in a logical predicate tree.
102 struct PredNode {
103   PredCombinerKind kind;
104   const tblgen::Pred *predicate;
105   SmallVector<PredNode *, 4> children;
106   std::string expr;
107 
108   // Prefix and suffix are used by ConcatPred.
109   std::string prefix;
110   std::string suffix;
111 };
112 } // end anonymous namespace
113 
114 // Get a predicate tree node kind based on the kind used in the predicate
115 // TableGen record.
116 static PredCombinerKind getPredCombinerKind(const tblgen::Pred &pred) {
117   if (!pred.isCombined())
118     return PredCombinerKind::Leaf;
119 
120   const auto &combinedPred = static_cast<const tblgen::CombinedPred &>(pred);
121   return llvm::StringSwitch<PredCombinerKind>(
122              combinedPred.getCombinerDef()->getName())
123       .Case("PredCombinerAnd", PredCombinerKind::And)
124       .Case("PredCombinerOr", PredCombinerKind::Or)
125       .Case("PredCombinerNot", PredCombinerKind::Not)
126       .Case("PredCombinerSubstLeaves", PredCombinerKind::SubstLeaves)
127       .Case("PredCombinerConcat", PredCombinerKind::Concat);
128 }
129 
130 namespace {
131 // Substitution<pattern, replacement>.
132 using Subst = std::pair<StringRef, StringRef>;
133 } // end anonymous namespace
134 
135 // Build the predicate tree starting from the top-level predicate, which may
136 // have children, and perform leaf substitutions inplace.  Note that after
137 // substitution, nodes are still pointing to the original TableGen record.
138 // All nodes are created within "allocator".
139 static PredNode *buildPredicateTree(const tblgen::Pred &root,
140                                     llvm::BumpPtrAllocator &allocator,
141                                     ArrayRef<Subst> substitutions) {
142   auto *rootNode = allocator.Allocate<PredNode>();
143   new (rootNode) PredNode;
144   rootNode->kind = getPredCombinerKind(root);
145   rootNode->predicate = &root;
146   if (!root.isCombined()) {
147     rootNode->expr = root.getCondition();
148     // Apply all parent substitutions from innermost to outermost.
149     for (const auto &subst : llvm::reverse(substitutions)) {
150       auto pos = rootNode->expr.find(subst.first);
151       while (pos != std::string::npos) {
152         rootNode->expr.replace(pos, subst.first.size(), subst.second);
153         // Skip the newly inserted substring, which itself may consider the
154         // pattern to match.
155         pos += subst.second.size();
156         // Find the next possible match position.
157         pos = rootNode->expr.find(subst.first, pos);
158       }
159     }
160     return rootNode;
161   }
162 
163   // If the current combined predicate is a leaf substitution, append it to the
164   // list before continuing.
165   auto allSubstitutions = llvm::to_vector<4>(substitutions);
166   if (rootNode->kind == PredCombinerKind::SubstLeaves) {
167     const auto &substPred = static_cast<const tblgen::SubstLeavesPred &>(root);
168     allSubstitutions.push_back(
169         {substPred.getPattern(), substPred.getReplacement()});
170   }
171   // If the current predicate is a ConcatPred, record the prefix and suffix.
172   else if (rootNode->kind == PredCombinerKind::Concat) {
173     const auto &concatPred = static_cast<const tblgen::ConcatPred &>(root);
174     rootNode->prefix = concatPred.getPrefix();
175     rootNode->suffix = concatPred.getSuffix();
176   }
177 
178   // Build child subtrees.
179   auto combined = static_cast<const tblgen::CombinedPred &>(root);
180   for (const auto *record : combined.getChildren()) {
181     auto childTree =
182         buildPredicateTree(tblgen::Pred(record), allocator, allSubstitutions);
183     rootNode->children.push_back(childTree);
184   }
185   return rootNode;
186 }
187 
188 // Simplify a predicate tree rooted at "node" using the predicates that are
189 // known to be true(false).  For AND(OR) combined predicates, if any of the
190 // children is known to be false(true), the result is also false(true).
191 // Furthermore, for AND(OR) combined predicates, children that are known to be
192 // true(false) don't have to be checked dynamically.
193 static PredNode *propagateGroundTruth(
194     PredNode *node, const llvm::SmallPtrSetImpl<tblgen::Pred *> &knownTruePreds,
195     const llvm::SmallPtrSetImpl<tblgen::Pred *> &knownFalsePreds) {
196   // If the current predicate is known to be true or false, change the kind of
197   // the node and return immediately.
198   if (knownTruePreds.count(node->predicate) != 0) {
199     node->kind = PredCombinerKind::True;
200     node->children.clear();
201     return node;
202   }
203   if (knownFalsePreds.count(node->predicate) != 0) {
204     node->kind = PredCombinerKind::False;
205     node->children.clear();
206     return node;
207   }
208 
209   // If the current node is a substitution, stop recursion now.
210   // The expressions in the leaves below this node were rewritten, but the nodes
211   // still point to the original predicate records.  While the original
212   // predicate may be known to be true or false, it is not necessarily the case
213   // after rewriting.
214   // TODO(zinenko,jpienaar): we can support ground truth for rewritten
215   // predicates by either (a) having our own unique'ing of the predicates
216   // instead of relying on TableGen record pointers or (b) taking ground truth
217   // values optionally prefixed with a list of substitutions to apply, e.g.
218   // "predX is true by itself as well as predSubY leaf substitution had been
219   // applied to it".
220   if (node->kind == PredCombinerKind::SubstLeaves) {
221     return node;
222   }
223 
224   // Otherwise, look at child nodes.
225 
226   // Move child nodes into some local variable so that they can be optimized
227   // separately and re-added if necessary.
228   llvm::SmallVector<PredNode *, 4> children;
229   std::swap(node->children, children);
230 
231   for (auto &child : children) {
232     // First, simplify the child.  This maintains the predicate as it was.
233     auto simplifiedChild =
234         propagateGroundTruth(child, knownTruePreds, knownFalsePreds);
235 
236     // Just add the child if we don't know how to simplify the current node.
237     if (node->kind != PredCombinerKind::And &&
238         node->kind != PredCombinerKind::Or) {
239       node->children.push_back(simplifiedChild);
240       continue;
241     }
242 
243     // Second, based on the type define which known values of child predicates
244     // immediately collapse this predicate to a known value, and which others
245     // may be safely ignored.
246     //   OR(..., True, ...) = True
247     //   OR(..., False, ...) = OR(..., ...)
248     //   AND(..., False, ...) = False
249     //   AND(..., True, ...) = AND(..., ...)
250     auto collapseKind = node->kind == PredCombinerKind::And
251                             ? PredCombinerKind::False
252                             : PredCombinerKind::True;
253     auto eraseKind = node->kind == PredCombinerKind::And
254                          ? PredCombinerKind::True
255                          : PredCombinerKind::False;
256     const auto &collapseList =
257         node->kind == PredCombinerKind::And ? knownFalsePreds : knownTruePreds;
258     const auto &eraseList =
259         node->kind == PredCombinerKind::And ? knownTruePreds : knownFalsePreds;
260     if (simplifiedChild->kind == collapseKind ||
261         collapseList.count(simplifiedChild->predicate) != 0) {
262       node->kind = collapseKind;
263       node->children.clear();
264       return node;
265     } else if (simplifiedChild->kind == eraseKind ||
266                eraseList.count(simplifiedChild->predicate) != 0) {
267       continue;
268     }
269     node->children.push_back(simplifiedChild);
270   }
271   return node;
272 }
273 
274 // Combine a list of predicate expressions using a binary combiner.  If a list
275 // is empty, return "init".
276 static std::string combineBinary(ArrayRef<std::string> children,
277                                  std::string combiner, std::string init) {
278   if (children.empty())
279     return init;
280 
281   auto size = children.size();
282   if (size == 1)
283     return children.front();
284 
285   std::string str;
286   llvm::raw_string_ostream os(str);
287   os << '(' << children.front() << ')';
288   for (unsigned i = 1; i < size; ++i) {
289     os << ' ' << combiner << " (" << children[i] << ')';
290   }
291   return os.str();
292 }
293 
294 // Prepend negation to the only condition in the predicate expression list.
295 static std::string combineNot(ArrayRef<std::string> children) {
296   assert(children.size() == 1 && "expected exactly one child predicate of Neg");
297   return (Twine("!(") + children.front() + Twine(')')).str();
298 }
299 
300 // Recursively traverse the predicate tree in depth-first post-order and build
301 // the final expression.
302 static std::string getCombinedCondition(const PredNode &root) {
303   // Immediately return for non-combiner predicates that don't have children.
304   if (root.kind == PredCombinerKind::Leaf)
305     return root.expr;
306   if (root.kind == PredCombinerKind::True)
307     return "true";
308   if (root.kind == PredCombinerKind::False)
309     return "false";
310 
311   // Recurse into children.
312   llvm::SmallVector<std::string, 4> childExpressions;
313   childExpressions.reserve(root.children.size());
314   for (const auto &child : root.children)
315     childExpressions.push_back(getCombinedCondition(*child));
316 
317   // Combine the expressions based on the predicate node kind.
318   if (root.kind == PredCombinerKind::And)
319     return combineBinary(childExpressions, "&&", "true");
320   if (root.kind == PredCombinerKind::Or)
321     return combineBinary(childExpressions, "||", "false");
322   if (root.kind == PredCombinerKind::Not)
323     return combineNot(childExpressions);
324   if (root.kind == PredCombinerKind::Concat) {
325     assert(childExpressions.size() == 1 &&
326            "ConcatPred should only have one child");
327     return root.prefix + childExpressions.front() + root.suffix;
328   }
329 
330   // Substitutions were applied before so just ignore them.
331   if (root.kind == PredCombinerKind::SubstLeaves) {
332     assert(childExpressions.size() == 1 &&
333            "substitution predicate must have one child");
334     return childExpressions[0];
335   }
336 
337   llvm::PrintFatalError(root.predicate->getLoc(), "unsupported predicate kind");
338 }
339 
340 std::string tblgen::CombinedPred::getConditionImpl() const {
341   llvm::BumpPtrAllocator allocator;
342   auto predicateTree = buildPredicateTree(*this, allocator, {});
343   predicateTree = propagateGroundTruth(
344       predicateTree,
345       /*knownTruePreds=*/llvm::SmallPtrSet<tblgen::Pred *, 2>(),
346       /*knownFalsePreds=*/llvm::SmallPtrSet<tblgen::Pred *, 2>());
347 
348   return getCombinedCondition(*predicateTree);
349 }
350 
351 StringRef tblgen::SubstLeavesPred::getPattern() const {
352   return def->getValueAsString("pattern");
353 }
354 
355 StringRef tblgen::SubstLeavesPred::getReplacement() const {
356   return def->getValueAsString("replacement");
357 }
358 
359 StringRef tblgen::ConcatPred::getPrefix() const {
360   return def->getValueAsString("prefix");
361 }
362 
363 StringRef tblgen::ConcatPred::getSuffix() const {
364   return def->getValueAsString("suffix");
365 }
366