Teach tblgen to build permutations of instructions, so that the target author
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.h
1 //===- DAGISelEmitter.h - Generate an instruction selector ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef DAGISEL_EMITTER_H
15 #define DAGISEL_EMITTER_H
16
17 #include "TableGenBackend.h"
18 #include "CodeGenTarget.h"
19
20 namespace llvm {
21   class Record;
22   struct Init;
23   class ListInit;
24   class DagInit;
25   class SDNodeInfo;
26   class TreePattern;
27   class TreePatternNode;
28   class DAGISelEmitter;
29   
30   /// SDTypeConstraint - This is a discriminated union of constraints,
31   /// corresponding to the SDTypeConstraint tablegen class in Target.td.
32   struct SDTypeConstraint {
33     SDTypeConstraint(Record *R);
34     
35     unsigned OperandNo;   // The operand # this constraint applies to.
36     enum { 
37       SDTCisVT, SDTCisInt, SDTCisFP, SDTCisSameAs, SDTCisVTSmallerThanOp
38     } ConstraintType;
39     
40     union {   // The discriminated union.
41       struct {
42         MVT::ValueType VT;
43       } SDTCisVT_Info;
44       struct {
45         unsigned OtherOperandNum;
46       } SDTCisSameAs_Info;
47       struct {
48         unsigned OtherOperandNum;
49       } SDTCisVTSmallerThanOp_Info;
50     } x;
51
52     /// ApplyTypeConstraint - Given a node in a pattern, apply this type
53     /// constraint to the nodes operands.  This returns true if it makes a
54     /// change, false otherwise.  If a type contradiction is found, throw an
55     /// exception.
56     bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
57                              TreePattern &TP) const;
58     
59     /// getOperandNum - Return the node corresponding to operand #OpNo in tree
60     /// N, which has NumResults results.
61     TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
62                                    unsigned NumResults) const;
63   };
64   
65   /// SDNodeInfo - One of these records is created for each SDNode instance in
66   /// the target .td file.  This represents the various dag nodes we will be
67   /// processing.
68   class SDNodeInfo {
69     Record *Def;
70     std::string EnumName;
71     std::string SDClassName;
72     unsigned Properties;
73     unsigned NumResults;
74     int NumOperands;
75     std::vector<SDTypeConstraint> TypeConstraints;
76   public:
77     SDNodeInfo(Record *R);  // Parse the specified record.
78     
79     unsigned getNumResults() const { return NumResults; }
80     int getNumOperands() const { return NumOperands; }
81     Record *getRecord() const { return Def; }
82     const std::string &getEnumName() const { return EnumName; }
83     const std::string &getSDClassName() const { return SDClassName; }
84     
85     const std::vector<SDTypeConstraint> &getTypeConstraints() const {
86       return TypeConstraints;
87     }
88     
89     // SelectionDAG node properties.
90     enum SDNP { SDNPCommutative, SDNPAssociative };
91
92     /// hasProperty - Return true if this node has the specified property.
93     ///
94     bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
95
96     /// ApplyTypeConstraints - Given a node in a pattern, apply the type
97     /// constraints for this node to the operands of the node.  This returns
98     /// true if it makes a change, false otherwise.  If a type contradiction is
99     /// found, throw an exception.
100     bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
101       bool MadeChange = false;
102       for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
103         MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
104       return MadeChange;
105     }
106   };
107
108   /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
109   /// patterns), and as such should be ref counted.  We currently just leak all
110   /// TreePatternNode objects!
111   class TreePatternNode {
112     /// The inferred type for this node, or MVT::LAST_VALUETYPE if it hasn't
113     /// been determined yet.
114     MVT::ValueType Ty;
115
116     /// Operator - The Record for the operator if this is an interior node (not
117     /// a leaf).
118     Record *Operator;
119     
120     /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
121     ///
122     Init *Val;
123     
124     /// Name - The name given to this node with the :$foo notation.
125     ///
126     std::string Name;
127     
128     /// PredicateFn - The predicate function to execute on this node to check
129     /// for a match.  If this string is empty, no predicate is involved.
130     std::string PredicateFn;
131     
132     /// TransformFn - The transformation function to execute on this node before
133     /// it can be substituted into the resulting instruction on a pattern match.
134     Record *TransformFn;
135     
136     std::vector<TreePatternNode*> Children;
137   public:
138     TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch) 
139       : Ty(MVT::LAST_VALUETYPE), Operator(Op), Val(0), TransformFn(0),
140         Children(Ch) {}
141     TreePatternNode(Init *val)    // leaf ctor
142       : Ty(MVT::LAST_VALUETYPE), Operator(0), Val(val), TransformFn(0) {}
143     ~TreePatternNode();
144     
145     const std::string &getName() const { return Name; }
146     void setName(const std::string &N) { Name = N; }
147     
148     bool isLeaf() const { return Val != 0; }
149     bool hasTypeSet() const { return Ty != MVT::LAST_VALUETYPE; }
150     MVT::ValueType getType() const { return Ty; }
151     void setType(MVT::ValueType VT) { Ty = VT; }
152     
153     Init *getLeafValue() const { assert(isLeaf()); return Val; }
154     Record *getOperator() const { assert(!isLeaf()); return Operator; }
155     
156     unsigned getNumChildren() const { return Children.size(); }
157     TreePatternNode *getChild(unsigned N) const { return Children[N]; }
158     void setChild(unsigned i, TreePatternNode *N) {
159       Children[i] = N;
160     }
161     
162     const std::string &getPredicateFn() const { return PredicateFn; }
163     void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
164
165     Record *getTransformFn() const { return TransformFn; }
166     void setTransformFn(Record *Fn) { TransformFn = Fn; }
167     
168     void print(std::ostream &OS) const;
169     void dump() const;
170     
171   public:   // Higher level manipulation routines.
172
173     /// clone - Return a new copy of this tree.
174     ///
175     TreePatternNode *clone() const;
176     
177     /// isIsomorphicTo - Return true if this node is recursively isomorphic to
178     /// the specified node.  For this comparison, all of the state of the node
179     /// is considered, except for the assigned name.  Nodes with differing names
180     /// that are otherwise identical are considered isomorphic.
181     bool isIsomorphicTo(const TreePatternNode *N) const;
182     
183     /// SubstituteFormalArguments - Replace the formal arguments in this tree
184     /// with actual values specified by ArgMap.
185     void SubstituteFormalArguments(std::map<std::string,
186                                             TreePatternNode*> &ArgMap);
187
188     /// InlinePatternFragments - If this pattern refers to any pattern
189     /// fragments, inline them into place, giving us a pattern without any
190     /// PatFrag references.
191     TreePatternNode *InlinePatternFragments(TreePattern &TP);
192     
193     /// ApplyTypeConstraints - Apply all of the type constraints relevent to
194     /// this node and its children in the tree.  This returns true if it makes a
195     /// change, false otherwise.  If a type contradiction is found, throw an
196     /// exception.
197     bool ApplyTypeConstraints(TreePattern &TP);
198     
199     /// UpdateNodeType - Set the node type of N to VT if VT contains
200     /// information.  If N already contains a conflicting type, then throw an
201     /// exception.  This returns true if any information was updated.
202     ///
203     bool UpdateNodeType(MVT::ValueType VT, TreePattern &TP);
204     
205     /// ContainsUnresolvedType - Return true if this tree contains any
206     /// unresolved types.
207     bool ContainsUnresolvedType() const {
208       if (Ty == MVT::LAST_VALUETYPE) return true;
209       for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
210         if (getChild(i)->ContainsUnresolvedType()) return true;
211       return false;
212     }
213     
214     /// canPatternMatch - If it is impossible for this pattern to match on this
215     /// target, fill in Reason and return false.  Otherwise, return true.
216     bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
217   };
218   
219   
220   /// TreePattern - Represent a pattern, used for instructions, pattern
221   /// fragments, etc.
222   ///
223   class TreePattern {
224     /// Trees - The list of pattern trees which corresponds to this pattern.
225     /// Note that PatFrag's only have a single tree.
226     ///
227     std::vector<TreePatternNode*> Trees;
228     
229     /// TheRecord - The actual TableGen record corresponding to this pattern.
230     ///
231     Record *TheRecord;
232       
233     /// Args - This is a list of all of the arguments to this pattern (for
234     /// PatFrag patterns), which are the 'node' markers in this pattern.
235     std::vector<std::string> Args;
236     
237     /// ISE - the DAG isel emitter coordinating this madness.
238     ///
239     DAGISelEmitter &ISE;
240   public:
241       
242     /// TreePattern constructor - Parse the specified DagInits into the
243     /// current record.
244     TreePattern(Record *TheRec, ListInit *RawPat, DAGISelEmitter &ise);
245     TreePattern(Record *TheRec, DagInit *Pat, DAGISelEmitter &ise);
246     TreePattern(Record *TheRec, TreePatternNode *Pat, DAGISelEmitter &ise);
247         
248     /// getTrees - Return the tree patterns which corresponds to this pattern.
249     ///
250     const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
251     unsigned getNumTrees() const { return Trees.size(); }
252     TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
253     TreePatternNode *getOnlyTree() const {
254       assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
255       return Trees[0];
256     }
257         
258     /// getRecord - Return the actual TableGen record corresponding to this
259     /// pattern.
260     ///
261     Record *getRecord() const { return TheRecord; }
262     
263     unsigned getNumArgs() const { return Args.size(); }
264     const std::string &getArgName(unsigned i) const {
265       assert(i < Args.size() && "Argument reference out of range!");
266       return Args[i];
267     }
268     std::vector<std::string> &getArgList() { return Args; }
269     
270     DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
271
272     /// InlinePatternFragments - If this pattern refers to any pattern
273     /// fragments, inline them into place, giving us a pattern without any
274     /// PatFrag references.
275     void InlinePatternFragments() {
276       for (unsigned i = 0, e = Trees.size(); i != e; ++i)
277         Trees[i] = Trees[i]->InlinePatternFragments(*this);
278     }
279     
280     /// InferAllTypes - Infer/propagate as many types throughout the expression
281     /// patterns as possible.  Return true if all types are infered, false
282     /// otherwise.  Throw an exception if a type contradiction is found.
283     bool InferAllTypes();
284     
285     /// error - Throw an exception, prefixing it with information about this
286     /// pattern.
287     void error(const std::string &Msg) const;
288     
289     void print(std::ostream &OS) const;
290     void dump() const;
291     
292   private:
293     MVT::ValueType getIntrinsicType(Record *R) const;
294     TreePatternNode *ParseTreePattern(DagInit *DI);
295   };
296
297
298   class DAGInstruction {
299     TreePattern *Pattern;
300     unsigned NumResults;
301     unsigned NumOperands;
302     std::vector<MVT::ValueType> ResultTypes;
303     std::vector<MVT::ValueType> OperandTypes;
304     TreePatternNode *ResultPattern;
305   public:
306     DAGInstruction(TreePattern *TP,
307                    const std::vector<MVT::ValueType> &resultTypes,
308                    const std::vector<MVT::ValueType> &operandTypes)
309       : Pattern(TP), ResultTypes(resultTypes), OperandTypes(operandTypes), 
310         ResultPattern(0) {}
311
312     TreePattern *getPattern() const { return Pattern; }
313     unsigned getNumResults() const { return ResultTypes.size(); }
314     unsigned getNumOperands() const { return OperandTypes.size(); }
315     
316     void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
317     
318     MVT::ValueType getResultType(unsigned RN) const {
319       assert(RN < ResultTypes.size());
320       return ResultTypes[RN];
321     }
322     
323     MVT::ValueType getOperandType(unsigned ON) const {
324       assert(ON < OperandTypes.size());
325       return OperandTypes[ON];
326     }
327     TreePatternNode *getResultPattern() const { return ResultPattern; }
328   };
329   
330   
331 /// InstrSelectorEmitter - The top-level class which coordinates construction
332 /// and emission of the instruction selector.
333 ///
334 class DAGISelEmitter : public TableGenBackend {
335 public:
336   typedef std::pair<TreePatternNode*, TreePatternNode*> PatternToMatch;
337 private:
338   RecordKeeper &Records;
339   CodeGenTarget Target;
340
341   std::map<Record*, SDNodeInfo> SDNodes;
342   std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
343   std::map<Record*, TreePattern*> PatternFragments;
344   std::map<Record*, DAGInstruction> Instructions;
345   
346   /// PatternsToMatch - All of the things we are matching on the DAG.  The first
347   /// value is the pattern to match, the second pattern is the result to
348   /// emit.
349   std::vector<PatternToMatch> PatternsToMatch;
350 public:
351   DAGISelEmitter(RecordKeeper &R) : Records(R) {}
352
353   // run - Output the isel, returning true on failure.
354   void run(std::ostream &OS);
355   
356   const SDNodeInfo &getSDNodeInfo(Record *R) const {
357     assert(SDNodes.count(R) && "Unknown node!");
358     return SDNodes.find(R)->second;
359   }
360
361   TreePattern *getPatternFragment(Record *R) const {
362     assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
363     return PatternFragments.find(R)->second;
364   }
365   
366   const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
367     assert(SDNodeXForms.count(R) && "Invalid transform!");
368     return SDNodeXForms.find(R)->second;
369   }
370   
371   const DAGInstruction &getInstruction(Record *R) const {
372     assert(Instructions.count(R) && "Unknown instruction!");
373     return Instructions.find(R)->second;
374   }
375   
376 private:
377   void ParseNodeInfo();
378   void ParseNodeTransforms(std::ostream &OS);
379   void ParsePatternFragments(std::ostream &OS);
380   void ParseInstructions();
381   void ParsePatterns();
382   void GenerateVariants();
383   void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
384                                    std::map<std::string,
385                                             TreePatternNode*> &InstInputs,
386                                    std::map<std::string, Record*> &InstResults);
387   void EmitMatchForPattern(TreePatternNode *N, const std::string &RootName,
388                            std::map<std::string,std::string> &VarMap,
389                            unsigned PatternNo, std::ostream &OS);
390   unsigned CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
391                                 std::map<std::string,std::string> &VariableMap, 
392                                 std::ostream &OS);      
393   void EmitCodeForPattern(PatternToMatch &Pattern, std::ostream &OS);
394   void EmitInstructionSelector(std::ostream &OS);
395 };
396
397 } // End llvm namespace
398
399 #endif