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