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