code simplification, no functionality change.
[oota-llvm.git] / utils / TableGen / CodeGenDAGPatterns.h
1 //===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef CODEGEN_DAGPATTERNS_H
16 #define CODEGEN_DAGPATTERNS_H
17
18 #include <set>
19
20 #include "CodeGenTarget.h"
21 #include "CodeGenIntrinsics.h"
22
23 namespace llvm {
24   class Record;
25   struct Init;
26   class ListInit;
27   class DagInit;
28   class SDNodeInfo;
29   class TreePattern;
30   class TreePatternNode;
31   class CodeGenDAGPatterns;
32   class ComplexPattern;
33
34 /// EMVT::DAGISelGenValueType - These are some extended forms of
35 /// MVT::SimpleValueType that we use as lattice values during type inference.
36 namespace EMVT {
37   enum DAGISelGenValueType {
38     isFP  = MVT::LAST_VALUETYPE,
39     isInt,
40     isUnknown
41   };
42
43   /// isExtIntegerVT - Return true if the specified extended value type vector
44   /// contains isInt or an integer value type.
45   bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs);
46
47   /// isExtFloatingPointVT - Return true if the specified extended value type 
48   /// vector contains isFP or a FP value type.
49   bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs);
50 }
51
52 /// Set type used to track multiply used variables in patterns
53 typedef std::set<std::string> MultipleUseVarSet;
54
55 /// SDTypeConstraint - This is a discriminated union of constraints,
56 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
57 struct SDTypeConstraint {
58   SDTypeConstraint(Record *R);
59   
60   unsigned OperandNo;   // The operand # this constraint applies to.
61   enum { 
62     SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs, 
63     SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize,
64     SDTCisEltOfVec
65   } ConstraintType;
66   
67   union {   // The discriminated union.
68     struct {
69       unsigned char VT;
70     } SDTCisVT_Info;
71     struct {
72       unsigned OtherOperandNum;
73     } SDTCisSameAs_Info;
74     struct {
75       unsigned OtherOperandNum;
76     } SDTCisVTSmallerThanOp_Info;
77     struct {
78       unsigned BigOperandNum;
79     } SDTCisOpSmallerThanOp_Info;
80     struct {
81       unsigned OtherOperandNum;
82     } SDTCisIntVectorOfSameSize_Info;
83     struct {
84       unsigned OtherOperandNum;
85     } SDTCisEltOfVec_Info;
86   } x;
87
88   /// ApplyTypeConstraint - Given a node in a pattern, apply this type
89   /// constraint to the nodes operands.  This returns true if it makes a
90   /// change, false otherwise.  If a type contradiction is found, throw an
91   /// exception.
92   bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
93                            TreePattern &TP) const;
94   
95   /// getOperandNum - Return the node corresponding to operand #OpNo in tree
96   /// N, which has NumResults results.
97   TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
98                                  unsigned NumResults) const;
99 };
100
101 /// SDNodeInfo - One of these records is created for each SDNode instance in
102 /// the target .td file.  This represents the various dag nodes we will be
103 /// processing.
104 class SDNodeInfo {
105   Record *Def;
106   std::string EnumName;
107   std::string SDClassName;
108   unsigned Properties;
109   unsigned NumResults;
110   int NumOperands;
111   std::vector<SDTypeConstraint> TypeConstraints;
112 public:
113   SDNodeInfo(Record *R);  // Parse the specified record.
114   
115   unsigned getNumResults() const { return NumResults; }
116   int getNumOperands() const { return NumOperands; }
117   Record *getRecord() const { return Def; }
118   const std::string &getEnumName() const { return EnumName; }
119   const std::string &getSDClassName() const { return SDClassName; }
120   
121   const std::vector<SDTypeConstraint> &getTypeConstraints() const {
122     return TypeConstraints;
123   }
124   
125   /// hasProperty - Return true if this node has the specified property.
126   ///
127   bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
128
129   /// ApplyTypeConstraints - Given a node in a pattern, apply the type
130   /// constraints for this node to the operands of the node.  This returns
131   /// true if it makes a change, false otherwise.  If a type contradiction is
132   /// found, throw an exception.
133   bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
134     bool MadeChange = false;
135     for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
136       MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
137     return MadeChange;
138   }
139 };
140
141 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
142 /// patterns), and as such should be ref counted.  We currently just leak all
143 /// TreePatternNode objects!
144 class TreePatternNode {
145   /// The inferred type for this node, or EMVT::isUnknown if it hasn't
146   /// been determined yet.
147   std::vector<unsigned char> Types;
148   
149   /// Operator - The Record for the operator if this is an interior node (not
150   /// a leaf).
151   Record *Operator;
152   
153   /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
154   ///
155   Init *Val;
156   
157   /// Name - The name given to this node with the :$foo notation.
158   ///
159   std::string Name;
160   
161   /// PredicateFn - The predicate function to execute on this node to check
162   /// for a match.  If this string is empty, no predicate is involved.
163   std::string PredicateFn;
164   
165   /// TransformFn - The transformation function to execute on this node before
166   /// it can be substituted into the resulting instruction on a pattern match.
167   Record *TransformFn;
168   
169   std::vector<TreePatternNode*> Children;
170 public:
171   TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch) 
172     : Types(), Operator(Op), Val(0), TransformFn(0),
173     Children(Ch) { Types.push_back(EMVT::isUnknown); }
174   TreePatternNode(Init *val)    // leaf ctor
175     : Types(), Operator(0), Val(val), TransformFn(0) {
176     Types.push_back(EMVT::isUnknown);
177   }
178   ~TreePatternNode();
179   
180   const std::string &getName() const { return Name; }
181   void setName(const std::string &N) { Name = N; }
182   
183   bool isLeaf() const { return Val != 0; }
184   bool hasTypeSet() const {
185     return (Types[0] < MVT::LAST_VALUETYPE) || (Types[0] == MVT::iPTR) || 
186           (Types[0] == MVT::iPTRAny);
187   }
188   bool isTypeCompletelyUnknown() const {
189     return Types[0] == EMVT::isUnknown;
190   }
191   bool isTypeDynamicallyResolved() const {
192     return (Types[0] == MVT::iPTR) || (Types[0] == MVT::iPTRAny);
193   }
194   MVT::SimpleValueType getTypeNum(unsigned Num) const {
195     assert(hasTypeSet() && "Doesn't have a type yet!");
196     assert(Types.size() > Num && "Type num out of range!");
197     return (MVT::SimpleValueType)Types[Num];
198   }
199   unsigned char getExtTypeNum(unsigned Num) const { 
200     assert(Types.size() > Num && "Extended type num out of range!");
201     return Types[Num]; 
202   }
203   const std::vector<unsigned char> &getExtTypes() const { return Types; }
204   void setTypes(const std::vector<unsigned char> &T) { Types = T; }
205   void removeTypes() { Types = std::vector<unsigned char>(1, EMVT::isUnknown); }
206   
207   Init *getLeafValue() const { assert(isLeaf()); return Val; }
208   Record *getOperator() const { assert(!isLeaf()); return Operator; }
209   
210   unsigned getNumChildren() const { return Children.size(); }
211   TreePatternNode *getChild(unsigned N) const { return Children[N]; }
212   void setChild(unsigned i, TreePatternNode *N) {
213     Children[i] = N;
214   }
215
216   const std::string &getPredicateFn() const { return PredicateFn; }
217   void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
218
219   Record *getTransformFn() const { return TransformFn; }
220   void setTransformFn(Record *Fn) { TransformFn = Fn; }
221   
222   /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
223   /// CodeGenIntrinsic information for it, otherwise return a null pointer.
224   const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
225
226   /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is
227   /// marked isCommutative.
228   bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const;
229   
230   void print(std::ostream &OS) const;
231   void dump() const;
232   
233 public:   // Higher level manipulation routines.
234
235   /// clone - Return a new copy of this tree.
236   ///
237   TreePatternNode *clone() const;
238   
239   /// isIsomorphicTo - Return true if this node is recursively isomorphic to
240   /// the specified node.  For this comparison, all of the state of the node
241   /// is considered, except for the assigned name.  Nodes with differing names
242   /// that are otherwise identical are considered isomorphic.
243   bool isIsomorphicTo(const TreePatternNode *N,
244                       const MultipleUseVarSet &DepVars) const;
245   
246   /// SubstituteFormalArguments - Replace the formal arguments in this tree
247   /// with actual values specified by ArgMap.
248   void SubstituteFormalArguments(std::map<std::string,
249                                           TreePatternNode*> &ArgMap);
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   TreePatternNode *InlinePatternFragments(TreePattern &TP);
255   
256   /// ApplyTypeConstraints - Apply all of the type constraints relevent to
257   /// this node and its children in the tree.  This returns true if it makes a
258   /// change, false otherwise.  If a type contradiction is found, throw an
259   /// exception.
260   bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
261   
262   /// UpdateNodeType - Set the node type of N to VT if VT contains
263   /// information.  If N already contains a conflicting type, then throw an
264   /// exception.  This returns true if any information was updated.
265   ///
266   bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
267                       TreePattern &TP);
268   bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
269     std::vector<unsigned char> ExtVTs(1, ExtVT);
270     return UpdateNodeType(ExtVTs, TP);
271   }
272   
273   /// ContainsUnresolvedType - Return true if this tree contains any
274   /// unresolved types.
275   bool ContainsUnresolvedType() const {
276     if (!hasTypeSet() && !isTypeDynamicallyResolved()) return true;
277     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
278       if (getChild(i)->ContainsUnresolvedType()) return true;
279     return false;
280   }
281   
282   /// canPatternMatch - If it is impossible for this pattern to match on this
283   /// target, fill in Reason and return false.  Otherwise, return true.
284   bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP);
285 };
286
287
288 /// TreePattern - Represent a pattern, used for instructions, pattern
289 /// fragments, etc.
290 ///
291 class TreePattern {
292   /// Trees - The list of pattern trees which corresponds to this pattern.
293   /// Note that PatFrag's only have a single tree.
294   ///
295   std::vector<TreePatternNode*> Trees;
296   
297   /// TheRecord - The actual TableGen record corresponding to this pattern.
298   ///
299   Record *TheRecord;
300     
301   /// Args - This is a list of all of the arguments to this pattern (for
302   /// PatFrag patterns), which are the 'node' markers in this pattern.
303   std::vector<std::string> Args;
304   
305   /// CDP - the top-level object coordinating this madness.
306   ///
307   CodeGenDAGPatterns &CDP;
308
309   /// isInputPattern - True if this is an input pattern, something to match.
310   /// False if this is an output pattern, something to emit.
311   bool isInputPattern;
312 public:
313     
314   /// TreePattern constructor - Parse the specified DagInits into the
315   /// current record.
316   TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
317               CodeGenDAGPatterns &ise);
318   TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
319               CodeGenDAGPatterns &ise);
320   TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
321               CodeGenDAGPatterns &ise);
322       
323   /// getTrees - Return the tree patterns which corresponds to this pattern.
324   ///
325   const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
326   unsigned getNumTrees() const { return Trees.size(); }
327   TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
328   TreePatternNode *getOnlyTree() const {
329     assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
330     return Trees[0];
331   }
332       
333   /// getRecord - Return the actual TableGen record corresponding to this
334   /// pattern.
335   ///
336   Record *getRecord() const { return TheRecord; }
337   
338   unsigned getNumArgs() const { return Args.size(); }
339   const std::string &getArgName(unsigned i) const {
340     assert(i < Args.size() && "Argument reference out of range!");
341     return Args[i];
342   }
343   std::vector<std::string> &getArgList() { return Args; }
344   
345   CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
346
347   /// InlinePatternFragments - If this pattern refers to any pattern
348   /// fragments, inline them into place, giving us a pattern without any
349   /// PatFrag references.
350   void InlinePatternFragments() {
351     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
352       Trees[i] = Trees[i]->InlinePatternFragments(*this);
353   }
354   
355   /// InferAllTypes - Infer/propagate as many types throughout the expression
356   /// patterns as possible.  Return true if all types are infered, false
357   /// otherwise.  Throw an exception if a type contradiction is found.
358   bool InferAllTypes();
359   
360   /// error - Throw an exception, prefixing it with information about this
361   /// pattern.
362   void error(const std::string &Msg) const;
363   
364   void print(std::ostream &OS) const;
365   void dump() const;
366   
367 private:
368   TreePatternNode *ParseTreePattern(DagInit *DI);
369 };
370
371 /// DAGDefaultOperand - One of these is created for each PredicateOperand
372 /// or OptionalDefOperand that has a set ExecuteAlways / DefaultOps field.
373 struct DAGDefaultOperand {
374   std::vector<TreePatternNode*> DefaultOps;
375 };
376
377 class DAGInstruction {
378   TreePattern *Pattern;
379   std::vector<Record*> Results;
380   std::vector<Record*> Operands;
381   std::vector<Record*> ImpResults;
382   std::vector<Record*> ImpOperands;
383   TreePatternNode *ResultPattern;
384 public:
385   DAGInstruction(TreePattern *TP,
386                  const std::vector<Record*> &results,
387                  const std::vector<Record*> &operands,
388                  const std::vector<Record*> &impresults,
389                  const std::vector<Record*> &impoperands)
390     : Pattern(TP), Results(results), Operands(operands), 
391       ImpResults(impresults), ImpOperands(impoperands),
392       ResultPattern(0) {}
393
394   const TreePattern *getPattern() const { return Pattern; }
395   unsigned getNumResults() const { return Results.size(); }
396   unsigned getNumOperands() const { return Operands.size(); }
397   unsigned getNumImpResults() const { return ImpResults.size(); }
398   unsigned getNumImpOperands() const { return ImpOperands.size(); }
399   const std::vector<Record*>& getImpResults() const { return ImpResults; }
400   
401   void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
402   
403   Record *getResult(unsigned RN) const {
404     assert(RN < Results.size());
405     return Results[RN];
406   }
407   
408   Record *getOperand(unsigned ON) const {
409     assert(ON < Operands.size());
410     return Operands[ON];
411   }
412
413   Record *getImpResult(unsigned RN) const {
414     assert(RN < ImpResults.size());
415     return ImpResults[RN];
416   }
417   
418   Record *getImpOperand(unsigned ON) const {
419     assert(ON < ImpOperands.size());
420     return ImpOperands[ON];
421   }
422
423   TreePatternNode *getResultPattern() const { return ResultPattern; }
424 };
425   
426 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
427 /// processed to produce isel.
428 struct PatternToMatch {
429   PatternToMatch(ListInit *preds,
430                  TreePatternNode *src, TreePatternNode *dst,
431                  const std::vector<Record*> &dstregs,
432                  unsigned complexity):
433     Predicates(preds), SrcPattern(src), DstPattern(dst), Dstregs(dstregs),
434     AddedComplexity(complexity) {};
435
436   ListInit        *Predicates;  // Top level predicate conditions to match.
437   TreePatternNode *SrcPattern;  // Source pattern to match.
438   TreePatternNode *DstPattern;  // Resulting pattern.
439   std::vector<Record*> Dstregs; // Physical register defs being matched.
440   unsigned         AddedComplexity; // Add to matching pattern complexity.
441
442   ListInit        *getPredicates() const { return Predicates; }
443   TreePatternNode *getSrcPattern() const { return SrcPattern; }
444   TreePatternNode *getDstPattern() const { return DstPattern; }
445   const std::vector<Record*> &getDstRegs() const { return Dstregs; }
446   unsigned         getAddedComplexity() const { return AddedComplexity; }
447
448   std::string getPredicateCheck() const;
449 };
450
451   
452 class CodeGenDAGPatterns {
453   RecordKeeper &Records;
454   CodeGenTarget Target;
455   std::vector<CodeGenIntrinsic> Intrinsics;
456   
457   std::map<Record*, SDNodeInfo> SDNodes;
458   std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
459   std::map<Record*, ComplexPattern> ComplexPatterns;
460   std::map<Record*, TreePattern*> PatternFragments;
461   std::map<Record*, DAGDefaultOperand> DefaultOperands;
462   std::map<Record*, DAGInstruction> Instructions;
463   
464   // Specific SDNode definitions:
465   Record *intrinsic_void_sdnode;
466   Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
467   
468   /// PatternsToMatch - All of the things we are matching on the DAG.  The first
469   /// value is the pattern to match, the second pattern is the result to
470   /// emit.
471   std::vector<PatternToMatch> PatternsToMatch;
472 public:
473   CodeGenDAGPatterns(RecordKeeper &R); 
474   ~CodeGenDAGPatterns();
475   
476   CodeGenTarget &getTargetInfo() { return Target; }
477   const CodeGenTarget &getTargetInfo() const { return Target; }
478   
479   Record *getSDNodeNamed(const std::string &Name) const;
480   
481   const SDNodeInfo &getSDNodeInfo(Record *R) const {
482     assert(SDNodes.count(R) && "Unknown node!");
483     return SDNodes.find(R)->second;
484   }
485   
486   // Node transformation lookups.
487   typedef std::pair<Record*, std::string> NodeXForm;
488   const NodeXForm &getSDNodeTransform(Record *R) const {
489     assert(SDNodeXForms.count(R) && "Invalid transform!");
490     return SDNodeXForms.find(R)->second;
491   }
492   
493   typedef std::map<Record*, NodeXForm>::const_iterator nx_iterator;
494   nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
495   nx_iterator nx_end() const { return SDNodeXForms.end(); }
496
497   
498   const ComplexPattern &getComplexPattern(Record *R) const {
499     assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
500     return ComplexPatterns.find(R)->second;
501   }
502   
503   const CodeGenIntrinsic &getIntrinsic(Record *R) const {
504     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
505       if (Intrinsics[i].TheDef == R) return Intrinsics[i];
506     assert(0 && "Unknown intrinsic!");
507     abort();
508   }
509   
510   const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
511     assert(IID-1 < Intrinsics.size() && "Bad intrinsic ID!");
512     return Intrinsics[IID-1];
513   }
514   
515   unsigned getIntrinsicID(Record *R) const {
516     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
517       if (Intrinsics[i].TheDef == R) return i;
518     assert(0 && "Unknown intrinsic!");
519     abort();
520   }
521   
522   const DAGDefaultOperand &getDefaultOperand(Record *R) {
523     assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!");
524     return DefaultOperands.find(R)->second;
525   }
526   
527   // Pattern Fragment information.
528   TreePattern *getPatternFragment(Record *R) const {
529     assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
530     return PatternFragments.find(R)->second;
531   }
532   typedef std::map<Record*, TreePattern*>::const_iterator pf_iterator;
533   pf_iterator pf_begin() const { return PatternFragments.begin(); }
534   pf_iterator pf_end() const { return PatternFragments.end(); }
535
536   // Patterns to match information.
537   typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
538   ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
539   ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
540   
541   
542   
543   const DAGInstruction &getInstruction(Record *R) const {
544     assert(Instructions.count(R) && "Unknown instruction!");
545     return Instructions.find(R)->second;
546   }
547   
548   Record *get_intrinsic_void_sdnode() const {
549     return intrinsic_void_sdnode;
550   }
551   Record *get_intrinsic_w_chain_sdnode() const {
552     return intrinsic_w_chain_sdnode;
553   }
554   Record *get_intrinsic_wo_chain_sdnode() const {
555     return intrinsic_wo_chain_sdnode;
556   }
557   
558 private:
559   void ParseNodeInfo();
560   void ParseNodeTransforms();
561   void ParseComplexPatterns();
562   void ParsePatternFragments();
563   void ParseDefaultOperands();
564   void ParseInstructions();
565   void ParsePatterns();
566   void InferInstructionFlags();
567   void GenerateVariants();
568   
569   void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
570                                    std::map<std::string,
571                                    TreePatternNode*> &InstInputs,
572                                    std::map<std::string,
573                                    TreePatternNode*> &InstResults,
574                                    std::vector<Record*> &InstImpInputs,
575                                    std::vector<Record*> &InstImpResults);
576 };
577 } // end namespace llvm
578
579 #endif