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