Emit the first half of the instruction selector.
[oota-llvm.git] / utils / 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   TreePatternNode *getChild(unsigned c) const {
84     assert(c < Children.size() && "Child access out of range!");
85     return getChildren()[c];
86   }
87
88   Init *getValue() const {
89     assert(Operator == 0 && "This is not a leaf node!");
90     return Value;
91   }
92
93   /// clone - Make a copy of this tree and all of its children.
94   ///
95   TreePatternNode *clone() const;
96
97   void dump() const;
98
99   /// InstantiateNonterminals - If this pattern refers to any nonterminals which
100   /// are not themselves completely resolved, clone the nonterminal and resolve
101   /// it with the using context we provide.
102   void InstantiateNonterminals(InstrSelectorEmitter &ISE);
103
104   // UpdateNodeType - Set the node type of N to VT if VT contains information.
105   // If N already contains a conflicting type, then throw an exception.  This
106   // returns true if any information was updated.
107   //
108   bool updateNodeType(MVT::ValueType VT, const std::string &RecName);
109 };
110
111 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N);
112
113
114
115 /// Pattern - Represent a pattern of one form or another.  Currently, three
116 /// types of patterns are possible: Instruction's, Nonterminals, and Expanders.
117 ///
118 struct Pattern {
119   enum PatternType {
120     Nonterminal, Instruction, Expander
121   };
122 private:
123   /// PTy - The type of pattern this is.
124   ///
125   PatternType PTy;
126
127   /// Tree - The tree pattern which corresponds to this pattern.  Note that if
128   /// there was a (set) node on the outside level that it has been stripped off.
129   ///
130   TreePatternNode *Tree;
131   
132   /// Result - If this is an instruction or expander pattern, this is the
133   /// register result, specified with a (set) in the pattern.
134   ///
135   Record *Result;
136
137   /// TheRecord - The actual TableGen record corresponding to this pattern.
138   ///
139   Record *TheRecord;
140
141   /// Resolved - This is true of the pattern is useful in practice.  In
142   /// particular, some non-terminals will have non-resolvable types.  When a
143   /// user of the non-terminal is later found, they will have inferred a type
144   /// for the result of the non-terminal, which cause a clone of an unresolved
145   /// nonterminal to be made which is "resolved".
146   ///
147   bool Resolved;
148
149   /// ISE - the instruction selector emitter coordinating this madness.
150   ///
151   InstrSelectorEmitter &ISE;
152 public:
153
154   /// Pattern constructor - Parse the specified DagInitializer into the current
155   /// record.
156   Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
157           InstrSelectorEmitter &ise);
158
159   /// Pattern - Constructor used for cloning nonterminal patterns
160   Pattern(TreePatternNode *tree, Record *rec, bool res,
161           InstrSelectorEmitter &ise) : PTy(Nonterminal), Tree(tree), Result(0),
162                                        TheRecord(rec), Resolved(res), ISE(ise){}
163
164   /// getPatternType - Return what flavor of Record this pattern originated from
165   ///
166   PatternType getPatternType() const { return PTy; }
167
168   /// getTree - Return the tree pattern which corresponds to this pattern.
169   ///
170   TreePatternNode *getTree() const { return Tree; }
171   
172   Record *getResult() const { return Result; }
173
174   /// getRecord - Return the actual TableGen record corresponding to this
175   /// pattern.
176   ///
177   Record *getRecord() const { return TheRecord; }
178
179   bool isResolved() const { return Resolved; }
180
181   /// InferAllTypes - Runs the type inference engine on the current pattern,
182   /// stopping when nothing can be inferred, then updating the Resolved field.
183   void InferAllTypes();
184
185   /// InstantiateNonterminals - If this pattern refers to any nonterminals which
186   /// are not themselves completely resolved, clone the nonterminal and resolve
187   /// it with the using context we provide.
188   void InstantiateNonterminals() {
189     Tree->InstantiateNonterminals(ISE);
190   }
191
192   /// clone - This method is used to make an exact copy of the current pattern,
193   /// then change the "TheRecord" instance variable to the specified record.
194   ///
195   Pattern *clone(Record *R) const;
196
197   /// error - Throw an exception, prefixing it with information about this
198   /// pattern.
199   void error(const std::string &Msg) const;
200
201 private:
202   MVT::ValueType getIntrinsicType(Record *R) const;
203   TreePatternNode *ParseTreePattern(DagInit *DI);
204   bool InferTypes(TreePatternNode *N, bool &MadeChange);
205 };
206
207 std::ostream &operator<<(std::ostream &OS, const Pattern &P);
208
209
210 /// PatternOrganizer - This class represents all of the patterns which are
211 /// useful for the instruction selector, neatly catagorized in a hierarchical
212 /// structure.
213 struct PatternOrganizer {
214   /// PatternsForNode - The list of patterns which can produce a value of a
215   /// particular slot type, given a particular root node in the tree.  All of
216   /// the patterns in this vector produce the same value type and have the same
217   /// root DAG node.
218   typedef std::vector<Pattern*> PatternsForNode;
219
220   /// NodesForSlot - This map keeps track of all of the root DAG nodes which can
221   /// lead to the production of a value for this slot.  All of the patterns in
222   /// this data structure produces values of the same slot.
223   typedef std::map<Record*, PatternsForNode> NodesForSlot;
224
225   /// AllPatterns - This data structure contains all patterns in the instruction
226   /// selector.
227   std::map<std::string, NodesForSlot> AllPatterns;
228
229   // Forwarding functions...
230   typedef std::map<std::string, NodesForSlot>::iterator iterator;
231   iterator begin() { return AllPatterns.begin(); }
232   iterator end()   { return AllPatterns.end(); }
233
234
235   /// addPattern - Add the specified pattern to the appropriate location in the
236   /// collection.
237   void addPattern(Pattern *P);
238 };
239
240
241 /// InstrSelectorEmitter - The top-level class which coordinates construction
242 /// and emission of the instruction selector.
243 ///
244 class InstrSelectorEmitter : public TableGenBackend {
245   RecordKeeper &Records;
246   CodeGenTarget Target;
247
248   std::map<Record*, NodeType> NodeTypes;
249
250   /// Patterns - a list of all of the patterns defined by the target description
251   ///
252   std::map<Record*, Pattern*> Patterns;
253
254   /// InstantiatedNTs - A data structure to keep track of which nonterminals
255   /// have been instantiated already...
256   ///
257   std::map<std::pair<Pattern*,MVT::ValueType>, Record*> InstantiatedNTs;
258
259   /// ComputableValues - This map indicates which patterns can be used to
260   /// generate a value that is used by the selector.  The keys of this map
261   /// implicitly define the values that are used by the selector.
262   ///
263   PatternOrganizer ComputableValues;
264
265 public:
266   InstrSelectorEmitter(RecordKeeper &R) : Records(R) {}
267   
268   // run - Output the instruction set description, returning true on failure.
269   void run(std::ostream &OS);
270
271   const CodeGenTarget &getTarget() const { return Target; }
272   std::map<Record*, NodeType> &getNodeTypes() { return NodeTypes; }
273
274   /// getPattern - return the pattern corresponding to the specified record, or
275   /// null if there is none.
276   Pattern *getPattern(Record *R) const {
277     std::map<Record*, Pattern*>::const_iterator I = Patterns.find(R);
278     return I != Patterns.end() ? I->second : 0;
279   }
280
281   /// ReadNonterminal - This method parses the specified record as a
282   /// nonterminal, but only if it hasn't been read in already.
283   Pattern *ReadNonterminal(Record *R);
284
285   /// InstantiateNonterminal - This method takes the nonterminal specified by
286   /// NT, which should not be completely resolved, clones it, applies ResultTy
287   /// to its root, then runs the type inference stuff on it.  This should
288   /// produce a newly resolved nonterminal, which we make a record for and
289   /// return.  To be extra fancy and efficient, this only makes one clone for
290   /// each type it is instantiated with.
291   Record *InstantiateNonterminal(Pattern *NT, MVT::ValueType ResultTy);
292
293 private:
294   // ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
295   // turning them into the more accessible NodeTypes data structure.
296   void ReadNodeTypes();
297
298   // ReadNonTerminals - Read in all nonterminals and incorporate them into our
299   // pattern database.
300   void ReadNonterminals();
301
302   // ReadInstructionPatterns - Read in all subclasses of Instruction, and
303   // process those with a useful Pattern field.
304   void ReadInstructionPatterns();
305
306   // ReadExpanderPatterns - Read in all of the expanded patterns.
307   void ReadExpanderPatterns();
308
309   // InstantiateNonterminals - Instantiate any unresolved nonterminals with
310   // information from the context that they are used in.
311   void InstantiateNonterminals();
312   
313   // CalculateComputableValues - Fill in the ComputableValues map through
314   // analysis of the patterns we are playing with.
315   void CalculateComputableValues();
316 };
317
318 #endif