SetTheory.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. //===- SetTheory.cpp - Generate ordered sets from DAG expressions ---------===//
  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. // This file implements the SetTheory class that computes ordered sets of
  10. // Records from DAG expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/TableGen/SetTheory.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/Support/Casting.h"
  18. #include "llvm/Support/Format.h"
  19. #include "llvm/Support/SMLoc.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include "llvm/TableGen/Error.h"
  22. #include "llvm/TableGen/Record.h"
  23. #include <algorithm>
  24. #include <cstdint>
  25. #include <string>
  26. #include <utility>
  27. using namespace llvm;
  28. // Define the standard operators.
  29. namespace {
  30. using RecSet = SetTheory::RecSet;
  31. using RecVec = SetTheory::RecVec;
  32. // (add a, b, ...) Evaluate and union all arguments.
  33. struct AddOp : public SetTheory::Operator {
  34. void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
  35. ArrayRef<SMLoc> Loc) override {
  36. ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
  37. }
  38. };
  39. // (sub Add, Sub, ...) Set difference.
  40. struct SubOp : public SetTheory::Operator {
  41. void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
  42. ArrayRef<SMLoc> Loc) override {
  43. if (Expr->arg_size() < 2)
  44. PrintFatalError(Loc, "Set difference needs at least two arguments: " +
  45. Expr->getAsString());
  46. RecSet Add, Sub;
  47. ST.evaluate(*Expr->arg_begin(), Add, Loc);
  48. ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Sub, Loc);
  49. for (const auto &I : Add)
  50. if (!Sub.count(I))
  51. Elts.insert(I);
  52. }
  53. };
  54. // (and S1, S2) Set intersection.
  55. struct AndOp : public SetTheory::Operator {
  56. void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
  57. ArrayRef<SMLoc> Loc) override {
  58. if (Expr->arg_size() != 2)
  59. PrintFatalError(Loc, "Set intersection requires two arguments: " +
  60. Expr->getAsString());
  61. RecSet S1, S2;
  62. ST.evaluate(Expr->arg_begin()[0], S1, Loc);
  63. ST.evaluate(Expr->arg_begin()[1], S2, Loc);
  64. for (const auto &I : S1)
  65. if (S2.count(I))
  66. Elts.insert(I);
  67. }
  68. };
  69. // SetIntBinOp - Abstract base class for (Op S, N) operators.
  70. struct SetIntBinOp : public SetTheory::Operator {
  71. virtual void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
  72. RecSet &Elts, ArrayRef<SMLoc> Loc) = 0;
  73. void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
  74. ArrayRef<SMLoc> Loc) override {
  75. if (Expr->arg_size() != 2)
  76. PrintFatalError(Loc, "Operator requires (Op Set, Int) arguments: " +
  77. Expr->getAsString());
  78. RecSet Set;
  79. ST.evaluate(Expr->arg_begin()[0], Set, Loc);
  80. IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[1]);
  81. if (!II)
  82. PrintFatalError(Loc, "Second argument must be an integer: " +
  83. Expr->getAsString());
  84. apply2(ST, Expr, Set, II->getValue(), Elts, Loc);
  85. }
  86. };
  87. // (shl S, N) Shift left, remove the first N elements.
  88. struct ShlOp : public SetIntBinOp {
  89. void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
  90. RecSet &Elts, ArrayRef<SMLoc> Loc) override {
  91. if (N < 0)
  92. PrintFatalError(Loc, "Positive shift required: " +
  93. Expr->getAsString());
  94. if (unsigned(N) < Set.size())
  95. Elts.insert(Set.begin() + N, Set.end());
  96. }
  97. };
  98. // (trunc S, N) Truncate after the first N elements.
  99. struct TruncOp : public SetIntBinOp {
  100. void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
  101. RecSet &Elts, ArrayRef<SMLoc> Loc) override {
  102. if (N < 0)
  103. PrintFatalError(Loc, "Positive length required: " +
  104. Expr->getAsString());
  105. if (unsigned(N) > Set.size())
  106. N = Set.size();
  107. Elts.insert(Set.begin(), Set.begin() + N);
  108. }
  109. };
  110. // Left/right rotation.
  111. struct RotOp : public SetIntBinOp {
  112. const bool Reverse;
  113. RotOp(bool Rev) : Reverse(Rev) {}
  114. void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
  115. RecSet &Elts, ArrayRef<SMLoc> Loc) override {
  116. if (Reverse)
  117. N = -N;
  118. // N > 0 -> rotate left, N < 0 -> rotate right.
  119. if (Set.empty())
  120. return;
  121. if (N < 0)
  122. N = Set.size() - (-N % Set.size());
  123. else
  124. N %= Set.size();
  125. Elts.insert(Set.begin() + N, Set.end());
  126. Elts.insert(Set.begin(), Set.begin() + N);
  127. }
  128. };
  129. // (decimate S, N) Pick every N'th element of S.
  130. struct DecimateOp : public SetIntBinOp {
  131. void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
  132. RecSet &Elts, ArrayRef<SMLoc> Loc) override {
  133. if (N <= 0)
  134. PrintFatalError(Loc, "Positive stride required: " +
  135. Expr->getAsString());
  136. for (unsigned I = 0; I < Set.size(); I += N)
  137. Elts.insert(Set[I]);
  138. }
  139. };
  140. // (interleave S1, S2, ...) Interleave elements of the arguments.
  141. struct InterleaveOp : public SetTheory::Operator {
  142. void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
  143. ArrayRef<SMLoc> Loc) override {
  144. // Evaluate the arguments individually.
  145. SmallVector<RecSet, 4> Args(Expr->getNumArgs());
  146. unsigned MaxSize = 0;
  147. for (unsigned i = 0, e = Expr->getNumArgs(); i != e; ++i) {
  148. ST.evaluate(Expr->getArg(i), Args[i], Loc);
  149. MaxSize = std::max(MaxSize, unsigned(Args[i].size()));
  150. }
  151. // Interleave arguments into Elts.
  152. for (unsigned n = 0; n != MaxSize; ++n)
  153. for (unsigned i = 0, e = Expr->getNumArgs(); i != e; ++i)
  154. if (n < Args[i].size())
  155. Elts.insert(Args[i][n]);
  156. }
  157. };
  158. // (sequence "Format", From, To) Generate a sequence of records by name.
  159. struct SequenceOp : public SetTheory::Operator {
  160. void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
  161. ArrayRef<SMLoc> Loc) override {
  162. int Step = 1;
  163. if (Expr->arg_size() > 4)
  164. PrintFatalError(Loc, "Bad args to (sequence \"Format\", From, To): " +
  165. Expr->getAsString());
  166. else if (Expr->arg_size() == 4) {
  167. if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[3])) {
  168. Step = II->getValue();
  169. } else
  170. PrintFatalError(Loc, "Stride must be an integer: " +
  171. Expr->getAsString());
  172. }
  173. std::string Format;
  174. if (StringInit *SI = dyn_cast<StringInit>(Expr->arg_begin()[0]))
  175. Format = std::string(SI->getValue());
  176. else
  177. PrintFatalError(Loc, "Format must be a string: " + Expr->getAsString());
  178. int64_t From, To;
  179. if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[1]))
  180. From = II->getValue();
  181. else
  182. PrintFatalError(Loc, "From must be an integer: " + Expr->getAsString());
  183. if (From < 0 || From >= (1 << 30))
  184. PrintFatalError(Loc, "From out of range");
  185. if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[2]))
  186. To = II->getValue();
  187. else
  188. PrintFatalError(Loc, "To must be an integer: " + Expr->getAsString());
  189. if (To < 0 || To >= (1 << 30))
  190. PrintFatalError(Loc, "To out of range");
  191. RecordKeeper &Records =
  192. cast<DefInit>(Expr->getOperator())->getDef()->getRecords();
  193. Step *= From <= To ? 1 : -1;
  194. while (true) {
  195. if (Step > 0 && From > To)
  196. break;
  197. else if (Step < 0 && From < To)
  198. break;
  199. std::string Name;
  200. raw_string_ostream OS(Name);
  201. OS << format(Format.c_str(), unsigned(From));
  202. Record *Rec = Records.getDef(OS.str());
  203. if (!Rec)
  204. PrintFatalError(Loc, "No def named '" + Name + "': " +
  205. Expr->getAsString());
  206. // Try to reevaluate Rec in case it is a set.
  207. if (const RecVec *Result = ST.expand(Rec))
  208. Elts.insert(Result->begin(), Result->end());
  209. else
  210. Elts.insert(Rec);
  211. From += Step;
  212. }
  213. }
  214. };
  215. // Expand a Def into a set by evaluating one of its fields.
  216. struct FieldExpander : public SetTheory::Expander {
  217. StringRef FieldName;
  218. FieldExpander(StringRef fn) : FieldName(fn) {}
  219. void expand(SetTheory &ST, Record *Def, RecSet &Elts) override {
  220. ST.evaluate(Def->getValueInit(FieldName), Elts, Def->getLoc());
  221. }
  222. };
  223. } // end anonymous namespace
  224. // Pin the vtables to this file.
  225. void SetTheory::Operator::anchor() {}
  226. void SetTheory::Expander::anchor() {}
  227. SetTheory::SetTheory() {
  228. addOperator("add", std::make_unique<AddOp>());
  229. addOperator("sub", std::make_unique<SubOp>());
  230. addOperator("and", std::make_unique<AndOp>());
  231. addOperator("shl", std::make_unique<ShlOp>());
  232. addOperator("trunc", std::make_unique<TruncOp>());
  233. addOperator("rotl", std::make_unique<RotOp>(false));
  234. addOperator("rotr", std::make_unique<RotOp>(true));
  235. addOperator("decimate", std::make_unique<DecimateOp>());
  236. addOperator("interleave", std::make_unique<InterleaveOp>());
  237. addOperator("sequence", std::make_unique<SequenceOp>());
  238. }
  239. void SetTheory::addOperator(StringRef Name, std::unique_ptr<Operator> Op) {
  240. Operators[Name] = std::move(Op);
  241. }
  242. void SetTheory::addExpander(StringRef ClassName, std::unique_ptr<Expander> E) {
  243. Expanders[ClassName] = std::move(E);
  244. }
  245. void SetTheory::addFieldExpander(StringRef ClassName, StringRef FieldName) {
  246. addExpander(ClassName, std::make_unique<FieldExpander>(FieldName));
  247. }
  248. void SetTheory::evaluate(Init *Expr, RecSet &Elts, ArrayRef<SMLoc> Loc) {
  249. // A def in a list can be a just an element, or it may expand.
  250. if (DefInit *Def = dyn_cast<DefInit>(Expr)) {
  251. if (const RecVec *Result = expand(Def->getDef()))
  252. return Elts.insert(Result->begin(), Result->end());
  253. Elts.insert(Def->getDef());
  254. return;
  255. }
  256. // Lists simply expand.
  257. if (ListInit *LI = dyn_cast<ListInit>(Expr))
  258. return evaluate(LI->begin(), LI->end(), Elts, Loc);
  259. // Anything else must be a DAG.
  260. DagInit *DagExpr = dyn_cast<DagInit>(Expr);
  261. if (!DagExpr)
  262. PrintFatalError(Loc, "Invalid set element: " + Expr->getAsString());
  263. DefInit *OpInit = dyn_cast<DefInit>(DagExpr->getOperator());
  264. if (!OpInit)
  265. PrintFatalError(Loc, "Bad set expression: " + Expr->getAsString());
  266. auto I = Operators.find(OpInit->getDef()->getName());
  267. if (I == Operators.end())
  268. PrintFatalError(Loc, "Unknown set operator: " + Expr->getAsString());
  269. I->second->apply(*this, DagExpr, Elts, Loc);
  270. }
  271. const RecVec *SetTheory::expand(Record *Set) {
  272. // Check existing entries for Set and return early.
  273. ExpandMap::iterator I = Expansions.find(Set);
  274. if (I != Expansions.end())
  275. return &I->second;
  276. // This is the first time we see Set. Find a suitable expander.
  277. ArrayRef<std::pair<Record *, SMRange>> SC = Set->getSuperClasses();
  278. for (const auto &SCPair : SC) {
  279. // Skip unnamed superclasses.
  280. if (!isa<StringInit>(SCPair.first->getNameInit()))
  281. continue;
  282. auto I = Expanders.find(SCPair.first->getName());
  283. if (I != Expanders.end()) {
  284. // This breaks recursive definitions.
  285. RecVec &EltVec = Expansions[Set];
  286. RecSet Elts;
  287. I->second->expand(*this, Set, Elts);
  288. EltVec.assign(Elts.begin(), Elts.end());
  289. return &EltVec;
  290. }
  291. }
  292. // Set is not expandable.
  293. return nullptr;
  294. }