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