1 //===- Predicate.cpp - Predicate class ------------------------------------===// 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 // 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 std::string(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(std::string(subst.first)); 151 while (pos != std::string::npos) { 152 rootNode->expr.replace(pos, subst.first.size(), 153 std::string(subst.second)); 154 // Skip the newly inserted substring, which itself may consider the 155 // pattern to match. 156 pos += subst.second.size(); 157 // Find the next possible match position. 158 pos = rootNode->expr.find(std::string(subst.first), pos); 159 } 160 } 161 return rootNode; 162 } 163 164 // If the current combined predicate is a leaf substitution, append it to the 165 // list before continuing. 166 auto allSubstitutions = llvm::to_vector<4>(substitutions); 167 if (rootNode->kind == PredCombinerKind::SubstLeaves) { 168 const auto &substPred = static_cast<const tblgen::SubstLeavesPred &>(root); 169 allSubstitutions.push_back( 170 {substPred.getPattern(), substPred.getReplacement()}); 171 } 172 // If the current predicate is a ConcatPred, record the prefix and suffix. 173 else if (rootNode->kind == PredCombinerKind::Concat) { 174 const auto &concatPred = static_cast<const tblgen::ConcatPred &>(root); 175 rootNode->prefix = std::string(concatPred.getPrefix()); 176 rootNode->suffix = std::string(concatPred.getSuffix()); 177 } 178 179 // Build child subtrees. 180 auto combined = static_cast<const tblgen::CombinedPred &>(root); 181 for (const auto *record : combined.getChildren()) { 182 auto childTree = 183 buildPredicateTree(tblgen::Pred(record), allocator, allSubstitutions); 184 rootNode->children.push_back(childTree); 185 } 186 return rootNode; 187 } 188 189 // Simplify a predicate tree rooted at "node" using the predicates that are 190 // known to be true(false). For AND(OR) combined predicates, if any of the 191 // children is known to be false(true), the result is also false(true). 192 // Furthermore, for AND(OR) combined predicates, children that are known to be 193 // true(false) don't have to be checked dynamically. 194 static PredNode *propagateGroundTruth( 195 PredNode *node, const llvm::SmallPtrSetImpl<tblgen::Pred *> &knownTruePreds, 196 const llvm::SmallPtrSetImpl<tblgen::Pred *> &knownFalsePreds) { 197 // If the current predicate is known to be true or false, change the kind of 198 // the node and return immediately. 199 if (knownTruePreds.count(node->predicate) != 0) { 200 node->kind = PredCombinerKind::True; 201 node->children.clear(); 202 return node; 203 } 204 if (knownFalsePreds.count(node->predicate) != 0) { 205 node->kind = PredCombinerKind::False; 206 node->children.clear(); 207 return node; 208 } 209 210 // If the current node is a substitution, stop recursion now. 211 // The expressions in the leaves below this node were rewritten, but the nodes 212 // still point to the original predicate records. While the original 213 // predicate may be known to be true or false, it is not necessarily the case 214 // after rewriting. 215 // TODO(zinenko,jpienaar): we can support ground truth for rewritten 216 // predicates by either (a) having our own unique'ing of the predicates 217 // instead of relying on TableGen record pointers or (b) taking ground truth 218 // values optionally prefixed with a list of substitutions to apply, e.g. 219 // "predX is true by itself as well as predSubY leaf substitution had been 220 // applied to it". 221 if (node->kind == PredCombinerKind::SubstLeaves) { 222 return node; 223 } 224 225 // Otherwise, look at child nodes. 226 227 // Move child nodes into some local variable so that they can be optimized 228 // separately and re-added if necessary. 229 llvm::SmallVector<PredNode *, 4> children; 230 std::swap(node->children, children); 231 232 for (auto &child : children) { 233 // First, simplify the child. This maintains the predicate as it was. 234 auto simplifiedChild = 235 propagateGroundTruth(child, knownTruePreds, knownFalsePreds); 236 237 // Just add the child if we don't know how to simplify the current node. 238 if (node->kind != PredCombinerKind::And && 239 node->kind != PredCombinerKind::Or) { 240 node->children.push_back(simplifiedChild); 241 continue; 242 } 243 244 // Second, based on the type define which known values of child predicates 245 // immediately collapse this predicate to a known value, and which others 246 // may be safely ignored. 247 // OR(..., True, ...) = True 248 // OR(..., False, ...) = OR(..., ...) 249 // AND(..., False, ...) = False 250 // AND(..., True, ...) = AND(..., ...) 251 auto collapseKind = node->kind == PredCombinerKind::And 252 ? PredCombinerKind::False 253 : PredCombinerKind::True; 254 auto eraseKind = node->kind == PredCombinerKind::And 255 ? PredCombinerKind::True 256 : PredCombinerKind::False; 257 const auto &collapseList = 258 node->kind == PredCombinerKind::And ? knownFalsePreds : knownTruePreds; 259 const auto &eraseList = 260 node->kind == PredCombinerKind::And ? knownTruePreds : knownFalsePreds; 261 if (simplifiedChild->kind == collapseKind || 262 collapseList.count(simplifiedChild->predicate) != 0) { 263 node->kind = collapseKind; 264 node->children.clear(); 265 return node; 266 } else if (simplifiedChild->kind == eraseKind || 267 eraseList.count(simplifiedChild->predicate) != 0) { 268 continue; 269 } 270 node->children.push_back(simplifiedChild); 271 } 272 return node; 273 } 274 275 // Combine a list of predicate expressions using a binary combiner. If a list 276 // is empty, return "init". 277 static std::string combineBinary(ArrayRef<std::string> children, 278 std::string combiner, std::string init) { 279 if (children.empty()) 280 return init; 281 282 auto size = children.size(); 283 if (size == 1) 284 return children.front(); 285 286 std::string str; 287 llvm::raw_string_ostream os(str); 288 os << '(' << children.front() << ')'; 289 for (unsigned i = 1; i < size; ++i) { 290 os << ' ' << combiner << " (" << children[i] << ')'; 291 } 292 return os.str(); 293 } 294 295 // Prepend negation to the only condition in the predicate expression list. 296 static std::string combineNot(ArrayRef<std::string> children) { 297 assert(children.size() == 1 && "expected exactly one child predicate of Neg"); 298 return (Twine("!(") + children.front() + Twine(')')).str(); 299 } 300 301 // Recursively traverse the predicate tree in depth-first post-order and build 302 // the final expression. 303 static std::string getCombinedCondition(const PredNode &root) { 304 // Immediately return for non-combiner predicates that don't have children. 305 if (root.kind == PredCombinerKind::Leaf) 306 return root.expr; 307 if (root.kind == PredCombinerKind::True) 308 return "true"; 309 if (root.kind == PredCombinerKind::False) 310 return "false"; 311 312 // Recurse into children. 313 llvm::SmallVector<std::string, 4> childExpressions; 314 childExpressions.reserve(root.children.size()); 315 for (const auto &child : root.children) 316 childExpressions.push_back(getCombinedCondition(*child)); 317 318 // Combine the expressions based on the predicate node kind. 319 if (root.kind == PredCombinerKind::And) 320 return combineBinary(childExpressions, "&&", "true"); 321 if (root.kind == PredCombinerKind::Or) 322 return combineBinary(childExpressions, "||", "false"); 323 if (root.kind == PredCombinerKind::Not) 324 return combineNot(childExpressions); 325 if (root.kind == PredCombinerKind::Concat) { 326 assert(childExpressions.size() == 1 && 327 "ConcatPred should only have one child"); 328 return root.prefix + childExpressions.front() + root.suffix; 329 } 330 331 // Substitutions were applied before so just ignore them. 332 if (root.kind == PredCombinerKind::SubstLeaves) { 333 assert(childExpressions.size() == 1 && 334 "substitution predicate must have one child"); 335 return childExpressions[0]; 336 } 337 338 llvm::PrintFatalError(root.predicate->getLoc(), "unsupported predicate kind"); 339 } 340 341 std::string tblgen::CombinedPred::getConditionImpl() const { 342 llvm::BumpPtrAllocator allocator; 343 auto predicateTree = buildPredicateTree(*this, allocator, {}); 344 predicateTree = propagateGroundTruth( 345 predicateTree, 346 /*knownTruePreds=*/llvm::SmallPtrSet<tblgen::Pred *, 2>(), 347 /*knownFalsePreds=*/llvm::SmallPtrSet<tblgen::Pred *, 2>()); 348 349 return getCombinedCondition(*predicateTree); 350 } 351 352 StringRef tblgen::SubstLeavesPred::getPattern() const { 353 return def->getValueAsString("pattern"); 354 } 355 356 StringRef tblgen::SubstLeavesPred::getReplacement() const { 357 return def->getValueAsString("replacement"); 358 } 359 360 StringRef tblgen::ConcatPred::getPrefix() const { 361 return def->getValueAsString("prefix"); 362 } 363 364 StringRef tblgen::ConcatPred::getSuffix() const { 365 return def->getValueAsString("suffix"); 366 } 367