blob: 4be9afdcacd22587a39f22259aadbfd82e3fba76 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
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//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file declares the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Benjamin Kramer00e08fc2014-08-13 16:26:38 +000015#ifndef LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H
16#define LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H
Chris Lattner6cefb772008-01-05 22:25:12 +000017
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000018#include "CodeGenHwModes.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "CodeGenIntrinsics.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000020#include "CodeGenTarget.h"
Matt Arsenault082879a2017-12-20 19:36:28 +000021#include "SDNodeProperties.h"
Craig Topper0f562fe2018-12-05 00:47:59 +000022#include "llvm/ADT/MapVector.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000023#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringMap.h"
Zachary Turnere4442992017-09-20 18:01:40 +000025#include "llvm/ADT/StringSet.h"
Craig Topper655b8de2012-02-05 07:21:30 +000026#include "llvm/Support/ErrorHandling.h"
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +000027#include "llvm/Support/MathExtras.h"
Chris Lattnere14d2e22010-03-19 01:07:44 +000028#include <algorithm>
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +000029#include <array>
Daniel Sanders8f5a5912017-11-11 03:23:44 +000030#include <functional>
Chris Lattnere14d2e22010-03-19 01:07:44 +000031#include <map>
Craig Topper0f562fe2018-12-05 00:47:59 +000032#include <numeric>
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000033#include <set>
34#include <vector>
Chris Lattner6cefb772008-01-05 22:25:12 +000035
36namespace llvm {
Chris Lattner6cefb772008-01-05 22:25:12 +000037
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +000038class Record;
39class Init;
40class ListInit;
41class DagInit;
42class SDNodeInfo;
43class TreePattern;
44class TreePatternNode;
45class CodeGenDAGPatterns;
46class ComplexPattern;
47
Florian Hahn0b596f02018-05-30 21:00:18 +000048/// Shared pointer for TreePatternNode.
49using TreePatternNodePtr = std::shared_ptr<TreePatternNode>;
50
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +000051/// This represents a set of MVTs. Since the underlying type for the MVT
52/// is uint8_t, there are at most 256 values. To reduce the number of memory
53/// allocations and deallocations, represent the set as a sequence of bits.
54/// To reduce the allocations even further, make MachineValueTypeSet own
55/// the storage and use std::array as the bit container.
56struct MachineValueTypeSet {
57 static_assert(std::is_same<std::underlying_type<MVT::SimpleValueType>::type,
58 uint8_t>::value,
59 "Change uint8_t here to the SimpleValueType's type");
60 static unsigned constexpr Capacity = std::numeric_limits<uint8_t>::max()+1;
61 using WordType = uint64_t;
Craig Toppera6dd78b2017-09-21 04:55:04 +000062 static unsigned constexpr WordWidth = CHAR_BIT*sizeof(WordType);
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +000063 static unsigned constexpr NumWords = Capacity/WordWidth;
64 static_assert(NumWords*WordWidth == Capacity,
65 "Capacity should be a multiple of WordWidth");
66
67 LLVM_ATTRIBUTE_ALWAYS_INLINE
68 MachineValueTypeSet() {
69 clear();
70 }
71
72 LLVM_ATTRIBUTE_ALWAYS_INLINE
73 unsigned size() const {
74 unsigned Count = 0;
75 for (WordType W : Words)
76 Count += countPopulation(W);
77 return Count;
78 }
79 LLVM_ATTRIBUTE_ALWAYS_INLINE
80 void clear() {
81 std::memset(Words.data(), 0, NumWords*sizeof(WordType));
82 }
83 LLVM_ATTRIBUTE_ALWAYS_INLINE
84 bool empty() const {
85 for (WordType W : Words)
86 if (W != 0)
87 return false;
88 return true;
89 }
90 LLVM_ATTRIBUTE_ALWAYS_INLINE
91 unsigned count(MVT T) const {
92 return (Words[T.SimpleTy / WordWidth] >> (T.SimpleTy % WordWidth)) & 1;
93 }
94 std::pair<MachineValueTypeSet&,bool> insert(MVT T) {
95 bool V = count(T.SimpleTy);
96 Words[T.SimpleTy / WordWidth] |= WordType(1) << (T.SimpleTy % WordWidth);
97 return {*this, V};
98 }
99 MachineValueTypeSet &insert(const MachineValueTypeSet &S) {
100 for (unsigned i = 0; i != NumWords; ++i)
101 Words[i] |= S.Words[i];
102 return *this;
103 }
104 LLVM_ATTRIBUTE_ALWAYS_INLINE
105 void erase(MVT T) {
106 Words[T.SimpleTy / WordWidth] &= ~(WordType(1) << (T.SimpleTy % WordWidth));
107 }
108
109 struct const_iterator {
110 // Some implementations of the C++ library require these traits to be
111 // defined.
112 using iterator_category = std::forward_iterator_tag;
113 using value_type = MVT;
114 using difference_type = ptrdiff_t;
115 using pointer = const MVT*;
116 using reference = const MVT&;
117
118 LLVM_ATTRIBUTE_ALWAYS_INLINE
119 MVT operator*() const {
120 assert(Pos != Capacity);
121 return MVT::SimpleValueType(Pos);
122 }
123 LLVM_ATTRIBUTE_ALWAYS_INLINE
124 const_iterator(const MachineValueTypeSet *S, bool End) : Set(S) {
125 Pos = End ? Capacity : find_from_pos(0);
126 }
127 LLVM_ATTRIBUTE_ALWAYS_INLINE
128 const_iterator &operator++() {
129 assert(Pos != Capacity);
130 Pos = find_from_pos(Pos+1);
131 return *this;
132 }
133
134 LLVM_ATTRIBUTE_ALWAYS_INLINE
135 bool operator==(const const_iterator &It) const {
136 return Set == It.Set && Pos == It.Pos;
137 }
138 LLVM_ATTRIBUTE_ALWAYS_INLINE
139 bool operator!=(const const_iterator &It) const {
140 return !operator==(It);
141 }
142
143 private:
144 unsigned find_from_pos(unsigned P) const {
145 unsigned SkipWords = P / WordWidth;
146 unsigned SkipBits = P % WordWidth;
147 unsigned Count = SkipWords * WordWidth;
148
149 // If P is in the middle of a word, process it manually here, because
150 // the trailing bits need to be masked off to use findFirstSet.
151 if (SkipBits != 0) {
152 WordType W = Set->Words[SkipWords];
153 W &= maskLeadingOnes<WordType>(WordWidth-SkipBits);
154 if (W != 0)
155 return Count + findFirstSet(W);
156 Count += WordWidth;
157 SkipWords++;
158 }
159
160 for (unsigned i = SkipWords; i != NumWords; ++i) {
161 WordType W = Set->Words[i];
162 if (W != 0)
163 return Count + findFirstSet(W);
164 Count += WordWidth;
165 }
166 return Capacity;
167 }
168
169 const MachineValueTypeSet *Set;
170 unsigned Pos;
171 };
172
173 LLVM_ATTRIBUTE_ALWAYS_INLINE
174 const_iterator begin() const { return const_iterator(this, false); }
175 LLVM_ATTRIBUTE_ALWAYS_INLINE
176 const_iterator end() const { return const_iterator(this, true); }
177
178 LLVM_ATTRIBUTE_ALWAYS_INLINE
179 bool operator==(const MachineValueTypeSet &S) const {
180 return Words == S.Words;
181 }
182 LLVM_ATTRIBUTE_ALWAYS_INLINE
183 bool operator!=(const MachineValueTypeSet &S) const {
184 return !operator==(S);
185 }
186
187private:
188 friend struct const_iterator;
189 std::array<WordType,NumWords> Words;
190};
191
192struct TypeSetByHwMode : public InfoByHwMode<MachineValueTypeSet> {
193 using SetType = MachineValueTypeSet;
Jim Grosbach398abb42010-12-24 05:06:32 +0000194
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000195 TypeSetByHwMode() = default;
196 TypeSetByHwMode(const TypeSetByHwMode &VTS) = default;
197 TypeSetByHwMode(MVT::SimpleValueType VT)
198 : TypeSetByHwMode(ValueTypeByHwMode(VT)) {}
199 TypeSetByHwMode(ValueTypeByHwMode VT)
200 : TypeSetByHwMode(ArrayRef<ValueTypeByHwMode>(&VT, 1)) {}
201 TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList);
Jim Grosbach398abb42010-12-24 05:06:32 +0000202
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000203 SetType &getOrCreate(unsigned Mode) {
204 if (hasMode(Mode))
205 return get(Mode);
206 return Map.insert({Mode,SetType()}).first->second;
207 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000208
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000209 bool isValueTypeByHwMode(bool AllowEmpty) const;
210 ValueTypeByHwMode getValueTypeByHwMode() const;
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000211
212 LLVM_ATTRIBUTE_ALWAYS_INLINE
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000213 bool isMachineValueType() const {
214 return isDefaultOnly() && Map.begin()->second.size() == 1;
215 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000216
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000217 LLVM_ATTRIBUTE_ALWAYS_INLINE
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000218 MVT getMachineValueType() const {
219 assert(isMachineValueType());
220 return *Map.begin()->second.begin();
221 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000222
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000223 bool isPossible() const;
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000224
225 LLVM_ATTRIBUTE_ALWAYS_INLINE
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000226 bool isDefaultOnly() const {
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000227 return Map.size() == 1 && Map.begin()->first == DefaultMode;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000228 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000229
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000230 bool insert(const ValueTypeByHwMode &VVT);
231 bool constrain(const TypeSetByHwMode &VTS);
232 template <typename Predicate> bool constrain(Predicate P);
Zachary Turnere4442992017-09-20 18:01:40 +0000233 template <typename Predicate>
234 bool assign_if(const TypeSetByHwMode &VTS, Predicate P);
Jim Grosbach398abb42010-12-24 05:06:32 +0000235
Zachary Turnere4442992017-09-20 18:01:40 +0000236 void writeToStream(raw_ostream &OS) const;
237 static void writeToStream(const SetType &S, raw_ostream &OS);
Jim Grosbach398abb42010-12-24 05:06:32 +0000238
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000239 bool operator==(const TypeSetByHwMode &VTS) const;
240 bool operator!=(const TypeSetByHwMode &VTS) const { return !(*this == VTS); }
Jim Grosbach398abb42010-12-24 05:06:32 +0000241
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000242 void dump() const;
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000243 bool validate() const;
Craig Topper90790c32014-01-28 04:49:01 +0000244
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000245private:
246 /// Intersect two sets. Return true if anything has changed.
247 bool intersect(SetType &Out, const SetType &In);
248};
Jim Grosbach398abb42010-12-24 05:06:32 +0000249
Krzysztof Parzyszekbbd7d722017-09-22 18:29:37 +0000250raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T);
251
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000252struct TypeInfer {
253 TypeInfer(TreePattern &T) : TP(T), ForceMode(0) {}
Jim Grosbach398abb42010-12-24 05:06:32 +0000254
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000255 bool isConcrete(const TypeSetByHwMode &VTS, bool AllowEmpty) const {
256 return VTS.isValueTypeByHwMode(AllowEmpty);
257 }
258 ValueTypeByHwMode getConcrete(const TypeSetByHwMode &VTS,
259 bool AllowEmpty) const {
260 assert(VTS.isValueTypeByHwMode(AllowEmpty));
261 return VTS.getValueTypeByHwMode();
262 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000263
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000264 /// The protocol in the following functions (Merge*, force*, Enforce*,
265 /// expand*) is to return "true" if a change has been made, "false"
266 /// otherwise.
Chris Lattner6cefb772008-01-05 22:25:12 +0000267
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000268 bool MergeInTypeInfo(TypeSetByHwMode &Out, const TypeSetByHwMode &In);
269 bool MergeInTypeInfo(TypeSetByHwMode &Out, MVT::SimpleValueType InVT) {
270 return MergeInTypeInfo(Out, TypeSetByHwMode(InVT));
271 }
272 bool MergeInTypeInfo(TypeSetByHwMode &Out, ValueTypeByHwMode InVT) {
273 return MergeInTypeInfo(Out, TypeSetByHwMode(InVT));
274 }
Bob Wilson36e3e662009-08-12 22:30:59 +0000275
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000276 /// Reduce the set \p Out to have at most one element for each mode.
277 bool forceArbitrary(TypeSetByHwMode &Out);
Chris Lattner2cacec52010-03-15 06:00:16 +0000278
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000279 /// The following four functions ensure that upon return the set \p Out
280 /// will only contain types of the specified kind: integer, floating-point,
281 /// scalar, or vector.
282 /// If \p Out is empty, all legal types of the specified kind will be added
283 /// to it. Otherwise, all types that are not of the specified kind will be
284 /// removed from \p Out.
285 bool EnforceInteger(TypeSetByHwMode &Out);
286 bool EnforceFloatingPoint(TypeSetByHwMode &Out);
287 bool EnforceScalar(TypeSetByHwMode &Out);
288 bool EnforceVector(TypeSetByHwMode &Out);
Chris Lattner2cacec52010-03-15 06:00:16 +0000289
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000290 /// If \p Out is empty, fill it with all legal types. Otherwise, leave it
291 /// unchanged.
292 bool EnforceAny(TypeSetByHwMode &Out);
293 /// Make sure that for each type in \p Small, there exists a larger type
294 /// in \p Big.
295 bool EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big);
296 /// 1. Ensure that for each type T in \p Vec, T is a vector type, and that
297 /// for each type U in \p Elem, U is a scalar type.
298 /// 2. Ensure that for each (scalar) type U in \p Elem, there exists a
299 /// (vector) type T in \p Vec, such that U is the element type of T.
300 bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Elem);
301 bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
302 const ValueTypeByHwMode &VVT);
303 /// Ensure that for each type T in \p Sub, T is a vector type, and there
304 /// exists a type U in \p Vec such that U is a vector type with the same
305 /// element type as T and at least as many elements as T.
306 bool EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
307 TypeSetByHwMode &Sub);
308 /// 1. Ensure that \p V has a scalar type iff \p W has a scalar type.
309 /// 2. Ensure that for each vector type T in \p V, there exists a vector
310 /// type U in \p W, such that T and U have the same number of elements.
311 /// 3. Ensure that for each vector type U in \p W, there exists a vector
312 /// type T in \p V, such that T and U have the same number of elements
313 /// (reverse of 2).
314 bool EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W);
315 /// 1. Ensure that for each type T in \p A, there exists a type U in \p B,
316 /// such that T and U have equal size in bits.
317 /// 2. Ensure that for each type U in \p B, there exists a type T in \p A
318 /// such that T and U have equal size in bits (reverse of 1).
319 bool EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B);
Chris Lattner2cacec52010-03-15 06:00:16 +0000320
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000321 /// For each overloaded type (i.e. of form *Any), replace it with the
322 /// corresponding subset of legal, specific types.
323 void expandOverloads(TypeSetByHwMode &VTS);
324 void expandOverloads(TypeSetByHwMode::SetType &Out,
325 const TypeSetByHwMode::SetType &Legal);
Jim Grosbach398abb42010-12-24 05:06:32 +0000326
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000327 struct ValidateOnExit {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000328 ValidateOnExit(TypeSetByHwMode &T, TypeInfer &TI) : Infer(TI), VTS(T) {}
329 #ifndef NDEBUG
330 ~ValidateOnExit();
331 #else
332 ~ValidateOnExit() {} // Empty destructor with NDEBUG.
333 #endif
334 TypeInfer &Infer;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000335 TypeSetByHwMode &VTS;
Chris Lattner2cacec52010-03-15 06:00:16 +0000336 };
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000337
Ulrich Weigandc62320c2018-07-13 16:42:15 +0000338 struct SuppressValidation {
339 SuppressValidation(TypeInfer &TI) : Infer(TI), SavedValidate(TI.Validate) {
340 Infer.Validate = false;
341 }
342 ~SuppressValidation() {
343 Infer.Validate = SavedValidate;
344 }
345 TypeInfer &Infer;
346 bool SavedValidate;
347 };
348
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000349 TreePattern &TP;
350 unsigned ForceMode; // Mode to use when set.
351 bool CodeGen = false; // Set during generation of matcher code.
Ulrich Weigandc62320c2018-07-13 16:42:15 +0000352 bool Validate = true; // Indicate whether to validate types.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000353
354private:
Simon Pilgrim8f783892018-08-17 15:54:07 +0000355 const TypeSetByHwMode &getLegalTypes();
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000356
Simon Pilgrim8f783892018-08-17 15:54:07 +0000357 /// Cached legal types (in default mode).
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000358 bool LegalTypesCached = false;
Simon Pilgrim8f783892018-08-17 15:54:07 +0000359 TypeSetByHwMode LegalCache;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000360};
Chris Lattner6cefb772008-01-05 22:25:12 +0000361
Scott Michel327d0652008-03-05 17:49:05 +0000362/// Set type used to track multiply used variables in patterns
Zachary Turnere4442992017-09-20 18:01:40 +0000363typedef StringSet<> MultipleUseVarSet;
Scott Michel327d0652008-03-05 17:49:05 +0000364
Chris Lattner6cefb772008-01-05 22:25:12 +0000365/// SDTypeConstraint - This is a discriminated union of constraints,
366/// corresponding to the SDTypeConstraint tablegen class in Target.td.
367struct SDTypeConstraint {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000368 SDTypeConstraint(Record *R, const CodeGenHwModes &CGH);
Jim Grosbach398abb42010-12-24 05:06:32 +0000369
Chris Lattner6cefb772008-01-05 22:25:12 +0000370 unsigned OperandNo; // The operand # this constraint applies to.
Jim Grosbach398abb42010-12-24 05:06:32 +0000371 enum {
372 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisVec, SDTCisSameAs,
David Greene60322692011-01-24 20:53:18 +0000373 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisEltOfVec,
Craig Topperce6f7432015-11-26 07:02:18 +0000374 SDTCisSubVecOfVec, SDTCVecEltisVT, SDTCisSameNumEltsAs, SDTCisSameSizeAs
Chris Lattner6cefb772008-01-05 22:25:12 +0000375 } ConstraintType;
Jim Grosbach398abb42010-12-24 05:06:32 +0000376
Chris Lattner6cefb772008-01-05 22:25:12 +0000377 union { // The discriminated union.
378 struct {
Chris Lattner6cefb772008-01-05 22:25:12 +0000379 unsigned OtherOperandNum;
380 } SDTCisSameAs_Info;
381 struct {
382 unsigned OtherOperandNum;
383 } SDTCisVTSmallerThanOp_Info;
384 struct {
385 unsigned BigOperandNum;
386 } SDTCisOpSmallerThanOp_Info;
387 struct {
388 unsigned OtherOperandNum;
Nate Begemanb5af3342008-02-09 01:37:05 +0000389 } SDTCisEltOfVec_Info;
David Greene60322692011-01-24 20:53:18 +0000390 struct {
391 unsigned OtherOperandNum;
392 } SDTCisSubVecOfVec_Info;
Craig Topper8ad519f2015-03-05 07:11:34 +0000393 struct {
Craig Topper8ad519f2015-03-05 07:11:34 +0000394 unsigned OtherOperandNum;
395 } SDTCisSameNumEltsAs_Info;
Craig Topperce6f7432015-11-26 07:02:18 +0000396 struct {
397 unsigned OtherOperandNum;
398 } SDTCisSameSizeAs_Info;
Chris Lattner6cefb772008-01-05 22:25:12 +0000399 } x;
400
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000401 // The VT for SDTCisVT and SDTCVecEltisVT.
402 // Must not be in the union because it has a non-trivial destructor.
403 ValueTypeByHwMode VVT;
404
Chris Lattner6cefb772008-01-05 22:25:12 +0000405 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
406 /// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000407 /// change, false otherwise. If a type contradiction is found, an error
408 /// is flagged.
Florian Hahn74dff3b2018-06-14 20:32:58 +0000409 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
Chris Lattner6cefb772008-01-05 22:25:12 +0000410 TreePattern &TP) const;
Chris Lattner6cefb772008-01-05 22:25:12 +0000411};
412
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000413/// ScopedName - A name of a node associated with a "scope" that indicates
414/// the context (e.g. instance of Pattern or PatFrag) in which the name was
415/// used. This enables substitution of pattern fragments while keeping track
416/// of what name(s) were originally given to various nodes in the tree.
417class ScopedName {
418 unsigned Scope;
419 std::string Identifier;
420public:
421 ScopedName(unsigned Scope, StringRef Identifier)
422 : Scope(Scope), Identifier(Identifier) {
423 assert(Scope != 0 &&
424 "Scope == 0 is used to indicate predicates without arguments");
425 }
426
427 unsigned getScope() const { return Scope; }
428 const std::string &getIdentifier() const { return Identifier; }
429
430 std::string getFullName() const;
431
432 bool operator==(const ScopedName &o) const;
433 bool operator!=(const ScopedName &o) const;
434};
435
Chris Lattner6cefb772008-01-05 22:25:12 +0000436/// SDNodeInfo - One of these records is created for each SDNode instance in
437/// the target .td file. This represents the various dag nodes we will be
438/// processing.
439class SDNodeInfo {
440 Record *Def;
Craig Topper2a129872017-05-31 21:12:46 +0000441 StringRef EnumName;
442 StringRef SDClassName;
Chris Lattner6cefb772008-01-05 22:25:12 +0000443 unsigned Properties;
444 unsigned NumResults;
445 int NumOperands;
446 std::vector<SDTypeConstraint> TypeConstraints;
447public:
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000448 // Parse the specified record.
449 SDNodeInfo(Record *R, const CodeGenHwModes &CGH);
Jim Grosbach398abb42010-12-24 05:06:32 +0000450
Chris Lattner6cefb772008-01-05 22:25:12 +0000451 unsigned getNumResults() const { return NumResults; }
Jim Grosbach398abb42010-12-24 05:06:32 +0000452
Chris Lattner2a22cdc2010-03-28 08:48:47 +0000453 /// getNumOperands - This is the number of operands required or -1 if
454 /// variadic.
Chris Lattner6cefb772008-01-05 22:25:12 +0000455 int getNumOperands() const { return NumOperands; }
456 Record *getRecord() const { return Def; }
Craig Topper2a129872017-05-31 21:12:46 +0000457 StringRef getEnumName() const { return EnumName; }
458 StringRef getSDClassName() const { return SDClassName; }
Jim Grosbach398abb42010-12-24 05:06:32 +0000459
Chris Lattner6cefb772008-01-05 22:25:12 +0000460 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
461 return TypeConstraints;
462 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000463
Chris Lattner22579812010-02-28 00:22:30 +0000464 /// getKnownType - If the type constraints on this node imply a fixed type
465 /// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000466 /// MVT::SimpleValueType. Otherwise, return MVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000467 MVT::SimpleValueType getKnownType(unsigned ResNo) const;
Jim Grosbach398abb42010-12-24 05:06:32 +0000468
Chris Lattner6cefb772008-01-05 22:25:12 +0000469 /// hasProperty - Return true if this node has the specified property.
470 ///
471 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
472
473 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
474 /// constraints for this node to the operands of the node. This returns
475 /// true if it makes a change, false otherwise. If a type contradiction is
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000476 /// found, an error is flagged.
Florian Hahn74dff3b2018-06-14 20:32:58 +0000477 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const;
Chris Lattner6cefb772008-01-05 22:25:12 +0000478};
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000479
Chris Lattner54379062011-04-17 21:38:24 +0000480/// TreePredicateFn - This is an abstraction that represents the predicates on
481/// a PatFrag node. This is a simple one-word wrapper around a pointer to
482/// provide nice accessors.
483class TreePredicateFn {
484 /// PatFragRec - This is the TreePattern for the PatFrag that we
485 /// originally came from.
486 TreePattern *PatFragRec;
487public:
488 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
Chris Lattner7ed13912011-04-17 22:05:17 +0000489 TreePredicateFn(TreePattern *N);
Chris Lattner54379062011-04-17 21:38:24 +0000490
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000491
Chris Lattner54379062011-04-17 21:38:24 +0000492 TreePattern *getOrigPatFragRecord() const { return PatFragRec; }
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000493
Chris Lattner54379062011-04-17 21:38:24 +0000494 /// isAlwaysTrue - Return true if this is a noop predicate.
495 bool isAlwaysTrue() const;
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000496
Daniel Sandersb10e0a22017-10-15 19:01:32 +0000497 bool isImmediatePattern() const { return hasImmCode(); }
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000498
Chris Lattner1518afd2011-04-18 06:22:33 +0000499 /// getImmediatePredicateCode - Return the code that evaluates this pattern if
500 /// this is an immediate predicate. It is an error to call this on a
501 /// non-immediate pattern.
Daniel Sanders91007462017-10-15 02:06:44 +0000502 std::string getImmediatePredicateCode() const {
503 std::string Result = getImmCode();
Chris Lattner1518afd2011-04-18 06:22:33 +0000504 assert(!Result.empty() && "Isn't an immediate pattern!");
505 return Result;
506 }
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000507
Chris Lattner54379062011-04-17 21:38:24 +0000508 bool operator==(const TreePredicateFn &RHS) const {
509 return PatFragRec == RHS.PatFragRec;
510 }
511
512 bool operator!=(const TreePredicateFn &RHS) const { return !(*this == RHS); }
513
514 /// Return the name to use in the generated code to reference this, this is
515 /// "Predicate_foo" if from a pattern fragment "foo".
516 std::string getFnName() const;
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000517
Chris Lattner54379062011-04-17 21:38:24 +0000518 /// getCodeToRunOnSDNode - Return the code for the function body that
519 /// evaluates this predicate. The argument is expected to be in "Node",
520 /// not N. This handles casting and conversion to a concrete node type as
521 /// appropriate.
522 std::string getCodeToRunOnSDNode() const;
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000523
Daniel Sanders5cd5b632017-10-13 20:42:18 +0000524 /// Get the data type of the argument to getImmediatePredicateCode().
Simon Pilgrime4d6a6e2017-10-14 21:27:53 +0000525 StringRef getImmType() const;
Daniel Sanders5cd5b632017-10-13 20:42:18 +0000526
Daniel Sanders94aa10e2017-10-13 21:28:03 +0000527 /// Get a string that describes the type returned by getImmType() but is
528 /// usable as part of an identifier.
Simon Pilgrime4d6a6e2017-10-14 21:27:53 +0000529 StringRef getImmTypeIdentifier() const;
Daniel Sanders94aa10e2017-10-13 21:28:03 +0000530
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000531 // Predicate code uses the PatFrag's captured operands.
532 bool usesOperands() const;
533
Daniel Sanders91007462017-10-15 02:06:44 +0000534 // Is the desired predefined predicate for a load?
535 bool isLoad() const;
536 // Is the desired predefined predicate for a store?
537 bool isStore() const;
Daniel Sanders438d60f2017-11-13 22:26:13 +0000538 // Is the desired predefined predicate for an atomic?
539 bool isAtomic() const;
Daniel Sanders91007462017-10-15 02:06:44 +0000540
541 /// Is this predicate the predefined unindexed load predicate?
542 /// Is this predicate the predefined unindexed store predicate?
543 bool isUnindexed() const;
544 /// Is this predicate the predefined non-extending load predicate?
545 bool isNonExtLoad() const;
546 /// Is this predicate the predefined any-extend load predicate?
547 bool isAnyExtLoad() const;
548 /// Is this predicate the predefined sign-extend load predicate?
549 bool isSignExtLoad() const;
550 /// Is this predicate the predefined zero-extend load predicate?
551 bool isZeroExtLoad() const;
552 /// Is this predicate the predefined non-truncating store predicate?
553 bool isNonTruncStore() const;
554 /// Is this predicate the predefined truncating store predicate?
555 bool isTruncStore() const;
556
Daniel Sanders22434af2017-11-13 23:03:47 +0000557 /// Is this predicate the predefined monotonic atomic predicate?
558 bool isAtomicOrderingMonotonic() const;
559 /// Is this predicate the predefined acquire atomic predicate?
560 bool isAtomicOrderingAcquire() const;
561 /// Is this predicate the predefined release atomic predicate?
562 bool isAtomicOrderingRelease() const;
563 /// Is this predicate the predefined acquire-release atomic predicate?
564 bool isAtomicOrderingAcquireRelease() const;
565 /// Is this predicate the predefined sequentially consistent atomic predicate?
566 bool isAtomicOrderingSequentiallyConsistent() const;
567
Daniel Sanders053346d2017-11-30 21:05:59 +0000568 /// Is this predicate the predefined acquire-or-stronger atomic predicate?
569 bool isAtomicOrderingAcquireOrStronger() const;
570 /// Is this predicate the predefined weaker-than-acquire atomic predicate?
571 bool isAtomicOrderingWeakerThanAcquire() const;
572
573 /// Is this predicate the predefined release-or-stronger atomic predicate?
574 bool isAtomicOrderingReleaseOrStronger() const;
575 /// Is this predicate the predefined weaker-than-release atomic predicate?
576 bool isAtomicOrderingWeakerThanRelease() const;
577
Daniel Sanders91007462017-10-15 02:06:44 +0000578 /// If non-null, indicates that this predicate is a predefined memory VT
579 /// predicate for a load/store and returns the ValueType record for the memory VT.
580 Record *getMemoryVT() const;
581 /// If non-null, indicates that this predicate is a predefined memory VT
582 /// predicate (checking only the scalar type) for load/store and returns the
583 /// ValueType record for the memory VT.
584 Record *getScalarMemoryVT() const;
585
Daniel Sandersa2824b62018-06-15 23:13:43 +0000586 // If true, indicates that GlobalISel-based C++ code was supplied.
587 bool hasGISelPredicateCode() const;
588 std::string getGISelPredicateCode() const;
589
Chris Lattner54379062011-04-17 21:38:24 +0000590private:
Daniel Sandersb10e0a22017-10-15 19:01:32 +0000591 bool hasPredCode() const;
592 bool hasImmCode() const;
Daniel Sanders91007462017-10-15 02:06:44 +0000593 std::string getPredCode() const;
594 std::string getImmCode() const;
Daniel Sanders5cd5b632017-10-13 20:42:18 +0000595 bool immCodeUsesAPInt() const;
596 bool immCodeUsesAPFloat() const;
Daniel Sanders91007462017-10-15 02:06:44 +0000597
598 bool isPredefinedPredicateEqualTo(StringRef Field, bool Value) const;
Chris Lattner54379062011-04-17 21:38:24 +0000599};
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000600
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000601struct TreePredicateCall {
602 TreePredicateFn Fn;
603
604 // Scope -- unique identifier for retrieving named arguments. 0 is used when
605 // the predicate does not use named arguments.
606 unsigned Scope;
607
608 TreePredicateCall(const TreePredicateFn &Fn, unsigned Scope)
609 : Fn(Fn), Scope(Scope) {}
610
611 bool operator==(const TreePredicateCall &o) const {
612 return Fn == o.Fn && Scope == o.Scope;
613 }
614 bool operator!=(const TreePredicateCall &o) const {
615 return !(*this == o);
616 }
617};
Chris Lattner6cefb772008-01-05 22:25:12 +0000618
Chris Lattner6cefb772008-01-05 22:25:12 +0000619class TreePatternNode {
Chris Lattnerd7349192010-03-19 21:37:09 +0000620 /// The type of each node result. Before and during type inference, each
621 /// result may be a set of possible types. After (successful) type inference,
622 /// each is a single concrete type.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000623 std::vector<TypeSetByHwMode> Types;
Jim Grosbach398abb42010-12-24 05:06:32 +0000624
Craig Topper0f562fe2018-12-05 00:47:59 +0000625 /// The index of each result in results of the pattern.
626 std::vector<unsigned> ResultPerm;
627
Chris Lattner6cefb772008-01-05 22:25:12 +0000628 /// Operator - The Record for the operator if this is an interior node (not
629 /// a leaf).
630 Record *Operator;
Jim Grosbach398abb42010-12-24 05:06:32 +0000631
Chris Lattner6cefb772008-01-05 22:25:12 +0000632 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
633 ///
David Greene05bce0b2011-07-29 22:43:06 +0000634 Init *Val;
Jim Grosbach398abb42010-12-24 05:06:32 +0000635
Chris Lattner6cefb772008-01-05 22:25:12 +0000636 /// Name - The name given to this node with the :$foo notation.
637 ///
638 std::string Name;
Jim Grosbach398abb42010-12-24 05:06:32 +0000639
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000640 std::vector<ScopedName> NamesAsPredicateArg;
641
642 /// PredicateCalls - The predicate functions to execute on this node to check
Dan Gohman0540e172008-10-15 06:17:21 +0000643 /// for a match. If this list is empty, no predicate is involved.
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000644 std::vector<TreePredicateCall> PredicateCalls;
Jim Grosbach398abb42010-12-24 05:06:32 +0000645
Chris Lattner6cefb772008-01-05 22:25:12 +0000646 /// TransformFn - The transformation function to execute on this node before
647 /// it can be substituted into the resulting instruction on a pattern match.
648 Record *TransformFn;
Jim Grosbach398abb42010-12-24 05:06:32 +0000649
Florian Hahn0b596f02018-05-30 21:00:18 +0000650 std::vector<TreePatternNodePtr> Children;
651
Chris Lattner6cefb772008-01-05 22:25:12 +0000652public:
Craig Toppercfe3c912018-07-15 06:52:49 +0000653 TreePatternNode(Record *Op, std::vector<TreePatternNodePtr> Ch,
Jim Grosbach398abb42010-12-24 05:06:32 +0000654 unsigned NumResults)
Craig Toppercfe3c912018-07-15 06:52:49 +0000655 : Operator(Op), Val(nullptr), TransformFn(nullptr),
656 Children(std::move(Ch)) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000657 Types.resize(NumResults);
Craig Topper0f562fe2018-12-05 00:47:59 +0000658 ResultPerm.resize(NumResults);
659 std::iota(ResultPerm.begin(), ResultPerm.end(), 0);
Chris Lattnerd7349192010-03-19 21:37:09 +0000660 }
David Greene05bce0b2011-07-29 22:43:06 +0000661 TreePatternNode(Init *val, unsigned NumResults) // leaf ctor
Craig Topper695aa802014-04-16 04:21:27 +0000662 : Operator(nullptr), Val(val), TransformFn(nullptr) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000663 Types.resize(NumResults);
Craig Topper0f562fe2018-12-05 00:47:59 +0000664 ResultPerm.resize(NumResults);
665 std::iota(ResultPerm.begin(), ResultPerm.end(), 0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000666 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000667
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +0000668 bool hasName() const { return !Name.empty(); }
Chris Lattner6cefb772008-01-05 22:25:12 +0000669 const std::string &getName() const { return Name; }
Chris Lattnerc2173052010-03-28 06:50:34 +0000670 void setName(StringRef N) { Name.assign(N.begin(), N.end()); }
Jim Grosbach398abb42010-12-24 05:06:32 +0000671
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000672 const std::vector<ScopedName> &getNamesAsPredicateArg() const {
673 return NamesAsPredicateArg;
674 }
675 void setNamesAsPredicateArg(const std::vector<ScopedName>& Names) {
676 NamesAsPredicateArg = Names;
677 }
678 void addNameAsPredicateArg(const ScopedName &N) {
679 NamesAsPredicateArg.push_back(N);
680 }
681
Craig Topper695aa802014-04-16 04:21:27 +0000682 bool isLeaf() const { return Val != nullptr; }
Jim Grosbach398abb42010-12-24 05:06:32 +0000683
Chris Lattner2cacec52010-03-15 06:00:16 +0000684 // Type accessors.
Chris Lattnerd7349192010-03-19 21:37:09 +0000685 unsigned getNumTypes() const { return Types.size(); }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000686 ValueTypeByHwMode getType(unsigned ResNo) const {
687 return Types[ResNo].getValueTypeByHwMode();
Chris Lattnerd7349192010-03-19 21:37:09 +0000688 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000689 const std::vector<TypeSetByHwMode> &getExtTypes() const { return Types; }
690 const TypeSetByHwMode &getExtType(unsigned ResNo) const {
691 return Types[ResNo];
692 }
693 TypeSetByHwMode &getExtType(unsigned ResNo) { return Types[ResNo]; }
694 void setType(unsigned ResNo, const TypeSetByHwMode &T) { Types[ResNo] = T; }
695 MVT::SimpleValueType getSimpleType(unsigned ResNo) const {
696 return Types[ResNo].getMachineValueType().SimpleTy;
697 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000698
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000699 bool hasConcreteType(unsigned ResNo) const {
700 return Types[ResNo].isValueTypeByHwMode(false);
Chris Lattnerd7349192010-03-19 21:37:09 +0000701 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000702 bool isTypeCompletelyUnknown(unsigned ResNo, TreePattern &TP) const {
703 return Types[ResNo].empty();
Chris Lattnerd7349192010-03-19 21:37:09 +0000704 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000705
Craig Topper0f562fe2018-12-05 00:47:59 +0000706 unsigned getNumResults() const { return ResultPerm.size(); }
707 unsigned getResultIndex(unsigned ResNo) const { return ResultPerm[ResNo]; }
708 void setResultIndex(unsigned ResNo, unsigned RI) { ResultPerm[ResNo] = RI; }
709
David Greene05bce0b2011-07-29 22:43:06 +0000710 Init *getLeafValue() const { assert(isLeaf()); return Val; }
Chris Lattner6cefb772008-01-05 22:25:12 +0000711 Record *getOperator() const { assert(!isLeaf()); return Operator; }
Jim Grosbach398abb42010-12-24 05:06:32 +0000712
Chris Lattner6cefb772008-01-05 22:25:12 +0000713 unsigned getNumChildren() const { return Children.size(); }
Florian Hahn74dff3b2018-06-14 20:32:58 +0000714 TreePatternNode *getChild(unsigned N) const { return Children[N].get(); }
Florian Hahn0b596f02018-05-30 21:00:18 +0000715 const TreePatternNodePtr &getChildShared(unsigned N) const {
716 return Children[N];
Chris Lattner6cefb772008-01-05 22:25:12 +0000717 }
Florian Hahn0b596f02018-05-30 21:00:18 +0000718 void setChild(unsigned i, TreePatternNodePtr N) { Children[i] = N; }
Jim Grosbach398abb42010-12-24 05:06:32 +0000719
Chris Lattnere39650a2010-02-16 06:10:58 +0000720 /// hasChild - Return true if N is any of our children.
721 bool hasChild(const TreePatternNode *N) const {
722 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Florian Hahn0b596f02018-05-30 21:00:18 +0000723 if (Children[i].get() == N)
724 return true;
Chris Lattnere39650a2010-02-16 06:10:58 +0000725 return false;
726 }
Chris Lattnere67bde52008-01-06 05:36:50 +0000727
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000728 bool hasProperTypeByHwMode() const;
729 bool hasPossibleType() const;
730 bool setDefaultMode(unsigned Mode);
731
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000732 bool hasAnyPredicate() const { return !PredicateCalls.empty(); }
Simon Pilgrim4f7a8122017-09-22 16:57:28 +0000733
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000734 const std::vector<TreePredicateCall> &getPredicateCalls() const {
735 return PredicateCalls;
Chris Lattner54379062011-04-17 21:38:24 +0000736 }
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000737 void clearPredicateCalls() { PredicateCalls.clear(); }
738 void setPredicateCalls(const std::vector<TreePredicateCall> &Calls) {
739 assert(PredicateCalls.empty() && "Overwriting non-empty predicate list!");
740 PredicateCalls = Calls;
Dan Gohman0540e172008-10-15 06:17:21 +0000741 }
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000742 void addPredicateCall(const TreePredicateCall &Call) {
743 assert(!Call.Fn.isAlwaysTrue() && "Empty predicate string!");
744 assert(!is_contained(PredicateCalls, Call) && "predicate applied recursively");
745 PredicateCalls.push_back(Call);
746 }
747 void addPredicateCall(const TreePredicateFn &Fn, unsigned Scope) {
748 assert((Scope != 0) == Fn.usesOperands());
749 addPredicateCall(TreePredicateCall(Fn, Scope));
Dan Gohman0540e172008-10-15 06:17:21 +0000750 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000751
752 Record *getTransformFn() const { return TransformFn; }
753 void setTransformFn(Record *Fn) { TransformFn = Fn; }
Jim Grosbach398abb42010-12-24 05:06:32 +0000754
Chris Lattnere67bde52008-01-06 05:36:50 +0000755 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
756 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
757 const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
Evan Cheng6bd95672008-06-16 20:29:38 +0000758
Chris Lattner47661322010-02-14 22:22:58 +0000759 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
760 /// return the ComplexPattern information, otherwise return null.
761 const ComplexPattern *
762 getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const;
763
Tim Northoveree8d5c32014-05-20 11:52:46 +0000764 /// Returns the number of MachineInstr operands that would be produced by this
765 /// node if it mapped directly to an output Instruction's
766 /// operand. ComplexPattern specifies this explicitly; MIOperandInfo gives it
767 /// for Operands; otherwise 1.
768 unsigned getNumMIResults(const CodeGenDAGPatterns &CGP) const;
769
Chris Lattner47661322010-02-14 22:22:58 +0000770 /// NodeHasProperty - Return true if this node has the specified property.
Chris Lattner751d5aa2010-02-14 22:33:49 +0000771 bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
Jim Grosbach398abb42010-12-24 05:06:32 +0000772
Chris Lattner47661322010-02-14 22:22:58 +0000773 /// TreeHasProperty - Return true if any node in this tree has the specified
774 /// property.
Chris Lattner751d5aa2010-02-14 22:33:49 +0000775 bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
Jim Grosbach398abb42010-12-24 05:06:32 +0000776
Evan Cheng6bd95672008-06-16 20:29:38 +0000777 /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is
778 /// marked isCommutative.
779 bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const;
Jim Grosbach398abb42010-12-24 05:06:32 +0000780
Daniel Dunbar1a551802009-07-03 00:10:29 +0000781 void print(raw_ostream &OS) const;
Chris Lattner6cefb772008-01-05 22:25:12 +0000782 void dump() const;
Jim Grosbach398abb42010-12-24 05:06:32 +0000783
Chris Lattner6cefb772008-01-05 22:25:12 +0000784public: // Higher level manipulation routines.
785
786 /// clone - Return a new copy of this tree.
787 ///
Florian Hahn0b596f02018-05-30 21:00:18 +0000788 TreePatternNodePtr clone() const;
Chris Lattner47661322010-02-14 22:22:58 +0000789
790 /// RemoveAllTypes - Recursively strip all the types of this tree.
791 void RemoveAllTypes();
Jim Grosbach398abb42010-12-24 05:06:32 +0000792
Chris Lattner6cefb772008-01-05 22:25:12 +0000793 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
794 /// the specified node. For this comparison, all of the state of the node
795 /// is considered, except for the assigned name. Nodes with differing names
796 /// that are otherwise identical are considered isomorphic.
Florian Hahn74dff3b2018-06-14 20:32:58 +0000797 bool isIsomorphicTo(const TreePatternNode *N,
Scott Michel327d0652008-03-05 17:49:05 +0000798 const MultipleUseVarSet &DepVars) const;
Jim Grosbach398abb42010-12-24 05:06:32 +0000799
Chris Lattner6cefb772008-01-05 22:25:12 +0000800 /// SubstituteFormalArguments - Replace the formal arguments in this tree
801 /// with actual values specified by ArgMap.
Florian Hahn0b596f02018-05-30 21:00:18 +0000802 void
803 SubstituteFormalArguments(std::map<std::string, TreePatternNodePtr> &ArgMap);
Chris Lattner6cefb772008-01-05 22:25:12 +0000804
805 /// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigand3a904262018-07-13 13:18:00 +0000806 /// fragments, return the set of inlined versions (this can be more than
807 /// one if a PatFrags record has multiple alternatives).
808 void InlinePatternFragments(TreePatternNodePtr T,
809 TreePattern &TP,
810 std::vector<TreePatternNodePtr> &OutAlternatives);
Jim Grosbach398abb42010-12-24 05:06:32 +0000811
Bob Wilson6c01ca92009-01-05 17:23:09 +0000812 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +0000813 /// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000814 /// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner6cefb772008-01-05 22:25:12 +0000815 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
Jim Grosbach398abb42010-12-24 05:06:32 +0000816
Chris Lattner6cefb772008-01-05 22:25:12 +0000817 /// UpdateNodeType - Set the node type of N to VT if VT contains
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000818 /// information. If N already contains a conflicting type, then flag an
819 /// error. This returns true if any information was updated.
Chris Lattner6cefb772008-01-05 22:25:12 +0000820 ///
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000821 bool UpdateNodeType(unsigned ResNo, const TypeSetByHwMode &InTy,
822 TreePattern &TP);
Chris Lattnerd7349192010-03-19 21:37:09 +0000823 bool UpdateNodeType(unsigned ResNo, MVT::SimpleValueType InTy,
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000824 TreePattern &TP);
825 bool UpdateNodeType(unsigned ResNo, ValueTypeByHwMode InTy,
826 TreePattern &TP);
Jim Grosbach398abb42010-12-24 05:06:32 +0000827
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +0000828 // Update node type with types inferred from an instruction operand or result
829 // def from the ins/outs lists.
830 // Return true if the type changed.
831 bool UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand, TreePattern &TP);
832
Chris Lattner6cefb772008-01-05 22:25:12 +0000833 /// ContainsUnresolvedType - Return true if this tree contains any
834 /// unresolved types.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000835 bool ContainsUnresolvedType(TreePattern &TP) const;
Jim Grosbach398abb42010-12-24 05:06:32 +0000836
Chris Lattner6cefb772008-01-05 22:25:12 +0000837 /// canPatternMatch - If it is impossible for this pattern to match on this
838 /// target, fill in Reason and return false. Otherwise, return true.
Dan Gohmanee4fa192008-04-03 00:02:49 +0000839 bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000840};
841
Chris Lattner383fed92010-02-14 21:10:33 +0000842inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) {
843 TPN.print(OS);
844 return OS;
845}
Jim Grosbach398abb42010-12-24 05:06:32 +0000846
Chris Lattner6cefb772008-01-05 22:25:12 +0000847
848/// TreePattern - Represent a pattern, used for instructions, pattern
849/// fragments, etc.
850///
851class TreePattern {
852 /// Trees - The list of pattern trees which corresponds to this pattern.
853 /// Note that PatFrag's only have a single tree.
854 ///
Florian Hahn0b596f02018-05-30 21:00:18 +0000855 std::vector<TreePatternNodePtr> Trees;
Jim Grosbach398abb42010-12-24 05:06:32 +0000856
Chris Lattner2cacec52010-03-15 06:00:16 +0000857 /// NamedNodes - This is all of the nodes that have names in the trees in this
858 /// pattern.
Florian Hahn0b596f02018-05-30 21:00:18 +0000859 StringMap<SmallVector<TreePatternNode *, 1>> NamedNodes;
Jim Grosbach398abb42010-12-24 05:06:32 +0000860
Chris Lattner6cefb772008-01-05 22:25:12 +0000861 /// TheRecord - The actual TableGen record corresponding to this pattern.
862 ///
863 Record *TheRecord;
Jim Grosbach398abb42010-12-24 05:06:32 +0000864
Chris Lattner6cefb772008-01-05 22:25:12 +0000865 /// Args - This is a list of all of the arguments to this pattern (for
866 /// PatFrag patterns), which are the 'node' markers in this pattern.
867 std::vector<std::string> Args;
Jim Grosbach398abb42010-12-24 05:06:32 +0000868
Chris Lattner6cefb772008-01-05 22:25:12 +0000869 /// CDP - the top-level object coordinating this madness.
870 ///
Chris Lattnerfe718932008-01-06 01:10:31 +0000871 CodeGenDAGPatterns &CDP;
Chris Lattner6cefb772008-01-05 22:25:12 +0000872
873 /// isInputPattern - True if this is an input pattern, something to match.
874 /// False if this is an output pattern, something to emit.
875 bool isInputPattern;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000876
877 /// hasError - True if the currently processed nodes have unresolvable types
878 /// or other non-fatal errors
879 bool HasError;
Tim Northoveree8d5c32014-05-20 11:52:46 +0000880
881 /// It's important that the usage of operands in ComplexPatterns is
882 /// consistent: each named operand can be defined by at most one
883 /// ComplexPattern. This records the ComplexPattern instance and the operand
884 /// number for each operand encountered in a ComplexPattern to aid in that
885 /// check.
886 StringMap<std::pair<Record *, unsigned>> ComplexPatternOperands;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000887
888 TypeInfer Infer;
889
Chris Lattner6cefb772008-01-05 22:25:12 +0000890public:
Jim Grosbach398abb42010-12-24 05:06:32 +0000891
Chris Lattner6cefb772008-01-05 22:25:12 +0000892 /// TreePattern constructor - Parse the specified DagInits into the
893 /// current record.
David Greene05bce0b2011-07-29 22:43:06 +0000894 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +0000895 CodeGenDAGPatterns &ise);
David Greene05bce0b2011-07-29 22:43:06 +0000896 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +0000897 CodeGenDAGPatterns &ise);
Florian Hahn0b596f02018-05-30 21:00:18 +0000898 TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
David Blaikie9e092ac2014-11-17 22:55:41 +0000899 CodeGenDAGPatterns &ise);
Jim Grosbach398abb42010-12-24 05:06:32 +0000900
Chris Lattner6cefb772008-01-05 22:25:12 +0000901 /// getTrees - Return the tree patterns which corresponds to this pattern.
902 ///
Florian Hahn0b596f02018-05-30 21:00:18 +0000903 const std::vector<TreePatternNodePtr> &getTrees() const { return Trees; }
Chris Lattner6cefb772008-01-05 22:25:12 +0000904 unsigned getNumTrees() const { return Trees.size(); }
Florian Hahn0b596f02018-05-30 21:00:18 +0000905 const TreePatternNodePtr &getTree(unsigned i) const { return Trees[i]; }
Florian Hahndb3fe982018-06-10 21:06:24 +0000906 void setTree(unsigned i, TreePatternNodePtr Tree) { Trees[i] = Tree; }
Florian Hahn77fc0e92018-06-13 20:59:53 +0000907 const TreePatternNodePtr &getOnlyTree() const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000908 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
909 return Trees[0];
910 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000911
Florian Hahn0b596f02018-05-30 21:00:18 +0000912 const StringMap<SmallVector<TreePatternNode *, 1>> &getNamedNodesMap() {
Chris Lattner2cacec52010-03-15 06:00:16 +0000913 if (NamedNodes.empty())
914 ComputeNamedNodes();
915 return NamedNodes;
916 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000917
Chris Lattner6cefb772008-01-05 22:25:12 +0000918 /// getRecord - Return the actual TableGen record corresponding to this
919 /// pattern.
920 ///
921 Record *getRecord() const { return TheRecord; }
Jim Grosbach398abb42010-12-24 05:06:32 +0000922
Chris Lattner6cefb772008-01-05 22:25:12 +0000923 unsigned getNumArgs() const { return Args.size(); }
924 const std::string &getArgName(unsigned i) const {
925 assert(i < Args.size() && "Argument reference out of range!");
926 return Args[i];
927 }
928 std::vector<std::string> &getArgList() { return Args; }
Jim Grosbach398abb42010-12-24 05:06:32 +0000929
Chris Lattnerfe718932008-01-06 01:10:31 +0000930 CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
Chris Lattner6cefb772008-01-05 22:25:12 +0000931
932 /// InlinePatternFragments - If this pattern refers to any pattern
933 /// fragments, inline them into place, giving us a pattern without any
Ulrich Weigand3a904262018-07-13 13:18:00 +0000934 /// PatFrags references. This may increase the number of trees in the
935 /// pattern if a PatFrags has multiple alternatives.
Chris Lattner6cefb772008-01-05 22:25:12 +0000936 void InlinePatternFragments() {
Ulrich Weigand3a904262018-07-13 13:18:00 +0000937 std::vector<TreePatternNodePtr> Copy = Trees;
938 Trees.clear();
939 for (unsigned i = 0, e = Copy.size(); i != e; ++i)
940 Copy[i]->InlinePatternFragments(Copy[i], *this, Trees);
Chris Lattner6cefb772008-01-05 22:25:12 +0000941 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000942
Chris Lattner6cefb772008-01-05 22:25:12 +0000943 /// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +0000944 /// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000945 /// otherwise. Bail out if a type contradiction is found.
Florian Hahn0b596f02018-05-30 21:00:18 +0000946 bool InferAllTypes(
947 const StringMap<SmallVector<TreePatternNode *, 1>> *NamedTypes = nullptr);
Jim Grosbach398abb42010-12-24 05:06:32 +0000948
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000949 /// error - If this is the first error in the current resolution step,
950 /// print it and set the error flag. Otherwise, continue silently.
Matt Arsenaulta735d522014-11-11 23:48:11 +0000951 void error(const Twine &Msg);
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000952 bool hasError() const {
953 return HasError;
954 }
955 void resetError() {
956 HasError = false;
957 }
Jim Grosbach398abb42010-12-24 05:06:32 +0000958
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000959 TypeInfer &getInfer() { return Infer; }
960
Daniel Dunbar1a551802009-07-03 00:10:29 +0000961 void print(raw_ostream &OS) const;
Chris Lattner6cefb772008-01-05 22:25:12 +0000962 void dump() const;
Jim Grosbach398abb42010-12-24 05:06:32 +0000963
Chris Lattner6cefb772008-01-05 22:25:12 +0000964private:
Florian Hahn0b596f02018-05-30 21:00:18 +0000965 TreePatternNodePtr ParseTreePattern(Init *DI, StringRef OpName);
Chris Lattner2cacec52010-03-15 06:00:16 +0000966 void ComputeNamedNodes();
Florian Hahn74dff3b2018-06-14 20:32:58 +0000967 void ComputeNamedNodes(TreePatternNode *N);
Chris Lattner6cefb772008-01-05 22:25:12 +0000968};
969
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000970
971inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
972 const TypeSetByHwMode &InTy,
973 TreePattern &TP) {
974 TypeSetByHwMode VTS(InTy);
975 TP.getInfer().expandOverloads(VTS);
976 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
977}
978
979inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
980 MVT::SimpleValueType InTy,
981 TreePattern &TP) {
982 TypeSetByHwMode VTS(InTy);
983 TP.getInfer().expandOverloads(VTS);
984 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
985}
986
987inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
988 ValueTypeByHwMode InTy,
989 TreePattern &TP) {
990 TypeSetByHwMode VTS(InTy);
991 TP.getInfer().expandOverloads(VTS);
992 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
993}
994
995
Tom Stellard6d3d7652012-09-06 14:15:52 +0000996/// DAGDefaultOperand - One of these is created for each OperandWithDefaultOps
997/// that has a set ExecuteAlways / DefaultOps field.
Chris Lattner6cefb772008-01-05 22:25:12 +0000998struct DAGDefaultOperand {
Florian Hahn0b596f02018-05-30 21:00:18 +0000999 std::vector<TreePatternNodePtr> DefaultOps;
Chris Lattner6cefb772008-01-05 22:25:12 +00001000};
1001
1002class DAGInstruction {
Chris Lattner6cefb772008-01-05 22:25:12 +00001003 std::vector<Record*> Results;
1004 std::vector<Record*> Operands;
1005 std::vector<Record*> ImpResults;
Ulrich Weigand3a904262018-07-13 13:18:00 +00001006 TreePatternNodePtr SrcPattern;
Florian Hahn0b596f02018-05-30 21:00:18 +00001007 TreePatternNodePtr ResultPattern;
1008
Chris Lattner6cefb772008-01-05 22:25:12 +00001009public:
Ulrich Weigand3a904262018-07-13 13:18:00 +00001010 DAGInstruction(const std::vector<Record*> &results,
Chris Lattner6cefb772008-01-05 22:25:12 +00001011 const std::vector<Record*> &operands,
Ulrich Weigand3a904262018-07-13 13:18:00 +00001012 const std::vector<Record*> &impresults,
1013 TreePatternNodePtr srcpattern = nullptr,
1014 TreePatternNodePtr resultpattern = nullptr)
1015 : Results(results), Operands(operands), ImpResults(impresults),
1016 SrcPattern(srcpattern), ResultPattern(resultpattern) {}
Chris Lattner6cefb772008-01-05 22:25:12 +00001017
Chris Lattner6cefb772008-01-05 22:25:12 +00001018 unsigned getNumResults() const { return Results.size(); }
1019 unsigned getNumOperands() const { return Operands.size(); }
1020 unsigned getNumImpResults() const { return ImpResults.size(); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001021 const std::vector<Record*>& getImpResults() const { return ImpResults; }
Jim Grosbach398abb42010-12-24 05:06:32 +00001022
Chris Lattner6cefb772008-01-05 22:25:12 +00001023 Record *getResult(unsigned RN) const {
1024 assert(RN < Results.size());
1025 return Results[RN];
1026 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001027
Chris Lattner6cefb772008-01-05 22:25:12 +00001028 Record *getOperand(unsigned ON) const {
1029 assert(ON < Operands.size());
1030 return Operands[ON];
1031 }
1032
1033 Record *getImpResult(unsigned RN) const {
1034 assert(RN < ImpResults.size());
1035 return ImpResults[RN];
1036 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001037
Ulrich Weigand3a904262018-07-13 13:18:00 +00001038 TreePatternNodePtr getSrcPattern() const { return SrcPattern; }
Florian Hahn0b596f02018-05-30 21:00:18 +00001039 TreePatternNodePtr getResultPattern() const { return ResultPattern; }
Chris Lattner6cefb772008-01-05 22:25:12 +00001040};
Jim Grosbach398abb42010-12-24 05:06:32 +00001041
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001042/// This class represents a condition that has to be satisfied for a pattern
1043/// to be tried. It is a generalization of a class "Pattern" from Target.td:
1044/// in addition to the Target.td's predicates, this class can also represent
1045/// conditions associated with HW modes. Both types will eventually become
1046/// strings containing C++ code to be executed, the difference is in how
1047/// these strings are generated.
1048class Predicate {
1049public:
1050 Predicate(Record *R, bool C = true) : Def(R), IfCond(C), IsHwMode(false) {
1051 assert(R->isSubClassOf("Predicate") &&
1052 "Predicate objects should only be created for records derived"
1053 "from Predicate class");
1054 }
1055 Predicate(StringRef FS, bool C = true) : Def(nullptr), Features(FS.str()),
1056 IfCond(C), IsHwMode(true) {}
1057
1058 /// Return a string which contains the C++ condition code that will serve
1059 /// as a predicate during instruction selection.
1060 std::string getCondString() const {
1061 // The string will excute in a subclass of SelectionDAGISel.
1062 // Cast to std::string explicitly to avoid ambiguity with StringRef.
1063 std::string C = IsHwMode
1064 ? std::string("MF->getSubtarget().checkFeatures(\"" + Features + "\")")
1065 : std::string(Def->getValueAsString("CondString"));
1066 return IfCond ? C : "!("+C+')';
1067 }
1068 bool operator==(const Predicate &P) const {
1069 return IfCond == P.IfCond && IsHwMode == P.IsHwMode && Def == P.Def;
1070 }
1071 bool operator<(const Predicate &P) const {
1072 if (IsHwMode != P.IsHwMode)
1073 return IsHwMode < P.IsHwMode;
1074 assert(!Def == !P.Def && "Inconsistency between Def and IsHwMode");
1075 if (IfCond != P.IfCond)
1076 return IfCond < P.IfCond;
1077 if (Def)
1078 return LessRecord()(Def, P.Def);
1079 return Features < P.Features;
1080 }
1081 Record *Def; ///< Predicate definition from .td file, null for
1082 ///< HW modes.
1083 std::string Features; ///< Feature string for HW mode.
1084 bool IfCond; ///< The boolean value that the condition has to
1085 ///< evaluate to for this predicate to be true.
1086 bool IsHwMode; ///< Does this predicate correspond to a HW mode?
1087};
1088
Chris Lattnerfe718932008-01-06 01:10:31 +00001089/// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
Chris Lattner6cefb772008-01-05 22:25:12 +00001090/// processed to produce isel.
Chris Lattnerb49985a2010-02-18 06:47:49 +00001091class PatternToMatch {
1092public:
Craig Topper84fc2f52018-06-10 23:15:48 +00001093 PatternToMatch(Record *srcrecord, std::vector<Predicate> preds,
Florian Hahn0b596f02018-05-30 21:00:18 +00001094 TreePatternNodePtr src, TreePatternNodePtr dst,
Craig Topper84fc2f52018-06-10 23:15:48 +00001095 std::vector<Record *> dstregs, int complexity,
Florian Hahn0b596f02018-05-30 21:00:18 +00001096 unsigned uid, unsigned setmode = 0)
1097 : SrcRecord(srcrecord), SrcPattern(src), DstPattern(dst),
Craig Topper674b07e2018-07-15 01:10:28 +00001098 Predicates(std::move(preds)), Dstregs(std::move(dstregs)),
Florian Hahn0b596f02018-05-30 21:00:18 +00001099 AddedComplexity(complexity), ID(uid), ForceMode(setmode) {}
Chris Lattner6cefb772008-01-05 22:25:12 +00001100
Jim Grosbach997759a2010-12-07 23:05:49 +00001101 Record *SrcRecord; // Originating Record for the pattern.
Florian Hahn0b596f02018-05-30 21:00:18 +00001102 TreePatternNodePtr SrcPattern; // Source pattern to match.
1103 TreePatternNodePtr DstPattern; // Resulting pattern.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001104 std::vector<Predicate> Predicates; // Top level predicate conditions
1105 // to match.
Chris Lattner6cefb772008-01-05 22:25:12 +00001106 std::vector<Record*> Dstregs; // Physical register defs being matched.
Tom Stellardf3b62df2014-08-01 00:32:36 +00001107 int AddedComplexity; // Add to matching pattern complexity.
Chris Lattner117ccb72010-03-01 22:09:11 +00001108 unsigned ID; // Unique ID for the record.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001109 unsigned ForceMode; // Force this mode in type inference when set.
Chris Lattner6cefb772008-01-05 22:25:12 +00001110
Jim Grosbach997759a2010-12-07 23:05:49 +00001111 Record *getSrcRecord() const { return SrcRecord; }
Florian Hahn0b596f02018-05-30 21:00:18 +00001112 TreePatternNode *getSrcPattern() const { return SrcPattern.get(); }
1113 TreePatternNodePtr getSrcPatternShared() const { return SrcPattern; }
1114 TreePatternNode *getDstPattern() const { return DstPattern.get(); }
1115 TreePatternNodePtr getDstPatternShared() const { return DstPattern; }
Chris Lattner6cefb772008-01-05 22:25:12 +00001116 const std::vector<Record*> &getDstRegs() const { return Dstregs; }
Tom Stellardf3b62df2014-08-01 00:32:36 +00001117 int getAddedComplexity() const { return AddedComplexity; }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001118 const std::vector<Predicate> &getPredicates() const { return Predicates; }
Dan Gohman22bb3112008-08-22 00:20:26 +00001119
1120 std::string getPredicateCheck() const;
Jim Grosbach398abb42010-12-24 05:06:32 +00001121
Chris Lattner48e86db2010-03-29 01:40:38 +00001122 /// Compute the complexity metric for the input pattern. This roughly
1123 /// corresponds to the number of nodes that are covered.
Tom Stellardf3b62df2014-08-01 00:32:36 +00001124 int getPatternComplexity(const CodeGenDAGPatterns &CGP) const;
Chris Lattner6cefb772008-01-05 22:25:12 +00001125};
1126
Chris Lattnerfe718932008-01-06 01:10:31 +00001127class CodeGenDAGPatterns {
Chris Lattner6cefb772008-01-05 22:25:12 +00001128 RecordKeeper &Records;
1129 CodeGenTarget Target;
Justin Bognera3d02c72016-07-15 16:31:37 +00001130 CodeGenIntrinsicTable Intrinsics;
1131 CodeGenIntrinsicTable TgtIntrinsics;
Jim Grosbach398abb42010-12-24 05:06:32 +00001132
Sean Silva90fee072012-09-19 01:47:00 +00001133 std::map<Record*, SDNodeInfo, LessRecordByID> SDNodes;
Krzysztof Parzyszek2ea93a22017-09-12 15:31:26 +00001134 std::map<Record*, std::pair<Record*, std::string>, LessRecordByID>
1135 SDNodeXForms;
Sean Silva90fee072012-09-19 01:47:00 +00001136 std::map<Record*, ComplexPattern, LessRecordByID> ComplexPatterns;
David Blaikiebea87da2014-11-13 21:40:02 +00001137 std::map<Record *, std::unique_ptr<TreePattern>, LessRecordByID>
1138 PatternFragments;
Sean Silva90fee072012-09-19 01:47:00 +00001139 std::map<Record*, DAGDefaultOperand, LessRecordByID> DefaultOperands;
1140 std::map<Record*, DAGInstruction, LessRecordByID> Instructions;
Jim Grosbach398abb42010-12-24 05:06:32 +00001141
Chris Lattner6cefb772008-01-05 22:25:12 +00001142 // Specific SDNode definitions:
1143 Record *intrinsic_void_sdnode;
1144 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
Jim Grosbach398abb42010-12-24 05:06:32 +00001145
Chris Lattner6cefb772008-01-05 22:25:12 +00001146 /// PatternsToMatch - All of the things we are matching on the DAG. The first
1147 /// value is the pattern to match, the second pattern is the result to
1148 /// emit.
1149 std::vector<PatternToMatch> PatternsToMatch;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001150
1151 TypeSetByHwMode LegalVTS;
1152
Daniel Sanders8f5a5912017-11-11 03:23:44 +00001153 using PatternRewriterFn = std::function<void (TreePattern *)>;
1154 PatternRewriterFn PatternRewriter;
1155
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001156 unsigned NumScopes = 0;
1157
Chris Lattner6cefb772008-01-05 22:25:12 +00001158public:
Daniel Sanders8f5a5912017-11-11 03:23:44 +00001159 CodeGenDAGPatterns(RecordKeeper &R,
1160 PatternRewriterFn PatternRewriter = nullptr);
Jim Grosbach398abb42010-12-24 05:06:32 +00001161
Dan Gohmanee4fa192008-04-03 00:02:49 +00001162 CodeGenTarget &getTargetInfo() { return Target; }
Chris Lattner6cefb772008-01-05 22:25:12 +00001163 const CodeGenTarget &getTargetInfo() const { return Target; }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001164 const TypeSetByHwMode &getLegalTypes() const { return LegalVTS; }
Jim Grosbach398abb42010-12-24 05:06:32 +00001165
Daniel Sanders04312952017-10-13 19:00:01 +00001166 Record *getSDNodeNamed(const std::string &Name) const;
Jim Grosbach398abb42010-12-24 05:06:32 +00001167
Chris Lattner6cefb772008-01-05 22:25:12 +00001168 const SDNodeInfo &getSDNodeInfo(Record *R) const {
Simon Pilgrimf3cf8532017-10-07 14:34:24 +00001169 auto F = SDNodes.find(R);
1170 assert(F != SDNodes.end() && "Unknown node!");
1171 return F->second;
Chris Lattner6cefb772008-01-05 22:25:12 +00001172 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001173
Chris Lattner443e3f92008-01-05 22:54:53 +00001174 // Node transformation lookups.
1175 typedef std::pair<Record*, std::string> NodeXForm;
1176 const NodeXForm &getSDNodeTransform(Record *R) const {
Simon Pilgrimf3cf8532017-10-07 14:34:24 +00001177 auto F = SDNodeXForms.find(R);
1178 assert(F != SDNodeXForms.end() && "Invalid transform!");
1179 return F->second;
Chris Lattner6cefb772008-01-05 22:25:12 +00001180 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001181
Sean Silva90fee072012-09-19 01:47:00 +00001182 typedef std::map<Record*, NodeXForm, LessRecordByID>::const_iterator
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001183 nx_iterator;
Chris Lattner443e3f92008-01-05 22:54:53 +00001184 nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
1185 nx_iterator nx_end() const { return SDNodeXForms.end(); }
1186
Jim Grosbach398abb42010-12-24 05:06:32 +00001187
Chris Lattner6cefb772008-01-05 22:25:12 +00001188 const ComplexPattern &getComplexPattern(Record *R) const {
Simon Pilgrimf3cf8532017-10-07 14:34:24 +00001189 auto F = ComplexPatterns.find(R);
1190 assert(F != ComplexPatterns.end() && "Unknown addressing mode!");
1191 return F->second;
Chris Lattner6cefb772008-01-05 22:25:12 +00001192 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001193
Chris Lattner6cefb772008-01-05 22:25:12 +00001194 const CodeGenIntrinsic &getIntrinsic(Record *R) const {
1195 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
1196 if (Intrinsics[i].TheDef == R) return Intrinsics[i];
Dale Johannesen49de9822009-02-05 01:49:45 +00001197 for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
1198 if (TgtIntrinsics[i].TheDef == R) return TgtIntrinsics[i];
Craig Topper655b8de2012-02-05 07:21:30 +00001199 llvm_unreachable("Unknown intrinsic!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001200 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001201
Chris Lattner6cefb772008-01-05 22:25:12 +00001202 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
Dale Johannesen49de9822009-02-05 01:49:45 +00001203 if (IID-1 < Intrinsics.size())
1204 return Intrinsics[IID-1];
1205 if (IID-Intrinsics.size()-1 < TgtIntrinsics.size())
1206 return TgtIntrinsics[IID-Intrinsics.size()-1];
Craig Topper655b8de2012-02-05 07:21:30 +00001207 llvm_unreachable("Bad intrinsic ID!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001208 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001209
Chris Lattner6cefb772008-01-05 22:25:12 +00001210 unsigned getIntrinsicID(Record *R) const {
1211 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
1212 if (Intrinsics[i].TheDef == R) return i;
Dale Johannesen49de9822009-02-05 01:49:45 +00001213 for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
1214 if (TgtIntrinsics[i].TheDef == R) return i + Intrinsics.size();
Craig Topper655b8de2012-02-05 07:21:30 +00001215 llvm_unreachable("Unknown intrinsic!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001216 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001217
Chris Lattnerb49985a2010-02-18 06:47:49 +00001218 const DAGDefaultOperand &getDefaultOperand(Record *R) const {
Simon Pilgrimf3cf8532017-10-07 14:34:24 +00001219 auto F = DefaultOperands.find(R);
1220 assert(F != DefaultOperands.end() &&"Isn't an analyzed default operand!");
1221 return F->second;
Chris Lattner6cefb772008-01-05 22:25:12 +00001222 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001223
Chris Lattner6cefb772008-01-05 22:25:12 +00001224 // Pattern Fragment information.
1225 TreePattern *getPatternFragment(Record *R) const {
Simon Pilgrimf3cf8532017-10-07 14:34:24 +00001226 auto F = PatternFragments.find(R);
1227 assert(F != PatternFragments.end() && "Invalid pattern fragment request!");
1228 return F->second.get();
Chris Lattner6cefb772008-01-05 22:25:12 +00001229 }
Chris Lattnerd7349192010-03-19 21:37:09 +00001230 TreePattern *getPatternFragmentIfRead(Record *R) const {
Simon Pilgrimf3cf8532017-10-07 14:34:24 +00001231 auto F = PatternFragments.find(R);
1232 if (F == PatternFragments.end())
David Blaikiebea87da2014-11-13 21:40:02 +00001233 return nullptr;
Simon Pilgrimf3cf8532017-10-07 14:34:24 +00001234 return F->second.get();
Chris Lattnerd7349192010-03-19 21:37:09 +00001235 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001236
David Blaikiede67e5c2014-11-13 21:56:57 +00001237 typedef std::map<Record *, std::unique_ptr<TreePattern>,
1238 LessRecordByID>::const_iterator pf_iterator;
Chris Lattner6cefb772008-01-05 22:25:12 +00001239 pf_iterator pf_begin() const { return PatternFragments.begin(); }
1240 pf_iterator pf_end() const { return PatternFragments.end(); }
Ahmed Bougacha8097fcb2016-12-21 23:26:20 +00001241 iterator_range<pf_iterator> ptfs() const { return PatternFragments; }
Chris Lattner6cefb772008-01-05 22:25:12 +00001242
1243 // Patterns to match information.
Chris Lattner60d81392008-01-05 22:30:17 +00001244 typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
1245 ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
1246 ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
Ahmed Bougacha8097fcb2016-12-21 23:26:20 +00001247 iterator_range<ptm_iterator> ptms() const { return PatternsToMatch; }
Jim Grosbach398abb42010-12-24 05:06:32 +00001248
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00001249 /// Parse the Pattern for an instruction, and insert the result in DAGInsts.
1250 typedef std::map<Record*, DAGInstruction, LessRecordByID> DAGInstMap;
Ulrich Weigand3a904262018-07-13 13:18:00 +00001251 void parseInstructionPattern(
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00001252 CodeGenInstruction &CGI, ListInit *Pattern,
1253 DAGInstMap &DAGInsts);
Jim Grosbach398abb42010-12-24 05:06:32 +00001254
Chris Lattner6cefb772008-01-05 22:25:12 +00001255 const DAGInstruction &getInstruction(Record *R) const {
Simon Pilgrimf3cf8532017-10-07 14:34:24 +00001256 auto F = Instructions.find(R);
1257 assert(F != Instructions.end() && "Unknown instruction!");
1258 return F->second;
Chris Lattner6cefb772008-01-05 22:25:12 +00001259 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001260
Chris Lattner6cefb772008-01-05 22:25:12 +00001261 Record *get_intrinsic_void_sdnode() const {
1262 return intrinsic_void_sdnode;
1263 }
1264 Record *get_intrinsic_w_chain_sdnode() const {
1265 return intrinsic_w_chain_sdnode;
1266 }
1267 Record *get_intrinsic_wo_chain_sdnode() const {
1268 return intrinsic_wo_chain_sdnode;
1269 }
Jim Grosbach398abb42010-12-24 05:06:32 +00001270
Jakob Stoklund Olesen11ee5082009-10-15 18:50:03 +00001271 bool hasTargetIntrinsics() { return !TgtIntrinsics.empty(); }
1272
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001273 unsigned allocateScope() { return ++NumScopes; }
1274
Chris Lattner6cefb772008-01-05 22:25:12 +00001275private:
1276 void ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001277 void ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001278 void ParseComplexPatterns();
Hal Finkelc72cf872014-02-28 00:26:56 +00001279 void ParsePatternFragments(bool OutFrags = false);
Chris Lattner6cefb772008-01-05 22:25:12 +00001280 void ParseDefaultOperands();
1281 void ParseInstructions();
1282 void ParsePatterns();
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001283 void ExpandHwModeBasedTypes();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001284 void InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001285 void GenerateVariants();
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00001286 void VerifyInstructionFlags();
Jim Grosbach398abb42010-12-24 05:06:32 +00001287
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001288 std::vector<Predicate> makePredList(ListInit *L);
1289
Ulrich Weigand3a904262018-07-13 13:18:00 +00001290 void ParseOnePattern(Record *TheDef,
1291 TreePattern &Pattern, TreePattern &Result,
1292 const std::vector<Record *> &InstImpResults);
Craig Topper3ace6d82017-06-25 17:33:49 +00001293 void AddPatternToMatch(TreePattern *Pattern, PatternToMatch &&PTM);
Florian Hahn0b596f02018-05-30 21:00:18 +00001294 void FindPatternInputsAndOutputs(
Florian Hahn74dff3b2018-06-14 20:32:58 +00001295 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn0b596f02018-05-30 21:00:18 +00001296 std::map<std::string, TreePatternNodePtr> &InstInputs,
Craig Topper0f562fe2018-12-05 00:47:59 +00001297 MapVector<std::string, TreePatternNodePtr,
1298 std::map<std::string, unsigned>> &InstResults,
Florian Hahn0b596f02018-05-30 21:00:18 +00001299 std::vector<Record *> &InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00001300};
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001301
1302
Florian Hahn74dff3b2018-06-14 20:32:58 +00001303inline bool SDNodeInfo::ApplyTypeConstraints(TreePatternNode *N,
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001304 TreePattern &TP) const {
1305 bool MadeChange = false;
1306 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
1307 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
1308 return MadeChange;
1309 }
Matt Arsenault082879a2017-12-20 19:36:28 +00001310
Chris Lattner6cefb772008-01-05 22:25:12 +00001311} // end namespace llvm
1312
1313#endif