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