This implements a large amount of the matcher, in fact, all of it except for one bug
[oota-llvm.git] / support / tools / TableGen / InstrSelectorEmitter.h
1 //===- InstrInfoEmitter.h - Generate a Instruction Set Desc. ----*- C++ -*-===//
2 //
3 // This tablegen backend is responsible for emitting a description of the target
4 // instruction set for the code generator.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #ifndef INSTRSELECTOR_EMITTER_H
9 #define INSTRSELECTOR_EMITTER_H
10
11 #include "TableGenBackend.h"
12 #include "CodeGenWrappers.h"
13 #include <vector>
14 #include <map>
15 class DagInit;
16 class Init;
17 class InstrSelectorEmitter;
18
19 /// NodeType - Represents Information parsed from the DagNode entries.
20 ///
21 struct NodeType {
22   enum ArgResultTypes {
23     // Both argument and return types...
24     Val,            // A non-void type
25     Arg0,           // Value matches the type of Arg0
26     Ptr,            // Tree node is the type of the target pointer
27
28     // Return types
29     Void,           // Tree node always returns void
30   };
31
32   ArgResultTypes ResultType;
33   std::vector<ArgResultTypes> ArgTypes;
34
35   NodeType(ArgResultTypes RT, std::vector<ArgResultTypes> &AT) : ResultType(RT){
36     AT.swap(ArgTypes);
37   }
38
39   NodeType() : ResultType(Val) {}
40   NodeType(const NodeType &N) : ResultType(N.ResultType), ArgTypes(N.ArgTypes){}
41
42   static ArgResultTypes Translate(Record *R);
43 };
44
45
46
47 /// TreePatternNode - Represent a node of the tree patterns.
48 ///
49 class TreePatternNode {
50   /// Operator - The operation that this node represents... this is null if this
51   /// is a leaf.
52   Record *Operator;
53
54   /// Type - The inferred value type...
55   ///
56   MVT::ValueType                Type;
57
58   /// Children - If this is not a leaf (Operator != 0), this is the subtrees
59   /// that we contain.
60   std::vector<TreePatternNode*> Children;
61
62   /// Value - If this node is a leaf, this indicates what the thing is.
63   ///
64   Init *Value;
65 public:
66   TreePatternNode(Record *o, const std::vector<TreePatternNode*> &c)
67     : Operator(o), Type(MVT::Other), Children(c), Value(0) {}
68   TreePatternNode(Init *V) : Operator(0), Type(MVT::Other), Value(V) {}
69
70   Record *getOperator() const {
71     assert(Operator && "This is a leaf node!");
72     return Operator;
73   }
74   MVT::ValueType getType() const { return Type; }
75   void setType(MVT::ValueType T) { Type = T; }
76
77   bool isLeaf() const { return Operator == 0; }
78
79   const std::vector<TreePatternNode*> &getChildren() const {
80     assert(Operator != 0 && "This is a leaf node!");
81     return Children;
82   }
83   unsigned getNumChildren() const { return Children.size(); }
84   TreePatternNode *getChild(unsigned c) const {
85     assert(c < Children.size() && "Child access out of range!");
86     return getChildren()[c];
87   }
88
89   Init *getValue() const {
90     assert(Operator == 0 && "This is not a leaf node!");
91     return Value;
92   }
93
94   /// getValueRecord - Returns the value of this tree node as a record.  For now
95   /// we only allow DefInit's as our leaf values, so this is used.
96   Record *getValueRecord() const;
97
98   /// clone - Make a copy of this tree and all of its children.
99   ///
100   TreePatternNode *clone() const;
101
102   void dump() const;
103
104   /// InstantiateNonterminals - If this pattern refers to any nonterminals which
105   /// are not themselves completely resolved, clone the nonterminal and resolve
106   /// it with the using context we provide.
107   void InstantiateNonterminals(InstrSelectorEmitter &ISE);
108
109   /// UpdateNodeType - Set the node type of N to VT if VT contains information.
110   /// If N already contains a conflicting type, then throw an exception.  This
111   /// returns true if any information was updated.
112   ///
113   bool updateNodeType(MVT::ValueType VT, const std::string &RecName);
114 };
115
116 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N);
117
118
119
120 /// Pattern - Represent a pattern of one form or another.  Currently, three
121 /// types of patterns are possible: Instruction's, Nonterminals, and Expanders.
122 ///
123 struct Pattern {
124   enum PatternType {
125     Nonterminal, Instruction, Expander
126   };
127 private:
128   /// PTy - The type of pattern this is.
129   ///
130   PatternType PTy;
131
132   /// Tree - The tree pattern which corresponds to this pattern.  Note that if
133   /// there was a (set) node on the outside level that it has been stripped off.
134   ///
135   TreePatternNode *Tree;
136   
137   /// Result - If this is an instruction or expander pattern, this is the
138   /// register result, specified with a (set) in the pattern.
139   ///
140   Record *Result;
141
142   /// TheRecord - The actual TableGen record corresponding to this pattern.
143   ///
144   Record *TheRecord;
145
146   /// Resolved - This is true of the pattern is useful in practice.  In
147   /// particular, some non-terminals will have non-resolvable types.  When a
148   /// user of the non-terminal is later found, they will have inferred a type
149   /// for the result of the non-terminal, which cause a clone of an unresolved
150   /// nonterminal to be made which is "resolved".
151   ///
152   bool Resolved;
153
154   /// ISE - the instruction selector emitter coordinating this madness.
155   ///
156   InstrSelectorEmitter &ISE;
157 public:
158
159   /// Pattern constructor - Parse the specified DagInitializer into the current
160   /// record.
161   Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
162           InstrSelectorEmitter &ise);
163
164   /// Pattern - Constructor used for cloning nonterminal patterns
165   Pattern(TreePatternNode *tree, Record *rec, bool res,
166           InstrSelectorEmitter &ise) : PTy(Nonterminal), Tree(tree), Result(0),
167                                        TheRecord(rec), Resolved(res), ISE(ise){}
168
169   /// getPatternType - Return what flavor of Record this pattern originated from
170   ///
171   PatternType getPatternType() const { return PTy; }
172
173   /// getTree - Return the tree pattern which corresponds to this pattern.
174   ///
175   TreePatternNode *getTree() const { return Tree; }
176   
177   Record *getResult() const { return Result; }
178
179   /// getRecord - Return the actual TableGen record corresponding to this
180   /// pattern.
181   ///
182   Record *getRecord() const { return TheRecord; }
183
184   bool isResolved() const { return Resolved; }
185
186   /// InferAllTypes - Runs the type inference engine on the current pattern,
187   /// stopping when nothing can be inferred, then updating the Resolved field.
188   void InferAllTypes();
189
190   /// InstantiateNonterminals - If this pattern refers to any nonterminals which
191   /// are not themselves completely resolved, clone the nonterminal and resolve
192   /// it with the using context we provide.
193   void InstantiateNonterminals() {
194     Tree->InstantiateNonterminals(ISE);
195   }
196
197   /// clone - This method is used to make an exact copy of the current pattern,
198   /// then change the "TheRecord" instance variable to the specified record.
199   ///
200   Pattern *clone(Record *R) const;
201
202   /// error - Throw an exception, prefixing it with information about this
203   /// pattern.
204   void error(const std::string &Msg) const;
205
206   /// getSlotName - If this is a leaf node, return the slot name that the
207   /// operand will update.
208   std::string getSlotName() const;
209   static std::string getSlotName(Record *R);
210
211 private:
212   MVT::ValueType getIntrinsicType(Record *R) const;
213   TreePatternNode *ParseTreePattern(DagInit *DI);
214   bool InferTypes(TreePatternNode *N, bool &MadeChange);
215 };
216
217 std::ostream &operator<<(std::ostream &OS, const Pattern &P);
218
219
220 /// PatternOrganizer - This class represents all of the patterns which are
221 /// useful for the instruction selector, neatly catagorized in a hierarchical
222 /// structure.
223 struct PatternOrganizer {
224   /// PatternsForNode - The list of patterns which can produce a value of a
225   /// particular slot type, given a particular root node in the tree.  All of
226   /// the patterns in this vector produce the same value type and have the same
227   /// root DAG node.
228   typedef std::vector<Pattern*> PatternsForNode;
229
230   /// NodesForSlot - This map keeps track of all of the root DAG nodes which can
231   /// lead to the production of a value for this slot.  All of the patterns in
232   /// this data structure produces values of the same slot.
233   typedef std::map<Record*, PatternsForNode> NodesForSlot;
234
235   /// AllPatterns - This data structure contains all patterns in the instruction
236   /// selector.
237   std::map<std::string, NodesForSlot> AllPatterns;
238
239   // Forwarding functions...
240   typedef std::map<std::string, NodesForSlot>::iterator iterator;
241   iterator begin() { return AllPatterns.begin(); }
242   iterator end()   { return AllPatterns.end(); }
243
244
245   /// addPattern - Add the specified pattern to the appropriate location in the
246   /// collection.
247   void addPattern(Pattern *P);
248 };
249
250
251 /// InstrSelectorEmitter - The top-level class which coordinates construction
252 /// and emission of the instruction selector.
253 ///
254 class InstrSelectorEmitter : public TableGenBackend {
255   RecordKeeper &Records;
256   CodeGenTarget Target;
257
258   std::map<Record*, NodeType> NodeTypes;
259
260   /// Patterns - a list of all of the patterns defined by the target description
261   ///
262   std::map<Record*, Pattern*> Patterns;
263
264   /// InstantiatedNTs - A data structure to keep track of which nonterminals
265   /// have been instantiated already...
266   ///
267   std::map<std::pair<Pattern*,MVT::ValueType>, Record*> InstantiatedNTs;
268
269   /// ComputableValues - This map indicates which patterns can be used to
270   /// generate a value that is used by the selector.  The keys of this map
271   /// implicitly define the values that are used by the selector.
272   ///
273   PatternOrganizer ComputableValues;
274
275 public:
276   InstrSelectorEmitter(RecordKeeper &R) : Records(R) {}
277   
278   // run - Output the instruction set description, returning true on failure.
279   void run(std::ostream &OS);
280
281   const CodeGenTarget &getTarget() const { return Target; }
282   std::map<Record*, NodeType> &getNodeTypes() { return NodeTypes; }
283   const NodeType &getNodeType(Record *R) const {
284     std::map<Record*, NodeType>::const_iterator I = NodeTypes.find(R);
285     assert(I != NodeTypes.end() && "Unknown node type!");
286     return I->second;
287   }
288
289   /// getPattern - return the pattern corresponding to the specified record, or
290   /// null if there is none.
291   Pattern *getPattern(Record *R) const {
292     std::map<Record*, Pattern*>::const_iterator I = Patterns.find(R);
293     return I != Patterns.end() ? I->second : 0;
294   }
295
296   /// ReadNonterminal - This method parses the specified record as a
297   /// nonterminal, but only if it hasn't been read in already.
298   Pattern *ReadNonterminal(Record *R);
299
300   /// InstantiateNonterminal - This method takes the nonterminal specified by
301   /// NT, which should not be completely resolved, clones it, applies ResultTy
302   /// to its root, then runs the type inference stuff on it.  This should
303   /// produce a newly resolved nonterminal, which we make a record for and
304   /// return.  To be extra fancy and efficient, this only makes one clone for
305   /// each type it is instantiated with.
306   Record *InstantiateNonterminal(Pattern *NT, MVT::ValueType ResultTy);
307
308 private:
309   // ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
310   // turning them into the more accessible NodeTypes data structure.
311   void ReadNodeTypes();
312
313   // ReadNonTerminals - Read in all nonterminals and incorporate them into our
314   // pattern database.
315   void ReadNonterminals();
316
317   // ReadInstructionPatterns - Read in all subclasses of Instruction, and
318   // process those with a useful Pattern field.
319   void ReadInstructionPatterns();
320
321   // ReadExpanderPatterns - Read in all of the expanded patterns.
322   void ReadExpanderPatterns();
323
324   // InstantiateNonterminals - Instantiate any unresolved nonterminals with
325   // information from the context that they are used in.
326   void InstantiateNonterminals();
327   
328   // CalculateComputableValues - Fill in the ComputableValues map through
329   // analysis of the patterns we are playing with.
330   void CalculateComputableValues();
331
332   // EmitMatchCosters - Given a list of patterns, which all have the same root
333   // pattern operator, emit an efficient decision tree to decide which one to
334   // pick.  This is structured this way to avoid reevaluations of non-obvious
335   // subexpressions.
336   void EmitMatchCosters(std::ostream &OS,
337             const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
338                         const std::string &VarPrefix, unsigned Indent);
339 };
340
341 #endif