Completely rewrite tblgen's type inference mechanism,
[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 #include <algorithm>
20 #include <vector>
21
22 #include "CodeGenTarget.h"
23 #include "CodeGenIntrinsics.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringMap.h"
26
27 namespace llvm {
28   class Record;
29   struct Init;
30   class ListInit;
31   class DagInit;
32   class SDNodeInfo;
33   class TreePattern;
34   class TreePatternNode;
35   class CodeGenDAGPatterns;
36   class ComplexPattern;
37
38 /// EEVT::DAGISelGenValueType - These are some extended forms of
39 /// MVT::SimpleValueType that we use as lattice values during type inference.
40 /// The existing MVT iAny, fAny and vAny types suffice to represent
41 /// arbitrary integer, floating-point, and vector types, so only an unknown
42 /// value is needed.
43 namespace EEVT {
44   enum DAGISelGenValueType {
45     // FIXME: Remove EEVT::isUnknown!
46     isUnknown  = MVT::LAST_VALUETYPE
47   };
48   
49   /// TypeSet - This is either empty if it's completely unknown, or holds a set
50   /// of types.  It is used during type inference because register classes can
51   /// have multiple possible types and we don't know which one they get until
52   /// type inference is complete.
53   ///
54   /// TypeSet can have three states:
55   ///    Vector is empty: The type is completely unknown, it can be any valid
56   ///       target type.
57   ///    Vector has multiple constrained types: (e.g. v4i32 + v4f32) it is one
58   ///       of those types only.
59   ///    Vector has one concrete type: The type is completely known.
60   ///
61   class TypeSet {
62     SmallVector<MVT::SimpleValueType, 2> TypeVec;
63   public:
64     TypeSet() {}
65     TypeSet(MVT::SimpleValueType VT, TreePattern &TP);
66     TypeSet(const std::vector<MVT::SimpleValueType> &VTList);    
67     
68     bool isCompletelyUnknown() const { return TypeVec.empty(); }
69     
70     bool isConcrete() const {
71       if (TypeVec.size() != 1) return false;
72       unsigned char T = TypeVec[0]; (void)T;
73       assert(T < MVT::LAST_VALUETYPE || T == MVT::iPTR || T == MVT::iPTRAny);
74       return true;
75     }
76     
77     MVT::SimpleValueType getConcrete() const {
78       assert(isConcrete() && "Type isn't concrete yet");
79       return (MVT::SimpleValueType)TypeVec[0];
80     }
81     
82     bool isDynamicallyResolved() const {
83       return getConcrete() == MVT::iPTR || getConcrete() == MVT::iPTRAny;
84     }
85     
86     const SmallVectorImpl<MVT::SimpleValueType> &getTypeList() const {
87       assert(!TypeVec.empty() && "Not a type list!");
88       return TypeVec;
89     }
90     
91     /// hasIntegerTypes - Return true if this TypeSet contains any integer value
92     /// types.
93     bool hasIntegerTypes() const;
94     
95     /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
96     /// a floating point value type.
97     bool hasFloatingPointTypes() const;
98     
99     /// hasVectorTypes - Return true if this TypeSet contains a vector value
100     /// type.
101     bool hasVectorTypes() const;
102     
103     /// getName() - Return this TypeSet as a string.
104     std::string getName() const;
105     
106     /// MergeInTypeInfo - This merges in type information from the specified
107     /// argument.  If 'this' changes, it returns true.  If the two types are
108     /// contradictory (e.g. merge f32 into i32) then this throws an exception.
109     bool MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP);
110
111     bool MergeInTypeInfo(MVT::SimpleValueType InVT, TreePattern &TP) {
112       return MergeInTypeInfo(EEVT::TypeSet(InVT, TP), TP);
113     }
114
115     /// Force this type list to only contain integer types.
116     bool EnforceInteger(TreePattern &TP);
117
118     /// Force this type list to only contain floating point types.
119     bool EnforceFloatingPoint(TreePattern &TP);
120
121     /// EnforceScalar - Remove all vector types from this type list.
122     bool EnforceScalar(TreePattern &TP);
123
124     /// EnforceVector - Remove all non-vector types from this type list.
125     bool EnforceVector(TreePattern &TP);
126
127     /// EnforceSmallerThan - 'this' must be a smaller VT than Other.  Update
128     /// this an other based on this information.
129     bool EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP);
130     
131     /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
132     /// whose element is VT.
133     bool EnforceVectorEltTypeIs(MVT::SimpleValueType VT, TreePattern &TP);
134     
135     bool operator!=(const TypeSet &RHS) const { return TypeVec != RHS.TypeVec; }
136     bool operator==(const TypeSet &RHS) const { return TypeVec == RHS.TypeVec; }
137   };
138 }
139
140 /// Set type used to track multiply used variables in patterns
141 typedef std::set<std::string> MultipleUseVarSet;
142
143 /// SDTypeConstraint - This is a discriminated union of constraints,
144 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
145 struct SDTypeConstraint {
146   SDTypeConstraint(Record *R);
147   
148   unsigned OperandNo;   // The operand # this constraint applies to.
149   enum { 
150     SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisVec, SDTCisSameAs, 
151     SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisEltOfVec
152   } ConstraintType;
153   
154   union {   // The discriminated union.
155     struct {
156       MVT::SimpleValueType VT;
157     } SDTCisVT_Info;
158     struct {
159       unsigned OtherOperandNum;
160     } SDTCisSameAs_Info;
161     struct {
162       unsigned OtherOperandNum;
163     } SDTCisVTSmallerThanOp_Info;
164     struct {
165       unsigned BigOperandNum;
166     } SDTCisOpSmallerThanOp_Info;
167     struct {
168       unsigned OtherOperandNum;
169     } SDTCisEltOfVec_Info;
170   } x;
171
172   /// ApplyTypeConstraint - Given a node in a pattern, apply this type
173   /// constraint to the nodes operands.  This returns true if it makes a
174   /// change, false otherwise.  If a type contradiction is found, throw an
175   /// exception.
176   bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
177                            TreePattern &TP) const;
178   
179   /// getOperandNum - Return the node corresponding to operand #OpNo in tree
180   /// N, which has NumResults results.
181   TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
182                                  unsigned NumResults) const;
183 };
184
185 /// SDNodeInfo - One of these records is created for each SDNode instance in
186 /// the target .td file.  This represents the various dag nodes we will be
187 /// processing.
188 class SDNodeInfo {
189   Record *Def;
190   std::string EnumName;
191   std::string SDClassName;
192   unsigned Properties;
193   unsigned NumResults;
194   int NumOperands;
195   std::vector<SDTypeConstraint> TypeConstraints;
196 public:
197   SDNodeInfo(Record *R);  // Parse the specified record.
198   
199   unsigned getNumResults() const { return NumResults; }
200   int getNumOperands() const { return NumOperands; }
201   Record *getRecord() const { return Def; }
202   const std::string &getEnumName() const { return EnumName; }
203   const std::string &getSDClassName() const { return SDClassName; }
204   
205   const std::vector<SDTypeConstraint> &getTypeConstraints() const {
206     return TypeConstraints;
207   }
208   
209   /// getKnownType - If the type constraints on this node imply a fixed type
210   /// (e.g. all stores return void, etc), then return it as an
211   /// MVT::SimpleValueType.  Otherwise, return EEVT::isUnknown.
212   unsigned getKnownType() const;
213   
214   /// hasProperty - Return true if this node has the specified property.
215   ///
216   bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
217
218   /// ApplyTypeConstraints - Given a node in a pattern, apply the type
219   /// constraints for this node to the operands of the node.  This returns
220   /// true if it makes a change, false otherwise.  If a type contradiction is
221   /// found, throw an exception.
222   bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
223     bool MadeChange = false;
224     for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
225       MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
226     return MadeChange;
227   }
228 };
229
230 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
231 /// patterns), and as such should be ref counted.  We currently just leak all
232 /// TreePatternNode objects!
233 class TreePatternNode {
234   /// The type of this node.  Before and during type inference, this may be a
235   /// set of possible types.  After (successful) type inference, this is a
236   /// single type.
237   EEVT::TypeSet Type;
238   
239   /// Operator - The Record for the operator if this is an interior node (not
240   /// a leaf).
241   Record *Operator;
242   
243   /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
244   ///
245   Init *Val;
246   
247   /// Name - The name given to this node with the :$foo notation.
248   ///
249   std::string Name;
250   
251   /// PredicateFns - The predicate functions to execute on this node to check
252   /// for a match.  If this list is empty, no predicate is involved.
253   std::vector<std::string> PredicateFns;
254   
255   /// TransformFn - The transformation function to execute on this node before
256   /// it can be substituted into the resulting instruction on a pattern match.
257   Record *TransformFn;
258   
259   std::vector<TreePatternNode*> Children;
260 public:
261   TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch) 
262     : Operator(Op), Val(0), TransformFn(0), Children(Ch) { }
263   TreePatternNode(Init *val)    // leaf ctor
264     : Operator(0), Val(val), TransformFn(0) {
265   }
266   ~TreePatternNode();
267   
268   const std::string &getName() const { return Name; }
269   void setName(const std::string &N) { Name = N; }
270   
271   bool isLeaf() const { return Val != 0; }
272   
273   // Type accessors.
274   MVT::SimpleValueType getType() const { return Type.getConcrete(); }
275   const EEVT::TypeSet &getExtType() const { return Type; }
276   EEVT::TypeSet &getExtType() { return Type; }
277   void setType(const EEVT::TypeSet &T) { Type = T; }
278   
279   bool hasTypeSet() const { return Type.isConcrete(); }
280   bool isTypeCompletelyUnknown() const { return Type.isCompletelyUnknown(); }
281   bool isTypeDynamicallyResolved() const { return Type.isDynamicallyResolved();}
282   
283   Init *getLeafValue() const { assert(isLeaf()); return Val; }
284   Record *getOperator() const { assert(!isLeaf()); return Operator; }
285   
286   unsigned getNumChildren() const { return Children.size(); }
287   TreePatternNode *getChild(unsigned N) const { return Children[N]; }
288   void setChild(unsigned i, TreePatternNode *N) {
289     Children[i] = N;
290   }
291   
292   /// hasChild - Return true if N is any of our children.
293   bool hasChild(const TreePatternNode *N) const {
294     for (unsigned i = 0, e = Children.size(); i != e; ++i)
295       if (Children[i] == N) return true;
296     return false;
297   }
298
299   const std::vector<std::string> &getPredicateFns() const {return PredicateFns;}
300   void clearPredicateFns() { PredicateFns.clear(); }
301   void setPredicateFns(const std::vector<std::string> &Fns) {
302     assert(PredicateFns.empty() && "Overwriting non-empty predicate list!");
303     PredicateFns = Fns;
304   }
305   void addPredicateFn(const std::string &Fn) { 
306     assert(!Fn.empty() && "Empty predicate string!");
307     if (std::find(PredicateFns.begin(), PredicateFns.end(), Fn) ==
308           PredicateFns.end())
309       PredicateFns.push_back(Fn);
310   }
311
312   Record *getTransformFn() const { return TransformFn; }
313   void setTransformFn(Record *Fn) { TransformFn = Fn; }
314   
315   /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
316   /// CodeGenIntrinsic information for it, otherwise return a null pointer.
317   const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
318
319   /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
320   /// return the ComplexPattern information, otherwise return null.
321   const ComplexPattern *
322   getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const;
323
324   /// NodeHasProperty - Return true if this node has the specified property.
325   bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
326   
327   /// TreeHasProperty - Return true if any node in this tree has the specified
328   /// property.
329   bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
330   
331   /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is
332   /// marked isCommutative.
333   bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const;
334   
335   void print(raw_ostream &OS) const;
336   void dump() const;
337   
338 public:   // Higher level manipulation routines.
339
340   /// clone - Return a new copy of this tree.
341   ///
342   TreePatternNode *clone() const;
343
344   /// RemoveAllTypes - Recursively strip all the types of this tree.
345   void RemoveAllTypes();
346   
347   /// isIsomorphicTo - Return true if this node is recursively isomorphic to
348   /// the specified node.  For this comparison, all of the state of the node
349   /// is considered, except for the assigned name.  Nodes with differing names
350   /// that are otherwise identical are considered isomorphic.
351   bool isIsomorphicTo(const TreePatternNode *N,
352                       const MultipleUseVarSet &DepVars) const;
353   
354   /// SubstituteFormalArguments - Replace the formal arguments in this tree
355   /// with actual values specified by ArgMap.
356   void SubstituteFormalArguments(std::map<std::string,
357                                           TreePatternNode*> &ArgMap);
358
359   /// InlinePatternFragments - If this pattern refers to any pattern
360   /// fragments, inline them into place, giving us a pattern without any
361   /// PatFrag references.
362   TreePatternNode *InlinePatternFragments(TreePattern &TP);
363   
364   /// ApplyTypeConstraints - Apply all of the type constraints relevant to
365   /// this node and its children in the tree.  This returns true if it makes a
366   /// change, false otherwise.  If a type contradiction is found, throw an
367   /// exception.
368   bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
369   
370   /// UpdateNodeType - Set the node type of N to VT if VT contains
371   /// information.  If N already contains a conflicting type, then throw an
372   /// exception.  This returns true if any information was updated.
373   ///
374   bool UpdateNodeType(const EEVT::TypeSet &InTy, TreePattern &TP) {
375     return Type.MergeInTypeInfo(InTy, TP);
376   }
377
378   bool UpdateNodeType(MVT::SimpleValueType InTy, TreePattern &TP) {
379     return Type.MergeInTypeInfo(EEVT::TypeSet(InTy, TP), TP);
380   }
381   
382   /// ContainsUnresolvedType - Return true if this tree contains any
383   /// unresolved types.
384   bool ContainsUnresolvedType() const {
385     if (!hasTypeSet()) return true;
386     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
387       if (getChild(i)->ContainsUnresolvedType()) return true;
388     return false;
389   }
390   
391   /// canPatternMatch - If it is impossible for this pattern to match on this
392   /// target, fill in Reason and return false.  Otherwise, return true.
393   bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP);
394 };
395
396 inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) {
397   TPN.print(OS);
398   return OS;
399 }
400   
401
402 /// TreePattern - Represent a pattern, used for instructions, pattern
403 /// fragments, etc.
404 ///
405 class TreePattern {
406   /// Trees - The list of pattern trees which corresponds to this pattern.
407   /// Note that PatFrag's only have a single tree.
408   ///
409   std::vector<TreePatternNode*> Trees;
410   
411   /// NamedNodes - This is all of the nodes that have names in the trees in this
412   /// pattern.
413   StringMap<SmallVector<TreePatternNode*,1> > NamedNodes;
414   
415   /// TheRecord - The actual TableGen record corresponding to this pattern.
416   ///
417   Record *TheRecord;
418     
419   /// Args - This is a list of all of the arguments to this pattern (for
420   /// PatFrag patterns), which are the 'node' markers in this pattern.
421   std::vector<std::string> Args;
422   
423   /// CDP - the top-level object coordinating this madness.
424   ///
425   CodeGenDAGPatterns &CDP;
426
427   /// isInputPattern - True if this is an input pattern, something to match.
428   /// False if this is an output pattern, something to emit.
429   bool isInputPattern;
430 public:
431     
432   /// TreePattern constructor - Parse the specified DagInits into the
433   /// current record.
434   TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
435               CodeGenDAGPatterns &ise);
436   TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
437               CodeGenDAGPatterns &ise);
438   TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
439               CodeGenDAGPatterns &ise);
440       
441   /// getTrees - Return the tree patterns which corresponds to this pattern.
442   ///
443   const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
444   unsigned getNumTrees() const { return Trees.size(); }
445   TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
446   TreePatternNode *getOnlyTree() const {
447     assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
448     return Trees[0];
449   }
450   
451   const StringMap<SmallVector<TreePatternNode*,1> > &getNamedNodesMap() {
452     if (NamedNodes.empty())
453       ComputeNamedNodes();
454     return NamedNodes;
455   }
456       
457   /// getRecord - Return the actual TableGen record corresponding to this
458   /// pattern.
459   ///
460   Record *getRecord() const { return TheRecord; }
461   
462   unsigned getNumArgs() const { return Args.size(); }
463   const std::string &getArgName(unsigned i) const {
464     assert(i < Args.size() && "Argument reference out of range!");
465     return Args[i];
466   }
467   std::vector<std::string> &getArgList() { return Args; }
468   
469   CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
470
471   /// InlinePatternFragments - If this pattern refers to any pattern
472   /// fragments, inline them into place, giving us a pattern without any
473   /// PatFrag references.
474   void InlinePatternFragments() {
475     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
476       Trees[i] = Trees[i]->InlinePatternFragments(*this);
477   }
478   
479   /// InferAllTypes - Infer/propagate as many types throughout the expression
480   /// patterns as possible.  Return true if all types are inferred, false
481   /// otherwise.  Throw an exception if a type contradiction is found.
482   bool InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> >
483                           *NamedTypes=0);
484   
485   /// error - Throw an exception, prefixing it with information about this
486   /// pattern.
487   void error(const std::string &Msg) const;
488   
489   void print(raw_ostream &OS) const;
490   void dump() const;
491   
492 private:
493   TreePatternNode *ParseTreePattern(DagInit *DI);
494   void ComputeNamedNodes();
495   void ComputeNamedNodes(TreePatternNode *N);
496 };
497
498 /// DAGDefaultOperand - One of these is created for each PredicateOperand
499 /// or OptionalDefOperand that has a set ExecuteAlways / DefaultOps field.
500 struct DAGDefaultOperand {
501   std::vector<TreePatternNode*> DefaultOps;
502 };
503
504 class DAGInstruction {
505   TreePattern *Pattern;
506   std::vector<Record*> Results;
507   std::vector<Record*> Operands;
508   std::vector<Record*> ImpResults;
509   std::vector<Record*> ImpOperands;
510   TreePatternNode *ResultPattern;
511 public:
512   DAGInstruction(TreePattern *TP,
513                  const std::vector<Record*> &results,
514                  const std::vector<Record*> &operands,
515                  const std::vector<Record*> &impresults,
516                  const std::vector<Record*> &impoperands)
517     : Pattern(TP), Results(results), Operands(operands), 
518       ImpResults(impresults), ImpOperands(impoperands),
519       ResultPattern(0) {}
520
521   const TreePattern *getPattern() const { return Pattern; }
522   unsigned getNumResults() const { return Results.size(); }
523   unsigned getNumOperands() const { return Operands.size(); }
524   unsigned getNumImpResults() const { return ImpResults.size(); }
525   unsigned getNumImpOperands() const { return ImpOperands.size(); }
526   const std::vector<Record*>& getImpResults() const { return ImpResults; }
527   
528   void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
529   
530   Record *getResult(unsigned RN) const {
531     assert(RN < Results.size());
532     return Results[RN];
533   }
534   
535   Record *getOperand(unsigned ON) const {
536     assert(ON < Operands.size());
537     return Operands[ON];
538   }
539
540   Record *getImpResult(unsigned RN) const {
541     assert(RN < ImpResults.size());
542     return ImpResults[RN];
543   }
544   
545   Record *getImpOperand(unsigned ON) const {
546     assert(ON < ImpOperands.size());
547     return ImpOperands[ON];
548   }
549
550   TreePatternNode *getResultPattern() const { return ResultPattern; }
551 };
552   
553 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
554 /// processed to produce isel.
555 class PatternToMatch {
556 public:
557   PatternToMatch(ListInit *preds,
558                  TreePatternNode *src, TreePatternNode *dst,
559                  const std::vector<Record*> &dstregs,
560                  unsigned complexity, unsigned uid)
561     : Predicates(preds), SrcPattern(src), DstPattern(dst),
562       Dstregs(dstregs), AddedComplexity(complexity), ID(uid) {}
563
564   ListInit        *Predicates;  // Top level predicate conditions to match.
565   TreePatternNode *SrcPattern;  // Source pattern to match.
566   TreePatternNode *DstPattern;  // Resulting pattern.
567   std::vector<Record*> Dstregs; // Physical register defs being matched.
568   unsigned         AddedComplexity; // Add to matching pattern complexity.
569   unsigned         ID;          // Unique ID for the record.
570
571   ListInit        *getPredicates() const { return Predicates; }
572   TreePatternNode *getSrcPattern() const { return SrcPattern; }
573   TreePatternNode *getDstPattern() const { return DstPattern; }
574   const std::vector<Record*> &getDstRegs() const { return Dstregs; }
575   unsigned         getAddedComplexity() const { return AddedComplexity; }
576
577   std::string getPredicateCheck() const;
578 };
579
580 // Deterministic comparison of Record*.
581 struct RecordPtrCmp {
582   bool operator()(const Record *LHS, const Record *RHS) const;
583 };
584   
585 class CodeGenDAGPatterns {
586   RecordKeeper &Records;
587   CodeGenTarget Target;
588   std::vector<CodeGenIntrinsic> Intrinsics;
589   std::vector<CodeGenIntrinsic> TgtIntrinsics;
590   
591   std::map<Record*, SDNodeInfo, RecordPtrCmp> SDNodes;
592   std::map<Record*, std::pair<Record*, std::string>, RecordPtrCmp> SDNodeXForms;
593   std::map<Record*, ComplexPattern, RecordPtrCmp> ComplexPatterns;
594   std::map<Record*, TreePattern*, RecordPtrCmp> PatternFragments;
595   std::map<Record*, DAGDefaultOperand, RecordPtrCmp> DefaultOperands;
596   std::map<Record*, DAGInstruction, RecordPtrCmp> Instructions;
597   
598   // Specific SDNode definitions:
599   Record *intrinsic_void_sdnode;
600   Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
601   
602   /// PatternsToMatch - All of the things we are matching on the DAG.  The first
603   /// value is the pattern to match, the second pattern is the result to
604   /// emit.
605   std::vector<PatternToMatch> PatternsToMatch;
606 public:
607   CodeGenDAGPatterns(RecordKeeper &R); 
608   ~CodeGenDAGPatterns();
609   
610   CodeGenTarget &getTargetInfo() { return Target; }
611   const CodeGenTarget &getTargetInfo() const { return Target; }
612   
613   Record *getSDNodeNamed(const std::string &Name) const;
614   
615   const SDNodeInfo &getSDNodeInfo(Record *R) const {
616     assert(SDNodes.count(R) && "Unknown node!");
617     return SDNodes.find(R)->second;
618   }
619   
620   // Node transformation lookups.
621   typedef std::pair<Record*, std::string> NodeXForm;
622   const NodeXForm &getSDNodeTransform(Record *R) const {
623     assert(SDNodeXForms.count(R) && "Invalid transform!");
624     return SDNodeXForms.find(R)->second;
625   }
626   
627   typedef std::map<Record*, NodeXForm, RecordPtrCmp>::const_iterator
628           nx_iterator;
629   nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
630   nx_iterator nx_end() const { return SDNodeXForms.end(); }
631
632   
633   const ComplexPattern &getComplexPattern(Record *R) const {
634     assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
635     return ComplexPatterns.find(R)->second;
636   }
637   
638   const CodeGenIntrinsic &getIntrinsic(Record *R) const {
639     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
640       if (Intrinsics[i].TheDef == R) return Intrinsics[i];
641     for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
642       if (TgtIntrinsics[i].TheDef == R) return TgtIntrinsics[i];
643     assert(0 && "Unknown intrinsic!");
644     abort();
645   }
646   
647   const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
648     if (IID-1 < Intrinsics.size())
649       return Intrinsics[IID-1];
650     if (IID-Intrinsics.size()-1 < TgtIntrinsics.size())
651       return TgtIntrinsics[IID-Intrinsics.size()-1];
652     assert(0 && "Bad intrinsic ID!");
653     abort();
654   }
655   
656   unsigned getIntrinsicID(Record *R) const {
657     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
658       if (Intrinsics[i].TheDef == R) return i;
659     for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
660       if (TgtIntrinsics[i].TheDef == R) return i + Intrinsics.size();
661     assert(0 && "Unknown intrinsic!");
662     abort();
663   }
664   
665   const DAGDefaultOperand &getDefaultOperand(Record *R) const {
666     assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!");
667     return DefaultOperands.find(R)->second;
668   }
669   
670   // Pattern Fragment information.
671   TreePattern *getPatternFragment(Record *R) const {
672     assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
673     return PatternFragments.find(R)->second;
674   }
675   typedef std::map<Record*, TreePattern*, RecordPtrCmp>::const_iterator
676           pf_iterator;
677   pf_iterator pf_begin() const { return PatternFragments.begin(); }
678   pf_iterator pf_end() const { return PatternFragments.end(); }
679
680   // Patterns to match information.
681   typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
682   ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
683   ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
684   
685   
686   
687   const DAGInstruction &getInstruction(Record *R) const {
688     assert(Instructions.count(R) && "Unknown instruction!");
689     return Instructions.find(R)->second;
690   }
691   
692   Record *get_intrinsic_void_sdnode() const {
693     return intrinsic_void_sdnode;
694   }
695   Record *get_intrinsic_w_chain_sdnode() const {
696     return intrinsic_w_chain_sdnode;
697   }
698   Record *get_intrinsic_wo_chain_sdnode() const {
699     return intrinsic_wo_chain_sdnode;
700   }
701   
702   bool hasTargetIntrinsics() { return !TgtIntrinsics.empty(); }
703
704 private:
705   void ParseNodeInfo();
706   void ParseNodeTransforms();
707   void ParseComplexPatterns();
708   void ParsePatternFragments();
709   void ParseDefaultOperands();
710   void ParseInstructions();
711   void ParsePatterns();
712   void InferInstructionFlags();
713   void GenerateVariants();
714   
715   void AddPatternToMatch(const TreePattern *Pattern, const PatternToMatch &PTM);
716   void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
717                                    std::map<std::string,
718                                    TreePatternNode*> &InstInputs,
719                                    std::map<std::string,
720                                    TreePatternNode*> &InstResults,
721                                    std::vector<Record*> &InstImpInputs,
722                                    std::vector<Record*> &InstImpResults);
723 };
724 } // end namespace llvm
725
726 #endif