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 LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H
16 #define LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H
17 
18 #include "CodeGenHwModes.h"
19 #include "CodeGenIntrinsics.h"
20 #include "CodeGenTarget.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MathExtras.h"
26 #include <algorithm>
27 #include <array>
28 #include <functional>
29 #include <map>
30 #include <set>
31 #include <vector>
32 
33 namespace llvm {
34 
35 class Record;
36 class Init;
37 class ListInit;
38 class DagInit;
39 class SDNodeInfo;
40 class TreePattern;
41 class TreePatternNode;
42 class CodeGenDAGPatterns;
43 class ComplexPattern;
44 
45 /// This represents a set of MVTs. Since the underlying type for the MVT
46 /// is uint8_t, there are at most 256 values. To reduce the number of memory
47 /// allocations and deallocations, represent the set as a sequence of bits.
48 /// To reduce the allocations even further, make MachineValueTypeSet own
49 /// the storage and use std::array as the bit container.
50 struct MachineValueTypeSet {
51   static_assert(std::is_same<std::underlying_type<MVT::SimpleValueType>::type,
52                              uint8_t>::value,
53                 "Change uint8_t here to the SimpleValueType's type");
54   static unsigned constexpr Capacity = std::numeric_limits<uint8_t>::max()+1;
55   using WordType = uint64_t;
56   static unsigned constexpr WordWidth = CHAR_BIT*sizeof(WordType);
57   static unsigned constexpr NumWords = Capacity/WordWidth;
58   static_assert(NumWords*WordWidth == Capacity,
59                 "Capacity should be a multiple of WordWidth");
60 
61   LLVM_ATTRIBUTE_ALWAYS_INLINE
62   MachineValueTypeSet() {
63     clear();
64   }
65 
66   LLVM_ATTRIBUTE_ALWAYS_INLINE
67   unsigned size() const {
68     unsigned Count = 0;
69     for (WordType W : Words)
70       Count += countPopulation(W);
71     return Count;
72   }
73   LLVM_ATTRIBUTE_ALWAYS_INLINE
74   void clear() {
75     std::memset(Words.data(), 0, NumWords*sizeof(WordType));
76   }
77   LLVM_ATTRIBUTE_ALWAYS_INLINE
78   bool empty() const {
79     for (WordType W : Words)
80       if (W != 0)
81         return false;
82     return true;
83   }
84   LLVM_ATTRIBUTE_ALWAYS_INLINE
85   unsigned count(MVT T) const {
86     return (Words[T.SimpleTy / WordWidth] >> (T.SimpleTy % WordWidth)) & 1;
87   }
88   std::pair<MachineValueTypeSet&,bool> insert(MVT T) {
89     bool V = count(T.SimpleTy);
90     Words[T.SimpleTy / WordWidth] |= WordType(1) << (T.SimpleTy % WordWidth);
91     return {*this, V};
92   }
93   MachineValueTypeSet &insert(const MachineValueTypeSet &S) {
94     for (unsigned i = 0; i != NumWords; ++i)
95       Words[i] |= S.Words[i];
96     return *this;
97   }
98   LLVM_ATTRIBUTE_ALWAYS_INLINE
99   void erase(MVT T) {
100     Words[T.SimpleTy / WordWidth] &= ~(WordType(1) << (T.SimpleTy % WordWidth));
101   }
102 
103   struct const_iterator {
104     // Some implementations of the C++ library require these traits to be
105     // defined.
106     using iterator_category = std::forward_iterator_tag;
107     using value_type = MVT;
108     using difference_type = ptrdiff_t;
109     using pointer = const MVT*;
110     using reference = const MVT&;
111 
112     LLVM_ATTRIBUTE_ALWAYS_INLINE
113     MVT operator*() const {
114       assert(Pos != Capacity);
115       return MVT::SimpleValueType(Pos);
116     }
117     LLVM_ATTRIBUTE_ALWAYS_INLINE
118     const_iterator(const MachineValueTypeSet *S, bool End) : Set(S) {
119       Pos = End ? Capacity : find_from_pos(0);
120     }
121     LLVM_ATTRIBUTE_ALWAYS_INLINE
122     const_iterator &operator++() {
123       assert(Pos != Capacity);
124       Pos = find_from_pos(Pos+1);
125       return *this;
126     }
127 
128     LLVM_ATTRIBUTE_ALWAYS_INLINE
129     bool operator==(const const_iterator &It) const {
130       return Set == It.Set && Pos == It.Pos;
131     }
132     LLVM_ATTRIBUTE_ALWAYS_INLINE
133     bool operator!=(const const_iterator &It) const {
134       return !operator==(It);
135     }
136 
137   private:
138     unsigned find_from_pos(unsigned P) const {
139       unsigned SkipWords = P / WordWidth;
140       unsigned SkipBits = P % WordWidth;
141       unsigned Count = SkipWords * WordWidth;
142 
143       // If P is in the middle of a word, process it manually here, because
144       // the trailing bits need to be masked off to use findFirstSet.
145       if (SkipBits != 0) {
146         WordType W = Set->Words[SkipWords];
147         W &= maskLeadingOnes<WordType>(WordWidth-SkipBits);
148         if (W != 0)
149           return Count + findFirstSet(W);
150         Count += WordWidth;
151         SkipWords++;
152       }
153 
154       for (unsigned i = SkipWords; i != NumWords; ++i) {
155         WordType W = Set->Words[i];
156         if (W != 0)
157           return Count + findFirstSet(W);
158         Count += WordWidth;
159       }
160       return Capacity;
161     }
162 
163     const MachineValueTypeSet *Set;
164     unsigned Pos;
165   };
166 
167   LLVM_ATTRIBUTE_ALWAYS_INLINE
168   const_iterator begin() const { return const_iterator(this, false); }
169   LLVM_ATTRIBUTE_ALWAYS_INLINE
170   const_iterator end()   const { return const_iterator(this, true); }
171 
172   LLVM_ATTRIBUTE_ALWAYS_INLINE
173   bool operator==(const MachineValueTypeSet &S) const {
174     return Words == S.Words;
175   }
176   LLVM_ATTRIBUTE_ALWAYS_INLINE
177   bool operator!=(const MachineValueTypeSet &S) const {
178     return !operator==(S);
179   }
180 
181 private:
182   friend struct const_iterator;
183   std::array<WordType,NumWords> Words;
184 };
185 
186 struct TypeSetByHwMode : public InfoByHwMode<MachineValueTypeSet> {
187   using SetType = MachineValueTypeSet;
188 
189   TypeSetByHwMode() = default;
190   TypeSetByHwMode(const TypeSetByHwMode &VTS) = default;
191   TypeSetByHwMode(MVT::SimpleValueType VT)
192     : TypeSetByHwMode(ValueTypeByHwMode(VT)) {}
193   TypeSetByHwMode(ValueTypeByHwMode VT)
194     : TypeSetByHwMode(ArrayRef<ValueTypeByHwMode>(&VT, 1)) {}
195   TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList);
196 
197   SetType &getOrCreate(unsigned Mode) {
198     if (hasMode(Mode))
199       return get(Mode);
200     return Map.insert({Mode,SetType()}).first->second;
201   }
202 
203   bool isValueTypeByHwMode(bool AllowEmpty) const;
204   ValueTypeByHwMode getValueTypeByHwMode() const;
205 
206   LLVM_ATTRIBUTE_ALWAYS_INLINE
207   bool isMachineValueType() const {
208     return isDefaultOnly() && Map.begin()->second.size() == 1;
209   }
210 
211   LLVM_ATTRIBUTE_ALWAYS_INLINE
212   MVT getMachineValueType() const {
213     assert(isMachineValueType());
214     return *Map.begin()->second.begin();
215   }
216 
217   bool isPossible() const;
218 
219   LLVM_ATTRIBUTE_ALWAYS_INLINE
220   bool isDefaultOnly() const {
221     return Map.size() == 1 && Map.begin()->first == DefaultMode;
222   }
223 
224   bool insert(const ValueTypeByHwMode &VVT);
225   bool constrain(const TypeSetByHwMode &VTS);
226   template <typename Predicate> bool constrain(Predicate P);
227   template <typename Predicate>
228   bool assign_if(const TypeSetByHwMode &VTS, Predicate P);
229 
230   void writeToStream(raw_ostream &OS) const;
231   static void writeToStream(const SetType &S, raw_ostream &OS);
232 
233   bool operator==(const TypeSetByHwMode &VTS) const;
234   bool operator!=(const TypeSetByHwMode &VTS) const { return !(*this == VTS); }
235 
236   void dump() const;
237   void validate() const;
238 
239 private:
240   /// Intersect two sets. Return true if anything has changed.
241   bool intersect(SetType &Out, const SetType &In);
242 };
243 
244 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T);
245 
246 struct TypeInfer {
247   TypeInfer(TreePattern &T) : TP(T), ForceMode(0) {}
248 
249   bool isConcrete(const TypeSetByHwMode &VTS, bool AllowEmpty) const {
250     return VTS.isValueTypeByHwMode(AllowEmpty);
251   }
252   ValueTypeByHwMode getConcrete(const TypeSetByHwMode &VTS,
253                                 bool AllowEmpty) const {
254     assert(VTS.isValueTypeByHwMode(AllowEmpty));
255     return VTS.getValueTypeByHwMode();
256   }
257 
258   /// The protocol in the following functions (Merge*, force*, Enforce*,
259   /// expand*) is to return "true" if a change has been made, "false"
260   /// otherwise.
261 
262   bool MergeInTypeInfo(TypeSetByHwMode &Out, const TypeSetByHwMode &In);
263   bool MergeInTypeInfo(TypeSetByHwMode &Out, MVT::SimpleValueType InVT) {
264     return MergeInTypeInfo(Out, TypeSetByHwMode(InVT));
265   }
266   bool MergeInTypeInfo(TypeSetByHwMode &Out, ValueTypeByHwMode InVT) {
267     return MergeInTypeInfo(Out, TypeSetByHwMode(InVT));
268   }
269 
270   /// Reduce the set \p Out to have at most one element for each mode.
271   bool forceArbitrary(TypeSetByHwMode &Out);
272 
273   /// The following four functions ensure that upon return the set \p Out
274   /// will only contain types of the specified kind: integer, floating-point,
275   /// scalar, or vector.
276   /// If \p Out is empty, all legal types of the specified kind will be added
277   /// to it. Otherwise, all types that are not of the specified kind will be
278   /// removed from \p Out.
279   bool EnforceInteger(TypeSetByHwMode &Out);
280   bool EnforceFloatingPoint(TypeSetByHwMode &Out);
281   bool EnforceScalar(TypeSetByHwMode &Out);
282   bool EnforceVector(TypeSetByHwMode &Out);
283 
284   /// If \p Out is empty, fill it with all legal types. Otherwise, leave it
285   /// unchanged.
286   bool EnforceAny(TypeSetByHwMode &Out);
287   /// Make sure that for each type in \p Small, there exists a larger type
288   /// in \p Big.
289   bool EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big);
290   /// 1. Ensure that for each type T in \p Vec, T is a vector type, and that
291   ///    for each type U in \p Elem, U is a scalar type.
292   /// 2. Ensure that for each (scalar) type U in \p Elem, there exists a
293   ///    (vector) type T in \p Vec, such that U is the element type of T.
294   bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Elem);
295   bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
296                               const ValueTypeByHwMode &VVT);
297   /// Ensure that for each type T in \p Sub, T is a vector type, and there
298   /// exists a type U in \p Vec such that U is a vector type with the same
299   /// element type as T and at least as many elements as T.
300   bool EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
301                                     TypeSetByHwMode &Sub);
302   /// 1. Ensure that \p V has a scalar type iff \p W has a scalar type.
303   /// 2. Ensure that for each vector type T in \p V, there exists a vector
304   ///    type U in \p W, such that T and U have the same number of elements.
305   /// 3. Ensure that for each vector type U in \p W, there exists a vector
306   ///    type T in \p V, such that T and U have the same number of elements
307   ///    (reverse of 2).
308   bool EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W);
309   /// 1. Ensure that for each type T in \p A, there exists a type U in \p B,
310   ///    such that T and U have equal size in bits.
311   /// 2. Ensure that for each type U in \p B, there exists a type T in \p A
312   ///    such that T and U have equal size in bits (reverse of 1).
313   bool EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B);
314 
315   /// For each overloaded type (i.e. of form *Any), replace it with the
316   /// corresponding subset of legal, specific types.
317   void expandOverloads(TypeSetByHwMode &VTS);
318   void expandOverloads(TypeSetByHwMode::SetType &Out,
319                        const TypeSetByHwMode::SetType &Legal);
320 
321   struct ValidateOnExit {
322     ValidateOnExit(TypeSetByHwMode &T) : VTS(T) {}
323     ~ValidateOnExit() { VTS.validate(); }
324     TypeSetByHwMode &VTS;
325   };
326 
327   TreePattern &TP;
328   unsigned ForceMode;     // Mode to use when set.
329   bool CodeGen = false;   // Set during generation of matcher code.
330 
331 private:
332   TypeSetByHwMode getLegalTypes();
333 
334   /// Cached legal types.
335   bool LegalTypesCached = false;
336   TypeSetByHwMode::SetType LegalCache = {};
337 };
338 
339 /// Set type used to track multiply used variables in patterns
340 typedef StringSet<> MultipleUseVarSet;
341 
342 /// SDTypeConstraint - This is a discriminated union of constraints,
343 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
344 struct SDTypeConstraint {
345   SDTypeConstraint(Record *R, const CodeGenHwModes &CGH);
346 
347   unsigned OperandNo;   // The operand # this constraint applies to.
348   enum {
349     SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisVec, SDTCisSameAs,
350     SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisEltOfVec,
351     SDTCisSubVecOfVec, SDTCVecEltisVT, SDTCisSameNumEltsAs, SDTCisSameSizeAs
352   } ConstraintType;
353 
354   union {   // The discriminated union.
355     struct {
356       unsigned OtherOperandNum;
357     } SDTCisSameAs_Info;
358     struct {
359       unsigned OtherOperandNum;
360     } SDTCisVTSmallerThanOp_Info;
361     struct {
362       unsigned BigOperandNum;
363     } SDTCisOpSmallerThanOp_Info;
364     struct {
365       unsigned OtherOperandNum;
366     } SDTCisEltOfVec_Info;
367     struct {
368       unsigned OtherOperandNum;
369     } SDTCisSubVecOfVec_Info;
370     struct {
371       unsigned OtherOperandNum;
372     } SDTCisSameNumEltsAs_Info;
373     struct {
374       unsigned OtherOperandNum;
375     } SDTCisSameSizeAs_Info;
376   } x;
377 
378   // The VT for SDTCisVT and SDTCVecEltisVT.
379   // Must not be in the union because it has a non-trivial destructor.
380   ValueTypeByHwMode VVT;
381 
382   /// ApplyTypeConstraint - Given a node in a pattern, apply this type
383   /// constraint to the nodes operands.  This returns true if it makes a
384   /// change, false otherwise.  If a type contradiction is found, an error
385   /// is flagged.
386   bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
387                            TreePattern &TP) const;
388 };
389 
390 /// SDNodeInfo - One of these records is created for each SDNode instance in
391 /// the target .td file.  This represents the various dag nodes we will be
392 /// processing.
393 class SDNodeInfo {
394   Record *Def;
395   StringRef EnumName;
396   StringRef SDClassName;
397   unsigned Properties;
398   unsigned NumResults;
399   int NumOperands;
400   std::vector<SDTypeConstraint> TypeConstraints;
401 public:
402   // Parse the specified record.
403   SDNodeInfo(Record *R, const CodeGenHwModes &CGH);
404 
405   unsigned getNumResults() const { return NumResults; }
406 
407   /// getNumOperands - This is the number of operands required or -1 if
408   /// variadic.
409   int getNumOperands() const { return NumOperands; }
410   Record *getRecord() const { return Def; }
411   StringRef getEnumName() const { return EnumName; }
412   StringRef getSDClassName() const { return SDClassName; }
413 
414   const std::vector<SDTypeConstraint> &getTypeConstraints() const {
415     return TypeConstraints;
416   }
417 
418   /// getKnownType - If the type constraints on this node imply a fixed type
419   /// (e.g. all stores return void, etc), then return it as an
420   /// MVT::SimpleValueType.  Otherwise, return MVT::Other.
421   MVT::SimpleValueType getKnownType(unsigned ResNo) const;
422 
423   /// hasProperty - Return true if this node has the specified property.
424   ///
425   bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
426 
427   /// ApplyTypeConstraints - Given a node in a pattern, apply the type
428   /// constraints for this node to the operands of the node.  This returns
429   /// true if it makes a change, false otherwise.  If a type contradiction is
430   /// found, an error is flagged.
431   bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const;
432 };
433 
434 /// TreePredicateFn - This is an abstraction that represents the predicates on
435 /// a PatFrag node.  This is a simple one-word wrapper around a pointer to
436 /// provide nice accessors.
437 class TreePredicateFn {
438   /// PatFragRec - This is the TreePattern for the PatFrag that we
439   /// originally came from.
440   TreePattern *PatFragRec;
441 public:
442   /// TreePredicateFn constructor.  Here 'N' is a subclass of PatFrag.
443   TreePredicateFn(TreePattern *N);
444 
445 
446   TreePattern *getOrigPatFragRecord() const { return PatFragRec; }
447 
448   /// isAlwaysTrue - Return true if this is a noop predicate.
449   bool isAlwaysTrue() const;
450 
451   bool isImmediatePattern() const { return hasImmCode(); }
452 
453   /// getImmediatePredicateCode - Return the code that evaluates this pattern if
454   /// this is an immediate predicate.  It is an error to call this on a
455   /// non-immediate pattern.
456   std::string getImmediatePredicateCode() const {
457     std::string Result = getImmCode();
458     assert(!Result.empty() && "Isn't an immediate pattern!");
459     return Result;
460   }
461 
462   bool operator==(const TreePredicateFn &RHS) const {
463     return PatFragRec == RHS.PatFragRec;
464   }
465 
466   bool operator!=(const TreePredicateFn &RHS) const { return !(*this == RHS); }
467 
468   /// Return the name to use in the generated code to reference this, this is
469   /// "Predicate_foo" if from a pattern fragment "foo".
470   std::string getFnName() const;
471 
472   /// getCodeToRunOnSDNode - Return the code for the function body that
473   /// evaluates this predicate.  The argument is expected to be in "Node",
474   /// not N.  This handles casting and conversion to a concrete node type as
475   /// appropriate.
476   std::string getCodeToRunOnSDNode() const;
477 
478   /// Get the data type of the argument to getImmediatePredicateCode().
479   StringRef getImmType() const;
480 
481   /// Get a string that describes the type returned by getImmType() but is
482   /// usable as part of an identifier.
483   StringRef getImmTypeIdentifier() const;
484 
485   // Is the desired predefined predicate for a load?
486   bool isLoad() const;
487   // Is the desired predefined predicate for a store?
488   bool isStore() const;
489   // Is the desired predefined predicate for an atomic?
490   bool isAtomic() const;
491 
492   /// Is this predicate the predefined unindexed load predicate?
493   /// Is this predicate the predefined unindexed store predicate?
494   bool isUnindexed() const;
495   /// Is this predicate the predefined non-extending load predicate?
496   bool isNonExtLoad() const;
497   /// Is this predicate the predefined any-extend load predicate?
498   bool isAnyExtLoad() const;
499   /// Is this predicate the predefined sign-extend load predicate?
500   bool isSignExtLoad() const;
501   /// Is this predicate the predefined zero-extend load predicate?
502   bool isZeroExtLoad() const;
503   /// Is this predicate the predefined non-truncating store predicate?
504   bool isNonTruncStore() const;
505   /// Is this predicate the predefined truncating store predicate?
506   bool isTruncStore() const;
507 
508   /// Is this predicate the predefined monotonic atomic predicate?
509   bool isAtomicOrderingMonotonic() const;
510   /// Is this predicate the predefined acquire atomic predicate?
511   bool isAtomicOrderingAcquire() const;
512   /// Is this predicate the predefined release atomic predicate?
513   bool isAtomicOrderingRelease() const;
514   /// Is this predicate the predefined acquire-release atomic predicate?
515   bool isAtomicOrderingAcquireRelease() const;
516   /// Is this predicate the predefined sequentially consistent atomic predicate?
517   bool isAtomicOrderingSequentiallyConsistent() const;
518 
519   /// If non-null, indicates that this predicate is a predefined memory VT
520   /// predicate for a load/store and returns the ValueType record for the memory VT.
521   Record *getMemoryVT() const;
522   /// If non-null, indicates that this predicate is a predefined memory VT
523   /// predicate (checking only the scalar type) for load/store and returns the
524   /// ValueType record for the memory VT.
525   Record *getScalarMemoryVT() const;
526 
527 private:
528   bool hasPredCode() const;
529   bool hasImmCode() const;
530   std::string getPredCode() const;
531   std::string getImmCode() const;
532   bool immCodeUsesAPInt() const;
533   bool immCodeUsesAPFloat() const;
534 
535   bool isPredefinedPredicateEqualTo(StringRef Field, bool Value) const;
536 };
537 
538 
539 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
540 /// patterns), and as such should be ref counted.  We currently just leak all
541 /// TreePatternNode objects!
542 class TreePatternNode {
543   /// The type of each node result.  Before and during type inference, each
544   /// result may be a set of possible types.  After (successful) type inference,
545   /// each is a single concrete type.
546   std::vector<TypeSetByHwMode> Types;
547 
548   /// Operator - The Record for the operator if this is an interior node (not
549   /// a leaf).
550   Record *Operator;
551 
552   /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
553   ///
554   Init *Val;
555 
556   /// Name - The name given to this node with the :$foo notation.
557   ///
558   std::string Name;
559 
560   /// PredicateFns - The predicate functions to execute on this node to check
561   /// for a match.  If this list is empty, no predicate is involved.
562   std::vector<TreePredicateFn> PredicateFns;
563 
564   /// TransformFn - The transformation function to execute on this node before
565   /// it can be substituted into the resulting instruction on a pattern match.
566   Record *TransformFn;
567 
568   std::vector<TreePatternNode*> Children;
569 public:
570   TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch,
571                   unsigned NumResults)
572     : Operator(Op), Val(nullptr), TransformFn(nullptr), Children(Ch) {
573     Types.resize(NumResults);
574   }
575   TreePatternNode(Init *val, unsigned NumResults)    // leaf ctor
576     : Operator(nullptr), Val(val), TransformFn(nullptr) {
577     Types.resize(NumResults);
578   }
579   ~TreePatternNode();
580 
581   bool hasName() const { return !Name.empty(); }
582   const std::string &getName() const { return Name; }
583   void setName(StringRef N) { Name.assign(N.begin(), N.end()); }
584 
585   bool isLeaf() const { return Val != nullptr; }
586 
587   // Type accessors.
588   unsigned getNumTypes() const { return Types.size(); }
589   ValueTypeByHwMode getType(unsigned ResNo) const {
590     return Types[ResNo].getValueTypeByHwMode();
591   }
592   const std::vector<TypeSetByHwMode> &getExtTypes() const { return Types; }
593   const TypeSetByHwMode &getExtType(unsigned ResNo) const {
594     return Types[ResNo];
595   }
596   TypeSetByHwMode &getExtType(unsigned ResNo) { return Types[ResNo]; }
597   void setType(unsigned ResNo, const TypeSetByHwMode &T) { Types[ResNo] = T; }
598   MVT::SimpleValueType getSimpleType(unsigned ResNo) const {
599     return Types[ResNo].getMachineValueType().SimpleTy;
600   }
601 
602   bool hasConcreteType(unsigned ResNo) const {
603     return Types[ResNo].isValueTypeByHwMode(false);
604   }
605   bool isTypeCompletelyUnknown(unsigned ResNo, TreePattern &TP) const {
606     return Types[ResNo].empty();
607   }
608 
609   Init *getLeafValue() const { assert(isLeaf()); return Val; }
610   Record *getOperator() const { assert(!isLeaf()); return Operator; }
611 
612   unsigned getNumChildren() const { return Children.size(); }
613   TreePatternNode *getChild(unsigned N) const { return Children[N]; }
614   void setChild(unsigned i, TreePatternNode *N) {
615     Children[i] = N;
616   }
617 
618   /// hasChild - Return true if N is any of our children.
619   bool hasChild(const TreePatternNode *N) const {
620     for (unsigned i = 0, e = Children.size(); i != e; ++i)
621       if (Children[i] == N) return true;
622     return false;
623   }
624 
625   bool hasProperTypeByHwMode() const;
626   bool hasPossibleType() const;
627   bool setDefaultMode(unsigned Mode);
628 
629   bool hasAnyPredicate() const { return !PredicateFns.empty(); }
630 
631   const std::vector<TreePredicateFn> &getPredicateFns() const {
632     return PredicateFns;
633   }
634   void clearPredicateFns() { PredicateFns.clear(); }
635   void setPredicateFns(const std::vector<TreePredicateFn> &Fns) {
636     assert(PredicateFns.empty() && "Overwriting non-empty predicate list!");
637     PredicateFns = Fns;
638   }
639   void addPredicateFn(const TreePredicateFn &Fn) {
640     assert(!Fn.isAlwaysTrue() && "Empty predicate string!");
641     if (!is_contained(PredicateFns, Fn))
642       PredicateFns.push_back(Fn);
643   }
644 
645   Record *getTransformFn() const { return TransformFn; }
646   void setTransformFn(Record *Fn) { TransformFn = Fn; }
647 
648   /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
649   /// CodeGenIntrinsic information for it, otherwise return a null pointer.
650   const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
651 
652   /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
653   /// return the ComplexPattern information, otherwise return null.
654   const ComplexPattern *
655   getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const;
656 
657   /// Returns the number of MachineInstr operands that would be produced by this
658   /// node if it mapped directly to an output Instruction's
659   /// operand. ComplexPattern specifies this explicitly; MIOperandInfo gives it
660   /// for Operands; otherwise 1.
661   unsigned getNumMIResults(const CodeGenDAGPatterns &CGP) const;
662 
663   /// NodeHasProperty - Return true if this node has the specified property.
664   bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
665 
666   /// TreeHasProperty - Return true if any node in this tree has the specified
667   /// property.
668   bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
669 
670   /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is
671   /// marked isCommutative.
672   bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const;
673 
674   void print(raw_ostream &OS) const;
675   void dump() const;
676 
677 public:   // Higher level manipulation routines.
678 
679   /// clone - Return a new copy of this tree.
680   ///
681   TreePatternNode *clone() const;
682 
683   /// RemoveAllTypes - Recursively strip all the types of this tree.
684   void RemoveAllTypes();
685 
686   /// isIsomorphicTo - Return true if this node is recursively isomorphic to
687   /// the specified node.  For this comparison, all of the state of the node
688   /// is considered, except for the assigned name.  Nodes with differing names
689   /// that are otherwise identical are considered isomorphic.
690   bool isIsomorphicTo(const TreePatternNode *N,
691                       const MultipleUseVarSet &DepVars) const;
692 
693   /// SubstituteFormalArguments - Replace the formal arguments in this tree
694   /// with actual values specified by ArgMap.
695   void SubstituteFormalArguments(std::map<std::string,
696                                           TreePatternNode*> &ArgMap);
697 
698   /// InlinePatternFragments - If this pattern refers to any pattern
699   /// fragments, inline them into place, giving us a pattern without any
700   /// PatFrag references.
701   TreePatternNode *InlinePatternFragments(TreePattern &TP);
702 
703   /// ApplyTypeConstraints - Apply all of the type constraints relevant to
704   /// this node and its children in the tree.  This returns true if it makes a
705   /// change, false otherwise.  If a type contradiction is found, flag an error.
706   bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
707 
708   /// UpdateNodeType - Set the node type of N to VT if VT contains
709   /// information.  If N already contains a conflicting type, then flag an
710   /// error.  This returns true if any information was updated.
711   ///
712   bool UpdateNodeType(unsigned ResNo, const TypeSetByHwMode &InTy,
713                       TreePattern &TP);
714   bool UpdateNodeType(unsigned ResNo, MVT::SimpleValueType InTy,
715                       TreePattern &TP);
716   bool UpdateNodeType(unsigned ResNo, ValueTypeByHwMode InTy,
717                       TreePattern &TP);
718 
719   // Update node type with types inferred from an instruction operand or result
720   // def from the ins/outs lists.
721   // Return true if the type changed.
722   bool UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand, TreePattern &TP);
723 
724   /// ContainsUnresolvedType - Return true if this tree contains any
725   /// unresolved types.
726   bool ContainsUnresolvedType(TreePattern &TP) const;
727 
728   /// canPatternMatch - If it is impossible for this pattern to match on this
729   /// target, fill in Reason and return false.  Otherwise, return true.
730   bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP);
731 };
732 
733 inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) {
734   TPN.print(OS);
735   return OS;
736 }
737 
738 
739 /// TreePattern - Represent a pattern, used for instructions, pattern
740 /// fragments, etc.
741 ///
742 class TreePattern {
743   /// Trees - The list of pattern trees which corresponds to this pattern.
744   /// Note that PatFrag's only have a single tree.
745   ///
746   std::vector<TreePatternNode*> Trees;
747 
748   /// NamedNodes - This is all of the nodes that have names in the trees in this
749   /// pattern.
750   StringMap<SmallVector<TreePatternNode*,1> > NamedNodes;
751 
752   /// TheRecord - The actual TableGen record corresponding to this pattern.
753   ///
754   Record *TheRecord;
755 
756   /// Args - This is a list of all of the arguments to this pattern (for
757   /// PatFrag patterns), which are the 'node' markers in this pattern.
758   std::vector<std::string> Args;
759 
760   /// CDP - the top-level object coordinating this madness.
761   ///
762   CodeGenDAGPatterns &CDP;
763 
764   /// isInputPattern - True if this is an input pattern, something to match.
765   /// False if this is an output pattern, something to emit.
766   bool isInputPattern;
767 
768   /// hasError - True if the currently processed nodes have unresolvable types
769   /// or other non-fatal errors
770   bool HasError;
771 
772   /// It's important that the usage of operands in ComplexPatterns is
773   /// consistent: each named operand can be defined by at most one
774   /// ComplexPattern. This records the ComplexPattern instance and the operand
775   /// number for each operand encountered in a ComplexPattern to aid in that
776   /// check.
777   StringMap<std::pair<Record *, unsigned>> ComplexPatternOperands;
778 
779   TypeInfer Infer;
780 
781 public:
782 
783   /// TreePattern constructor - Parse the specified DagInits into the
784   /// current record.
785   TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
786               CodeGenDAGPatterns &ise);
787   TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
788               CodeGenDAGPatterns &ise);
789   TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
790               CodeGenDAGPatterns &ise);
791 
792   /// getTrees - Return the tree patterns which corresponds to this pattern.
793   ///
794   const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
795   unsigned getNumTrees() const { return Trees.size(); }
796   TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
797   void setTree(unsigned i, TreePatternNode *Tree) { Trees[i] = Tree; }
798   TreePatternNode *getOnlyTree() const {
799     assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
800     return Trees[0];
801   }
802 
803   const StringMap<SmallVector<TreePatternNode*,1> > &getNamedNodesMap() {
804     if (NamedNodes.empty())
805       ComputeNamedNodes();
806     return NamedNodes;
807   }
808 
809   /// getRecord - Return the actual TableGen record corresponding to this
810   /// pattern.
811   ///
812   Record *getRecord() const { return TheRecord; }
813 
814   unsigned getNumArgs() const { return Args.size(); }
815   const std::string &getArgName(unsigned i) const {
816     assert(i < Args.size() && "Argument reference out of range!");
817     return Args[i];
818   }
819   std::vector<std::string> &getArgList() { return Args; }
820 
821   CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
822 
823   /// InlinePatternFragments - If this pattern refers to any pattern
824   /// fragments, inline them into place, giving us a pattern without any
825   /// PatFrag references.
826   void InlinePatternFragments() {
827     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
828       Trees[i] = Trees[i]->InlinePatternFragments(*this);
829   }
830 
831   /// InferAllTypes - Infer/propagate as many types throughout the expression
832   /// patterns as possible.  Return true if all types are inferred, false
833   /// otherwise.  Bail out if a type contradiction is found.
834   bool InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> >
835                           *NamedTypes=nullptr);
836 
837   /// error - If this is the first error in the current resolution step,
838   /// print it and set the error flag.  Otherwise, continue silently.
839   void error(const Twine &Msg);
840   bool hasError() const {
841     return HasError;
842   }
843   void resetError() {
844     HasError = false;
845   }
846 
847   TypeInfer &getInfer() { return Infer; }
848 
849   void print(raw_ostream &OS) const;
850   void dump() const;
851 
852 private:
853   TreePatternNode *ParseTreePattern(Init *DI, StringRef OpName);
854   void ComputeNamedNodes();
855   void ComputeNamedNodes(TreePatternNode *N);
856 };
857 
858 
859 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
860                                             const TypeSetByHwMode &InTy,
861                                             TreePattern &TP) {
862   TypeSetByHwMode VTS(InTy);
863   TP.getInfer().expandOverloads(VTS);
864   return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
865 }
866 
867 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
868                                             MVT::SimpleValueType InTy,
869                                             TreePattern &TP) {
870   TypeSetByHwMode VTS(InTy);
871   TP.getInfer().expandOverloads(VTS);
872   return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
873 }
874 
875 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
876                                             ValueTypeByHwMode InTy,
877                                             TreePattern &TP) {
878   TypeSetByHwMode VTS(InTy);
879   TP.getInfer().expandOverloads(VTS);
880   return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
881 }
882 
883 
884 /// DAGDefaultOperand - One of these is created for each OperandWithDefaultOps
885 /// that has a set ExecuteAlways / DefaultOps field.
886 struct DAGDefaultOperand {
887   std::vector<TreePatternNode*> DefaultOps;
888 };
889 
890 class DAGInstruction {
891   TreePattern *Pattern;
892   std::vector<Record*> Results;
893   std::vector<Record*> Operands;
894   std::vector<Record*> ImpResults;
895   TreePatternNode *ResultPattern;
896 public:
897   DAGInstruction(TreePattern *TP,
898                  const std::vector<Record*> &results,
899                  const std::vector<Record*> &operands,
900                  const std::vector<Record*> &impresults)
901     : Pattern(TP), Results(results), Operands(operands),
902       ImpResults(impresults), ResultPattern(nullptr) {}
903 
904   TreePattern *getPattern() const { return Pattern; }
905   unsigned getNumResults() const { return Results.size(); }
906   unsigned getNumOperands() const { return Operands.size(); }
907   unsigned getNumImpResults() const { return ImpResults.size(); }
908   const std::vector<Record*>& getImpResults() const { return ImpResults; }
909 
910   void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
911 
912   Record *getResult(unsigned RN) const {
913     assert(RN < Results.size());
914     return Results[RN];
915   }
916 
917   Record *getOperand(unsigned ON) const {
918     assert(ON < Operands.size());
919     return Operands[ON];
920   }
921 
922   Record *getImpResult(unsigned RN) const {
923     assert(RN < ImpResults.size());
924     return ImpResults[RN];
925   }
926 
927   TreePatternNode *getResultPattern() const { return ResultPattern; }
928 };
929 
930 /// This class represents a condition that has to be satisfied for a pattern
931 /// to be tried. It is a generalization of a class "Pattern" from Target.td:
932 /// in addition to the Target.td's predicates, this class can also represent
933 /// conditions associated with HW modes. Both types will eventually become
934 /// strings containing C++ code to be executed, the difference is in how
935 /// these strings are generated.
936 class Predicate {
937 public:
938   Predicate(Record *R, bool C = true) : Def(R), IfCond(C), IsHwMode(false) {
939     assert(R->isSubClassOf("Predicate") &&
940            "Predicate objects should only be created for records derived"
941            "from Predicate class");
942   }
943   Predicate(StringRef FS, bool C = true) : Def(nullptr), Features(FS.str()),
944     IfCond(C), IsHwMode(true) {}
945 
946   /// Return a string which contains the C++ condition code that will serve
947   /// as a predicate during instruction selection.
948   std::string getCondString() const {
949     // The string will excute in a subclass of SelectionDAGISel.
950     // Cast to std::string explicitly to avoid ambiguity with StringRef.
951     std::string C = IsHwMode
952         ? std::string("MF->getSubtarget().checkFeatures(\"" + Features + "\")")
953         : std::string(Def->getValueAsString("CondString"));
954     return IfCond ? C : "!("+C+')';
955   }
956   bool operator==(const Predicate &P) const {
957     return IfCond == P.IfCond && IsHwMode == P.IsHwMode && Def == P.Def;
958   }
959   bool operator<(const Predicate &P) const {
960     if (IsHwMode != P.IsHwMode)
961       return IsHwMode < P.IsHwMode;
962     assert(!Def == !P.Def && "Inconsistency between Def and IsHwMode");
963     if (IfCond != P.IfCond)
964       return IfCond < P.IfCond;
965     if (Def)
966       return LessRecord()(Def, P.Def);
967     return Features < P.Features;
968   }
969   Record *Def;            ///< Predicate definition from .td file, null for
970                           ///< HW modes.
971   std::string Features;   ///< Feature string for HW mode.
972   bool IfCond;            ///< The boolean value that the condition has to
973                           ///< evaluate to for this predicate to be true.
974   bool IsHwMode;          ///< Does this predicate correspond to a HW mode?
975 };
976 
977 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
978 /// processed to produce isel.
979 class PatternToMatch {
980 public:
981   PatternToMatch(Record *srcrecord, const std::vector<Predicate> &preds,
982                  TreePatternNode *src, TreePatternNode *dst,
983                  const std::vector<Record*> &dstregs,
984                  int complexity, unsigned uid, unsigned setmode = 0)
985     : SrcRecord(srcrecord), SrcPattern(src), DstPattern(dst),
986       Predicates(preds), Dstregs(std::move(dstregs)),
987       AddedComplexity(complexity), ID(uid), ForceMode(setmode) {}
988 
989   PatternToMatch(Record *srcrecord, std::vector<Predicate> &&preds,
990                  TreePatternNode *src, TreePatternNode *dst,
991                  std::vector<Record*> &&dstregs,
992                  int complexity, unsigned uid, unsigned setmode = 0)
993     : SrcRecord(srcrecord), SrcPattern(src), DstPattern(dst),
994       Predicates(preds), Dstregs(std::move(dstregs)),
995       AddedComplexity(complexity), ID(uid), ForceMode(setmode) {}
996 
997   Record          *SrcRecord;   // Originating Record for the pattern.
998   TreePatternNode *SrcPattern;  // Source pattern to match.
999   TreePatternNode *DstPattern;  // Resulting pattern.
1000   std::vector<Predicate> Predicates;  // Top level predicate conditions
1001                                       // to match.
1002   std::vector<Record*> Dstregs; // Physical register defs being matched.
1003   int              AddedComplexity; // Add to matching pattern complexity.
1004   unsigned         ID;          // Unique ID for the record.
1005   unsigned         ForceMode;   // Force this mode in type inference when set.
1006 
1007   Record          *getSrcRecord()  const { return SrcRecord; }
1008   TreePatternNode *getSrcPattern() const { return SrcPattern; }
1009   TreePatternNode *getDstPattern() const { return DstPattern; }
1010   const std::vector<Record*> &getDstRegs() const { return Dstregs; }
1011   int         getAddedComplexity() const { return AddedComplexity; }
1012   const std::vector<Predicate> &getPredicates() const { return Predicates; }
1013 
1014   std::string getPredicateCheck() const;
1015 
1016   /// Compute the complexity metric for the input pattern.  This roughly
1017   /// corresponds to the number of nodes that are covered.
1018   int getPatternComplexity(const CodeGenDAGPatterns &CGP) const;
1019 };
1020 
1021 class CodeGenDAGPatterns {
1022   RecordKeeper &Records;
1023   CodeGenTarget Target;
1024   CodeGenIntrinsicTable Intrinsics;
1025   CodeGenIntrinsicTable TgtIntrinsics;
1026 
1027   std::map<Record*, SDNodeInfo, LessRecordByID> SDNodes;
1028   std::map<Record*, std::pair<Record*, std::string>, LessRecordByID>
1029       SDNodeXForms;
1030   std::map<Record*, ComplexPattern, LessRecordByID> ComplexPatterns;
1031   std::map<Record *, std::unique_ptr<TreePattern>, LessRecordByID>
1032       PatternFragments;
1033   std::map<Record*, DAGDefaultOperand, LessRecordByID> DefaultOperands;
1034   std::map<Record*, DAGInstruction, LessRecordByID> Instructions;
1035 
1036   // Specific SDNode definitions:
1037   Record *intrinsic_void_sdnode;
1038   Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
1039 
1040   /// PatternsToMatch - All of the things we are matching on the DAG.  The first
1041   /// value is the pattern to match, the second pattern is the result to
1042   /// emit.
1043   std::vector<PatternToMatch> PatternsToMatch;
1044 
1045   TypeSetByHwMode LegalVTS;
1046 
1047   using PatternRewriterFn = std::function<void (TreePattern *)>;
1048   PatternRewriterFn PatternRewriter;
1049 
1050 public:
1051   CodeGenDAGPatterns(RecordKeeper &R,
1052                      PatternRewriterFn PatternRewriter = nullptr);
1053 
1054   CodeGenTarget &getTargetInfo() { return Target; }
1055   const CodeGenTarget &getTargetInfo() const { return Target; }
1056   const TypeSetByHwMode &getLegalTypes() const { return LegalVTS; }
1057 
1058   Record *getSDNodeNamed(const std::string &Name) const;
1059 
1060   const SDNodeInfo &getSDNodeInfo(Record *R) const {
1061     auto F = SDNodes.find(R);
1062     assert(F != SDNodes.end() && "Unknown node!");
1063     return F->second;
1064   }
1065 
1066   // Node transformation lookups.
1067   typedef std::pair<Record*, std::string> NodeXForm;
1068   const NodeXForm &getSDNodeTransform(Record *R) const {
1069     auto F = SDNodeXForms.find(R);
1070     assert(F != SDNodeXForms.end() && "Invalid transform!");
1071     return F->second;
1072   }
1073 
1074   typedef std::map<Record*, NodeXForm, LessRecordByID>::const_iterator
1075           nx_iterator;
1076   nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
1077   nx_iterator nx_end() const { return SDNodeXForms.end(); }
1078 
1079 
1080   const ComplexPattern &getComplexPattern(Record *R) const {
1081     auto F = ComplexPatterns.find(R);
1082     assert(F != ComplexPatterns.end() && "Unknown addressing mode!");
1083     return F->second;
1084   }
1085 
1086   const CodeGenIntrinsic &getIntrinsic(Record *R) const {
1087     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
1088       if (Intrinsics[i].TheDef == R) return Intrinsics[i];
1089     for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
1090       if (TgtIntrinsics[i].TheDef == R) return TgtIntrinsics[i];
1091     llvm_unreachable("Unknown intrinsic!");
1092   }
1093 
1094   const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
1095     if (IID-1 < Intrinsics.size())
1096       return Intrinsics[IID-1];
1097     if (IID-Intrinsics.size()-1 < TgtIntrinsics.size())
1098       return TgtIntrinsics[IID-Intrinsics.size()-1];
1099     llvm_unreachable("Bad intrinsic ID!");
1100   }
1101 
1102   unsigned getIntrinsicID(Record *R) const {
1103     for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
1104       if (Intrinsics[i].TheDef == R) return i;
1105     for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
1106       if (TgtIntrinsics[i].TheDef == R) return i + Intrinsics.size();
1107     llvm_unreachable("Unknown intrinsic!");
1108   }
1109 
1110   const DAGDefaultOperand &getDefaultOperand(Record *R) const {
1111     auto F = DefaultOperands.find(R);
1112     assert(F != DefaultOperands.end() &&"Isn't an analyzed default operand!");
1113     return F->second;
1114   }
1115 
1116   // Pattern Fragment information.
1117   TreePattern *getPatternFragment(Record *R) const {
1118     auto F = PatternFragments.find(R);
1119     assert(F != PatternFragments.end() && "Invalid pattern fragment request!");
1120     return F->second.get();
1121   }
1122   TreePattern *getPatternFragmentIfRead(Record *R) const {
1123     auto F = PatternFragments.find(R);
1124     if (F == PatternFragments.end())
1125       return nullptr;
1126     return F->second.get();
1127   }
1128 
1129   typedef std::map<Record *, std::unique_ptr<TreePattern>,
1130                    LessRecordByID>::const_iterator pf_iterator;
1131   pf_iterator pf_begin() const { return PatternFragments.begin(); }
1132   pf_iterator pf_end() const { return PatternFragments.end(); }
1133   iterator_range<pf_iterator> ptfs() const { return PatternFragments; }
1134 
1135   // Patterns to match information.
1136   typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
1137   ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
1138   ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
1139   iterator_range<ptm_iterator> ptms() const { return PatternsToMatch; }
1140 
1141   /// Parse the Pattern for an instruction, and insert the result in DAGInsts.
1142   typedef std::map<Record*, DAGInstruction, LessRecordByID> DAGInstMap;
1143   const DAGInstruction &parseInstructionPattern(
1144       CodeGenInstruction &CGI, ListInit *Pattern,
1145       DAGInstMap &DAGInsts);
1146 
1147   const DAGInstruction &getInstruction(Record *R) const {
1148     auto F = Instructions.find(R);
1149     assert(F != Instructions.end() && "Unknown instruction!");
1150     return F->second;
1151   }
1152 
1153   Record *get_intrinsic_void_sdnode() const {
1154     return intrinsic_void_sdnode;
1155   }
1156   Record *get_intrinsic_w_chain_sdnode() const {
1157     return intrinsic_w_chain_sdnode;
1158   }
1159   Record *get_intrinsic_wo_chain_sdnode() const {
1160     return intrinsic_wo_chain_sdnode;
1161   }
1162 
1163   bool hasTargetIntrinsics() { return !TgtIntrinsics.empty(); }
1164 
1165 private:
1166   void ParseNodeInfo();
1167   void ParseNodeTransforms();
1168   void ParseComplexPatterns();
1169   void ParsePatternFragments(bool OutFrags = false);
1170   void ParseDefaultOperands();
1171   void ParseInstructions();
1172   void ParsePatterns();
1173   void ExpandHwModeBasedTypes();
1174   void InferInstructionFlags();
1175   void GenerateVariants();
1176   void VerifyInstructionFlags();
1177 
1178   std::vector<Predicate> makePredList(ListInit *L);
1179 
1180   void AddPatternToMatch(TreePattern *Pattern, PatternToMatch &&PTM);
1181   void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1182                                    std::map<std::string,
1183                                    TreePatternNode*> &InstInputs,
1184                                    std::map<std::string,
1185                                    TreePatternNode*> &InstResults,
1186                                    std::vector<Record*> &InstImpResults);
1187 };
1188 
1189 
1190 inline bool SDNodeInfo::ApplyTypeConstraints(TreePatternNode *N,
1191                                              TreePattern &TP) const {
1192     bool MadeChange = false;
1193     for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
1194       MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
1195     return MadeChange;
1196   }
1197 } // end namespace llvm
1198 
1199 #endif
1200