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