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