1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the CodeGenDAGPatterns class, which is used to read and
10 // represent the patterns present in a .td file for instructions.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenDAGPatterns.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
34 #define DEBUG_TYPE "dag-patterns"
36 static inline bool isIntegerOrPtr(MVT VT
) {
37 return VT
.isInteger() || VT
== MVT::iPTR
;
39 static inline bool isFloatingPoint(MVT VT
) {
40 return VT
.isFloatingPoint();
42 static inline bool isVector(MVT VT
) {
45 static inline bool isScalar(MVT VT
) {
46 return !VT
.isVector();
49 template <typename Predicate
>
50 static bool berase_if(MachineValueTypeSet
&S
, Predicate P
) {
52 // It is ok to iterate over MachineValueTypeSet and remove elements from it
63 // --- TypeSetByHwMode
65 // This is a parameterized type-set class. For each mode there is a list
66 // of types that are currently possible for a given tree node. Type
67 // inference will apply to each mode separately.
69 TypeSetByHwMode::TypeSetByHwMode(ArrayRef
<ValueTypeByHwMode
> VTList
) {
70 for (const ValueTypeByHwMode
&VVT
: VTList
) {
72 AddrSpaces
.push_back(VVT
.PtrAddrSpace
);
76 bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty
) const {
77 for (const auto &I
: *this) {
78 if (I
.second
.size() > 1)
80 if (!AllowEmpty
&& I
.second
.empty())
86 ValueTypeByHwMode
TypeSetByHwMode::getValueTypeByHwMode() const {
87 assert(isValueTypeByHwMode(true) &&
88 "The type set has multiple types for at least one HW mode");
89 ValueTypeByHwMode VVT
;
90 auto ASI
= AddrSpaces
.begin();
92 for (const auto &I
: *this) {
93 MVT T
= I
.second
.empty() ? MVT::Other
: *I
.second
.begin();
94 VVT
.getOrCreateTypeForMode(I
.first
, T
);
95 if (ASI
!= AddrSpaces
.end())
96 VVT
.PtrAddrSpace
= *ASI
++;
101 bool TypeSetByHwMode::isPossible() const {
102 for (const auto &I
: *this)
103 if (!I
.second
.empty())
108 bool TypeSetByHwMode::insert(const ValueTypeByHwMode
&VVT
) {
109 bool Changed
= false;
110 bool ContainsDefault
= false;
113 SmallDenseSet
<unsigned, 4> Modes
;
114 for (const auto &P
: VVT
) {
115 unsigned M
= P
.first
;
117 // Make sure there exists a set for each specific mode from VVT.
118 Changed
|= getOrCreate(M
).insert(P
.second
).second
;
119 // Cache VVT's default mode.
120 if (DefaultMode
== M
) {
121 ContainsDefault
= true;
126 // If VVT has a default mode, add the corresponding type to all
127 // modes in "this" that do not exist in VVT.
129 for (auto &I
: *this)
130 if (!Modes
.count(I
.first
))
131 Changed
|= I
.second
.insert(DT
).second
;
136 // Constrain the type set to be the intersection with VTS.
137 bool TypeSetByHwMode::constrain(const TypeSetByHwMode
&VTS
) {
138 bool Changed
= false;
140 for (const auto &I
: VTS
) {
141 unsigned M
= I
.first
;
142 if (M
== DefaultMode
|| hasMode(M
))
144 Map
.insert({M
, Map
.at(DefaultMode
)});
149 for (auto &I
: *this) {
150 unsigned M
= I
.first
;
151 SetType
&S
= I
.second
;
152 if (VTS
.hasMode(M
) || VTS
.hasDefault()) {
153 Changed
|= intersect(I
.second
, VTS
.get(M
));
154 } else if (!S
.empty()) {
162 template <typename Predicate
>
163 bool TypeSetByHwMode::constrain(Predicate P
) {
164 bool Changed
= false;
165 for (auto &I
: *this)
166 Changed
|= berase_if(I
.second
, [&P
](MVT VT
) { return !P(VT
); });
170 template <typename Predicate
>
171 bool TypeSetByHwMode::assign_if(const TypeSetByHwMode
&VTS
, Predicate P
) {
173 for (const auto &I
: VTS
) {
174 SetType
&S
= getOrCreate(I
.first
);
175 for (auto J
: I
.second
)
182 void TypeSetByHwMode::writeToStream(raw_ostream
&OS
) const {
183 SmallVector
<unsigned, 4> Modes
;
184 Modes
.reserve(Map
.size());
186 for (const auto &I
: *this)
187 Modes
.push_back(I
.first
);
192 array_pod_sort(Modes
.begin(), Modes
.end());
195 for (unsigned M
: Modes
) {
196 OS
<< ' ' << getModeName(M
) << ':';
197 writeToStream(get(M
), OS
);
202 void TypeSetByHwMode::writeToStream(const SetType
&S
, raw_ostream
&OS
) {
203 SmallVector
<MVT
, 4> Types(S
.begin(), S
.end());
204 array_pod_sort(Types
.begin(), Types
.end());
207 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
) {
208 OS
<< ValueTypeByHwMode::getMVTName(Types
[i
]);
215 bool TypeSetByHwMode::operator==(const TypeSetByHwMode
&VTS
) const {
216 // The isSimple call is much quicker than hasDefault - check this first.
217 bool IsSimple
= isSimple();
218 bool VTSIsSimple
= VTS
.isSimple();
219 if (IsSimple
&& VTSIsSimple
)
220 return *begin() == *VTS
.begin();
222 // Speedup: We have a default if the set is simple.
223 bool HaveDefault
= IsSimple
|| hasDefault();
224 bool VTSHaveDefault
= VTSIsSimple
|| VTS
.hasDefault();
225 if (HaveDefault
!= VTSHaveDefault
)
228 SmallDenseSet
<unsigned, 4> Modes
;
229 for (auto &I
: *this)
230 Modes
.insert(I
.first
);
231 for (const auto &I
: VTS
)
232 Modes
.insert(I
.first
);
235 // Both sets have default mode.
236 for (unsigned M
: Modes
) {
237 if (get(M
) != VTS
.get(M
))
241 // Neither set has default mode.
242 for (unsigned M
: Modes
) {
243 // If there is no default mode, an empty set is equivalent to not having
244 // the corresponding mode.
245 bool NoModeThis
= !hasMode(M
) || get(M
).empty();
246 bool NoModeVTS
= !VTS
.hasMode(M
) || VTS
.get(M
).empty();
247 if (NoModeThis
!= NoModeVTS
)
250 if (get(M
) != VTS
.get(M
))
259 raw_ostream
&operator<<(raw_ostream
&OS
, const TypeSetByHwMode
&T
) {
266 void TypeSetByHwMode::dump() const {
267 dbgs() << *this << '\n';
270 bool TypeSetByHwMode::intersect(SetType
&Out
, const SetType
&In
) {
271 bool OutP
= Out
.count(MVT::iPTR
), InP
= In
.count(MVT::iPTR
);
272 auto Int
= [&In
](MVT T
) -> bool { return !In
.count(T
); };
275 return berase_if(Out
, Int
);
277 // Compute the intersection of scalars separately to account for only
278 // one set containing iPTR.
279 // The itersection of iPTR with a set of integer scalar types that does not
280 // include iPTR will result in the most specific scalar type:
281 // - iPTR is more specific than any set with two elements or more
282 // - iPTR is less specific than any single integer scalar type.
284 // { iPTR } * { i32 } -> { i32 }
285 // { iPTR } * { i32 i64 } -> { iPTR }
287 // { iPTR i32 } * { i32 } -> { i32 }
288 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
289 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
291 // Compute the difference between the two sets in such a way that the
292 // iPTR is in the set that is being subtracted. This is to see if there
293 // are any extra scalars in the set without iPTR that are not in the
294 // set containing iPTR. Then the iPTR could be considered a "wildcard"
295 // matching these scalars. If there is only one such scalar, it would
296 // replace the iPTR, if there are more, the iPTR would be retained.
300 berase_if(Diff
, [&In
](MVT T
) { return In
.count(T
); });
301 // Pre-remove these elements and rely only on InP/OutP to determine
302 // whether a change has been made.
303 berase_if(Out
, [&Diff
](MVT T
) { return Diff
.count(T
); });
306 berase_if(Diff
, [&Out
](MVT T
) { return Out
.count(T
); });
307 Out
.erase(MVT::iPTR
);
310 // The actual intersection.
311 bool Changed
= berase_if(Out
, Int
);
312 unsigned NumD
= Diff
.size();
317 Out
.insert(*Diff
.begin());
318 // This is a change only if Out was the one with iPTR (which is now
322 // Multiple elements from Out are now replaced with iPTR.
323 Out
.insert(MVT::iPTR
);
329 bool TypeSetByHwMode::validate() const {
333 bool AllEmpty
= true;
334 for (const auto &I
: *this)
335 AllEmpty
&= I
.second
.empty();
343 bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode
&Out
,
344 const TypeSetByHwMode
&In
) {
345 ValidateOnExit
_1(Out
, *this);
347 if (In
.empty() || Out
== In
|| TP
.hasError())
354 bool Changed
= Out
.constrain(In
);
355 if (Changed
&& Out
.empty())
356 TP
.error("Type contradiction");
361 bool TypeInfer::forceArbitrary(TypeSetByHwMode
&Out
) {
362 ValidateOnExit
_1(Out
, *this);
365 assert(!Out
.empty() && "cannot pick from an empty set");
367 bool Changed
= false;
368 for (auto &I
: Out
) {
369 TypeSetByHwMode::SetType
&S
= I
.second
;
372 MVT T
= *S
.begin(); // Pick the first element.
380 bool TypeInfer::EnforceInteger(TypeSetByHwMode
&Out
) {
381 ValidateOnExit
_1(Out
, *this);
385 return Out
.constrain(isIntegerOrPtr
);
387 return Out
.assign_if(getLegalTypes(), isIntegerOrPtr
);
390 bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode
&Out
) {
391 ValidateOnExit
_1(Out
, *this);
395 return Out
.constrain(isFloatingPoint
);
397 return Out
.assign_if(getLegalTypes(), isFloatingPoint
);
400 bool TypeInfer::EnforceScalar(TypeSetByHwMode
&Out
) {
401 ValidateOnExit
_1(Out
, *this);
405 return Out
.constrain(isScalar
);
407 return Out
.assign_if(getLegalTypes(), isScalar
);
410 bool TypeInfer::EnforceVector(TypeSetByHwMode
&Out
) {
411 ValidateOnExit
_1(Out
, *this);
415 return Out
.constrain(isVector
);
417 return Out
.assign_if(getLegalTypes(), isVector
);
420 bool TypeInfer::EnforceAny(TypeSetByHwMode
&Out
) {
421 ValidateOnExit
_1(Out
, *this);
422 if (TP
.hasError() || !Out
.empty())
425 Out
= getLegalTypes();
429 template <typename Iter
, typename Pred
, typename Less
>
430 static Iter
min_if(Iter B
, Iter E
, Pred P
, Less L
) {
434 for (Iter I
= B
; I
!= E
; ++I
) {
437 if (Min
== E
|| L(*I
, *Min
))
443 template <typename Iter
, typename Pred
, typename Less
>
444 static Iter
max_if(Iter B
, Iter E
, Pred P
, Less L
) {
448 for (Iter I
= B
; I
!= E
; ++I
) {
451 if (Max
== E
|| L(*Max
, *I
))
457 /// Make sure that for each type in Small, there exists a larger type in Big.
458 bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode
&Small
,
459 TypeSetByHwMode
&Big
) {
460 ValidateOnExit
_1(Small
, *this), _2(Big
, *this);
463 bool Changed
= false;
466 Changed
|= EnforceAny(Small
);
468 Changed
|= EnforceAny(Big
);
470 assert(Small
.hasDefault() && Big
.hasDefault());
472 std::vector
<unsigned> Modes
= union_modes(Small
, Big
);
474 // 1. Only allow integer or floating point types and make sure that
475 // both sides are both integer or both floating point.
476 // 2. Make sure that either both sides have vector types, or neither
478 for (unsigned M
: Modes
) {
479 TypeSetByHwMode::SetType
&S
= Small
.get(M
);
480 TypeSetByHwMode::SetType
&B
= Big
.get(M
);
482 if (any_of(S
, isIntegerOrPtr
) && any_of(S
, isIntegerOrPtr
)) {
483 auto NotInt
= [](MVT VT
) { return !isIntegerOrPtr(VT
); };
484 Changed
|= berase_if(S
, NotInt
) |
485 berase_if(B
, NotInt
);
486 } else if (any_of(S
, isFloatingPoint
) && any_of(B
, isFloatingPoint
)) {
487 auto NotFP
= [](MVT VT
) { return !isFloatingPoint(VT
); };
488 Changed
|= berase_if(S
, NotFP
) |
490 } else if (S
.empty() || B
.empty()) {
491 Changed
= !S
.empty() || !B
.empty();
495 TP
.error("Incompatible types");
499 if (none_of(S
, isVector
) || none_of(B
, isVector
)) {
500 Changed
|= berase_if(S
, isVector
) |
501 berase_if(B
, isVector
);
505 auto LT
= [](MVT A
, MVT B
) -> bool {
506 return A
.getScalarSizeInBits() < B
.getScalarSizeInBits() ||
507 (A
.getScalarSizeInBits() == B
.getScalarSizeInBits() &&
508 A
.getSizeInBits() < B
.getSizeInBits());
510 auto LE
= [<
](MVT A
, MVT B
) -> bool {
511 // This function is used when removing elements: when a vector is compared
512 // to a non-vector, it should return false (to avoid removal).
513 if (A
.isVector() != B
.isVector())
516 return LT(A
, B
) || (A
.getScalarSizeInBits() == B
.getScalarSizeInBits() &&
517 A
.getSizeInBits() == B
.getSizeInBits());
520 for (unsigned M
: Modes
) {
521 TypeSetByHwMode::SetType
&S
= Small
.get(M
);
522 TypeSetByHwMode::SetType
&B
= Big
.get(M
);
523 // MinS = min scalar in Small, remove all scalars from Big that are
524 // smaller-or-equal than MinS.
525 auto MinS
= min_if(S
.begin(), S
.end(), isScalar
, LT
);
527 Changed
|= berase_if(B
, std::bind(LE
, std::placeholders::_1
, *MinS
));
529 // MaxS = max scalar in Big, remove all scalars from Small that are
531 auto MaxS
= max_if(B
.begin(), B
.end(), isScalar
, LT
);
533 Changed
|= berase_if(S
, std::bind(LE
, *MaxS
, std::placeholders::_1
));
535 // MinV = min vector in Small, remove all vectors from Big that are
536 // smaller-or-equal than MinV.
537 auto MinV
= min_if(S
.begin(), S
.end(), isVector
, LT
);
539 Changed
|= berase_if(B
, std::bind(LE
, std::placeholders::_1
, *MinV
));
541 // MaxV = max vector in Big, remove all vectors from Small that are
543 auto MaxV
= max_if(B
.begin(), B
.end(), isVector
, LT
);
545 Changed
|= berase_if(S
, std::bind(LE
, *MaxV
, std::placeholders::_1
));
551 /// 1. Ensure that for each type T in Vec, T is a vector type, and that
552 /// for each type U in Elem, U is a scalar type.
553 /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
554 /// type T in Vec, such that U is the element type of T.
555 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode
&Vec
,
556 TypeSetByHwMode
&Elem
) {
557 ValidateOnExit
_1(Vec
, *this), _2(Elem
, *this);
560 bool Changed
= false;
563 Changed
|= EnforceVector(Vec
);
565 Changed
|= EnforceScalar(Elem
);
567 for (unsigned M
: union_modes(Vec
, Elem
)) {
568 TypeSetByHwMode::SetType
&V
= Vec
.get(M
);
569 TypeSetByHwMode::SetType
&E
= Elem
.get(M
);
571 Changed
|= berase_if(V
, isScalar
); // Scalar = !vector
572 Changed
|= berase_if(E
, isVector
); // Vector = !scalar
573 assert(!V
.empty() && !E
.empty());
575 SmallSet
<MVT
,4> VT
, ST
;
576 // Collect element types from the "vector" set.
578 VT
.insert(T
.getVectorElementType());
579 // Collect scalar types from the "element" set.
583 // Remove from V all (vector) types whose element type is not in S.
584 Changed
|= berase_if(V
, [&ST
](MVT T
) -> bool {
585 return !ST
.count(T
.getVectorElementType());
587 // Remove from E all (scalar) types, for which there is no corresponding
589 Changed
|= berase_if(E
, [&VT
](MVT T
) -> bool { return !VT
.count(T
); });
595 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode
&Vec
,
596 const ValueTypeByHwMode
&VVT
) {
597 TypeSetByHwMode
Tmp(VVT
);
598 ValidateOnExit
_1(Vec
, *this), _2(Tmp
, *this);
599 return EnforceVectorEltTypeIs(Vec
, Tmp
);
602 /// Ensure that for each type T in Sub, T is a vector type, and there
603 /// exists a type U in Vec such that U is a vector type with the same
604 /// element type as T and at least as many elements as T.
605 bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode
&Vec
,
606 TypeSetByHwMode
&Sub
) {
607 ValidateOnExit
_1(Vec
, *this), _2(Sub
, *this);
611 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
612 auto IsSubVec
= [](MVT B
, MVT P
) -> bool {
613 if (!B
.isVector() || !P
.isVector())
615 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
616 // but until there are obvious use-cases for this, keep the
618 if (B
.isScalableVector() != P
.isScalableVector())
620 if (B
.getVectorElementType() != P
.getVectorElementType())
622 return B
.getVectorNumElements() < P
.getVectorNumElements();
625 /// Return true if S has no element (vector type) that T is a sub-vector of,
626 /// i.e. has the same element type as T and more elements.
627 auto NoSubV
= [&IsSubVec
](const TypeSetByHwMode::SetType
&S
, MVT T
) -> bool {
628 for (const auto &I
: S
)
634 /// Return true if S has no element (vector type) that T is a super-vector
635 /// of, i.e. has the same element type as T and fewer elements.
636 auto NoSupV
= [&IsSubVec
](const TypeSetByHwMode::SetType
&S
, MVT T
) -> bool {
637 for (const auto &I
: S
)
643 bool Changed
= false;
646 Changed
|= EnforceVector(Vec
);
648 Changed
|= EnforceVector(Sub
);
650 for (unsigned M
: union_modes(Vec
, Sub
)) {
651 TypeSetByHwMode::SetType
&S
= Sub
.get(M
);
652 TypeSetByHwMode::SetType
&V
= Vec
.get(M
);
654 Changed
|= berase_if(S
, isScalar
);
656 // Erase all types from S that are not sub-vectors of a type in V.
657 Changed
|= berase_if(S
, std::bind(NoSubV
, V
, std::placeholders::_1
));
659 // Erase all types from V that are not super-vectors of a type in S.
660 Changed
|= berase_if(V
, std::bind(NoSupV
, S
, std::placeholders::_1
));
666 /// 1. Ensure that V has a scalar type iff W has a scalar type.
667 /// 2. Ensure that for each vector type T in V, there exists a vector
668 /// type U in W, such that T and U have the same number of elements.
669 /// 3. Ensure that for each vector type U in W, there exists a vector
670 /// type T in V, such that T and U have the same number of elements
672 bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode
&V
, TypeSetByHwMode
&W
) {
673 ValidateOnExit
_1(V
, *this), _2(W
, *this);
677 bool Changed
= false;
679 Changed
|= EnforceAny(V
);
681 Changed
|= EnforceAny(W
);
683 // An actual vector type cannot have 0 elements, so we can treat scalars
684 // as zero-length vectors. This way both vectors and scalars can be
685 // processed identically.
686 auto NoLength
= [](const SmallSet
<unsigned,2> &Lengths
, MVT T
) -> bool {
687 return !Lengths
.count(T
.isVector() ? T
.getVectorNumElements() : 0);
690 for (unsigned M
: union_modes(V
, W
)) {
691 TypeSetByHwMode::SetType
&VS
= V
.get(M
);
692 TypeSetByHwMode::SetType
&WS
= W
.get(M
);
694 SmallSet
<unsigned,2> VN
, WN
;
696 VN
.insert(T
.isVector() ? T
.getVectorNumElements() : 0);
698 WN
.insert(T
.isVector() ? T
.getVectorNumElements() : 0);
700 Changed
|= berase_if(VS
, std::bind(NoLength
, WN
, std::placeholders::_1
));
701 Changed
|= berase_if(WS
, std::bind(NoLength
, VN
, std::placeholders::_1
));
706 /// 1. Ensure that for each type T in A, there exists a type U in B,
707 /// such that T and U have equal size in bits.
708 /// 2. Ensure that for each type U in B, there exists a type T in A
709 /// such that T and U have equal size in bits (reverse of 1).
710 bool TypeInfer::EnforceSameSize(TypeSetByHwMode
&A
, TypeSetByHwMode
&B
) {
711 ValidateOnExit
_1(A
, *this), _2(B
, *this);
714 bool Changed
= false;
716 Changed
|= EnforceAny(A
);
718 Changed
|= EnforceAny(B
);
720 auto NoSize
= [](const SmallSet
<unsigned,2> &Sizes
, MVT T
) -> bool {
721 return !Sizes
.count(T
.getSizeInBits());
724 for (unsigned M
: union_modes(A
, B
)) {
725 TypeSetByHwMode::SetType
&AS
= A
.get(M
);
726 TypeSetByHwMode::SetType
&BS
= B
.get(M
);
727 SmallSet
<unsigned,2> AN
, BN
;
730 AN
.insert(T
.getSizeInBits());
732 BN
.insert(T
.getSizeInBits());
734 Changed
|= berase_if(AS
, std::bind(NoSize
, BN
, std::placeholders::_1
));
735 Changed
|= berase_if(BS
, std::bind(NoSize
, AN
, std::placeholders::_1
));
741 void TypeInfer::expandOverloads(TypeSetByHwMode
&VTS
) {
742 ValidateOnExit
_1(VTS
, *this);
743 const TypeSetByHwMode
&Legal
= getLegalTypes();
744 assert(Legal
.isDefaultOnly() && "Default-mode only expected");
745 const TypeSetByHwMode::SetType
&LegalTypes
= Legal
.get(DefaultMode
);
748 expandOverloads(I
.second
, LegalTypes
);
751 void TypeInfer::expandOverloads(TypeSetByHwMode::SetType
&Out
,
752 const TypeSetByHwMode::SetType
&Legal
) {
755 if (!T
.isOverloaded())
759 // MachineValueTypeSet allows iteration and erasing.
764 switch (Ov
.SimpleTy
) {
766 Out
.insert(MVT::iPTR
);
769 for (MVT T
: MVT::integer_valuetypes())
772 for (MVT T
: MVT::integer_vector_valuetypes())
777 for (MVT T
: MVT::fp_valuetypes())
780 for (MVT T
: MVT::fp_vector_valuetypes())
785 for (MVT T
: MVT::vector_valuetypes())
790 for (MVT T
: MVT::all_valuetypes())
800 const TypeSetByHwMode
&TypeInfer::getLegalTypes() {
801 if (!LegalTypesCached
) {
802 TypeSetByHwMode::SetType
&LegalTypes
= LegalCache
.getOrCreate(DefaultMode
);
803 // Stuff all types from all modes into the default mode.
804 const TypeSetByHwMode
<S
= TP
.getDAGPatterns().getLegalTypes();
805 for (const auto &I
: LTS
)
806 LegalTypes
.insert(I
.second
);
807 LegalTypesCached
= true;
809 assert(LegalCache
.isDefaultOnly() && "Default-mode only expected");
814 TypeInfer::ValidateOnExit::~ValidateOnExit() {
815 if (Infer
.Validate
&& !VTS
.validate()) {
816 dbgs() << "Type set is empty for each HW mode:\n"
817 "possible type contradiction in the pattern below "
818 "(use -print-records with llvm-tblgen to see all "
819 "expanded records).\n";
821 llvm_unreachable(nullptr);
827 //===----------------------------------------------------------------------===//
828 // ScopedName Implementation
829 //===----------------------------------------------------------------------===//
831 bool ScopedName::operator==(const ScopedName
&o
) const {
832 return Scope
== o
.Scope
&& Identifier
== o
.Identifier
;
835 bool ScopedName::operator!=(const ScopedName
&o
) const {
836 return !(*this == o
);
840 //===----------------------------------------------------------------------===//
841 // TreePredicateFn Implementation
842 //===----------------------------------------------------------------------===//
844 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
845 TreePredicateFn::TreePredicateFn(TreePattern
*N
) : PatFragRec(N
) {
847 (!hasPredCode() || !hasImmCode()) &&
848 ".td file corrupt: can't have a node predicate *and* an imm predicate");
851 bool TreePredicateFn::hasPredCode() const {
852 return isLoad() || isStore() || isAtomic() ||
853 !PatFragRec
->getRecord()->getValueAsString("PredicateCode").empty();
856 std::string
TreePredicateFn::getPredCode() const {
857 std::string Code
= "";
859 if (!isLoad() && !isStore() && !isAtomic()) {
860 Record
*MemoryVT
= getMemoryVT();
863 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
864 "MemoryVT requires IsLoad or IsStore");
867 if (!isLoad() && !isStore()) {
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "IsUnindexed requires IsLoad or IsStore");
872 Record
*ScalarMemoryVT
= getScalarMemoryVT();
875 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
876 "ScalarMemoryVT requires IsLoad or IsStore");
879 if (isLoad() + isStore() + isAtomic() > 1)
880 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
881 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
884 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
885 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
886 getScalarMemoryVT() == nullptr)
887 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
888 "IsLoad cannot be used by itself");
891 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
892 "IsNonExtLoad requires IsLoad");
894 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
895 "IsAnyExtLoad requires IsLoad");
897 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
898 "IsSignExtLoad requires IsLoad");
900 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
901 "IsZeroExtLoad requires IsLoad");
905 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
906 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
907 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
908 "IsStore cannot be used by itself");
910 if (isNonTruncStore())
911 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
912 "IsNonTruncStore requires IsStore");
914 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
915 "IsTruncStore requires IsStore");
919 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
920 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
921 !isAtomicOrderingAcquireRelease() &&
922 !isAtomicOrderingSequentiallyConsistent() &&
923 !isAtomicOrderingAcquireOrStronger() &&
924 !isAtomicOrderingReleaseOrStronger() &&
925 !isAtomicOrderingWeakerThanAcquire() &&
926 !isAtomicOrderingWeakerThanRelease())
927 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
928 "IsAtomic cannot be used by itself");
930 if (isAtomicOrderingMonotonic())
931 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
932 "IsAtomicOrderingMonotonic requires IsAtomic");
933 if (isAtomicOrderingAcquire())
934 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
935 "IsAtomicOrderingAcquire requires IsAtomic");
936 if (isAtomicOrderingRelease())
937 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
938 "IsAtomicOrderingRelease requires IsAtomic");
939 if (isAtomicOrderingAcquireRelease())
940 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
941 "IsAtomicOrderingAcquireRelease requires IsAtomic");
942 if (isAtomicOrderingSequentiallyConsistent())
943 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
944 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
945 if (isAtomicOrderingAcquireOrStronger())
946 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
947 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
948 if (isAtomicOrderingReleaseOrStronger())
949 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
950 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
951 if (isAtomicOrderingWeakerThanAcquire())
952 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
953 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
956 if (isLoad() || isStore() || isAtomic()) {
957 if (ListInit
*AddressSpaces
= getAddressSpaces()) {
958 Code
+= "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
962 for (Init
*Val
: AddressSpaces
->getValues()) {
968 IntInit
*IntVal
= dyn_cast
<IntInit
>(Val
);
970 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
971 "AddressSpaces element must be integer");
974 Code
+= "AddrSpace != " + utostr(IntVal
->getValue());
977 Code
+= ")\nreturn false;\n";
980 Record
*MemoryVT
= getMemoryVT();
983 Code
+= ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
984 MemoryVT
->getName() + ") return false;\n")
988 if (isAtomic() && isAtomicOrderingMonotonic())
989 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
990 "AtomicOrdering::Monotonic) return false;\n";
991 if (isAtomic() && isAtomicOrderingAcquire())
992 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
993 "AtomicOrdering::Acquire) return false;\n";
994 if (isAtomic() && isAtomicOrderingRelease())
995 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
996 "AtomicOrdering::Release) return false;\n";
997 if (isAtomic() && isAtomicOrderingAcquireRelease())
998 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
999 "AtomicOrdering::AcquireRelease) return false;\n";
1000 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1001 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1002 "AtomicOrdering::SequentiallyConsistent) return false;\n";
1004 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1005 Code
+= "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1007 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1008 Code
+= "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1011 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1012 Code
+= "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1014 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1015 Code
+= "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1018 if (isLoad() || isStore()) {
1019 StringRef SDNodeName
= isLoad() ? "LoadSDNode" : "StoreSDNode";
1022 Code
+= ("if (cast<" + SDNodeName
+
1023 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1028 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1029 isZeroExtLoad()) > 1)
1030 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1031 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1032 "IsZeroExtLoad are mutually exclusive");
1034 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != "
1035 "ISD::NON_EXTLOAD) return false;\n";
1037 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1039 if (isSignExtLoad())
1040 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1042 if (isZeroExtLoad())
1043 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1046 if ((isNonTruncStore() + isTruncStore()) > 1)
1048 getOrigPatFragRecord()->getRecord()->getLoc(),
1049 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1050 if (isNonTruncStore())
1052 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1055 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1058 Record
*ScalarMemoryVT
= getScalarMemoryVT();
1061 Code
+= ("if (cast<" + SDNodeName
+
1062 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1063 ScalarMemoryVT
->getName() + ") return false;\n")
1067 std::string PredicateCode
= PatFragRec
->getRecord()->getValueAsString("PredicateCode");
1069 Code
+= PredicateCode
;
1071 if (PredicateCode
.empty() && !Code
.empty())
1072 Code
+= "return true;\n";
1077 bool TreePredicateFn::hasImmCode() const {
1078 return !PatFragRec
->getRecord()->getValueAsString("ImmediateCode").empty();
1081 std::string
TreePredicateFn::getImmCode() const {
1082 return PatFragRec
->getRecord()->getValueAsString("ImmediateCode");
1085 bool TreePredicateFn::immCodeUsesAPInt() const {
1086 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1089 bool TreePredicateFn::immCodeUsesAPFloat() const {
1091 // The return value will be false when IsAPFloat is unset.
1092 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1096 bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field
,
1100 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field
, Unset
);
1103 return Result
== Value
;
1105 bool TreePredicateFn::usesOperands() const {
1106 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1108 bool TreePredicateFn::isLoad() const {
1109 return isPredefinedPredicateEqualTo("IsLoad", true);
1111 bool TreePredicateFn::isStore() const {
1112 return isPredefinedPredicateEqualTo("IsStore", true);
1114 bool TreePredicateFn::isAtomic() const {
1115 return isPredefinedPredicateEqualTo("IsAtomic", true);
1117 bool TreePredicateFn::isUnindexed() const {
1118 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1120 bool TreePredicateFn::isNonExtLoad() const {
1121 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1123 bool TreePredicateFn::isAnyExtLoad() const {
1124 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1126 bool TreePredicateFn::isSignExtLoad() const {
1127 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1129 bool TreePredicateFn::isZeroExtLoad() const {
1130 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1132 bool TreePredicateFn::isNonTruncStore() const {
1133 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1135 bool TreePredicateFn::isTruncStore() const {
1136 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1138 bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1139 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1141 bool TreePredicateFn::isAtomicOrderingAcquire() const {
1142 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1144 bool TreePredicateFn::isAtomicOrderingRelease() const {
1145 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1147 bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1148 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1150 bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1151 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1154 bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1155 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1157 bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1158 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1160 bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1161 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1163 bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1164 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1166 Record
*TreePredicateFn::getMemoryVT() const {
1167 Record
*R
= getOrigPatFragRecord()->getRecord();
1168 if (R
->isValueUnset("MemoryVT"))
1170 return R
->getValueAsDef("MemoryVT");
1173 ListInit
*TreePredicateFn::getAddressSpaces() const {
1174 Record
*R
= getOrigPatFragRecord()->getRecord();
1175 if (R
->isValueUnset("AddressSpaces"))
1177 return R
->getValueAsListInit("AddressSpaces");
1180 Record
*TreePredicateFn::getScalarMemoryVT() const {
1181 Record
*R
= getOrigPatFragRecord()->getRecord();
1182 if (R
->isValueUnset("ScalarMemoryVT"))
1184 return R
->getValueAsDef("ScalarMemoryVT");
1186 bool TreePredicateFn::hasGISelPredicateCode() const {
1187 return !PatFragRec
->getRecord()
1188 ->getValueAsString("GISelPredicateCode")
1191 std::string
TreePredicateFn::getGISelPredicateCode() const {
1192 return PatFragRec
->getRecord()->getValueAsString("GISelPredicateCode");
1195 StringRef
TreePredicateFn::getImmType() const {
1196 if (immCodeUsesAPInt())
1197 return "const APInt &";
1198 if (immCodeUsesAPFloat())
1199 return "const APFloat &";
1203 StringRef
TreePredicateFn::getImmTypeIdentifier() const {
1204 if (immCodeUsesAPInt())
1206 else if (immCodeUsesAPFloat())
1211 /// isAlwaysTrue - Return true if this is a noop predicate.
1212 bool TreePredicateFn::isAlwaysTrue() const {
1213 return !hasPredCode() && !hasImmCode();
1216 /// Return the name to use in the generated code to reference this, this is
1217 /// "Predicate_foo" if from a pattern fragment "foo".
1218 std::string
TreePredicateFn::getFnName() const {
1219 return "Predicate_" + PatFragRec
->getRecord()->getName().str();
1222 /// getCodeToRunOnSDNode - Return the code for the function body that
1223 /// evaluates this predicate. The argument is expected to be in "Node",
1224 /// not N. This handles casting and conversion to a concrete node type as
1226 std::string
TreePredicateFn::getCodeToRunOnSDNode() const {
1227 // Handle immediate predicates first.
1228 std::string ImmCode
= getImmCode();
1229 if (!ImmCode
.empty()) {
1231 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1232 "IsLoad cannot be used with ImmLeaf or its subclasses");
1234 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1235 "IsStore cannot be used with ImmLeaf or its subclasses");
1238 getOrigPatFragRecord()->getRecord()->getLoc(),
1239 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1242 getOrigPatFragRecord()->getRecord()->getLoc(),
1243 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1246 getOrigPatFragRecord()->getRecord()->getLoc(),
1247 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1248 if (isSignExtLoad())
1250 getOrigPatFragRecord()->getRecord()->getLoc(),
1251 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1252 if (isZeroExtLoad())
1254 getOrigPatFragRecord()->getRecord()->getLoc(),
1255 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1256 if (isNonTruncStore())
1258 getOrigPatFragRecord()->getRecord()->getLoc(),
1259 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1262 getOrigPatFragRecord()->getRecord()->getLoc(),
1263 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1265 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1266 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1267 if (getScalarMemoryVT())
1269 getOrigPatFragRecord()->getRecord()->getLoc(),
1270 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1272 std::string Result
= (" " + getImmType() + " Imm = ").str();
1273 if (immCodeUsesAPFloat())
1274 Result
+= "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1275 else if (immCodeUsesAPInt())
1276 Result
+= "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1278 Result
+= "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1279 return Result
+ ImmCode
;
1282 // Handle arbitrary node predicates.
1283 assert(hasPredCode() && "Don't have any predicate code!");
1284 StringRef ClassName
;
1285 if (PatFragRec
->getOnlyTree()->isLeaf())
1286 ClassName
= "SDNode";
1288 Record
*Op
= PatFragRec
->getOnlyTree()->getOperator();
1289 ClassName
= PatFragRec
->getDAGPatterns().getSDNodeInfo(Op
).getSDClassName();
1292 if (ClassName
== "SDNode")
1293 Result
= " SDNode *N = Node;\n";
1295 Result
= " auto *N = cast<" + ClassName
.str() + ">(Node);\n";
1297 return (Twine(Result
) + " (void)N;\n" + getPredCode()).str();
1300 //===----------------------------------------------------------------------===//
1301 // PatternToMatch implementation
1304 static bool isImmAllOnesAllZerosMatch(const TreePatternNode
*P
) {
1307 DefInit
*DI
= dyn_cast
<DefInit
>(P
->getLeafValue());
1311 Record
*R
= DI
->getDef();
1312 return R
->getName() == "immAllOnesV" || R
->getName() == "immAllZerosV";
1315 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1316 /// patterns before small ones. This is used to determine the size of a
1318 static unsigned getPatternSize(const TreePatternNode
*P
,
1319 const CodeGenDAGPatterns
&CGP
) {
1320 unsigned Size
= 3; // The node itself.
1321 // If the root node is a ConstantSDNode, increases its size.
1322 // e.g. (set R32:$dst, 0).
1323 if (P
->isLeaf() && isa
<IntInit
>(P
->getLeafValue()))
1326 if (const ComplexPattern
*AM
= P
->getComplexPatternInfo(CGP
)) {
1327 Size
+= AM
->getComplexity();
1328 // We don't want to count any children twice, so return early.
1332 // If this node has some predicate function that must match, it adds to the
1333 // complexity of this node.
1334 if (!P
->getPredicateCalls().empty())
1337 // Count children in the count if they are also nodes.
1338 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
) {
1339 const TreePatternNode
*Child
= P
->getChild(i
);
1340 if (!Child
->isLeaf() && Child
->getNumTypes()) {
1341 const TypeSetByHwMode
&T0
= Child
->getExtType(0);
1342 // At this point, all variable type sets should be simple, i.e. only
1343 // have a default mode.
1344 if (T0
.getMachineValueType() != MVT::Other
) {
1345 Size
+= getPatternSize(Child
, CGP
);
1349 if (Child
->isLeaf()) {
1350 if (isa
<IntInit
>(Child
->getLeafValue()))
1351 Size
+= 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1352 else if (Child
->getComplexPatternInfo(CGP
))
1353 Size
+= getPatternSize(Child
, CGP
);
1354 else if (isImmAllOnesAllZerosMatch(Child
))
1355 Size
+= 4; // Matches a build_vector(+3) and a predicate (+1).
1356 else if (!Child
->getPredicateCalls().empty())
1364 /// Compute the complexity metric for the input pattern. This roughly
1365 /// corresponds to the number of nodes that are covered.
1366 int PatternToMatch::
1367 getPatternComplexity(const CodeGenDAGPatterns
&CGP
) const {
1368 return getPatternSize(getSrcPattern(), CGP
) + getAddedComplexity();
1371 /// getPredicateCheck - Return a single string containing all of this
1372 /// pattern's predicates concatenated with "&&" operators.
1374 std::string
PatternToMatch::getPredicateCheck() const {
1375 SmallVector
<const Predicate
*,4> PredList
;
1376 for (const Predicate
&P
: Predicates
)
1377 PredList
.push_back(&P
);
1378 llvm::sort(PredList
, deref
<llvm::less
>());
1381 for (unsigned i
= 0, e
= PredList
.size(); i
!= e
; ++i
) {
1384 Check
+= '(' + PredList
[i
]->getCondString() + ')';
1389 //===----------------------------------------------------------------------===//
1390 // SDTypeConstraint implementation
1393 SDTypeConstraint::SDTypeConstraint(Record
*R
, const CodeGenHwModes
&CGH
) {
1394 OperandNo
= R
->getValueAsInt("OperandNum");
1396 if (R
->isSubClassOf("SDTCisVT")) {
1397 ConstraintType
= SDTCisVT
;
1398 VVT
= getValueTypeByHwMode(R
->getValueAsDef("VT"), CGH
);
1399 for (const auto &P
: VVT
)
1400 if (P
.second
== MVT::isVoid
)
1401 PrintFatalError(R
->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1402 } else if (R
->isSubClassOf("SDTCisPtrTy")) {
1403 ConstraintType
= SDTCisPtrTy
;
1404 } else if (R
->isSubClassOf("SDTCisInt")) {
1405 ConstraintType
= SDTCisInt
;
1406 } else if (R
->isSubClassOf("SDTCisFP")) {
1407 ConstraintType
= SDTCisFP
;
1408 } else if (R
->isSubClassOf("SDTCisVec")) {
1409 ConstraintType
= SDTCisVec
;
1410 } else if (R
->isSubClassOf("SDTCisSameAs")) {
1411 ConstraintType
= SDTCisSameAs
;
1412 x
.SDTCisSameAs_Info
.OtherOperandNum
= R
->getValueAsInt("OtherOperandNum");
1413 } else if (R
->isSubClassOf("SDTCisVTSmallerThanOp")) {
1414 ConstraintType
= SDTCisVTSmallerThanOp
;
1415 x
.SDTCisVTSmallerThanOp_Info
.OtherOperandNum
=
1416 R
->getValueAsInt("OtherOperandNum");
1417 } else if (R
->isSubClassOf("SDTCisOpSmallerThanOp")) {
1418 ConstraintType
= SDTCisOpSmallerThanOp
;
1419 x
.SDTCisOpSmallerThanOp_Info
.BigOperandNum
=
1420 R
->getValueAsInt("BigOperandNum");
1421 } else if (R
->isSubClassOf("SDTCisEltOfVec")) {
1422 ConstraintType
= SDTCisEltOfVec
;
1423 x
.SDTCisEltOfVec_Info
.OtherOperandNum
= R
->getValueAsInt("OtherOpNum");
1424 } else if (R
->isSubClassOf("SDTCisSubVecOfVec")) {
1425 ConstraintType
= SDTCisSubVecOfVec
;
1426 x
.SDTCisSubVecOfVec_Info
.OtherOperandNum
=
1427 R
->getValueAsInt("OtherOpNum");
1428 } else if (R
->isSubClassOf("SDTCVecEltisVT")) {
1429 ConstraintType
= SDTCVecEltisVT
;
1430 VVT
= getValueTypeByHwMode(R
->getValueAsDef("VT"), CGH
);
1431 for (const auto &P
: VVT
) {
1434 PrintFatalError(R
->getLoc(),
1435 "Cannot use vector type as SDTCVecEltisVT");
1436 if (!T
.isInteger() && !T
.isFloatingPoint())
1437 PrintFatalError(R
->getLoc(), "Must use integer or floating point type "
1438 "as SDTCVecEltisVT");
1440 } else if (R
->isSubClassOf("SDTCisSameNumEltsAs")) {
1441 ConstraintType
= SDTCisSameNumEltsAs
;
1442 x
.SDTCisSameNumEltsAs_Info
.OtherOperandNum
=
1443 R
->getValueAsInt("OtherOperandNum");
1444 } else if (R
->isSubClassOf("SDTCisSameSizeAs")) {
1445 ConstraintType
= SDTCisSameSizeAs
;
1446 x
.SDTCisSameSizeAs_Info
.OtherOperandNum
=
1447 R
->getValueAsInt("OtherOperandNum");
1449 PrintFatalError(R
->getLoc(),
1450 "Unrecognized SDTypeConstraint '" + R
->getName() + "'!\n");
1454 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1455 /// N, and the result number in ResNo.
1456 static TreePatternNode
*getOperandNum(unsigned OpNo
, TreePatternNode
*N
,
1457 const SDNodeInfo
&NodeInfo
,
1459 unsigned NumResults
= NodeInfo
.getNumResults();
1460 if (OpNo
< NumResults
) {
1467 if (OpNo
>= N
->getNumChildren()) {
1469 raw_string_ostream
OS(S
);
1470 OS
<< "Invalid operand number in type constraint "
1471 << (OpNo
+NumResults
) << " ";
1473 PrintFatalError(OS
.str());
1476 return N
->getChild(OpNo
);
1479 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1480 /// constraint to the nodes operands. This returns true if it makes a
1481 /// change, false otherwise. If a type contradiction is found, flag an error.
1482 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode
*N
,
1483 const SDNodeInfo
&NodeInfo
,
1484 TreePattern
&TP
) const {
1488 unsigned ResNo
= 0; // The result number being referenced.
1489 TreePatternNode
*NodeToApply
= getOperandNum(OperandNo
, N
, NodeInfo
, ResNo
);
1490 TypeInfer
&TI
= TP
.getInfer();
1492 switch (ConstraintType
) {
1494 // Operand must be a particular type.
1495 return NodeToApply
->UpdateNodeType(ResNo
, VVT
, TP
);
1497 // Operand must be same as target pointer type.
1498 return NodeToApply
->UpdateNodeType(ResNo
, MVT::iPTR
, TP
);
1500 // Require it to be one of the legal integer VTs.
1501 return TI
.EnforceInteger(NodeToApply
->getExtType(ResNo
));
1503 // Require it to be one of the legal fp VTs.
1504 return TI
.EnforceFloatingPoint(NodeToApply
->getExtType(ResNo
));
1506 // Require it to be one of the legal vector VTs.
1507 return TI
.EnforceVector(NodeToApply
->getExtType(ResNo
));
1508 case SDTCisSameAs
: {
1509 unsigned OResNo
= 0;
1510 TreePatternNode
*OtherNode
=
1511 getOperandNum(x
.SDTCisSameAs_Info
.OtherOperandNum
, N
, NodeInfo
, OResNo
);
1512 return NodeToApply
->UpdateNodeType(ResNo
, OtherNode
->getExtType(OResNo
),TP
)|
1513 OtherNode
->UpdateNodeType(OResNo
,NodeToApply
->getExtType(ResNo
),TP
);
1515 case SDTCisVTSmallerThanOp
: {
1516 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1517 // have an integer type that is smaller than the VT.
1518 if (!NodeToApply
->isLeaf() ||
1519 !isa
<DefInit
>(NodeToApply
->getLeafValue()) ||
1520 !static_cast<DefInit
*>(NodeToApply
->getLeafValue())->getDef()
1521 ->isSubClassOf("ValueType")) {
1522 TP
.error(N
->getOperator()->getName() + " expects a VT operand!");
1525 DefInit
*DI
= static_cast<DefInit
*>(NodeToApply
->getLeafValue());
1526 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
1527 auto VVT
= getValueTypeByHwMode(DI
->getDef(), T
.getHwModes());
1528 TypeSetByHwMode
TypeListTmp(VVT
);
1530 unsigned OResNo
= 0;
1531 TreePatternNode
*OtherNode
=
1532 getOperandNum(x
.SDTCisVTSmallerThanOp_Info
.OtherOperandNum
, N
, NodeInfo
,
1535 return TI
.EnforceSmallerThan(TypeListTmp
, OtherNode
->getExtType(OResNo
));
1537 case SDTCisOpSmallerThanOp
: {
1538 unsigned BResNo
= 0;
1539 TreePatternNode
*BigOperand
=
1540 getOperandNum(x
.SDTCisOpSmallerThanOp_Info
.BigOperandNum
, N
, NodeInfo
,
1542 return TI
.EnforceSmallerThan(NodeToApply
->getExtType(ResNo
),
1543 BigOperand
->getExtType(BResNo
));
1545 case SDTCisEltOfVec
: {
1546 unsigned VResNo
= 0;
1547 TreePatternNode
*VecOperand
=
1548 getOperandNum(x
.SDTCisEltOfVec_Info
.OtherOperandNum
, N
, NodeInfo
,
1550 // Filter vector types out of VecOperand that don't have the right element
1552 return TI
.EnforceVectorEltTypeIs(VecOperand
->getExtType(VResNo
),
1553 NodeToApply
->getExtType(ResNo
));
1555 case SDTCisSubVecOfVec
: {
1556 unsigned VResNo
= 0;
1557 TreePatternNode
*BigVecOperand
=
1558 getOperandNum(x
.SDTCisSubVecOfVec_Info
.OtherOperandNum
, N
, NodeInfo
,
1561 // Filter vector types out of BigVecOperand that don't have the
1562 // right subvector type.
1563 return TI
.EnforceVectorSubVectorTypeIs(BigVecOperand
->getExtType(VResNo
),
1564 NodeToApply
->getExtType(ResNo
));
1566 case SDTCVecEltisVT
: {
1567 return TI
.EnforceVectorEltTypeIs(NodeToApply
->getExtType(ResNo
), VVT
);
1569 case SDTCisSameNumEltsAs
: {
1570 unsigned OResNo
= 0;
1571 TreePatternNode
*OtherNode
=
1572 getOperandNum(x
.SDTCisSameNumEltsAs_Info
.OtherOperandNum
,
1573 N
, NodeInfo
, OResNo
);
1574 return TI
.EnforceSameNumElts(OtherNode
->getExtType(OResNo
),
1575 NodeToApply
->getExtType(ResNo
));
1577 case SDTCisSameSizeAs
: {
1578 unsigned OResNo
= 0;
1579 TreePatternNode
*OtherNode
=
1580 getOperandNum(x
.SDTCisSameSizeAs_Info
.OtherOperandNum
,
1581 N
, NodeInfo
, OResNo
);
1582 return TI
.EnforceSameSize(OtherNode
->getExtType(OResNo
),
1583 NodeToApply
->getExtType(ResNo
));
1586 llvm_unreachable("Invalid ConstraintType!");
1589 // Update the node type to match an instruction operand or result as specified
1590 // in the ins or outs lists on the instruction definition. Return true if the
1591 // type was actually changed.
1592 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo
,
1595 // The 'unknown' operand indicates that types should be inferred from the
1597 if (Operand
->isSubClassOf("unknown_class"))
1600 // The Operand class specifies a type directly.
1601 if (Operand
->isSubClassOf("Operand")) {
1602 Record
*R
= Operand
->getValueAsDef("Type");
1603 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
1604 return UpdateNodeType(ResNo
, getValueTypeByHwMode(R
, T
.getHwModes()), TP
);
1607 // PointerLikeRegClass has a type that is determined at runtime.
1608 if (Operand
->isSubClassOf("PointerLikeRegClass"))
1609 return UpdateNodeType(ResNo
, MVT::iPTR
, TP
);
1611 // Both RegisterClass and RegisterOperand operands derive their types from a
1612 // register class def.
1613 Record
*RC
= nullptr;
1614 if (Operand
->isSubClassOf("RegisterClass"))
1616 else if (Operand
->isSubClassOf("RegisterOperand"))
1617 RC
= Operand
->getValueAsDef("RegClass");
1619 assert(RC
&& "Unknown operand type");
1620 CodeGenTarget
&Tgt
= TP
.getDAGPatterns().getTargetInfo();
1621 return UpdateNodeType(ResNo
, Tgt
.getRegisterClass(RC
).getValueTypes(), TP
);
1624 bool TreePatternNode::ContainsUnresolvedType(TreePattern
&TP
) const {
1625 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
)
1626 if (!TP
.getInfer().isConcrete(Types
[i
], true))
1628 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1629 if (getChild(i
)->ContainsUnresolvedType(TP
))
1634 bool TreePatternNode::hasProperTypeByHwMode() const {
1635 for (const TypeSetByHwMode
&S
: Types
)
1636 if (!S
.isDefaultOnly())
1638 for (const TreePatternNodePtr
&C
: Children
)
1639 if (C
->hasProperTypeByHwMode())
1644 bool TreePatternNode::hasPossibleType() const {
1645 for (const TypeSetByHwMode
&S
: Types
)
1646 if (!S
.isPossible())
1648 for (const TreePatternNodePtr
&C
: Children
)
1649 if (!C
->hasPossibleType())
1654 bool TreePatternNode::setDefaultMode(unsigned Mode
) {
1655 for (TypeSetByHwMode
&S
: Types
) {
1657 // Check if the selected mode had a type conflict.
1658 if (S
.get(DefaultMode
).empty())
1661 for (const TreePatternNodePtr
&C
: Children
)
1662 if (!C
->setDefaultMode(Mode
))
1667 //===----------------------------------------------------------------------===//
1668 // SDNodeInfo implementation
1670 SDNodeInfo::SDNodeInfo(Record
*R
, const CodeGenHwModes
&CGH
) : Def(R
) {
1671 EnumName
= R
->getValueAsString("Opcode");
1672 SDClassName
= R
->getValueAsString("SDClass");
1673 Record
*TypeProfile
= R
->getValueAsDef("TypeProfile");
1674 NumResults
= TypeProfile
->getValueAsInt("NumResults");
1675 NumOperands
= TypeProfile
->getValueAsInt("NumOperands");
1677 // Parse the properties.
1678 Properties
= parseSDPatternOperatorProperties(R
);
1680 // Parse the type constraints.
1681 std::vector
<Record
*> ConstraintList
=
1682 TypeProfile
->getValueAsListOfDefs("Constraints");
1683 for (Record
*R
: ConstraintList
)
1684 TypeConstraints
.emplace_back(R
, CGH
);
1687 /// getKnownType - If the type constraints on this node imply a fixed type
1688 /// (e.g. all stores return void, etc), then return it as an
1689 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1690 MVT::SimpleValueType
SDNodeInfo::getKnownType(unsigned ResNo
) const {
1691 unsigned NumResults
= getNumResults();
1692 assert(NumResults
<= 1 &&
1693 "We only work with nodes with zero or one result so far!");
1694 assert(ResNo
== 0 && "Only handles single result nodes so far");
1696 for (const SDTypeConstraint
&Constraint
: TypeConstraints
) {
1697 // Make sure that this applies to the correct node result.
1698 if (Constraint
.OperandNo
>= NumResults
) // FIXME: need value #
1701 switch (Constraint
.ConstraintType
) {
1703 case SDTypeConstraint::SDTCisVT
:
1704 if (Constraint
.VVT
.isSimple())
1705 return Constraint
.VVT
.getSimple().SimpleTy
;
1707 case SDTypeConstraint::SDTCisPtrTy
:
1714 //===----------------------------------------------------------------------===//
1715 // TreePatternNode implementation
1718 static unsigned GetNumNodeResults(Record
*Operator
, CodeGenDAGPatterns
&CDP
) {
1719 if (Operator
->getName() == "set" ||
1720 Operator
->getName() == "implicit")
1721 return 0; // All return nothing.
1723 if (Operator
->isSubClassOf("Intrinsic"))
1724 return CDP
.getIntrinsic(Operator
).IS
.RetVTs
.size();
1726 if (Operator
->isSubClassOf("SDNode"))
1727 return CDP
.getSDNodeInfo(Operator
).getNumResults();
1729 if (Operator
->isSubClassOf("PatFrags")) {
1730 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1731 // the forward reference case where one pattern fragment references another
1732 // before it is processed.
1733 if (TreePattern
*PFRec
= CDP
.getPatternFragmentIfRead(Operator
)) {
1734 // The number of results of a fragment with alternative records is the
1735 // maximum number of results across all alternatives.
1736 unsigned NumResults
= 0;
1737 for (auto T
: PFRec
->getTrees())
1738 NumResults
= std::max(NumResults
, T
->getNumTypes());
1742 ListInit
*LI
= Operator
->getValueAsListInit("Fragments");
1743 assert(LI
&& "Invalid Fragment");
1744 unsigned NumResults
= 0;
1745 for (Init
*I
: LI
->getValues()) {
1746 Record
*Op
= nullptr;
1747 if (DagInit
*Dag
= dyn_cast
<DagInit
>(I
))
1748 if (DefInit
*DI
= dyn_cast
<DefInit
>(Dag
->getOperator()))
1750 assert(Op
&& "Invalid Fragment");
1751 NumResults
= std::max(NumResults
, GetNumNodeResults(Op
, CDP
));
1756 if (Operator
->isSubClassOf("Instruction")) {
1757 CodeGenInstruction
&InstInfo
= CDP
.getTargetInfo().getInstruction(Operator
);
1759 unsigned NumDefsToAdd
= InstInfo
.Operands
.NumDefs
;
1761 // Subtract any defaulted outputs.
1762 for (unsigned i
= 0; i
!= InstInfo
.Operands
.NumDefs
; ++i
) {
1763 Record
*OperandNode
= InstInfo
.Operands
[i
].Rec
;
1765 if (OperandNode
->isSubClassOf("OperandWithDefaultOps") &&
1766 !CDP
.getDefaultOperand(OperandNode
).DefaultOps
.empty())
1770 // Add on one implicit def if it has a resolvable type.
1771 if (InstInfo
.HasOneImplicitDefWithKnownVT(CDP
.getTargetInfo()) !=MVT::Other
)
1773 return NumDefsToAdd
;
1776 if (Operator
->isSubClassOf("SDNodeXForm"))
1777 return 1; // FIXME: Generalize SDNodeXForm
1779 if (Operator
->isSubClassOf("ValueType"))
1780 return 1; // A type-cast of one result.
1782 if (Operator
->isSubClassOf("ComplexPattern"))
1785 errs() << *Operator
;
1786 PrintFatalError("Unhandled node in GetNumNodeResults");
1789 void TreePatternNode::print(raw_ostream
&OS
) const {
1791 OS
<< *getLeafValue();
1793 OS
<< '(' << getOperator()->getName();
1795 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
) {
1797 getExtType(i
).writeToStream(OS
);
1801 if (getNumChildren() != 0) {
1803 getChild(0)->print(OS
);
1804 for (unsigned i
= 1, e
= getNumChildren(); i
!= e
; ++i
) {
1806 getChild(i
)->print(OS
);
1812 for (const TreePredicateCall
&Pred
: PredicateCalls
) {
1815 OS
<< Pred
.Scope
<< ":";
1816 OS
<< Pred
.Fn
.getFnName() << ">>";
1819 OS
<< "<<X:" << TransformFn
->getName() << ">>";
1820 if (!getName().empty())
1821 OS
<< ":$" << getName();
1823 for (const ScopedName
&Name
: NamesAsPredicateArg
)
1824 OS
<< ":$pred:" << Name
.getScope() << ":" << Name
.getIdentifier();
1826 void TreePatternNode::dump() const {
1830 /// isIsomorphicTo - Return true if this node is recursively
1831 /// isomorphic to the specified node. For this comparison, the node's
1832 /// entire state is considered. The assigned name is ignored, since
1833 /// nodes with differing names are considered isomorphic. However, if
1834 /// the assigned name is present in the dependent variable set, then
1835 /// the assigned name is considered significant and the node is
1836 /// isomorphic if the names match.
1837 bool TreePatternNode::isIsomorphicTo(const TreePatternNode
*N
,
1838 const MultipleUseVarSet
&DepVars
) const {
1839 if (N
== this) return true;
1840 if (N
->isLeaf() != isLeaf() || getExtTypes() != N
->getExtTypes() ||
1841 getPredicateCalls() != N
->getPredicateCalls() ||
1842 getTransformFn() != N
->getTransformFn())
1846 if (DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue())) {
1847 if (DefInit
*NDI
= dyn_cast
<DefInit
>(N
->getLeafValue())) {
1848 return ((DI
->getDef() == NDI
->getDef())
1849 && (DepVars
.find(getName()) == DepVars
.end()
1850 || getName() == N
->getName()));
1853 return getLeafValue() == N
->getLeafValue();
1856 if (N
->getOperator() != getOperator() ||
1857 N
->getNumChildren() != getNumChildren()) return false;
1858 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1859 if (!getChild(i
)->isIsomorphicTo(N
->getChild(i
), DepVars
))
1864 /// clone - Make a copy of this tree and all of its children.
1866 TreePatternNodePtr
TreePatternNode::clone() const {
1867 TreePatternNodePtr New
;
1869 New
= std::make_shared
<TreePatternNode
>(getLeafValue(), getNumTypes());
1871 std::vector
<TreePatternNodePtr
> CChildren
;
1872 CChildren
.reserve(Children
.size());
1873 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1874 CChildren
.push_back(getChild(i
)->clone());
1875 New
= std::make_shared
<TreePatternNode
>(getOperator(), std::move(CChildren
),
1878 New
->setName(getName());
1879 New
->setNamesAsPredicateArg(getNamesAsPredicateArg());
1881 New
->setPredicateCalls(getPredicateCalls());
1882 New
->setTransformFn(getTransformFn());
1886 /// RemoveAllTypes - Recursively strip all the types of this tree.
1887 void TreePatternNode::RemoveAllTypes() {
1888 // Reset to unknown type.
1889 std::fill(Types
.begin(), Types
.end(), TypeSetByHwMode());
1890 if (isLeaf()) return;
1891 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1892 getChild(i
)->RemoveAllTypes();
1896 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1897 /// with actual values specified by ArgMap.
1898 void TreePatternNode::SubstituteFormalArguments(
1899 std::map
<std::string
, TreePatternNodePtr
> &ArgMap
) {
1900 if (isLeaf()) return;
1902 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
) {
1903 TreePatternNode
*Child
= getChild(i
);
1904 if (Child
->isLeaf()) {
1905 Init
*Val
= Child
->getLeafValue();
1906 // Note that, when substituting into an output pattern, Val might be an
1908 if (isa
<UnsetInit
>(Val
) || (isa
<DefInit
>(Val
) &&
1909 cast
<DefInit
>(Val
)->getDef()->getName() == "node")) {
1910 // We found a use of a formal argument, replace it with its value.
1911 TreePatternNodePtr NewChild
= ArgMap
[Child
->getName()];
1912 assert(NewChild
&& "Couldn't find formal argument!");
1913 assert((Child
->getPredicateCalls().empty() ||
1914 NewChild
->getPredicateCalls() == Child
->getPredicateCalls()) &&
1915 "Non-empty child predicate clobbered!");
1916 setChild(i
, std::move(NewChild
));
1919 getChild(i
)->SubstituteFormalArguments(ArgMap
);
1925 /// InlinePatternFragments - If this pattern refers to any pattern
1926 /// fragments, return the set of inlined versions (this can be more than
1927 /// one if a PatFrags record has multiple alternatives).
1928 void TreePatternNode::InlinePatternFragments(
1929 TreePatternNodePtr T
, TreePattern
&TP
,
1930 std::vector
<TreePatternNodePtr
> &OutAlternatives
) {
1936 OutAlternatives
.push_back(T
); // nothing to do.
1940 Record
*Op
= getOperator();
1942 if (!Op
->isSubClassOf("PatFrags")) {
1943 if (getNumChildren() == 0) {
1944 OutAlternatives
.push_back(T
);
1948 // Recursively inline children nodes.
1949 std::vector
<std::vector
<TreePatternNodePtr
> > ChildAlternatives
;
1950 ChildAlternatives
.resize(getNumChildren());
1951 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
) {
1952 TreePatternNodePtr Child
= getChildShared(i
);
1953 Child
->InlinePatternFragments(Child
, TP
, ChildAlternatives
[i
]);
1954 // If there are no alternatives for any child, there are no
1955 // alternatives for this expression as whole.
1956 if (ChildAlternatives
[i
].empty())
1959 for (auto NewChild
: ChildAlternatives
[i
])
1960 assert((Child
->getPredicateCalls().empty() ||
1961 NewChild
->getPredicateCalls() == Child
->getPredicateCalls()) &&
1962 "Non-empty child predicate clobbered!");
1965 // The end result is an all-pairs construction of the resultant pattern.
1966 std::vector
<unsigned> Idxs
;
1967 Idxs
.resize(ChildAlternatives
.size());
1970 // Create the variant and add it to the output list.
1971 std::vector
<TreePatternNodePtr
> NewChildren
;
1972 for (unsigned i
= 0, e
= ChildAlternatives
.size(); i
!= e
; ++i
)
1973 NewChildren
.push_back(ChildAlternatives
[i
][Idxs
[i
]]);
1974 TreePatternNodePtr R
= std::make_shared
<TreePatternNode
>(
1975 getOperator(), std::move(NewChildren
), getNumTypes());
1977 // Copy over properties.
1978 R
->setName(getName());
1979 R
->setNamesAsPredicateArg(getNamesAsPredicateArg());
1980 R
->setPredicateCalls(getPredicateCalls());
1981 R
->setTransformFn(getTransformFn());
1982 for (unsigned i
= 0, e
= getNumTypes(); i
!= e
; ++i
)
1983 R
->setType(i
, getExtType(i
));
1984 for (unsigned i
= 0, e
= getNumResults(); i
!= e
; ++i
)
1985 R
->setResultIndex(i
, getResultIndex(i
));
1987 // Register alternative.
1988 OutAlternatives
.push_back(R
);
1990 // Increment indices to the next permutation by incrementing the
1991 // indices from last index backward, e.g., generate the sequence
1992 // [0, 0], [0, 1], [1, 0], [1, 1].
1994 for (IdxsIdx
= Idxs
.size() - 1; IdxsIdx
>= 0; --IdxsIdx
) {
1995 if (++Idxs
[IdxsIdx
] == ChildAlternatives
[IdxsIdx
].size())
2000 NotDone
= (IdxsIdx
>= 0);
2006 // Otherwise, we found a reference to a fragment. First, look up its
2007 // TreePattern record.
2008 TreePattern
*Frag
= TP
.getDAGPatterns().getPatternFragment(Op
);
2010 // Verify that we are passing the right number of operands.
2011 if (Frag
->getNumArgs() != Children
.size()) {
2012 TP
.error("'" + Op
->getName() + "' fragment requires " +
2013 Twine(Frag
->getNumArgs()) + " operands!");
2017 TreePredicateFn
PredFn(Frag
);
2019 if (TreePredicateFn(Frag
).usesOperands())
2020 Scope
= TP
.getDAGPatterns().allocateScope();
2022 // Compute the map of formal to actual arguments.
2023 std::map
<std::string
, TreePatternNodePtr
> ArgMap
;
2024 for (unsigned i
= 0, e
= Frag
->getNumArgs(); i
!= e
; ++i
) {
2025 TreePatternNodePtr Child
= getChildShared(i
);
2027 Child
= Child
->clone();
2028 Child
->addNameAsPredicateArg(ScopedName(Scope
, Frag
->getArgName(i
)));
2030 ArgMap
[Frag
->getArgName(i
)] = Child
;
2033 // Loop over all fragment alternatives.
2034 for (auto Alternative
: Frag
->getTrees()) {
2035 TreePatternNodePtr FragTree
= Alternative
->clone();
2037 if (!PredFn
.isAlwaysTrue())
2038 FragTree
->addPredicateCall(PredFn
, Scope
);
2040 // Resolve formal arguments to their actual value.
2041 if (Frag
->getNumArgs())
2042 FragTree
->SubstituteFormalArguments(ArgMap
);
2044 // Transfer types. Note that the resolved alternative may have fewer
2045 // (but not more) results than the PatFrags node.
2046 FragTree
->setName(getName());
2047 for (unsigned i
= 0, e
= FragTree
->getNumTypes(); i
!= e
; ++i
)
2048 FragTree
->UpdateNodeType(i
, getExtType(i
), TP
);
2050 // Transfer in the old predicates.
2051 for (const TreePredicateCall
&Pred
: getPredicateCalls())
2052 FragTree
->addPredicateCall(Pred
);
2054 // The fragment we inlined could have recursive inlining that is needed. See
2055 // if there are any pattern fragments in it and inline them as needed.
2056 FragTree
->InlinePatternFragments(FragTree
, TP
, OutAlternatives
);
2060 /// getImplicitType - Check to see if the specified record has an implicit
2061 /// type which should be applied to it. This will infer the type of register
2062 /// references from the register file information, for example.
2064 /// When Unnamed is set, return the type of a DAG operand with no name, such as
2065 /// the F8RC register class argument in:
2067 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
2069 /// When Unnamed is false, return the type of a named DAG operand such as the
2070 /// GPR:$src operand above.
2072 static TypeSetByHwMode
getImplicitType(Record
*R
, unsigned ResNo
,
2076 CodeGenDAGPatterns
&CDP
= TP
.getDAGPatterns();
2078 // Check to see if this is a register operand.
2079 if (R
->isSubClassOf("RegisterOperand")) {
2080 assert(ResNo
== 0 && "Regoperand ref only has one result!");
2082 return TypeSetByHwMode(); // Unknown.
2083 Record
*RegClass
= R
->getValueAsDef("RegClass");
2084 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2085 return TypeSetByHwMode(T
.getRegisterClass(RegClass
).getValueTypes());
2088 // Check to see if this is a register or a register class.
2089 if (R
->isSubClassOf("RegisterClass")) {
2090 assert(ResNo
== 0 && "Regclass ref only has one result!");
2091 // An unnamed register class represents itself as an i32 immediate, for
2092 // example on a COPY_TO_REGCLASS instruction.
2094 return TypeSetByHwMode(MVT::i32
);
2096 // In a named operand, the register class provides the possible set of
2099 return TypeSetByHwMode(); // Unknown.
2100 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2101 return TypeSetByHwMode(T
.getRegisterClass(R
).getValueTypes());
2104 if (R
->isSubClassOf("PatFrags")) {
2105 assert(ResNo
== 0 && "FIXME: PatFrag with multiple results?");
2106 // Pattern fragment types will be resolved when they are inlined.
2107 return TypeSetByHwMode(); // Unknown.
2110 if (R
->isSubClassOf("Register")) {
2111 assert(ResNo
== 0 && "Registers only produce one result!");
2113 return TypeSetByHwMode(); // Unknown.
2114 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2115 return TypeSetByHwMode(T
.getRegisterVTs(R
));
2118 if (R
->isSubClassOf("SubRegIndex")) {
2119 assert(ResNo
== 0 && "SubRegisterIndices only produce one result!");
2120 return TypeSetByHwMode(MVT::i32
);
2123 if (R
->isSubClassOf("ValueType")) {
2124 assert(ResNo
== 0 && "This node only has one result!");
2125 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2127 // (sext_inreg GPR:$src, i16)
2130 return TypeSetByHwMode(MVT::Other
);
2131 // With a name, the ValueType simply provides the type of the named
2134 // (sext_inreg i32:$src, i16)
2137 return TypeSetByHwMode(); // Unknown.
2138 const CodeGenHwModes
&CGH
= CDP
.getTargetInfo().getHwModes();
2139 return TypeSetByHwMode(getValueTypeByHwMode(R
, CGH
));
2142 if (R
->isSubClassOf("CondCode")) {
2143 assert(ResNo
== 0 && "This node only has one result!");
2144 // Using a CondCodeSDNode.
2145 return TypeSetByHwMode(MVT::Other
);
2148 if (R
->isSubClassOf("ComplexPattern")) {
2149 assert(ResNo
== 0 && "FIXME: ComplexPattern with multiple results?");
2151 return TypeSetByHwMode(); // Unknown.
2152 return TypeSetByHwMode(CDP
.getComplexPattern(R
).getValueType());
2154 if (R
->isSubClassOf("PointerLikeRegClass")) {
2155 assert(ResNo
== 0 && "Regclass can only have one result!");
2156 TypeSetByHwMode
VTS(MVT::iPTR
);
2157 TP
.getInfer().expandOverloads(VTS
);
2161 if (R
->getName() == "node" || R
->getName() == "srcvalue" ||
2162 R
->getName() == "zero_reg" || R
->getName() == "immAllOnesV" ||
2163 R
->getName() == "immAllZerosV" || R
->getName() == "undef_tied_input") {
2165 return TypeSetByHwMode(); // Unknown.
2168 if (R
->isSubClassOf("Operand")) {
2169 const CodeGenHwModes
&CGH
= CDP
.getTargetInfo().getHwModes();
2170 Record
*T
= R
->getValueAsDef("Type");
2171 return TypeSetByHwMode(getValueTypeByHwMode(T
, CGH
));
2174 TP
.error("Unknown node flavor used in pattern: " + R
->getName());
2175 return TypeSetByHwMode(MVT::Other
);
2179 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2180 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2181 const CodeGenIntrinsic
*TreePatternNode::
2182 getIntrinsicInfo(const CodeGenDAGPatterns
&CDP
) const {
2183 if (getOperator() != CDP
.get_intrinsic_void_sdnode() &&
2184 getOperator() != CDP
.get_intrinsic_w_chain_sdnode() &&
2185 getOperator() != CDP
.get_intrinsic_wo_chain_sdnode())
2188 unsigned IID
= cast
<IntInit
>(getChild(0)->getLeafValue())->getValue();
2189 return &CDP
.getIntrinsicInfo(IID
);
2192 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2193 /// return the ComplexPattern information, otherwise return null.
2194 const ComplexPattern
*
2195 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns
&CGP
) const {
2198 DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue());
2203 Rec
= getOperator();
2205 if (!Rec
->isSubClassOf("ComplexPattern"))
2207 return &CGP
.getComplexPattern(Rec
);
2210 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns
&CGP
) const {
2211 // A ComplexPattern specifically declares how many results it fills in.
2212 if (const ComplexPattern
*CP
= getComplexPatternInfo(CGP
))
2213 return CP
->getNumOperands();
2215 // If MIOperandInfo is specified, that gives the count.
2217 DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue());
2218 if (DI
&& DI
->getDef()->isSubClassOf("Operand")) {
2219 DagInit
*MIOps
= DI
->getDef()->getValueAsDag("MIOperandInfo");
2220 if (MIOps
->getNumArgs())
2221 return MIOps
->getNumArgs();
2225 // Otherwise there is just one result.
2229 /// NodeHasProperty - Return true if this node has the specified property.
2230 bool TreePatternNode::NodeHasProperty(SDNP Property
,
2231 const CodeGenDAGPatterns
&CGP
) const {
2233 if (const ComplexPattern
*CP
= getComplexPatternInfo(CGP
))
2234 return CP
->hasProperty(Property
);
2239 if (Property
!= SDNPHasChain
) {
2240 // The chain proprety is already present on the different intrinsic node
2241 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2242 // on the intrinsic. Anything else is specific to the individual intrinsic.
2243 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CGP
))
2244 return Int
->hasProperty(Property
);
2247 if (!Operator
->isSubClassOf("SDPatternOperator"))
2250 return CGP
.getSDNodeInfo(Operator
).hasProperty(Property
);
2256 /// TreeHasProperty - Return true if any node in this tree has the specified
2258 bool TreePatternNode::TreeHasProperty(SDNP Property
,
2259 const CodeGenDAGPatterns
&CGP
) const {
2260 if (NodeHasProperty(Property
, CGP
))
2262 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2263 if (getChild(i
)->TreeHasProperty(Property
, CGP
))
2268 /// isCommutativeIntrinsic - Return true if the node corresponds to a
2269 /// commutative intrinsic.
2271 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns
&CDP
) const {
2272 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CDP
))
2273 return Int
->isCommutative
;
2277 static bool isOperandClass(const TreePatternNode
*N
, StringRef Class
) {
2279 return N
->getOperator()->isSubClassOf(Class
);
2281 DefInit
*DI
= dyn_cast
<DefInit
>(N
->getLeafValue());
2282 if (DI
&& DI
->getDef()->isSubClassOf(Class
))
2288 static void emitTooManyOperandsError(TreePattern
&TP
,
2292 TP
.error("Instruction '" + InstName
+ "' was provided " + Twine(Actual
) +
2293 " operands but expected only " + Twine(Expected
) + "!");
2296 static void emitTooFewOperandsError(TreePattern
&TP
,
2299 TP
.error("Instruction '" + InstName
+
2300 "' expects more than the provided " + Twine(Actual
) + " operands!");
2303 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2304 /// this node and its children in the tree. This returns true if it makes a
2305 /// change, false otherwise. If a type contradiction is found, flag an error.
2306 bool TreePatternNode::ApplyTypeConstraints(TreePattern
&TP
, bool NotRegisters
) {
2310 CodeGenDAGPatterns
&CDP
= TP
.getDAGPatterns();
2312 if (DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue())) {
2313 // If it's a regclass or something else known, include the type.
2314 bool MadeChange
= false;
2315 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
)
2316 MadeChange
|= UpdateNodeType(i
, getImplicitType(DI
->getDef(), i
,
2318 !hasName(), TP
), TP
);
2322 if (IntInit
*II
= dyn_cast
<IntInit
>(getLeafValue())) {
2323 assert(Types
.size() == 1 && "Invalid IntInit");
2325 // Int inits are always integers. :)
2326 bool MadeChange
= TP
.getInfer().EnforceInteger(Types
[0]);
2328 if (!TP
.getInfer().isConcrete(Types
[0], false))
2331 ValueTypeByHwMode VVT
= TP
.getInfer().getConcrete(Types
[0], false);
2332 for (auto &P
: VVT
) {
2333 MVT::SimpleValueType VT
= P
.second
.SimpleTy
;
2334 if (VT
== MVT::iPTR
|| VT
== MVT::iPTRAny
)
2336 unsigned Size
= MVT(VT
).getSizeInBits();
2337 // Make sure that the value is representable for this type.
2340 // Check that the value doesn't use more bits than we have. It must
2341 // either be a sign- or zero-extended equivalent of the original.
2342 int64_t SignBitAndAbove
= II
->getValue() >> (Size
- 1);
2343 if (SignBitAndAbove
== -1 || SignBitAndAbove
== 0 ||
2344 SignBitAndAbove
== 1)
2347 TP
.error("Integer value '" + Twine(II
->getValue()) +
2348 "' is out of range for type '" + getEnumName(VT
) + "'!");
2357 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CDP
)) {
2358 bool MadeChange
= false;
2360 // Apply the result type to the node.
2361 unsigned NumRetVTs
= Int
->IS
.RetVTs
.size();
2362 unsigned NumParamVTs
= Int
->IS
.ParamVTs
.size();
2364 for (unsigned i
= 0, e
= NumRetVTs
; i
!= e
; ++i
)
2365 MadeChange
|= UpdateNodeType(i
, Int
->IS
.RetVTs
[i
], TP
);
2367 if (getNumChildren() != NumParamVTs
+ 1) {
2368 TP
.error("Intrinsic '" + Int
->Name
+ "' expects " + Twine(NumParamVTs
) +
2369 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2373 // Apply type info to the intrinsic ID.
2374 MadeChange
|= getChild(0)->UpdateNodeType(0, MVT::iPTR
, TP
);
2376 for (unsigned i
= 0, e
= getNumChildren()-1; i
!= e
; ++i
) {
2377 MadeChange
|= getChild(i
+1)->ApplyTypeConstraints(TP
, NotRegisters
);
2379 MVT::SimpleValueType OpVT
= Int
->IS
.ParamVTs
[i
];
2380 assert(getChild(i
+1)->getNumTypes() == 1 && "Unhandled case");
2381 MadeChange
|= getChild(i
+1)->UpdateNodeType(0, OpVT
, TP
);
2386 if (getOperator()->isSubClassOf("SDNode")) {
2387 const SDNodeInfo
&NI
= CDP
.getSDNodeInfo(getOperator());
2389 // Check that the number of operands is sane. Negative operands -> varargs.
2390 if (NI
.getNumOperands() >= 0 &&
2391 getNumChildren() != (unsigned)NI
.getNumOperands()) {
2392 TP
.error(getOperator()->getName() + " node requires exactly " +
2393 Twine(NI
.getNumOperands()) + " operands!");
2397 bool MadeChange
= false;
2398 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2399 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2400 MadeChange
|= NI
.ApplyTypeConstraints(this, TP
);
2404 if (getOperator()->isSubClassOf("Instruction")) {
2405 const DAGInstruction
&Inst
= CDP
.getInstruction(getOperator());
2406 CodeGenInstruction
&InstInfo
=
2407 CDP
.getTargetInfo().getInstruction(getOperator());
2409 bool MadeChange
= false;
2411 // Apply the result types to the node, these come from the things in the
2412 // (outs) list of the instruction.
2413 unsigned NumResultsToAdd
= std::min(InstInfo
.Operands
.NumDefs
,
2414 Inst
.getNumResults());
2415 for (unsigned ResNo
= 0; ResNo
!= NumResultsToAdd
; ++ResNo
)
2416 MadeChange
|= UpdateNodeTypeFromInst(ResNo
, Inst
.getResult(ResNo
), TP
);
2418 // If the instruction has implicit defs, we apply the first one as a result.
2419 // FIXME: This sucks, it should apply all implicit defs.
2420 if (!InstInfo
.ImplicitDefs
.empty()) {
2421 unsigned ResNo
= NumResultsToAdd
;
2423 // FIXME: Generalize to multiple possible types and multiple possible
2425 MVT::SimpleValueType VT
=
2426 InstInfo
.HasOneImplicitDefWithKnownVT(CDP
.getTargetInfo());
2428 if (VT
!= MVT::Other
)
2429 MadeChange
|= UpdateNodeType(ResNo
, VT
, TP
);
2432 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2434 if (getOperator()->getName() == "INSERT_SUBREG") {
2435 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2436 MadeChange
|= UpdateNodeType(0, getChild(0)->getExtType(0), TP
);
2437 MadeChange
|= getChild(0)->UpdateNodeType(0, getExtType(0), TP
);
2438 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2439 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2442 unsigned NChild
= getNumChildren();
2444 TP
.error("REG_SEQUENCE requires at least 3 operands!");
2448 if (NChild
% 2 == 0) {
2449 TP
.error("REG_SEQUENCE requires an odd number of operands!");
2453 if (!isOperandClass(getChild(0), "RegisterClass")) {
2454 TP
.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2458 for (unsigned I
= 1; I
< NChild
; I
+= 2) {
2459 TreePatternNode
*SubIdxChild
= getChild(I
+ 1);
2460 if (!isOperandClass(SubIdxChild
, "SubRegIndex")) {
2461 TP
.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2462 Twine(I
+ 1) + "!");
2468 // If one or more operands with a default value appear at the end of the
2469 // formal operand list for an instruction, we allow them to be overridden
2470 // by optional operands provided in the pattern.
2472 // But if an operand B without a default appears at any point after an
2473 // operand A with a default, then we don't allow A to be overridden,
2474 // because there would be no way to specify whether the next operand in
2475 // the pattern was intended to override A or skip it.
2476 unsigned NonOverridableOperands
= Inst
.getNumOperands();
2477 while (NonOverridableOperands
> 0 &&
2478 CDP
.operandHasDefault(Inst
.getOperand(NonOverridableOperands
-1)))
2479 --NonOverridableOperands
;
2481 unsigned ChildNo
= 0;
2482 for (unsigned i
= 0, e
= Inst
.getNumOperands(); i
!= e
; ++i
) {
2483 Record
*OperandNode
= Inst
.getOperand(i
);
2485 // If the operand has a default value, do we use it? We must use the
2486 // default if we've run out of children of the pattern DAG to consume,
2487 // or if the operand is followed by a non-defaulted one.
2488 if (CDP
.operandHasDefault(OperandNode
) &&
2489 (i
< NonOverridableOperands
|| ChildNo
>= getNumChildren()))
2492 // If we have run out of child nodes and there _isn't_ a default
2493 // value we can use for the next operand, give an error.
2494 if (ChildNo
>= getNumChildren()) {
2495 emitTooFewOperandsError(TP
, getOperator()->getName(), getNumChildren());
2499 TreePatternNode
*Child
= getChild(ChildNo
++);
2500 unsigned ChildResNo
= 0; // Instructions always use res #0 of their op.
2502 // If the operand has sub-operands, they may be provided by distinct
2503 // child patterns, so attempt to match each sub-operand separately.
2504 if (OperandNode
->isSubClassOf("Operand")) {
2505 DagInit
*MIOpInfo
= OperandNode
->getValueAsDag("MIOperandInfo");
2506 if (unsigned NumArgs
= MIOpInfo
->getNumArgs()) {
2507 // But don't do that if the whole operand is being provided by
2508 // a single ComplexPattern-related Operand.
2510 if (Child
->getNumMIResults(CDP
) < NumArgs
) {
2511 // Match first sub-operand against the child we already have.
2512 Record
*SubRec
= cast
<DefInit
>(MIOpInfo
->getArg(0))->getDef();
2514 Child
->UpdateNodeTypeFromInst(ChildResNo
, SubRec
, TP
);
2516 // And the remaining sub-operands against subsequent children.
2517 for (unsigned Arg
= 1; Arg
< NumArgs
; ++Arg
) {
2518 if (ChildNo
>= getNumChildren()) {
2519 emitTooFewOperandsError(TP
, getOperator()->getName(),
2523 Child
= getChild(ChildNo
++);
2525 SubRec
= cast
<DefInit
>(MIOpInfo
->getArg(Arg
))->getDef();
2527 Child
->UpdateNodeTypeFromInst(ChildResNo
, SubRec
, TP
);
2534 // If we didn't match by pieces above, attempt to match the whole
2536 MadeChange
|= Child
->UpdateNodeTypeFromInst(ChildResNo
, OperandNode
, TP
);
2539 if (!InstInfo
.Operands
.isVariadic
&& ChildNo
!= getNumChildren()) {
2540 emitTooManyOperandsError(TP
, getOperator()->getName(),
2541 ChildNo
, getNumChildren());
2545 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2546 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2550 if (getOperator()->isSubClassOf("ComplexPattern")) {
2551 bool MadeChange
= false;
2553 for (unsigned i
= 0; i
< getNumChildren(); ++i
)
2554 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2559 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2561 // Node transforms always take one operand.
2562 if (getNumChildren() != 1) {
2563 TP
.error("Node transform '" + getOperator()->getName() +
2564 "' requires one operand!");
2568 bool MadeChange
= getChild(0)->ApplyTypeConstraints(TP
, NotRegisters
);
2572 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2573 /// RHS of a commutative operation, not the on LHS.
2574 static bool OnlyOnRHSOfCommutative(TreePatternNode
*N
) {
2575 if (!N
->isLeaf() && N
->getOperator()->getName() == "imm")
2577 if (N
->isLeaf() && isa
<IntInit
>(N
->getLeafValue()))
2583 /// canPatternMatch - If it is impossible for this pattern to match on this
2584 /// target, fill in Reason and return false. Otherwise, return true. This is
2585 /// used as a sanity check for .td files (to prevent people from writing stuff
2586 /// that can never possibly work), and to prevent the pattern permuter from
2587 /// generating stuff that is useless.
2588 bool TreePatternNode::canPatternMatch(std::string
&Reason
,
2589 const CodeGenDAGPatterns
&CDP
) {
2590 if (isLeaf()) return true;
2592 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2593 if (!getChild(i
)->canPatternMatch(Reason
, CDP
))
2596 // If this is an intrinsic, handle cases that would make it not match. For
2597 // example, if an operand is required to be an immediate.
2598 if (getOperator()->isSubClassOf("Intrinsic")) {
2603 if (getOperator()->isSubClassOf("ComplexPattern"))
2606 // If this node is a commutative operator, check that the LHS isn't an
2608 const SDNodeInfo
&NodeInfo
= CDP
.getSDNodeInfo(getOperator());
2609 bool isCommIntrinsic
= isCommutativeIntrinsic(CDP
);
2610 if (NodeInfo
.hasProperty(SDNPCommutative
) || isCommIntrinsic
) {
2611 // Scan all of the operands of the node and make sure that only the last one
2612 // is a constant node, unless the RHS also is.
2613 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2614 unsigned Skip
= isCommIntrinsic
? 1 : 0; // First operand is intrinsic id.
2615 for (unsigned i
= Skip
, e
= getNumChildren()-1; i
!= e
; ++i
)
2616 if (OnlyOnRHSOfCommutative(getChild(i
))) {
2617 Reason
="Immediate value must be on the RHS of commutative operators!";
2626 //===----------------------------------------------------------------------===//
2627 // TreePattern implementation
2630 TreePattern::TreePattern(Record
*TheRec
, ListInit
*RawPat
, bool isInput
,
2631 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
),
2632 isInputPattern(isInput
), HasError(false),
2634 for (Init
*I
: RawPat
->getValues())
2635 Trees
.push_back(ParseTreePattern(I
, ""));
2638 TreePattern::TreePattern(Record
*TheRec
, DagInit
*Pat
, bool isInput
,
2639 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
),
2640 isInputPattern(isInput
), HasError(false),
2642 Trees
.push_back(ParseTreePattern(Pat
, ""));
2645 TreePattern::TreePattern(Record
*TheRec
, TreePatternNodePtr Pat
, bool isInput
,
2646 CodeGenDAGPatterns
&cdp
)
2647 : TheRecord(TheRec
), CDP(cdp
), isInputPattern(isInput
), HasError(false),
2649 Trees
.push_back(Pat
);
2652 void TreePattern::error(const Twine
&Msg
) {
2656 PrintError(TheRecord
->getLoc(), "In " + TheRecord
->getName() + ": " + Msg
);
2660 void TreePattern::ComputeNamedNodes() {
2661 for (TreePatternNodePtr
&Tree
: Trees
)
2662 ComputeNamedNodes(Tree
.get());
2665 void TreePattern::ComputeNamedNodes(TreePatternNode
*N
) {
2666 if (!N
->getName().empty())
2667 NamedNodes
[N
->getName()].push_back(N
);
2669 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
2670 ComputeNamedNodes(N
->getChild(i
));
2673 TreePatternNodePtr
TreePattern::ParseTreePattern(Init
*TheInit
,
2675 if (DefInit
*DI
= dyn_cast
<DefInit
>(TheInit
)) {
2676 Record
*R
= DI
->getDef();
2678 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2679 // TreePatternNode of its own. For example:
2680 /// (foo GPR, imm) -> (foo GPR, (imm))
2681 if (R
->isSubClassOf("SDNode") || R
->isSubClassOf("PatFrags"))
2682 return ParseTreePattern(
2683 DagInit::get(DI
, nullptr,
2684 std::vector
<std::pair
<Init
*, StringInit
*> >()),
2688 TreePatternNodePtr Res
= std::make_shared
<TreePatternNode
>(DI
, 1);
2689 if (R
->getName() == "node" && !OpName
.empty()) {
2691 error("'node' argument requires a name to match with operand list");
2692 Args
.push_back(OpName
);
2695 Res
->setName(OpName
);
2699 // ?:$name or just $name.
2700 if (isa
<UnsetInit
>(TheInit
)) {
2702 error("'?' argument requires a name to match with operand list");
2703 TreePatternNodePtr Res
= std::make_shared
<TreePatternNode
>(TheInit
, 1);
2704 Args
.push_back(OpName
);
2705 Res
->setName(OpName
);
2709 if (isa
<IntInit
>(TheInit
) || isa
<BitInit
>(TheInit
)) {
2710 if (!OpName
.empty())
2711 error("Constant int or bit argument should not have a name!");
2712 if (isa
<BitInit
>(TheInit
))
2713 TheInit
= TheInit
->convertInitializerTo(IntRecTy::get());
2714 return std::make_shared
<TreePatternNode
>(TheInit
, 1);
2717 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(TheInit
)) {
2718 // Turn this into an IntInit.
2719 Init
*II
= BI
->convertInitializerTo(IntRecTy::get());
2720 if (!II
|| !isa
<IntInit
>(II
))
2721 error("Bits value must be constants!");
2722 return ParseTreePattern(II
, OpName
);
2725 DagInit
*Dag
= dyn_cast
<DagInit
>(TheInit
);
2727 TheInit
->print(errs());
2728 error("Pattern has unexpected init kind!");
2730 DefInit
*OpDef
= dyn_cast
<DefInit
>(Dag
->getOperator());
2731 if (!OpDef
) error("Pattern has unexpected operator type!");
2732 Record
*Operator
= OpDef
->getDef();
2734 if (Operator
->isSubClassOf("ValueType")) {
2735 // If the operator is a ValueType, then this must be "type cast" of a leaf
2737 if (Dag
->getNumArgs() != 1)
2738 error("Type cast only takes one operand!");
2740 TreePatternNodePtr New
=
2741 ParseTreePattern(Dag
->getArg(0), Dag
->getArgNameStr(0));
2743 // Apply the type cast.
2744 assert(New
->getNumTypes() == 1 && "FIXME: Unhandled");
2745 const CodeGenHwModes
&CGH
= getDAGPatterns().getTargetInfo().getHwModes();
2746 New
->UpdateNodeType(0, getValueTypeByHwMode(Operator
, CGH
), *this);
2748 if (!OpName
.empty())
2749 error("ValueType cast should not have a name!");
2753 // Verify that this is something that makes sense for an operator.
2754 if (!Operator
->isSubClassOf("PatFrags") &&
2755 !Operator
->isSubClassOf("SDNode") &&
2756 !Operator
->isSubClassOf("Instruction") &&
2757 !Operator
->isSubClassOf("SDNodeXForm") &&
2758 !Operator
->isSubClassOf("Intrinsic") &&
2759 !Operator
->isSubClassOf("ComplexPattern") &&
2760 Operator
->getName() != "set" &&
2761 Operator
->getName() != "implicit")
2762 error("Unrecognized node '" + Operator
->getName() + "'!");
2764 // Check to see if this is something that is illegal in an input pattern.
2765 if (isInputPattern
) {
2766 if (Operator
->isSubClassOf("Instruction") ||
2767 Operator
->isSubClassOf("SDNodeXForm"))
2768 error("Cannot use '" + Operator
->getName() + "' in an input pattern!");
2770 if (Operator
->isSubClassOf("Intrinsic"))
2771 error("Cannot use '" + Operator
->getName() + "' in an output pattern!");
2773 if (Operator
->isSubClassOf("SDNode") &&
2774 Operator
->getName() != "imm" &&
2775 Operator
->getName() != "fpimm" &&
2776 Operator
->getName() != "tglobaltlsaddr" &&
2777 Operator
->getName() != "tconstpool" &&
2778 Operator
->getName() != "tjumptable" &&
2779 Operator
->getName() != "tframeindex" &&
2780 Operator
->getName() != "texternalsym" &&
2781 Operator
->getName() != "tblockaddress" &&
2782 Operator
->getName() != "tglobaladdr" &&
2783 Operator
->getName() != "bb" &&
2784 Operator
->getName() != "vt" &&
2785 Operator
->getName() != "mcsym")
2786 error("Cannot use '" + Operator
->getName() + "' in an output pattern!");
2789 std::vector
<TreePatternNodePtr
> Children
;
2791 // Parse all the operands.
2792 for (unsigned i
= 0, e
= Dag
->getNumArgs(); i
!= e
; ++i
)
2793 Children
.push_back(ParseTreePattern(Dag
->getArg(i
), Dag
->getArgNameStr(i
)));
2795 // Get the actual number of results before Operator is converted to an intrinsic
2796 // node (which is hard-coded to have either zero or one result).
2797 unsigned NumResults
= GetNumNodeResults(Operator
, CDP
);
2799 // If the operator is an intrinsic, then this is just syntactic sugar for
2800 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2801 // convert the intrinsic name to a number.
2802 if (Operator
->isSubClassOf("Intrinsic")) {
2803 const CodeGenIntrinsic
&Int
= getDAGPatterns().getIntrinsic(Operator
);
2804 unsigned IID
= getDAGPatterns().getIntrinsicID(Operator
)+1;
2806 // If this intrinsic returns void, it must have side-effects and thus a
2808 if (Int
.IS
.RetVTs
.empty())
2809 Operator
= getDAGPatterns().get_intrinsic_void_sdnode();
2810 else if (Int
.ModRef
!= CodeGenIntrinsic::NoMem
|| Int
.hasSideEffects
)
2811 // Has side-effects, requires chain.
2812 Operator
= getDAGPatterns().get_intrinsic_w_chain_sdnode();
2813 else // Otherwise, no chain.
2814 Operator
= getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2816 Children
.insert(Children
.begin(),
2817 std::make_shared
<TreePatternNode
>(IntInit::get(IID
), 1));
2820 if (Operator
->isSubClassOf("ComplexPattern")) {
2821 for (unsigned i
= 0; i
< Children
.size(); ++i
) {
2822 TreePatternNodePtr Child
= Children
[i
];
2824 if (Child
->getName().empty())
2825 error("All arguments to a ComplexPattern must be named");
2827 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2828 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2829 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2830 auto OperandId
= std::make_pair(Operator
, i
);
2831 auto PrevOp
= ComplexPatternOperands
.find(Child
->getName());
2832 if (PrevOp
!= ComplexPatternOperands
.end()) {
2833 if (PrevOp
->getValue() != OperandId
)
2834 error("All ComplexPattern operands must appear consistently: "
2835 "in the same order in just one ComplexPattern instance.");
2837 ComplexPatternOperands
[Child
->getName()] = OperandId
;
2841 TreePatternNodePtr Result
=
2842 std::make_shared
<TreePatternNode
>(Operator
, std::move(Children
),
2844 Result
->setName(OpName
);
2846 if (Dag
->getName()) {
2847 assert(Result
->getName().empty());
2848 Result
->setName(Dag
->getNameStr());
2853 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2854 /// will never match in favor of something obvious that will. This is here
2855 /// strictly as a convenience to target authors because it allows them to write
2856 /// more type generic things and have useless type casts fold away.
2858 /// This returns true if any change is made.
2859 static bool SimplifyTree(TreePatternNodePtr
&N
) {
2863 // If we have a bitconvert with a resolved type and if the source and
2864 // destination types are the same, then the bitconvert is useless, remove it.
2865 if (N
->getOperator()->getName() == "bitconvert" &&
2866 N
->getExtType(0).isValueTypeByHwMode(false) &&
2867 N
->getExtType(0) == N
->getChild(0)->getExtType(0) &&
2868 N
->getName().empty()) {
2869 N
= N
->getChildShared(0);
2874 // Walk all children.
2875 bool MadeChange
= false;
2876 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
2877 TreePatternNodePtr Child
= N
->getChildShared(i
);
2878 MadeChange
|= SimplifyTree(Child
);
2879 N
->setChild(i
, std::move(Child
));
2886 /// InferAllTypes - Infer/propagate as many types throughout the expression
2887 /// patterns as possible. Return true if all types are inferred, false
2888 /// otherwise. Flags an error if a type contradiction is found.
2890 InferAllTypes(const StringMap
<SmallVector
<TreePatternNode
*,1> > *InNamedTypes
) {
2891 if (NamedNodes
.empty())
2892 ComputeNamedNodes();
2894 bool MadeChange
= true;
2895 while (MadeChange
) {
2897 for (TreePatternNodePtr
&Tree
: Trees
) {
2898 MadeChange
|= Tree
->ApplyTypeConstraints(*this, false);
2899 MadeChange
|= SimplifyTree(Tree
);
2902 // If there are constraints on our named nodes, apply them.
2903 for (auto &Entry
: NamedNodes
) {
2904 SmallVectorImpl
<TreePatternNode
*> &Nodes
= Entry
.second
;
2906 // If we have input named node types, propagate their types to the named
2909 if (!InNamedTypes
->count(Entry
.getKey())) {
2910 error("Node '" + std::string(Entry
.getKey()) +
2911 "' in output pattern but not input pattern");
2915 const SmallVectorImpl
<TreePatternNode
*> &InNodes
=
2916 InNamedTypes
->find(Entry
.getKey())->second
;
2918 // The input types should be fully resolved by now.
2919 for (TreePatternNode
*Node
: Nodes
) {
2920 // If this node is a register class, and it is the root of the pattern
2921 // then we're mapping something onto an input register. We allow
2922 // changing the type of the input register in this case. This allows
2923 // us to match things like:
2924 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2925 if (Node
== Trees
[0].get() && Node
->isLeaf()) {
2926 DefInit
*DI
= dyn_cast
<DefInit
>(Node
->getLeafValue());
2927 if (DI
&& (DI
->getDef()->isSubClassOf("RegisterClass") ||
2928 DI
->getDef()->isSubClassOf("RegisterOperand")))
2932 assert(Node
->getNumTypes() == 1 &&
2933 InNodes
[0]->getNumTypes() == 1 &&
2934 "FIXME: cannot name multiple result nodes yet");
2935 MadeChange
|= Node
->UpdateNodeType(0, InNodes
[0]->getExtType(0),
2940 // If there are multiple nodes with the same name, they must all have the
2942 if (Entry
.second
.size() > 1) {
2943 for (unsigned i
= 0, e
= Nodes
.size()-1; i
!= e
; ++i
) {
2944 TreePatternNode
*N1
= Nodes
[i
], *N2
= Nodes
[i
+1];
2945 assert(N1
->getNumTypes() == 1 && N2
->getNumTypes() == 1 &&
2946 "FIXME: cannot name multiple result nodes yet");
2948 MadeChange
|= N1
->UpdateNodeType(0, N2
->getExtType(0), *this);
2949 MadeChange
|= N2
->UpdateNodeType(0, N1
->getExtType(0), *this);
2955 bool HasUnresolvedTypes
= false;
2956 for (const TreePatternNodePtr
&Tree
: Trees
)
2957 HasUnresolvedTypes
|= Tree
->ContainsUnresolvedType(*this);
2958 return !HasUnresolvedTypes
;
2961 void TreePattern::print(raw_ostream
&OS
) const {
2962 OS
<< getRecord()->getName();
2963 if (!Args
.empty()) {
2964 OS
<< "(" << Args
[0];
2965 for (unsigned i
= 1, e
= Args
.size(); i
!= e
; ++i
)
2966 OS
<< ", " << Args
[i
];
2971 if (Trees
.size() > 1)
2973 for (const TreePatternNodePtr
&Tree
: Trees
) {
2979 if (Trees
.size() > 1)
2983 void TreePattern::dump() const { print(errs()); }
2985 //===----------------------------------------------------------------------===//
2986 // CodeGenDAGPatterns implementation
2989 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper
&R
,
2990 PatternRewriterFn PatternRewriter
)
2991 : Records(R
), Target(R
), LegalVTS(Target
.getLegalValueTypes()),
2992 PatternRewriter(PatternRewriter
) {
2994 Intrinsics
= CodeGenIntrinsicTable(Records
, false);
2995 TgtIntrinsics
= CodeGenIntrinsicTable(Records
, true);
2997 ParseNodeTransforms();
2998 ParseComplexPatterns();
2999 ParsePatternFragments();
3000 ParseDefaultOperands();
3001 ParseInstructions();
3002 ParsePatternFragments(/*OutFrags*/true);
3005 // Break patterns with parameterized types into a series of patterns,
3006 // where each one has a fixed type and is predicated on the conditions
3007 // of the associated HW mode.
3008 ExpandHwModeBasedTypes();
3010 // Generate variants. For example, commutative patterns can match
3011 // multiple ways. Add them to PatternsToMatch as well.
3014 // Infer instruction flags. For example, we can detect loads,
3015 // stores, and side effects in many cases by examining an
3016 // instruction's pattern.
3017 InferInstructionFlags();
3019 // Verify that instruction flags match the patterns.
3020 VerifyInstructionFlags();
3023 Record
*CodeGenDAGPatterns::getSDNodeNamed(const std::string
&Name
) const {
3024 Record
*N
= Records
.getDef(Name
);
3025 if (!N
|| !N
->isSubClassOf("SDNode"))
3026 PrintFatalError("Error getting SDNode '" + Name
+ "'!");
3031 // Parse all of the SDNode definitions for the target, populating SDNodes.
3032 void CodeGenDAGPatterns::ParseNodeInfo() {
3033 std::vector
<Record
*> Nodes
= Records
.getAllDerivedDefinitions("SDNode");
3034 const CodeGenHwModes
&CGH
= getTargetInfo().getHwModes();
3036 while (!Nodes
.empty()) {
3037 Record
*R
= Nodes
.back();
3038 SDNodes
.insert(std::make_pair(R
, SDNodeInfo(R
, CGH
)));
3042 // Get the builtin intrinsic nodes.
3043 intrinsic_void_sdnode
= getSDNodeNamed("intrinsic_void");
3044 intrinsic_w_chain_sdnode
= getSDNodeNamed("intrinsic_w_chain");
3045 intrinsic_wo_chain_sdnode
= getSDNodeNamed("intrinsic_wo_chain");
3048 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3049 /// map, and emit them to the file as functions.
3050 void CodeGenDAGPatterns::ParseNodeTransforms() {
3051 std::vector
<Record
*> Xforms
= Records
.getAllDerivedDefinitions("SDNodeXForm");
3052 while (!Xforms
.empty()) {
3053 Record
*XFormNode
= Xforms
.back();
3054 Record
*SDNode
= XFormNode
->getValueAsDef("Opcode");
3055 StringRef Code
= XFormNode
->getValueAsString("XFormFunction");
3056 SDNodeXForms
.insert(std::make_pair(XFormNode
, NodeXForm(SDNode
, Code
)));
3062 void CodeGenDAGPatterns::ParseComplexPatterns() {
3063 std::vector
<Record
*> AMs
= Records
.getAllDerivedDefinitions("ComplexPattern");
3064 while (!AMs
.empty()) {
3065 ComplexPatterns
.insert(std::make_pair(AMs
.back(), AMs
.back()));
3071 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3072 /// file, building up the PatternFragments map. After we've collected them all,
3073 /// inline fragments together as necessary, so that there are no references left
3074 /// inside a pattern fragment to a pattern fragment.
3076 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags
) {
3077 std::vector
<Record
*> Fragments
= Records
.getAllDerivedDefinitions("PatFrags");
3079 // First step, parse all of the fragments.
3080 for (Record
*Frag
: Fragments
) {
3081 if (OutFrags
!= Frag
->isSubClassOf("OutPatFrag"))
3084 ListInit
*LI
= Frag
->getValueAsListInit("Fragments");
3086 (PatternFragments
[Frag
] = llvm::make_unique
<TreePattern
>(
3087 Frag
, LI
, !Frag
->isSubClassOf("OutPatFrag"),
3090 // Validate the argument list, converting it to set, to discard duplicates.
3091 std::vector
<std::string
> &Args
= P
->getArgList();
3092 // Copy the args so we can take StringRefs to them.
3093 auto ArgsCopy
= Args
;
3094 SmallDenseSet
<StringRef
, 4> OperandsSet
;
3095 OperandsSet
.insert(ArgsCopy
.begin(), ArgsCopy
.end());
3097 if (OperandsSet
.count(""))
3098 P
->error("Cannot have unnamed 'node' values in pattern fragment!");
3100 // Parse the operands list.
3101 DagInit
*OpsList
= Frag
->getValueAsDag("Operands");
3102 DefInit
*OpsOp
= dyn_cast
<DefInit
>(OpsList
->getOperator());
3103 // Special cases: ops == outs == ins. Different names are used to
3104 // improve readability.
3106 (OpsOp
->getDef()->getName() != "ops" &&
3107 OpsOp
->getDef()->getName() != "outs" &&
3108 OpsOp
->getDef()->getName() != "ins"))
3109 P
->error("Operands list should start with '(ops ... '!");
3111 // Copy over the arguments.
3113 for (unsigned j
= 0, e
= OpsList
->getNumArgs(); j
!= e
; ++j
) {
3114 if (!isa
<DefInit
>(OpsList
->getArg(j
)) ||
3115 cast
<DefInit
>(OpsList
->getArg(j
))->getDef()->getName() != "node")
3116 P
->error("Operands list should all be 'node' values.");
3117 if (!OpsList
->getArgName(j
))
3118 P
->error("Operands list should have names for each operand!");
3119 StringRef ArgNameStr
= OpsList
->getArgNameStr(j
);
3120 if (!OperandsSet
.count(ArgNameStr
))
3121 P
->error("'" + ArgNameStr
+
3122 "' does not occur in pattern or was multiply specified!");
3123 OperandsSet
.erase(ArgNameStr
);
3124 Args
.push_back(ArgNameStr
);
3127 if (!OperandsSet
.empty())
3128 P
->error("Operands list does not contain an entry for operand '" +
3129 *OperandsSet
.begin() + "'!");
3131 // If there is a node transformation corresponding to this, keep track of
3133 Record
*Transform
= Frag
->getValueAsDef("OperandTransform");
3134 if (!getSDNodeTransform(Transform
).second
.empty()) // not noop xform?
3135 for (auto T
: P
->getTrees())
3136 T
->setTransformFn(Transform
);
3139 // Now that we've parsed all of the tree fragments, do a closure on them so
3140 // that there are not references to PatFrags left inside of them.
3141 for (Record
*Frag
: Fragments
) {
3142 if (OutFrags
!= Frag
->isSubClassOf("OutPatFrag"))
3145 TreePattern
&ThePat
= *PatternFragments
[Frag
];
3146 ThePat
.InlinePatternFragments();
3148 // Infer as many types as possible. Don't worry about it if we don't infer
3149 // all of them, some may depend on the inputs of the pattern. Also, don't
3150 // validate type sets; validation may cause spurious failures e.g. if a
3151 // fragment needs floating-point types but the current target does not have
3152 // any (this is only an error if that fragment is ever used!).
3154 TypeInfer::SuppressValidation
SV(ThePat
.getInfer());
3155 ThePat
.InferAllTypes();
3156 ThePat
.resetError();
3159 // If debugging, print out the pattern fragment result.
3160 LLVM_DEBUG(ThePat
.dump());
3164 void CodeGenDAGPatterns::ParseDefaultOperands() {
3165 std::vector
<Record
*> DefaultOps
;
3166 DefaultOps
= Records
.getAllDerivedDefinitions("OperandWithDefaultOps");
3168 // Find some SDNode.
3169 assert(!SDNodes
.empty() && "No SDNodes parsed?");
3170 Init
*SomeSDNode
= DefInit::get(SDNodes
.begin()->first
);
3172 for (unsigned i
= 0, e
= DefaultOps
.size(); i
!= e
; ++i
) {
3173 DagInit
*DefaultInfo
= DefaultOps
[i
]->getValueAsDag("DefaultOps");
3175 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3176 // SomeSDnode so that we can parse this.
3177 std::vector
<std::pair
<Init
*, StringInit
*> > Ops
;
3178 for (unsigned op
= 0, e
= DefaultInfo
->getNumArgs(); op
!= e
; ++op
)
3179 Ops
.push_back(std::make_pair(DefaultInfo
->getArg(op
),
3180 DefaultInfo
->getArgName(op
)));
3181 DagInit
*DI
= DagInit::get(SomeSDNode
, nullptr, Ops
);
3183 // Create a TreePattern to parse this.
3184 TreePattern
P(DefaultOps
[i
], DI
, false, *this);
3185 assert(P
.getNumTrees() == 1 && "This ctor can only produce one tree!");
3187 // Copy the operands over into a DAGDefaultOperand.
3188 DAGDefaultOperand DefaultOpInfo
;
3190 const TreePatternNodePtr
&T
= P
.getTree(0);
3191 for (unsigned op
= 0, e
= T
->getNumChildren(); op
!= e
; ++op
) {
3192 TreePatternNodePtr TPN
= T
->getChildShared(op
);
3193 while (TPN
->ApplyTypeConstraints(P
, false))
3194 /* Resolve all types */;
3196 if (TPN
->ContainsUnresolvedType(P
)) {
3197 PrintFatalError("Value #" + Twine(i
) + " of OperandWithDefaultOps '" +
3198 DefaultOps
[i
]->getName() +
3199 "' doesn't have a concrete type!");
3201 DefaultOpInfo
.DefaultOps
.push_back(std::move(TPN
));
3204 // Insert it into the DefaultOperands map so we can find it later.
3205 DefaultOperands
[DefaultOps
[i
]] = DefaultOpInfo
;
3209 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3210 /// instruction input. Return true if this is a real use.
3211 static bool HandleUse(TreePattern
&I
, TreePatternNodePtr Pat
,
3212 std::map
<std::string
, TreePatternNodePtr
> &InstInputs
) {
3213 // No name -> not interesting.
3214 if (Pat
->getName().empty()) {
3215 if (Pat
->isLeaf()) {
3216 DefInit
*DI
= dyn_cast
<DefInit
>(Pat
->getLeafValue());
3217 if (DI
&& (DI
->getDef()->isSubClassOf("RegisterClass") ||
3218 DI
->getDef()->isSubClassOf("RegisterOperand")))
3219 I
.error("Input " + DI
->getDef()->getName() + " must be named!");
3225 if (Pat
->isLeaf()) {
3226 DefInit
*DI
= dyn_cast
<DefInit
>(Pat
->getLeafValue());
3228 I
.error("Input $" + Pat
->getName() + " must be an identifier!");
3231 Rec
= Pat
->getOperator();
3234 // SRCVALUE nodes are ignored.
3235 if (Rec
->getName() == "srcvalue")
3238 TreePatternNodePtr
&Slot
= InstInputs
[Pat
->getName()];
3244 if (Slot
->isLeaf()) {
3245 SlotRec
= cast
<DefInit
>(Slot
->getLeafValue())->getDef();
3247 assert(Slot
->getNumChildren() == 0 && "can't be a use with children!");
3248 SlotRec
= Slot
->getOperator();
3251 // Ensure that the inputs agree if we've already seen this input.
3253 I
.error("All $" + Pat
->getName() + " inputs must agree with each other");
3254 // Ensure that the types can agree as well.
3255 Slot
->UpdateNodeType(0, Pat
->getExtType(0), I
);
3256 Pat
->UpdateNodeType(0, Slot
->getExtType(0), I
);
3257 if (Slot
->getExtTypes() != Pat
->getExtTypes())
3258 I
.error("All $" + Pat
->getName() + " inputs must agree with each other");
3262 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3263 /// part of "I", the instruction), computing the set of inputs and outputs of
3264 /// the pattern. Report errors if we see anything naughty.
3265 void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3266 TreePattern
&I
, TreePatternNodePtr Pat
,
3267 std::map
<std::string
, TreePatternNodePtr
> &InstInputs
,
3268 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
3270 std::vector
<Record
*> &InstImpResults
) {
3272 // The instruction pattern still has unresolved fragments. For *named*
3273 // nodes we must resolve those here. This may not result in multiple
3275 if (!Pat
->getName().empty()) {
3276 TreePattern
SrcPattern(I
.getRecord(), Pat
, true, *this);
3277 SrcPattern
.InlinePatternFragments();
3278 SrcPattern
.InferAllTypes();
3279 Pat
= SrcPattern
.getOnlyTree();
3282 if (Pat
->isLeaf()) {
3283 bool isUse
= HandleUse(I
, Pat
, InstInputs
);
3284 if (!isUse
&& Pat
->getTransformFn())
3285 I
.error("Cannot specify a transform function for a non-input value!");
3289 if (Pat
->getOperator()->getName() == "implicit") {
3290 for (unsigned i
= 0, e
= Pat
->getNumChildren(); i
!= e
; ++i
) {
3291 TreePatternNode
*Dest
= Pat
->getChild(i
);
3292 if (!Dest
->isLeaf())
3293 I
.error("implicitly defined value should be a register!");
3295 DefInit
*Val
= dyn_cast
<DefInit
>(Dest
->getLeafValue());
3296 if (!Val
|| !Val
->getDef()->isSubClassOf("Register"))
3297 I
.error("implicitly defined value should be a register!");
3298 InstImpResults
.push_back(Val
->getDef());
3303 if (Pat
->getOperator()->getName() != "set") {
3304 // If this is not a set, verify that the children nodes are not void typed,
3306 for (unsigned i
= 0, e
= Pat
->getNumChildren(); i
!= e
; ++i
) {
3307 if (Pat
->getChild(i
)->getNumTypes() == 0)
3308 I
.error("Cannot have void nodes inside of patterns!");
3309 FindPatternInputsAndOutputs(I
, Pat
->getChildShared(i
), InstInputs
,
3310 InstResults
, InstImpResults
);
3313 // If this is a non-leaf node with no children, treat it basically as if
3314 // it were a leaf. This handles nodes like (imm).
3315 bool isUse
= HandleUse(I
, Pat
, InstInputs
);
3317 if (!isUse
&& Pat
->getTransformFn())
3318 I
.error("Cannot specify a transform function for a non-input value!");
3322 // Otherwise, this is a set, validate and collect instruction results.
3323 if (Pat
->getNumChildren() == 0)
3324 I
.error("set requires operands!");
3326 if (Pat
->getTransformFn())
3327 I
.error("Cannot specify a transform function on a set node!");
3329 // Check the set destinations.
3330 unsigned NumDests
= Pat
->getNumChildren()-1;
3331 for (unsigned i
= 0; i
!= NumDests
; ++i
) {
3332 TreePatternNodePtr Dest
= Pat
->getChildShared(i
);
3333 // For set destinations we also must resolve fragments here.
3334 TreePattern
DestPattern(I
.getRecord(), Dest
, false, *this);
3335 DestPattern
.InlinePatternFragments();
3336 DestPattern
.InferAllTypes();
3337 Dest
= DestPattern
.getOnlyTree();
3339 if (!Dest
->isLeaf())
3340 I
.error("set destination should be a register!");
3342 DefInit
*Val
= dyn_cast
<DefInit
>(Dest
->getLeafValue());
3344 I
.error("set destination should be a register!");
3348 if (Val
->getDef()->isSubClassOf("RegisterClass") ||
3349 Val
->getDef()->isSubClassOf("ValueType") ||
3350 Val
->getDef()->isSubClassOf("RegisterOperand") ||
3351 Val
->getDef()->isSubClassOf("PointerLikeRegClass")) {
3352 if (Dest
->getName().empty())
3353 I
.error("set destination must have a name!");
3354 if (InstResults
.count(Dest
->getName()))
3355 I
.error("cannot set '" + Dest
->getName() + "' multiple times");
3356 InstResults
[Dest
->getName()] = Dest
;
3357 } else if (Val
->getDef()->isSubClassOf("Register")) {
3358 InstImpResults
.push_back(Val
->getDef());
3360 I
.error("set destination should be a register!");
3364 // Verify and collect info from the computation.
3365 FindPatternInputsAndOutputs(I
, Pat
->getChildShared(NumDests
), InstInputs
,
3366 InstResults
, InstImpResults
);
3369 //===----------------------------------------------------------------------===//
3370 // Instruction Analysis
3371 //===----------------------------------------------------------------------===//
3373 class InstAnalyzer
{
3374 const CodeGenDAGPatterns
&CDP
;
3376 bool hasSideEffects
;
3383 InstAnalyzer(const CodeGenDAGPatterns
&cdp
)
3384 : CDP(cdp
), hasSideEffects(false), mayStore(false), mayLoad(false),
3385 isBitcast(false), isVariadic(false), hasChain(false) {}
3387 void Analyze(const PatternToMatch
&Pat
) {
3388 const TreePatternNode
*N
= Pat
.getSrcPattern();
3390 // These properties are detected only on the root node.
3391 isBitcast
= IsNodeBitcast(N
);
3395 bool IsNodeBitcast(const TreePatternNode
*N
) const {
3396 if (hasSideEffects
|| mayLoad
|| mayStore
|| isVariadic
)
3401 if (N
->getNumChildren() != 1 || !N
->getChild(0)->isLeaf())
3404 const SDNodeInfo
&OpInfo
= CDP
.getSDNodeInfo(N
->getOperator());
3405 if (OpInfo
.getNumResults() != 1 || OpInfo
.getNumOperands() != 1)
3407 return OpInfo
.getEnumName() == "ISD::BITCAST";
3411 void AnalyzeNode(const TreePatternNode
*N
) {
3413 if (DefInit
*DI
= dyn_cast
<DefInit
>(N
->getLeafValue())) {
3414 Record
*LeafRec
= DI
->getDef();
3415 // Handle ComplexPattern leaves.
3416 if (LeafRec
->isSubClassOf("ComplexPattern")) {
3417 const ComplexPattern
&CP
= CDP
.getComplexPattern(LeafRec
);
3418 if (CP
.hasProperty(SDNPMayStore
)) mayStore
= true;
3419 if (CP
.hasProperty(SDNPMayLoad
)) mayLoad
= true;
3420 if (CP
.hasProperty(SDNPSideEffect
)) hasSideEffects
= true;
3426 // Analyze children.
3427 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
3428 AnalyzeNode(N
->getChild(i
));
3430 // Notice properties of the node.
3431 if (N
->NodeHasProperty(SDNPMayStore
, CDP
)) mayStore
= true;
3432 if (N
->NodeHasProperty(SDNPMayLoad
, CDP
)) mayLoad
= true;
3433 if (N
->NodeHasProperty(SDNPSideEffect
, CDP
)) hasSideEffects
= true;
3434 if (N
->NodeHasProperty(SDNPVariadic
, CDP
)) isVariadic
= true;
3435 if (N
->NodeHasProperty(SDNPHasChain
, CDP
)) hasChain
= true;
3437 if (const CodeGenIntrinsic
*IntInfo
= N
->getIntrinsicInfo(CDP
)) {
3438 // If this is an intrinsic, analyze it.
3439 if (IntInfo
->ModRef
& CodeGenIntrinsic::MR_Ref
)
3440 mayLoad
= true;// These may load memory.
3442 if (IntInfo
->ModRef
& CodeGenIntrinsic::MR_Mod
)
3443 mayStore
= true;// Intrinsics that can write to memory are 'mayStore'.
3445 if (IntInfo
->ModRef
>= CodeGenIntrinsic::ReadWriteMem
||
3446 IntInfo
->hasSideEffects
)
3447 // ReadWriteMem intrinsics can have other strange effects.
3448 hasSideEffects
= true;
3454 static bool InferFromPattern(CodeGenInstruction
&InstInfo
,
3455 const InstAnalyzer
&PatInfo
,
3459 // Remember where InstInfo got its flags.
3460 if (InstInfo
.hasUndefFlags())
3461 InstInfo
.InferredFrom
= PatDef
;
3463 // Check explicitly set flags for consistency.
3464 if (InstInfo
.hasSideEffects
!= PatInfo
.hasSideEffects
&&
3465 !InstInfo
.hasSideEffects_Unset
) {
3466 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3467 // the pattern has no side effects. That could be useful for div/rem
3468 // instructions that may trap.
3469 if (!InstInfo
.hasSideEffects
) {
3471 PrintError(PatDef
->getLoc(), "Pattern doesn't match hasSideEffects = " +
3472 Twine(InstInfo
.hasSideEffects
));
3476 if (InstInfo
.mayStore
!= PatInfo
.mayStore
&& !InstInfo
.mayStore_Unset
) {
3478 PrintError(PatDef
->getLoc(), "Pattern doesn't match mayStore = " +
3479 Twine(InstInfo
.mayStore
));
3482 if (InstInfo
.mayLoad
!= PatInfo
.mayLoad
&& !InstInfo
.mayLoad_Unset
) {
3483 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3484 // Some targets translate immediates to loads.
3485 if (!InstInfo
.mayLoad
) {
3487 PrintError(PatDef
->getLoc(), "Pattern doesn't match mayLoad = " +
3488 Twine(InstInfo
.mayLoad
));
3492 // Transfer inferred flags.
3493 InstInfo
.hasSideEffects
|= PatInfo
.hasSideEffects
;
3494 InstInfo
.mayStore
|= PatInfo
.mayStore
;
3495 InstInfo
.mayLoad
|= PatInfo
.mayLoad
;
3497 // These flags are silently added without any verification.
3498 // FIXME: To match historical behavior of TableGen, for now add those flags
3499 // only when we're inferring from the primary instruction pattern.
3500 if (PatDef
->isSubClassOf("Instruction")) {
3501 InstInfo
.isBitcast
|= PatInfo
.isBitcast
;
3502 InstInfo
.hasChain
|= PatInfo
.hasChain
;
3503 InstInfo
.hasChain_Inferred
= true;
3506 // Don't infer isVariadic. This flag means something different on SDNodes and
3507 // instructions. For example, a CALL SDNode is variadic because it has the
3508 // call arguments as operands, but a CALL instruction is not variadic - it
3509 // has argument registers as implicit, not explicit uses.
3514 /// hasNullFragReference - Return true if the DAG has any reference to the
3515 /// null_frag operator.
3516 static bool hasNullFragReference(DagInit
*DI
) {
3517 DefInit
*OpDef
= dyn_cast
<DefInit
>(DI
->getOperator());
3518 if (!OpDef
) return false;
3519 Record
*Operator
= OpDef
->getDef();
3521 // If this is the null fragment, return true.
3522 if (Operator
->getName() == "null_frag") return true;
3523 // If any of the arguments reference the null fragment, return true.
3524 for (unsigned i
= 0, e
= DI
->getNumArgs(); i
!= e
; ++i
) {
3525 DagInit
*Arg
= dyn_cast
<DagInit
>(DI
->getArg(i
));
3526 if (Arg
&& hasNullFragReference(Arg
))
3533 /// hasNullFragReference - Return true if any DAG in the list references
3534 /// the null_frag operator.
3535 static bool hasNullFragReference(ListInit
*LI
) {
3536 for (Init
*I
: LI
->getValues()) {
3537 DagInit
*DI
= dyn_cast
<DagInit
>(I
);
3538 assert(DI
&& "non-dag in an instruction Pattern list?!");
3539 if (hasNullFragReference(DI
))
3545 /// Get all the instructions in a tree.
3547 getInstructionsInTree(TreePatternNode
*Tree
, SmallVectorImpl
<Record
*> &Instrs
) {
3550 if (Tree
->getOperator()->isSubClassOf("Instruction"))
3551 Instrs
.push_back(Tree
->getOperator());
3552 for (unsigned i
= 0, e
= Tree
->getNumChildren(); i
!= e
; ++i
)
3553 getInstructionsInTree(Tree
->getChild(i
), Instrs
);
3556 /// Check the class of a pattern leaf node against the instruction operand it
3558 static bool checkOperandClass(CGIOperandList::OperandInfo
&OI
,
3563 // Allow direct value types to be used in instruction set patterns.
3564 // The type will be checked later.
3565 if (Leaf
->isSubClassOf("ValueType"))
3568 // Patterns can also be ComplexPattern instances.
3569 if (Leaf
->isSubClassOf("ComplexPattern"))
3575 void CodeGenDAGPatterns::parseInstructionPattern(
3576 CodeGenInstruction
&CGI
, ListInit
*Pat
, DAGInstMap
&DAGInsts
) {
3578 assert(!DAGInsts
.count(CGI
.TheDef
) && "Instruction already parsed!");
3580 // Parse the instruction.
3581 TreePattern
I(CGI
.TheDef
, Pat
, true, *this);
3583 // InstInputs - Keep track of all of the inputs of the instruction, along
3584 // with the record they are declared as.
3585 std::map
<std::string
, TreePatternNodePtr
> InstInputs
;
3587 // InstResults - Keep track of all the virtual registers that are 'set'
3588 // in the instruction, including what reg class they are.
3589 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
3592 std::vector
<Record
*> InstImpResults
;
3594 // Verify that the top-level forms in the instruction are of void type, and
3595 // fill in the InstResults map.
3596 SmallString
<32> TypesString
;
3597 for (unsigned j
= 0, e
= I
.getNumTrees(); j
!= e
; ++j
) {
3598 TypesString
.clear();
3599 TreePatternNodePtr Pat
= I
.getTree(j
);
3600 if (Pat
->getNumTypes() != 0) {
3601 raw_svector_ostream
OS(TypesString
);
3602 for (unsigned k
= 0, ke
= Pat
->getNumTypes(); k
!= ke
; ++k
) {
3605 Pat
->getExtType(k
).writeToStream(OS
);
3607 I
.error("Top-level forms in instruction pattern should have"
3608 " void types, has types " +
3612 // Find inputs and outputs, and verify the structure of the uses/defs.
3613 FindPatternInputsAndOutputs(I
, Pat
, InstInputs
, InstResults
,
3617 // Now that we have inputs and outputs of the pattern, inspect the operands
3618 // list for the instruction. This determines the order that operands are
3619 // added to the machine instruction the node corresponds to.
3620 unsigned NumResults
= InstResults
.size();
3622 // Parse the operands list from the (ops) list, validating it.
3623 assert(I
.getArgList().empty() && "Args list should still be empty here!");
3625 // Check that all of the results occur first in the list.
3626 std::vector
<Record
*> Results
;
3627 std::vector
<unsigned> ResultIndices
;
3628 SmallVector
<TreePatternNodePtr
, 2> ResNodes
;
3629 for (unsigned i
= 0; i
!= NumResults
; ++i
) {
3630 if (i
== CGI
.Operands
.size()) {
3631 const std::string
&OpName
=
3632 std::find_if(InstResults
.begin(), InstResults
.end(),
3633 [](const std::pair
<std::string
, TreePatternNodePtr
> &P
) {
3638 I
.error("'" + OpName
+ "' set but does not appear in operand list!");
3641 const std::string
&OpName
= CGI
.Operands
[i
].Name
;
3643 // Check that it exists in InstResults.
3644 auto InstResultIter
= InstResults
.find(OpName
);
3645 if (InstResultIter
== InstResults
.end() || !InstResultIter
->second
)
3646 I
.error("Operand $" + OpName
+ " does not exist in operand list!");
3648 TreePatternNodePtr RNode
= InstResultIter
->second
;
3649 Record
*R
= cast
<DefInit
>(RNode
->getLeafValue())->getDef();
3650 ResNodes
.push_back(std::move(RNode
));
3652 I
.error("Operand $" + OpName
+ " should be a set destination: all "
3653 "outputs must occur before inputs in operand list!");
3655 if (!checkOperandClass(CGI
.Operands
[i
], R
))
3656 I
.error("Operand $" + OpName
+ " class mismatch!");
3658 // Remember the return type.
3659 Results
.push_back(CGI
.Operands
[i
].Rec
);
3661 // Remember the result index.
3662 ResultIndices
.push_back(std::distance(InstResults
.begin(), InstResultIter
));
3664 // Okay, this one checks out.
3665 InstResultIter
->second
= nullptr;
3668 // Loop over the inputs next.
3669 std::vector
<TreePatternNodePtr
> ResultNodeOperands
;
3670 std::vector
<Record
*> Operands
;
3671 for (unsigned i
= NumResults
, e
= CGI
.Operands
.size(); i
!= e
; ++i
) {
3672 CGIOperandList::OperandInfo
&Op
= CGI
.Operands
[i
];
3673 const std::string
&OpName
= Op
.Name
;
3675 I
.error("Operand #" + Twine(i
) + " in operands list has no name!");
3677 if (!InstInputs
.count(OpName
)) {
3678 // If this is an operand with a DefaultOps set filled in, we can ignore
3679 // this. When we codegen it, we will do so as always executed.
3680 if (Op
.Rec
->isSubClassOf("OperandWithDefaultOps")) {
3681 // Does it have a non-empty DefaultOps field? If so, ignore this
3683 if (!getDefaultOperand(Op
.Rec
).DefaultOps
.empty())
3686 I
.error("Operand $" + OpName
+
3687 " does not appear in the instruction pattern");
3689 TreePatternNodePtr InVal
= InstInputs
[OpName
];
3690 InstInputs
.erase(OpName
); // It occurred, remove from map.
3692 if (InVal
->isLeaf() && isa
<DefInit
>(InVal
->getLeafValue())) {
3693 Record
*InRec
= static_cast<DefInit
*>(InVal
->getLeafValue())->getDef();
3694 if (!checkOperandClass(Op
, InRec
))
3695 I
.error("Operand $" + OpName
+ "'s register class disagrees"
3696 " between the operand and pattern");
3698 Operands
.push_back(Op
.Rec
);
3700 // Construct the result for the dest-pattern operand list.
3701 TreePatternNodePtr OpNode
= InVal
->clone();
3703 // No predicate is useful on the result.
3704 OpNode
->clearPredicateCalls();
3706 // Promote the xform function to be an explicit node if set.
3707 if (Record
*Xform
= OpNode
->getTransformFn()) {
3708 OpNode
->setTransformFn(nullptr);
3709 std::vector
<TreePatternNodePtr
> Children
;
3710 Children
.push_back(OpNode
);
3711 OpNode
= std::make_shared
<TreePatternNode
>(Xform
, std::move(Children
),
3712 OpNode
->getNumTypes());
3715 ResultNodeOperands
.push_back(std::move(OpNode
));
3718 if (!InstInputs
.empty())
3719 I
.error("Input operand $" + InstInputs
.begin()->first
+
3720 " occurs in pattern but not in operands list!");
3722 TreePatternNodePtr ResultPattern
= std::make_shared
<TreePatternNode
>(
3723 I
.getRecord(), std::move(ResultNodeOperands
),
3724 GetNumNodeResults(I
.getRecord(), *this));
3725 // Copy fully inferred output node types to instruction result pattern.
3726 for (unsigned i
= 0; i
!= NumResults
; ++i
) {
3727 assert(ResNodes
[i
]->getNumTypes() == 1 && "FIXME: Unhandled");
3728 ResultPattern
->setType(i
, ResNodes
[i
]->getExtType(0));
3729 ResultPattern
->setResultIndex(i
, ResultIndices
[i
]);
3732 // FIXME: Assume only the first tree is the pattern. The others are clobber
3734 TreePatternNodePtr Pattern
= I
.getTree(0);
3735 TreePatternNodePtr SrcPattern
;
3736 if (Pattern
->getOperator()->getName() == "set") {
3737 SrcPattern
= Pattern
->getChild(Pattern
->getNumChildren()-1)->clone();
3739 // Not a set (store or something?)
3740 SrcPattern
= Pattern
;
3743 // Create and insert the instruction.
3744 // FIXME: InstImpResults should not be part of DAGInstruction.
3745 Record
*R
= I
.getRecord();
3746 DAGInsts
.emplace(std::piecewise_construct
, std::forward_as_tuple(R
),
3747 std::forward_as_tuple(Results
, Operands
, InstImpResults
,
3748 SrcPattern
, ResultPattern
));
3750 LLVM_DEBUG(I
.dump());
3753 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3754 /// any fragments involved. This populates the Instructions list with fully
3755 /// resolved instructions.
3756 void CodeGenDAGPatterns::ParseInstructions() {
3757 std::vector
<Record
*> Instrs
= Records
.getAllDerivedDefinitions("Instruction");
3759 for (Record
*Instr
: Instrs
) {
3760 ListInit
*LI
= nullptr;
3762 if (isa
<ListInit
>(Instr
->getValueInit("Pattern")))
3763 LI
= Instr
->getValueAsListInit("Pattern");
3765 // If there is no pattern, only collect minimal information about the
3766 // instruction for its operand list. We have to assume that there is one
3767 // result, as we have no detailed info. A pattern which references the
3768 // null_frag operator is as-if no pattern were specified. Normally this
3769 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3771 if (!LI
|| LI
->empty() || hasNullFragReference(LI
)) {
3772 std::vector
<Record
*> Results
;
3773 std::vector
<Record
*> Operands
;
3775 CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
3777 if (InstInfo
.Operands
.size() != 0) {
3778 for (unsigned j
= 0, e
= InstInfo
.Operands
.NumDefs
; j
< e
; ++j
)
3779 Results
.push_back(InstInfo
.Operands
[j
].Rec
);
3781 // The rest are inputs.
3782 for (unsigned j
= InstInfo
.Operands
.NumDefs
,
3783 e
= InstInfo
.Operands
.size(); j
< e
; ++j
)
3784 Operands
.push_back(InstInfo
.Operands
[j
].Rec
);
3787 // Create and insert the instruction.
3788 std::vector
<Record
*> ImpResults
;
3789 Instructions
.insert(std::make_pair(Instr
,
3790 DAGInstruction(Results
, Operands
, ImpResults
)));
3791 continue; // no pattern.
3794 CodeGenInstruction
&CGI
= Target
.getInstruction(Instr
);
3795 parseInstructionPattern(CGI
, LI
, Instructions
);
3798 // If we can, convert the instructions to be patterns that are matched!
3799 for (auto &Entry
: Instructions
) {
3800 Record
*Instr
= Entry
.first
;
3801 DAGInstruction
&TheInst
= Entry
.second
;
3802 TreePatternNodePtr SrcPattern
= TheInst
.getSrcPattern();
3803 TreePatternNodePtr ResultPattern
= TheInst
.getResultPattern();
3805 if (SrcPattern
&& ResultPattern
) {
3806 TreePattern
Pattern(Instr
, SrcPattern
, true, *this);
3807 TreePattern
Result(Instr
, ResultPattern
, false, *this);
3808 ParseOnePattern(Instr
, Pattern
, Result
, TheInst
.getImpResults());
3813 typedef std::pair
<TreePatternNode
*, unsigned> NameRecord
;
3815 static void FindNames(TreePatternNode
*P
,
3816 std::map
<std::string
, NameRecord
> &Names
,
3817 TreePattern
*PatternTop
) {
3818 if (!P
->getName().empty()) {
3819 NameRecord
&Rec
= Names
[P
->getName()];
3820 // If this is the first instance of the name, remember the node.
3821 if (Rec
.second
++ == 0)
3823 else if (Rec
.first
->getExtTypes() != P
->getExtTypes())
3824 PatternTop
->error("repetition of value: $" + P
->getName() +
3825 " where different uses have different types!");
3829 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
)
3830 FindNames(P
->getChild(i
), Names
, PatternTop
);
3834 std::vector
<Predicate
> CodeGenDAGPatterns::makePredList(ListInit
*L
) {
3835 std::vector
<Predicate
> Preds
;
3836 for (Init
*I
: L
->getValues()) {
3837 if (DefInit
*Pred
= dyn_cast
<DefInit
>(I
))
3838 Preds
.push_back(Pred
->getDef());
3840 llvm_unreachable("Non-def on the list");
3843 // Sort so that different orders get canonicalized to the same string.
3848 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern
*Pattern
,
3849 PatternToMatch
&&PTM
) {
3850 // Do some sanity checking on the pattern we're about to match.
3852 if (!PTM
.getSrcPattern()->canPatternMatch(Reason
, *this)) {
3853 PrintWarning(Pattern
->getRecord()->getLoc(),
3854 Twine("Pattern can never match: ") + Reason
);
3858 // If the source pattern's root is a complex pattern, that complex pattern
3859 // must specify the nodes it can potentially match.
3860 if (const ComplexPattern
*CP
=
3861 PTM
.getSrcPattern()->getComplexPatternInfo(*this))
3862 if (CP
->getRootNodes().empty())
3863 Pattern
->error("ComplexPattern at root must specify list of opcodes it"
3867 // Find all of the named values in the input and output, ensure they have the
3869 std::map
<std::string
, NameRecord
> SrcNames
, DstNames
;
3870 FindNames(PTM
.getSrcPattern(), SrcNames
, Pattern
);
3871 FindNames(PTM
.getDstPattern(), DstNames
, Pattern
);
3873 // Scan all of the named values in the destination pattern, rejecting them if
3874 // they don't exist in the input pattern.
3875 for (const auto &Entry
: DstNames
) {
3876 if (SrcNames
[Entry
.first
].first
== nullptr)
3877 Pattern
->error("Pattern has input without matching name in output: $" +
3881 // Scan all of the named values in the source pattern, rejecting them if the
3882 // name isn't used in the dest, and isn't used to tie two values together.
3883 for (const auto &Entry
: SrcNames
)
3884 if (DstNames
[Entry
.first
].first
== nullptr &&
3885 SrcNames
[Entry
.first
].second
== 1)
3886 Pattern
->error("Pattern has dead named input: $" + Entry
.first
);
3888 PatternsToMatch
.push_back(PTM
);
3891 void CodeGenDAGPatterns::InferInstructionFlags() {
3892 ArrayRef
<const CodeGenInstruction
*> Instructions
=
3893 Target
.getInstructionsByEnumValue();
3895 unsigned Errors
= 0;
3897 // Try to infer flags from all patterns in PatternToMatch. These include
3898 // both the primary instruction patterns (which always come first) and
3899 // patterns defined outside the instruction.
3900 for (const PatternToMatch
&PTM
: ptms()) {
3901 // We can only infer from single-instruction patterns, otherwise we won't
3902 // know which instruction should get the flags.
3903 SmallVector
<Record
*, 8> PatInstrs
;
3904 getInstructionsInTree(PTM
.getDstPattern(), PatInstrs
);
3905 if (PatInstrs
.size() != 1)
3908 // Get the single instruction.
3909 CodeGenInstruction
&InstInfo
= Target
.getInstruction(PatInstrs
.front());
3911 // Only infer properties from the first pattern. We'll verify the others.
3912 if (InstInfo
.InferredFrom
)
3915 InstAnalyzer
PatInfo(*this);
3916 PatInfo
.Analyze(PTM
);
3917 Errors
+= InferFromPattern(InstInfo
, PatInfo
, PTM
.getSrcRecord());
3921 PrintFatalError("pattern conflicts");
3923 // If requested by the target, guess any undefined properties.
3924 if (Target
.guessInstructionProperties()) {
3925 for (unsigned i
= 0, e
= Instructions
.size(); i
!= e
; ++i
) {
3926 CodeGenInstruction
*InstInfo
=
3927 const_cast<CodeGenInstruction
*>(Instructions
[i
]);
3928 if (InstInfo
->InferredFrom
)
3930 // The mayLoad and mayStore flags default to false.
3931 // Conservatively assume hasSideEffects if it wasn't explicit.
3932 if (InstInfo
->hasSideEffects_Unset
)
3933 InstInfo
->hasSideEffects
= true;
3938 // Complain about any flags that are still undefined.
3939 for (unsigned i
= 0, e
= Instructions
.size(); i
!= e
; ++i
) {
3940 CodeGenInstruction
*InstInfo
=
3941 const_cast<CodeGenInstruction
*>(Instructions
[i
]);
3942 if (InstInfo
->InferredFrom
)
3944 if (InstInfo
->hasSideEffects_Unset
)
3945 PrintError(InstInfo
->TheDef
->getLoc(),
3946 "Can't infer hasSideEffects from patterns");
3947 if (InstInfo
->mayStore_Unset
)
3948 PrintError(InstInfo
->TheDef
->getLoc(),
3949 "Can't infer mayStore from patterns");
3950 if (InstInfo
->mayLoad_Unset
)
3951 PrintError(InstInfo
->TheDef
->getLoc(),
3952 "Can't infer mayLoad from patterns");
3957 /// Verify instruction flags against pattern node properties.
3958 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3959 unsigned Errors
= 0;
3960 for (ptm_iterator I
= ptm_begin(), E
= ptm_end(); I
!= E
; ++I
) {
3961 const PatternToMatch
&PTM
= *I
;
3962 SmallVector
<Record
*, 8> Instrs
;
3963 getInstructionsInTree(PTM
.getDstPattern(), Instrs
);
3967 // Count the number of instructions with each flag set.
3968 unsigned NumSideEffects
= 0;
3969 unsigned NumStores
= 0;
3970 unsigned NumLoads
= 0;
3971 for (const Record
*Instr
: Instrs
) {
3972 const CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
3973 NumSideEffects
+= InstInfo
.hasSideEffects
;
3974 NumStores
+= InstInfo
.mayStore
;
3975 NumLoads
+= InstInfo
.mayLoad
;
3978 // Analyze the source pattern.
3979 InstAnalyzer
PatInfo(*this);
3980 PatInfo
.Analyze(PTM
);
3982 // Collect error messages.
3983 SmallVector
<std::string
, 4> Msgs
;
3985 // Check for missing flags in the output.
3986 // Permit extra flags for now at least.
3987 if (PatInfo
.hasSideEffects
&& !NumSideEffects
)
3988 Msgs
.push_back("pattern has side effects, but hasSideEffects isn't set");
3990 // Don't verify store flags on instructions with side effects. At least for
3991 // intrinsics, side effects implies mayStore.
3992 if (!PatInfo
.hasSideEffects
&& PatInfo
.mayStore
&& !NumStores
)
3993 Msgs
.push_back("pattern may store, but mayStore isn't set");
3995 // Similarly, mayStore implies mayLoad on intrinsics.
3996 if (!PatInfo
.mayStore
&& PatInfo
.mayLoad
&& !NumLoads
)
3997 Msgs
.push_back("pattern may load, but mayLoad isn't set");
3999 // Print error messages.
4004 for (const std::string
&Msg
: Msgs
)
4005 PrintError(PTM
.getSrcRecord()->getLoc(), Twine(Msg
) + " on the " +
4006 (Instrs
.size() == 1 ?
4007 "instruction" : "output instructions"));
4008 // Provide the location of the relevant instruction definitions.
4009 for (const Record
*Instr
: Instrs
) {
4010 if (Instr
!= PTM
.getSrcRecord())
4011 PrintError(Instr
->getLoc(), "defined here");
4012 const CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
4013 if (InstInfo
.InferredFrom
&&
4014 InstInfo
.InferredFrom
!= InstInfo
.TheDef
&&
4015 InstInfo
.InferredFrom
!= PTM
.getSrcRecord())
4016 PrintError(InstInfo
.InferredFrom
->getLoc(), "inferred from pattern");
4020 PrintFatalError("Errors in DAG patterns");
4023 /// Given a pattern result with an unresolved type, see if we can find one
4024 /// instruction with an unresolved result type. Force this result type to an
4025 /// arbitrary element if it's possible types to converge results.
4026 static bool ForceArbitraryInstResultType(TreePatternNode
*N
, TreePattern
&TP
) {
4030 // Analyze children.
4031 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4032 if (ForceArbitraryInstResultType(N
->getChild(i
), TP
))
4035 if (!N
->getOperator()->isSubClassOf("Instruction"))
4038 // If this type is already concrete or completely unknown we can't do
4040 TypeInfer
&TI
= TP
.getInfer();
4041 for (unsigned i
= 0, e
= N
->getNumTypes(); i
!= e
; ++i
) {
4042 if (N
->getExtType(i
).empty() || TI
.isConcrete(N
->getExtType(i
), false))
4045 // Otherwise, force its type to an arbitrary choice.
4046 if (TI
.forceArbitrary(N
->getExtType(i
)))
4053 // Promote xform function to be an explicit node wherever set.
4054 static TreePatternNodePtr
PromoteXForms(TreePatternNodePtr N
) {
4055 if (Record
*Xform
= N
->getTransformFn()) {
4056 N
->setTransformFn(nullptr);
4057 std::vector
<TreePatternNodePtr
> Children
;
4058 Children
.push_back(PromoteXForms(N
));
4059 return std::make_shared
<TreePatternNode
>(Xform
, std::move(Children
),
4064 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
4065 TreePatternNodePtr Child
= N
->getChildShared(i
);
4066 N
->setChild(i
, PromoteXForms(Child
));
4071 void CodeGenDAGPatterns::ParseOnePattern(Record
*TheDef
,
4072 TreePattern
&Pattern
, TreePattern
&Result
,
4073 const std::vector
<Record
*> &InstImpResults
) {
4075 // Inline pattern fragments and expand multiple alternatives.
4076 Pattern
.InlinePatternFragments();
4077 Result
.InlinePatternFragments();
4079 if (Result
.getNumTrees() != 1)
4080 Result
.error("Cannot use multi-alternative fragments in result pattern!");
4083 bool IterateInference
;
4084 bool InferredAllPatternTypes
, InferredAllResultTypes
;
4086 // Infer as many types as possible. If we cannot infer all of them, we
4087 // can never do anything with this pattern: report it to the user.
4088 InferredAllPatternTypes
=
4089 Pattern
.InferAllTypes(&Pattern
.getNamedNodesMap());
4091 // Infer as many types as possible. If we cannot infer all of them, we
4092 // can never do anything with this pattern: report it to the user.
4093 InferredAllResultTypes
=
4094 Result
.InferAllTypes(&Pattern
.getNamedNodesMap());
4096 IterateInference
= false;
4098 // Apply the type of the result to the source pattern. This helps us
4099 // resolve cases where the input type is known to be a pointer type (which
4100 // is considered resolved), but the result knows it needs to be 32- or
4101 // 64-bits. Infer the other way for good measure.
4102 for (auto T
: Pattern
.getTrees())
4103 for (unsigned i
= 0, e
= std::min(Result
.getOnlyTree()->getNumTypes(),
4106 IterateInference
|= T
->UpdateNodeType(
4107 i
, Result
.getOnlyTree()->getExtType(i
), Result
);
4108 IterateInference
|= Result
.getOnlyTree()->UpdateNodeType(
4109 i
, T
->getExtType(i
), Result
);
4112 // If our iteration has converged and the input pattern's types are fully
4113 // resolved but the result pattern is not fully resolved, we may have a
4114 // situation where we have two instructions in the result pattern and
4115 // the instructions require a common register class, but don't care about
4116 // what actual MVT is used. This is actually a bug in our modelling:
4117 // output patterns should have register classes, not MVTs.
4119 // In any case, to handle this, we just go through and disambiguate some
4120 // arbitrary types to the result pattern's nodes.
4121 if (!IterateInference
&& InferredAllPatternTypes
&&
4122 !InferredAllResultTypes
)
4124 ForceArbitraryInstResultType(Result
.getTree(0).get(), Result
);
4125 } while (IterateInference
);
4127 // Verify that we inferred enough types that we can do something with the
4128 // pattern and result. If these fire the user has to add type casts.
4129 if (!InferredAllPatternTypes
)
4130 Pattern
.error("Could not infer all types in pattern!");
4131 if (!InferredAllResultTypes
) {
4133 Result
.error("Could not infer all types in pattern result!");
4136 // Promote xform function to be an explicit node wherever set.
4137 TreePatternNodePtr DstShared
= PromoteXForms(Result
.getOnlyTree());
4139 TreePattern
Temp(Result
.getRecord(), DstShared
, false, *this);
4140 Temp
.InferAllTypes();
4142 ListInit
*Preds
= TheDef
->getValueAsListInit("Predicates");
4143 int Complexity
= TheDef
->getValueAsInt("AddedComplexity");
4145 if (PatternRewriter
)
4146 PatternRewriter(&Pattern
);
4148 // A pattern may end up with an "impossible" type, i.e. a situation
4149 // where all types have been eliminated for some node in this pattern.
4150 // This could occur for intrinsics that only make sense for a specific
4151 // value type, and use a specific register class. If, for some mode,
4152 // that register class does not accept that type, the type inference
4153 // will lead to a contradiction, which is not an error however, but
4154 // a sign that this pattern will simply never match.
4155 if (Temp
.getOnlyTree()->hasPossibleType())
4156 for (auto T
: Pattern
.getTrees())
4157 if (T
->hasPossibleType())
4158 AddPatternToMatch(&Pattern
,
4159 PatternToMatch(TheDef
, makePredList(Preds
),
4160 T
, Temp
.getOnlyTree(),
4161 InstImpResults
, Complexity
,
4165 void CodeGenDAGPatterns::ParsePatterns() {
4166 std::vector
<Record
*> Patterns
= Records
.getAllDerivedDefinitions("Pattern");
4168 for (Record
*CurPattern
: Patterns
) {
4169 DagInit
*Tree
= CurPattern
->getValueAsDag("PatternToMatch");
4171 // If the pattern references the null_frag, there's nothing to do.
4172 if (hasNullFragReference(Tree
))
4175 TreePattern
Pattern(CurPattern
, Tree
, true, *this);
4177 ListInit
*LI
= CurPattern
->getValueAsListInit("ResultInstrs");
4178 if (LI
->empty()) continue; // no pattern.
4180 // Parse the instruction.
4181 TreePattern
Result(CurPattern
, LI
, false, *this);
4183 if (Result
.getNumTrees() != 1)
4184 Result
.error("Cannot handle instructions producing instructions "
4185 "with temporaries yet!");
4187 // Validate that the input pattern is correct.
4188 std::map
<std::string
, TreePatternNodePtr
> InstInputs
;
4189 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
4191 std::vector
<Record
*> InstImpResults
;
4192 for (unsigned j
= 0, ee
= Pattern
.getNumTrees(); j
!= ee
; ++j
)
4193 FindPatternInputsAndOutputs(Pattern
, Pattern
.getTree(j
), InstInputs
,
4194 InstResults
, InstImpResults
);
4196 ParseOnePattern(CurPattern
, Pattern
, Result
, InstImpResults
);
4200 static void collectModes(std::set
<unsigned> &Modes
, const TreePatternNode
*N
) {
4201 for (const TypeSetByHwMode
&VTS
: N
->getExtTypes())
4202 for (const auto &I
: VTS
)
4203 Modes
.insert(I
.first
);
4205 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4206 collectModes(Modes
, N
->getChild(i
));
4209 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4210 const CodeGenHwModes
&CGH
= getTargetInfo().getHwModes();
4211 std::map
<unsigned,std::vector
<Predicate
>> ModeChecks
;
4212 std::vector
<PatternToMatch
> Copy
= PatternsToMatch
;
4213 PatternsToMatch
.clear();
4215 auto AppendPattern
= [this, &ModeChecks
](PatternToMatch
&P
, unsigned Mode
) {
4216 TreePatternNodePtr NewSrc
= P
.SrcPattern
->clone();
4217 TreePatternNodePtr NewDst
= P
.DstPattern
->clone();
4218 if (!NewSrc
->setDefaultMode(Mode
) || !NewDst
->setDefaultMode(Mode
)) {
4222 std::vector
<Predicate
> Preds
= P
.Predicates
;
4223 const std::vector
<Predicate
> &MC
= ModeChecks
[Mode
];
4224 Preds
.insert(Preds
.end(), MC
.begin(), MC
.end());
4225 PatternsToMatch
.emplace_back(P
.getSrcRecord(), Preds
, std::move(NewSrc
),
4226 std::move(NewDst
), P
.getDstRegs(),
4227 P
.getAddedComplexity(), Record::getNewUID(),
4231 for (PatternToMatch
&P
: Copy
) {
4232 TreePatternNodePtr SrcP
= nullptr, DstP
= nullptr;
4233 if (P
.SrcPattern
->hasProperTypeByHwMode())
4234 SrcP
= P
.SrcPattern
;
4235 if (P
.DstPattern
->hasProperTypeByHwMode())
4236 DstP
= P
.DstPattern
;
4237 if (!SrcP
&& !DstP
) {
4238 PatternsToMatch
.push_back(P
);
4242 std::set
<unsigned> Modes
;
4244 collectModes(Modes
, SrcP
.get());
4246 collectModes(Modes
, DstP
.get());
4248 // The predicate for the default mode needs to be constructed for each
4249 // pattern separately.
4250 // Since not all modes must be present in each pattern, if a mode m is
4251 // absent, then there is no point in constructing a check for m. If such
4252 // a check was created, it would be equivalent to checking the default
4253 // mode, except not all modes' predicates would be a part of the checking
4254 // code. The subsequently generated check for the default mode would then
4255 // have the exact same patterns, but a different predicate code. To avoid
4256 // duplicated patterns with different predicate checks, construct the
4257 // default check as a negation of all predicates that are actually present
4258 // in the source/destination patterns.
4259 std::vector
<Predicate
> DefaultPred
;
4261 for (unsigned M
: Modes
) {
4262 if (M
== DefaultMode
)
4264 if (ModeChecks
.find(M
) != ModeChecks
.end())
4267 // Fill the map entry for this mode.
4268 const HwMode
&HM
= CGH
.getMode(M
);
4269 ModeChecks
[M
].emplace_back(Predicate(HM
.Features
, true));
4271 // Add negations of the HM's predicates to the default predicate.
4272 DefaultPred
.emplace_back(Predicate(HM
.Features
, false));
4275 for (unsigned M
: Modes
) {
4276 if (M
== DefaultMode
)
4278 AppendPattern(P
, M
);
4281 bool HasDefault
= Modes
.count(DefaultMode
);
4283 AppendPattern(P
, DefaultMode
);
4287 /// Dependent variable map for CodeGenDAGPattern variant generation
4288 typedef StringMap
<int> DepVarMap
;
4290 static void FindDepVarsOf(TreePatternNode
*N
, DepVarMap
&DepMap
) {
4292 if (N
->hasName() && isa
<DefInit
>(N
->getLeafValue()))
4293 DepMap
[N
->getName()]++;
4295 for (size_t i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4296 FindDepVarsOf(N
->getChild(i
), DepMap
);
4300 /// Find dependent variables within child patterns
4301 static void FindDepVars(TreePatternNode
*N
, MultipleUseVarSet
&DepVars
) {
4302 DepVarMap depcounts
;
4303 FindDepVarsOf(N
, depcounts
);
4304 for (const auto &Pair
: depcounts
) {
4305 if (Pair
.getValue() > 1)
4306 DepVars
.insert(Pair
.getKey());
4311 /// Dump the dependent variable set:
4312 static void DumpDepVars(MultipleUseVarSet
&DepVars
) {
4313 if (DepVars
.empty()) {
4314 LLVM_DEBUG(errs() << "<empty set>");
4316 LLVM_DEBUG(errs() << "[ ");
4317 for (const auto &DepVar
: DepVars
) {
4318 LLVM_DEBUG(errs() << DepVar
.getKey() << " ");
4320 LLVM_DEBUG(errs() << "]");
4326 /// CombineChildVariants - Given a bunch of permutations of each child of the
4327 /// 'operator' node, put them together in all possible ways.
4328 static void CombineChildVariants(
4329 TreePatternNodePtr Orig
,
4330 const std::vector
<std::vector
<TreePatternNodePtr
>> &ChildVariants
,
4331 std::vector
<TreePatternNodePtr
> &OutVariants
, CodeGenDAGPatterns
&CDP
,
4332 const MultipleUseVarSet
&DepVars
) {
4333 // Make sure that each operand has at least one variant to choose from.
4334 for (const auto &Variants
: ChildVariants
)
4335 if (Variants
.empty())
4338 // The end result is an all-pairs construction of the resultant pattern.
4339 std::vector
<unsigned> Idxs
;
4340 Idxs
.resize(ChildVariants
.size());
4344 LLVM_DEBUG(if (!Idxs
.empty()) {
4345 errs() << Orig
->getOperator()->getName() << ": Idxs = [ ";
4346 for (unsigned Idx
: Idxs
) {
4347 errs() << Idx
<< " ";
4352 // Create the variant and add it to the output list.
4353 std::vector
<TreePatternNodePtr
> NewChildren
;
4354 for (unsigned i
= 0, e
= ChildVariants
.size(); i
!= e
; ++i
)
4355 NewChildren
.push_back(ChildVariants
[i
][Idxs
[i
]]);
4356 TreePatternNodePtr R
= std::make_shared
<TreePatternNode
>(
4357 Orig
->getOperator(), std::move(NewChildren
), Orig
->getNumTypes());
4359 // Copy over properties.
4360 R
->setName(Orig
->getName());
4361 R
->setNamesAsPredicateArg(Orig
->getNamesAsPredicateArg());
4362 R
->setPredicateCalls(Orig
->getPredicateCalls());
4363 R
->setTransformFn(Orig
->getTransformFn());
4364 for (unsigned i
= 0, e
= Orig
->getNumTypes(); i
!= e
; ++i
)
4365 R
->setType(i
, Orig
->getExtType(i
));
4367 // If this pattern cannot match, do not include it as a variant.
4368 std::string ErrString
;
4369 // Scan to see if this pattern has already been emitted. We can get
4370 // duplication due to things like commuting:
4371 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4372 // which are the same pattern. Ignore the dups.
4373 if (R
->canPatternMatch(ErrString
, CDP
) &&
4374 none_of(OutVariants
, [&](TreePatternNodePtr Variant
) {
4375 return R
->isIsomorphicTo(Variant
.get(), DepVars
);
4377 OutVariants
.push_back(R
);
4379 // Increment indices to the next permutation by incrementing the
4380 // indices from last index backward, e.g., generate the sequence
4381 // [0, 0], [0, 1], [1, 0], [1, 1].
4383 for (IdxsIdx
= Idxs
.size() - 1; IdxsIdx
>= 0; --IdxsIdx
) {
4384 if (++Idxs
[IdxsIdx
] == ChildVariants
[IdxsIdx
].size())
4389 NotDone
= (IdxsIdx
>= 0);
4393 /// CombineChildVariants - A helper function for binary operators.
4395 static void CombineChildVariants(TreePatternNodePtr Orig
,
4396 const std::vector
<TreePatternNodePtr
> &LHS
,
4397 const std::vector
<TreePatternNodePtr
> &RHS
,
4398 std::vector
<TreePatternNodePtr
> &OutVariants
,
4399 CodeGenDAGPatterns
&CDP
,
4400 const MultipleUseVarSet
&DepVars
) {
4401 std::vector
<std::vector
<TreePatternNodePtr
>> ChildVariants
;
4402 ChildVariants
.push_back(LHS
);
4403 ChildVariants
.push_back(RHS
);
4404 CombineChildVariants(Orig
, ChildVariants
, OutVariants
, CDP
, DepVars
);
4408 GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N
,
4409 std::vector
<TreePatternNodePtr
> &Children
) {
4410 assert(N
->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4411 Record
*Operator
= N
->getOperator();
4413 // Only permit raw nodes.
4414 if (!N
->getName().empty() || !N
->getPredicateCalls().empty() ||
4415 N
->getTransformFn()) {
4416 Children
.push_back(N
);
4420 if (N
->getChild(0)->isLeaf() || N
->getChild(0)->getOperator() != Operator
)
4421 Children
.push_back(N
->getChildShared(0));
4423 GatherChildrenOfAssociativeOpcode(N
->getChildShared(0), Children
);
4425 if (N
->getChild(1)->isLeaf() || N
->getChild(1)->getOperator() != Operator
)
4426 Children
.push_back(N
->getChildShared(1));
4428 GatherChildrenOfAssociativeOpcode(N
->getChildShared(1), Children
);
4431 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4432 /// the (potentially recursive) pattern by using algebraic laws.
4434 static void GenerateVariantsOf(TreePatternNodePtr N
,
4435 std::vector
<TreePatternNodePtr
> &OutVariants
,
4436 CodeGenDAGPatterns
&CDP
,
4437 const MultipleUseVarSet
&DepVars
) {
4438 // We cannot permute leaves or ComplexPattern uses.
4439 if (N
->isLeaf() || N
->getOperator()->isSubClassOf("ComplexPattern")) {
4440 OutVariants
.push_back(N
);
4444 // Look up interesting info about the node.
4445 const SDNodeInfo
&NodeInfo
= CDP
.getSDNodeInfo(N
->getOperator());
4447 // If this node is associative, re-associate.
4448 if (NodeInfo
.hasProperty(SDNPAssociative
)) {
4449 // Re-associate by pulling together all of the linked operators
4450 std::vector
<TreePatternNodePtr
> MaximalChildren
;
4451 GatherChildrenOfAssociativeOpcode(N
, MaximalChildren
);
4453 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4455 if (MaximalChildren
.size() == 3) {
4456 // Find the variants of all of our maximal children.
4457 std::vector
<TreePatternNodePtr
> AVariants
, BVariants
, CVariants
;
4458 GenerateVariantsOf(MaximalChildren
[0], AVariants
, CDP
, DepVars
);
4459 GenerateVariantsOf(MaximalChildren
[1], BVariants
, CDP
, DepVars
);
4460 GenerateVariantsOf(MaximalChildren
[2], CVariants
, CDP
, DepVars
);
4462 // There are only two ways we can permute the tree:
4463 // (A op B) op C and A op (B op C)
4464 // Within these forms, we can also permute A/B/C.
4466 // Generate legal pair permutations of A/B/C.
4467 std::vector
<TreePatternNodePtr
> ABVariants
;
4468 std::vector
<TreePatternNodePtr
> BAVariants
;
4469 std::vector
<TreePatternNodePtr
> ACVariants
;
4470 std::vector
<TreePatternNodePtr
> CAVariants
;
4471 std::vector
<TreePatternNodePtr
> BCVariants
;
4472 std::vector
<TreePatternNodePtr
> CBVariants
;
4473 CombineChildVariants(N
, AVariants
, BVariants
, ABVariants
, CDP
, DepVars
);
4474 CombineChildVariants(N
, BVariants
, AVariants
, BAVariants
, CDP
, DepVars
);
4475 CombineChildVariants(N
, AVariants
, CVariants
, ACVariants
, CDP
, DepVars
);
4476 CombineChildVariants(N
, CVariants
, AVariants
, CAVariants
, CDP
, DepVars
);
4477 CombineChildVariants(N
, BVariants
, CVariants
, BCVariants
, CDP
, DepVars
);
4478 CombineChildVariants(N
, CVariants
, BVariants
, CBVariants
, CDP
, DepVars
);
4480 // Combine those into the result: (x op x) op x
4481 CombineChildVariants(N
, ABVariants
, CVariants
, OutVariants
, CDP
, DepVars
);
4482 CombineChildVariants(N
, BAVariants
, CVariants
, OutVariants
, CDP
, DepVars
);
4483 CombineChildVariants(N
, ACVariants
, BVariants
, OutVariants
, CDP
, DepVars
);
4484 CombineChildVariants(N
, CAVariants
, BVariants
, OutVariants
, CDP
, DepVars
);
4485 CombineChildVariants(N
, BCVariants
, AVariants
, OutVariants
, CDP
, DepVars
);
4486 CombineChildVariants(N
, CBVariants
, AVariants
, OutVariants
, CDP
, DepVars
);
4488 // Combine those into the result: x op (x op x)
4489 CombineChildVariants(N
, CVariants
, ABVariants
, OutVariants
, CDP
, DepVars
);
4490 CombineChildVariants(N
, CVariants
, BAVariants
, OutVariants
, CDP
, DepVars
);
4491 CombineChildVariants(N
, BVariants
, ACVariants
, OutVariants
, CDP
, DepVars
);
4492 CombineChildVariants(N
, BVariants
, CAVariants
, OutVariants
, CDP
, DepVars
);
4493 CombineChildVariants(N
, AVariants
, BCVariants
, OutVariants
, CDP
, DepVars
);
4494 CombineChildVariants(N
, AVariants
, CBVariants
, OutVariants
, CDP
, DepVars
);
4499 // Compute permutations of all children.
4500 std::vector
<std::vector
<TreePatternNodePtr
>> ChildVariants
;
4501 ChildVariants
.resize(N
->getNumChildren());
4502 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4503 GenerateVariantsOf(N
->getChildShared(i
), ChildVariants
[i
], CDP
, DepVars
);
4505 // Build all permutations based on how the children were formed.
4506 CombineChildVariants(N
, ChildVariants
, OutVariants
, CDP
, DepVars
);
4508 // If this node is commutative, consider the commuted order.
4509 bool isCommIntrinsic
= N
->isCommutativeIntrinsic(CDP
);
4510 if (NodeInfo
.hasProperty(SDNPCommutative
) || isCommIntrinsic
) {
4511 assert((N
->getNumChildren()>=2 || isCommIntrinsic
) &&
4512 "Commutative but doesn't have 2 children!");
4513 // Don't count children which are actually register references.
4515 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
4516 TreePatternNode
*Child
= N
->getChild(i
);
4517 if (Child
->isLeaf())
4518 if (DefInit
*DI
= dyn_cast
<DefInit
>(Child
->getLeafValue())) {
4519 Record
*RR
= DI
->getDef();
4520 if (RR
->isSubClassOf("Register"))
4525 // Consider the commuted order.
4526 if (isCommIntrinsic
) {
4527 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4528 // operands are the commutative operands, and there might be more operands
4531 "Commutative intrinsic should have at least 3 children!");
4532 std::vector
<std::vector
<TreePatternNodePtr
>> Variants
;
4533 Variants
.push_back(std::move(ChildVariants
[0])); // Intrinsic id.
4534 Variants
.push_back(std::move(ChildVariants
[2]));
4535 Variants
.push_back(std::move(ChildVariants
[1]));
4536 for (unsigned i
= 3; i
!= NC
; ++i
)
4537 Variants
.push_back(std::move(ChildVariants
[i
]));
4538 CombineChildVariants(N
, Variants
, OutVariants
, CDP
, DepVars
);
4539 } else if (NC
== N
->getNumChildren()) {
4540 std::vector
<std::vector
<TreePatternNodePtr
>> Variants
;
4541 Variants
.push_back(std::move(ChildVariants
[1]));
4542 Variants
.push_back(std::move(ChildVariants
[0]));
4543 for (unsigned i
= 2; i
!= NC
; ++i
)
4544 Variants
.push_back(std::move(ChildVariants
[i
]));
4545 CombineChildVariants(N
, Variants
, OutVariants
, CDP
, DepVars
);
4551 // GenerateVariants - Generate variants. For example, commutative patterns can
4552 // match multiple ways. Add them to PatternsToMatch as well.
4553 void CodeGenDAGPatterns::GenerateVariants() {
4554 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4556 // Loop over all of the patterns we've collected, checking to see if we can
4557 // generate variants of the instruction, through the exploitation of
4558 // identities. This permits the target to provide aggressive matching without
4559 // the .td file having to contain tons of variants of instructions.
4561 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4562 // intentionally do not reconsider these. Any variants of added patterns have
4563 // already been added.
4565 const unsigned NumOriginalPatterns
= PatternsToMatch
.size();
4566 BitVector
MatchedPatterns(NumOriginalPatterns
);
4567 std::vector
<BitVector
> MatchedPredicates(NumOriginalPatterns
,
4568 BitVector(NumOriginalPatterns
));
4570 typedef std::pair
<MultipleUseVarSet
, std::vector
<TreePatternNodePtr
>>
4572 std::map
<unsigned, DepsAndVariants
> PatternsWithVariants
;
4574 // Collect patterns with more than one variant.
4575 for (unsigned i
= 0; i
!= NumOriginalPatterns
; ++i
) {
4576 MultipleUseVarSet DepVars
;
4577 std::vector
<TreePatternNodePtr
> Variants
;
4578 FindDepVars(PatternsToMatch
[i
].getSrcPattern(), DepVars
);
4579 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4580 LLVM_DEBUG(DumpDepVars(DepVars
));
4581 LLVM_DEBUG(errs() << "\n");
4582 GenerateVariantsOf(PatternsToMatch
[i
].getSrcPatternShared(), Variants
,
4585 assert(!Variants
.empty() && "Must create at least original variant!");
4586 if (Variants
.size() == 1) // No additional variants for this pattern.
4589 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4590 PatternsToMatch
[i
].getSrcPattern()->dump(); errs() << "\n");
4592 PatternsWithVariants
[i
] = std::make_pair(DepVars
, Variants
);
4594 // Cache matching predicates.
4595 if (MatchedPatterns
[i
])
4598 const std::vector
<Predicate
> &Predicates
=
4599 PatternsToMatch
[i
].getPredicates();
4601 BitVector
&Matches
= MatchedPredicates
[i
];
4602 MatchedPatterns
.set(i
);
4605 // Don't test patterns that have already been cached - it won't match.
4606 for (unsigned p
= 0; p
!= NumOriginalPatterns
; ++p
)
4607 if (!MatchedPatterns
[p
])
4608 Matches
[p
] = (Predicates
== PatternsToMatch
[p
].getPredicates());
4610 // Copy this to all the matching patterns.
4611 for (int p
= Matches
.find_first(); p
!= -1; p
= Matches
.find_next(p
))
4613 MatchedPatterns
.set(p
);
4614 MatchedPredicates
[p
] = Matches
;
4618 for (auto it
: PatternsWithVariants
) {
4619 unsigned i
= it
.first
;
4620 const MultipleUseVarSet
&DepVars
= it
.second
.first
;
4621 const std::vector
<TreePatternNodePtr
> &Variants
= it
.second
.second
;
4623 for (unsigned v
= 0, e
= Variants
.size(); v
!= e
; ++v
) {
4624 TreePatternNodePtr Variant
= Variants
[v
];
4625 BitVector
&Matches
= MatchedPredicates
[i
];
4627 LLVM_DEBUG(errs() << " VAR#" << v
<< ": "; Variant
->dump();
4630 // Scan to see if an instruction or explicit pattern already matches this.
4631 bool AlreadyExists
= false;
4632 for (unsigned p
= 0, e
= PatternsToMatch
.size(); p
!= e
; ++p
) {
4633 // Skip if the top level predicates do not match.
4636 // Check to see if this variant already exists.
4637 if (Variant
->isIsomorphicTo(PatternsToMatch
[p
].getSrcPattern(),
4639 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
4640 AlreadyExists
= true;
4644 // If we already have it, ignore the variant.
4645 if (AlreadyExists
) continue;
4647 // Otherwise, add it to the list of patterns we have.
4648 PatternsToMatch
.push_back(PatternToMatch(
4649 PatternsToMatch
[i
].getSrcRecord(), PatternsToMatch
[i
].getPredicates(),
4650 Variant
, PatternsToMatch
[i
].getDstPatternShared(),
4651 PatternsToMatch
[i
].getDstRegs(),
4652 PatternsToMatch
[i
].getAddedComplexity(), Record::getNewUID()));
4653 MatchedPredicates
.push_back(Matches
);
4655 // Add a new match the same as this pattern.
4656 for (auto &P
: MatchedPredicates
)
4660 LLVM_DEBUG(errs() << "\n");