Add support for the Any type. Minor fixes and enhancements for BasicBlock operands
[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     Any,            // No constraint on type
24     Val,            // A non-void type
25     Arg0,           // Value matches the type of Arg0
26     Arg1,           // Value matches the type of Arg1
27     Ptr,            // Tree node is the type of the target pointer
28     I8,             // Always bool
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<std::pair<TreePatternNode*, std::string> > 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<std::pair<TreePatternNode*,
67                                                          std::string> > &c)
68     : Operator(o), Type(MVT::Other), Children(c), Value(0) {}
69   TreePatternNode(Init *V) : Operator(0), Type(MVT::Other), Value(V) {}
70
71   Record *getOperator() const {
72     assert(Operator && "This is a leaf node!");
73     return Operator;
74   }
75   MVT::ValueType getType() const { return Type; }
76   void setType(MVT::ValueType T) { Type = T; }
77
78   bool isLeaf() const { return Operator == 0; }
79
80   unsigned getNumChildren() const { return Children.size(); }
81   TreePatternNode *getChild(unsigned c) const {
82     assert(Operator != 0 && "This is a leaf node!");
83     assert(c < Children.size() && "Child access out of range!");
84     return Children[c].first;
85   }
86   const std::string &getChildName(unsigned c) const {
87     assert(Operator != 0 && "This is a leaf node!");
88     assert(c < Children.size() && "Child access out of range!");
89     return Children[c].second;
90   }
91
92   Init *getValue() const {
93     assert(Operator == 0 && "This is not a leaf node!");
94     return Value;
95   }
96
97   /// getValueRecord - Returns the value of this tree node as a record.  For now
98   /// we only allow DefInit's as our leaf values, so this is used.
99   Record *getValueRecord() const;
100
101   /// clone - Make a copy of this tree and all of its children.
102   ///
103   TreePatternNode *clone() const;
104
105   void dump() const;
106
107   /// InstantiateNonterminals - If this pattern refers to any nonterminals which
108   /// are not themselves completely resolved, clone the nonterminal and resolve
109   /// it with the using context we provide.
110   void InstantiateNonterminals(InstrSelectorEmitter &ISE);
111
112   /// UpdateNodeType - Set the node type of N to VT if VT contains information.
113   /// If N already contains a conflicting type, then throw an exception.  This
114   /// returns true if any information was updated.
115   ///
116   bool updateNodeType(MVT::ValueType VT, const std::string &RecName);
117 };
118
119 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N);
120
121
122
123 /// Pattern - Represent a pattern of one form or another.  Currently, three
124 /// types of patterns are possible: Instruction's, Nonterminals, and Expanders.
125 ///
126 struct Pattern {
127   enum PatternType {
128     Nonterminal, Instruction, Expander
129   };
130 private:
131   /// PTy - The type of pattern this is.
132   ///
133   PatternType PTy;
134
135   /// Tree - The tree pattern which corresponds to this pattern.  Note that if
136   /// there was a (set) node on the outside level that it has been stripped off.
137   ///
138   TreePatternNode *Tree;
139   
140   /// Result - If this is an instruction or expander pattern, this is the
141   /// register result, specified with a (set) in the pattern.
142   ///
143   std::string ResultName;      // The name of the result value...
144   TreePatternNode *ResultNode; // The leaf node for the result register...
145
146   /// TheRecord - The actual TableGen record corresponding to this pattern.
147   ///
148   Record *TheRecord;
149
150   /// Resolved - This is true of the pattern is useful in practice.  In
151   /// particular, some non-terminals will have non-resolvable types.  When a
152   /// user of the non-terminal is later found, they will have inferred a type
153   /// for the result of the non-terminal, which cause a clone of an unresolved
154   /// nonterminal to be made which is "resolved".
155   ///
156   bool Resolved;
157
158   /// Args - This is a list of all of the arguments to this pattern, which are
159   /// the non-void leaf nodes in this pattern.
160   std::vector<std::pair<TreePatternNode*, std::string> > Args;
161
162   /// ISE - the instruction selector emitter coordinating this madness.
163   ///
164   InstrSelectorEmitter &ISE;
165 public:
166
167   /// Pattern constructor - Parse the specified DagInitializer into the current
168   /// record.
169   Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
170           InstrSelectorEmitter &ise);
171
172   /// Pattern - Constructor used for cloning nonterminal patterns
173   Pattern(TreePatternNode *tree, Record *rec, bool res,
174           InstrSelectorEmitter &ise)
175     : PTy(Nonterminal), Tree(tree), ResultNode(0), TheRecord(rec),
176       Resolved(res), ISE(ise) {
177     calculateArgs(Tree, "");
178   }
179
180   /// getPatternType - Return what flavor of Record this pattern originated from
181   ///
182   PatternType getPatternType() const { return PTy; }
183
184   /// getTree - Return the tree pattern which corresponds to this pattern.
185   ///
186   TreePatternNode *getTree() const { return Tree; }
187   
188   Record *getResult() const {
189     return ResultNode ? ResultNode->getValueRecord() : 0;
190   }
191   const std::string &getResultName() const { return ResultName; }
192   TreePatternNode *getResultNode() const { return ResultNode; }
193
194   /// getRecord - Return the actual TableGen record corresponding to this
195   /// pattern.
196   ///
197   Record *getRecord() const { return TheRecord; }
198
199   unsigned getNumArgs() const { return Args.size(); }
200   TreePatternNode *getArg(unsigned i) const {
201     assert(i < Args.size() && "Argument reference out of range!");
202     return Args[i].first;
203   }
204   Record *getArgRec(unsigned i) const {
205     return getArg(i)->getValueRecord();
206   }
207   Init *getArgVal(unsigned i) const {
208     return getArg(i)->getValue();
209   }
210   const std::string &getArgName(unsigned i) const {
211     assert(i < Args.size() && "Argument reference out of range!");
212     return Args[i].second;
213   }
214
215   bool isResolved() const { return Resolved; }
216
217   /// InferAllTypes - Runs the type inference engine on the current pattern,
218   /// stopping when nothing can be inferred, then updating the Resolved field.
219   void InferAllTypes();
220
221   /// InstantiateNonterminals - If this pattern refers to any nonterminals which
222   /// are not themselves completely resolved, clone the nonterminal and resolve
223   /// it with the using context we provide.
224   void InstantiateNonterminals() {
225     Tree->InstantiateNonterminals(ISE);
226   }
227
228   /// clone - This method is used to make an exact copy of the current pattern,
229   /// then change the "TheRecord" instance variable to the specified record.
230   ///
231   Pattern *clone(Record *R) const;
232
233   /// error - Throw an exception, prefixing it with information about this
234   /// pattern.
235   void error(const std::string &Msg) const;
236
237   /// getSlotName - If this is a leaf node, return the slot name that the
238   /// operand will update.
239   std::string getSlotName() const;
240   static std::string getSlotName(Record *R);
241
242   void dump() const;
243
244 private:
245   void calculateArgs(TreePatternNode *N, const std::string &Name);
246   MVT::ValueType getIntrinsicType(Record *R) const;
247   TreePatternNode *ParseTreePattern(DagInit *DI);
248   bool InferTypes(TreePatternNode *N, bool &MadeChange);
249 };
250
251 std::ostream &operator<<(std::ostream &OS, const Pattern &P);
252
253
254 /// PatternOrganizer - This class represents all of the patterns which are
255 /// useful for the instruction selector, neatly catagorized in a hierarchical
256 /// structure.
257 struct PatternOrganizer {
258   /// PatternsForNode - The list of patterns which can produce a value of a
259   /// particular slot type, given a particular root node in the tree.  All of
260   /// the patterns in this vector produce the same value type and have the same
261   /// root DAG node.
262   typedef std::vector<Pattern*> PatternsForNode;
263
264   /// NodesForSlot - This map keeps track of all of the root DAG nodes which can
265   /// lead to the production of a value for this slot.  All of the patterns in
266   /// this data structure produces values of the same slot.
267   typedef std::map<Record*, PatternsForNode> NodesForSlot;
268
269   /// AllPatterns - This data structure contains all patterns in the instruction
270   /// selector.
271   std::map<std::string, NodesForSlot> AllPatterns;
272
273   // Forwarding functions...
274   typedef std::map<std::string, NodesForSlot>::iterator iterator;
275   iterator begin() { return AllPatterns.begin(); }
276   iterator end()   { return AllPatterns.end(); }
277
278
279   /// addPattern - Add the specified pattern to the appropriate location in the
280   /// collection.
281   void addPattern(Pattern *P);
282 };
283
284
285 /// InstrSelectorEmitter - The top-level class which coordinates construction
286 /// and emission of the instruction selector.
287 ///
288 class InstrSelectorEmitter : public TableGenBackend {
289   RecordKeeper &Records;
290   CodeGenTarget Target;
291
292   std::map<Record*, NodeType> NodeTypes;
293
294   /// Patterns - a list of all of the patterns defined by the target description
295   ///
296   std::map<Record*, Pattern*> Patterns;
297
298   /// InstantiatedNTs - A data structure to keep track of which nonterminals
299   /// have been instantiated already...
300   ///
301   std::map<std::pair<Pattern*,MVT::ValueType>, Record*> InstantiatedNTs;
302
303   /// ComputableValues - This map indicates which patterns can be used to
304   /// generate a value that is used by the selector.  The keys of this map
305   /// implicitly define the values that are used by the selector.
306   ///
307   PatternOrganizer ComputableValues;
308
309 public:
310   InstrSelectorEmitter(RecordKeeper &R) : Records(R) {}
311   
312   // run - Output the instruction set description, returning true on failure.
313   void run(std::ostream &OS);
314
315   const CodeGenTarget &getTarget() const { return Target; }
316   std::map<Record*, NodeType> &getNodeTypes() { return NodeTypes; }
317   const NodeType &getNodeType(Record *R) const {
318     std::map<Record*, NodeType>::const_iterator I = NodeTypes.find(R);
319     assert(I != NodeTypes.end() && "Unknown node type!");
320     return I->second;
321   }
322
323   /// getPattern - return the pattern corresponding to the specified record, or
324   /// null if there is none.
325   Pattern *getPattern(Record *R) const {
326     std::map<Record*, Pattern*>::const_iterator I = Patterns.find(R);
327     return I != Patterns.end() ? I->second : 0;
328   }
329
330   /// ReadNonterminal - This method parses the specified record as a
331   /// nonterminal, but only if it hasn't been read in already.
332   Pattern *ReadNonterminal(Record *R);
333
334   /// InstantiateNonterminal - This method takes the nonterminal specified by
335   /// NT, which should not be completely resolved, clones it, applies ResultTy
336   /// to its root, then runs the type inference stuff on it.  This should
337   /// produce a newly resolved nonterminal, which we make a record for and
338   /// return.  To be extra fancy and efficient, this only makes one clone for
339   /// each type it is instantiated with.
340   Record *InstantiateNonterminal(Pattern *NT, MVT::ValueType ResultTy);
341
342 private:
343   // ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
344   // turning them into the more accessible NodeTypes data structure.
345   void ReadNodeTypes();
346
347   // ReadNonTerminals - Read in all nonterminals and incorporate them into our
348   // pattern database.
349   void ReadNonterminals();
350
351   // ReadInstructionPatterns - Read in all subclasses of Instruction, and
352   // process those with a useful Pattern field.
353   void ReadInstructionPatterns();
354
355   // ReadExpanderPatterns - Read in all of the expanded patterns.
356   void ReadExpanderPatterns();
357
358   // InstantiateNonterminals - Instantiate any unresolved nonterminals with
359   // information from the context that they are used in.
360   void InstantiateNonterminals();
361   
362   // CalculateComputableValues - Fill in the ComputableValues map through
363   // analysis of the patterns we are playing with.
364   void CalculateComputableValues();
365
366   // EmitMatchCosters - Given a list of patterns, which all have the same root
367   // pattern operator, emit an efficient decision tree to decide which one to
368   // pick.  This is structured this way to avoid reevaluations of non-obvious
369   // subexpressions.
370   void EmitMatchCosters(std::ostream &OS,
371             const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
372                         const std::string &VarPrefix, unsigned Indent);
373   
374   /// PrintExpanderOperand - Print out Arg as part of the instruction emission
375   /// process for the expander pattern P.  This argument may be referencing some
376   /// values defined in P, or may just be physical register references or
377   /// something like that.  If PrintArg is true, we are printing out arguments
378   /// to the BuildMI call.  If it is false, we are printing the result register
379   /// name.
380   void PrintExpanderOperand(Init *Arg, const std::string &NameVar,
381                             TreePatternNode *ArgDecl, Pattern *P,
382                             bool PrintArg, std::ostream &OS);
383 };
384
385 #endif