[Alignment][NFC] use llvm::Align for AsmPrinter::EmitAlignment
[llvm-core.git] / utils / TableGen / CodeGenDAGPatterns.cpp
blob07fffaec73d11123947b12792cd40a89e809ddc6
1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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"
28 #include <algorithm>
29 #include <cstdio>
30 #include <iterator>
31 #include <set>
32 using namespace llvm;
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) {
43 return VT.isVector();
45 static inline bool isScalar(MVT VT) {
46 return !VT.isVector();
49 template <typename Predicate>
50 static bool berase_if(MachineValueTypeSet &S, Predicate P) {
51 bool Erased = false;
52 // It is ok to iterate over MachineValueTypeSet and remove elements from it
53 // at the same time.
54 for (MVT T : S) {
55 if (!P(T))
56 continue;
57 Erased = true;
58 S.erase(T);
60 return Erased;
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) {
71 insert(VVT);
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)
79 return false;
80 if (!AllowEmpty && I.second.empty())
81 return false;
83 return true;
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++;
98 return VVT;
101 bool TypeSetByHwMode::isPossible() const {
102 for (const auto &I : *this)
103 if (!I.second.empty())
104 return true;
105 return false;
108 bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
109 bool Changed = false;
110 bool ContainsDefault = false;
111 MVT DT = MVT::Other;
113 SmallDenseSet<unsigned, 4> Modes;
114 for (const auto &P : VVT) {
115 unsigned M = P.first;
116 Modes.insert(M);
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;
122 DT = P.second;
126 // If VVT has a default mode, add the corresponding type to all
127 // modes in "this" that do not exist in VVT.
128 if (ContainsDefault)
129 for (auto &I : *this)
130 if (!Modes.count(I.first))
131 Changed |= I.second.insert(DT).second;
133 return Changed;
136 // Constrain the type set to be the intersection with VTS.
137 bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
138 bool Changed = false;
139 if (hasDefault()) {
140 for (const auto &I : VTS) {
141 unsigned M = I.first;
142 if (M == DefaultMode || hasMode(M))
143 continue;
144 Map.insert({M, Map.at(DefaultMode)});
145 Changed = true;
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()) {
155 S.clear();
156 Changed = true;
159 return Changed;
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); });
167 return Changed;
170 template <typename Predicate>
171 bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
172 assert(empty());
173 for (const auto &I : VTS) {
174 SetType &S = getOrCreate(I.first);
175 for (auto J : I.second)
176 if (P(J))
177 S.insert(J);
179 return !empty();
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);
188 if (Modes.empty()) {
189 OS << "{}";
190 return;
192 array_pod_sort(Modes.begin(), Modes.end());
194 OS << '{';
195 for (unsigned M : Modes) {
196 OS << ' ' << getModeName(M) << ':';
197 writeToStream(get(M), OS);
199 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());
206 OS << '[';
207 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
208 OS << ValueTypeByHwMode::getMVTName(Types[i]);
209 if (i != e-1)
210 OS << ' ';
212 OS << ']';
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)
226 return false;
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);
234 if (HaveDefault) {
235 // Both sets have default mode.
236 for (unsigned M : Modes) {
237 if (get(M) != VTS.get(M))
238 return false;
240 } else {
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)
248 return false;
249 if (!NoModeThis)
250 if (get(M) != VTS.get(M))
251 return false;
255 return true;
258 namespace llvm {
259 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
260 T.writeToStream(OS);
261 return OS;
265 LLVM_DUMP_METHOD
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); };
274 if (OutP == InP)
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.
283 // For example
284 // { iPTR } * { i32 } -> { i32 }
285 // { iPTR } * { i32 i64 } -> { iPTR }
286 // and
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.
297 SetType Diff;
298 if (InP) {
299 Diff = Out;
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); });
304 } else {
305 Diff = In;
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();
313 if (NumD == 0)
314 return Changed;
316 if (NumD == 1) {
317 Out.insert(*Diff.begin());
318 // This is a change only if Out was the one with iPTR (which is now
319 // being replaced).
320 Changed |= OutP;
321 } else {
322 // Multiple elements from Out are now replaced with iPTR.
323 Out.insert(MVT::iPTR);
324 Changed |= !OutP;
326 return Changed;
329 bool TypeSetByHwMode::validate() const {
330 #ifndef NDEBUG
331 if (empty())
332 return true;
333 bool AllEmpty = true;
334 for (const auto &I : *this)
335 AllEmpty &= I.second.empty();
336 return !AllEmpty;
337 #endif
338 return true;
341 // --- TypeInfer
343 bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
344 const TypeSetByHwMode &In) {
345 ValidateOnExit _1(Out, *this);
346 In.validate();
347 if (In.empty() || Out == In || TP.hasError())
348 return false;
349 if (Out.empty()) {
350 Out = In;
351 return true;
354 bool Changed = Out.constrain(In);
355 if (Changed && Out.empty())
356 TP.error("Type contradiction");
358 return Changed;
361 bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
362 ValidateOnExit _1(Out, *this);
363 if (TP.hasError())
364 return false;
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;
370 if (S.size() <= 1)
371 continue;
372 MVT T = *S.begin(); // Pick the first element.
373 S.clear();
374 S.insert(T);
375 Changed = true;
377 return Changed;
380 bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
381 ValidateOnExit _1(Out, *this);
382 if (TP.hasError())
383 return false;
384 if (!Out.empty())
385 return Out.constrain(isIntegerOrPtr);
387 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
390 bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
391 ValidateOnExit _1(Out, *this);
392 if (TP.hasError())
393 return false;
394 if (!Out.empty())
395 return Out.constrain(isFloatingPoint);
397 return Out.assign_if(getLegalTypes(), isFloatingPoint);
400 bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
401 ValidateOnExit _1(Out, *this);
402 if (TP.hasError())
403 return false;
404 if (!Out.empty())
405 return Out.constrain(isScalar);
407 return Out.assign_if(getLegalTypes(), isScalar);
410 bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
411 ValidateOnExit _1(Out, *this);
412 if (TP.hasError())
413 return false;
414 if (!Out.empty())
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())
423 return false;
425 Out = getLegalTypes();
426 return true;
429 template <typename Iter, typename Pred, typename Less>
430 static Iter min_if(Iter B, Iter E, Pred P, Less L) {
431 if (B == E)
432 return E;
433 Iter Min = E;
434 for (Iter I = B; I != E; ++I) {
435 if (!P(*I))
436 continue;
437 if (Min == E || L(*I, *Min))
438 Min = I;
440 return Min;
443 template <typename Iter, typename Pred, typename Less>
444 static Iter max_if(Iter B, Iter E, Pred P, Less L) {
445 if (B == E)
446 return E;
447 Iter Max = E;
448 for (Iter I = B; I != E; ++I) {
449 if (!P(*I))
450 continue;
451 if (Max == E || L(*Max, *I))
452 Max = I;
454 return Max;
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);
461 if (TP.hasError())
462 return false;
463 bool Changed = false;
465 if (Small.empty())
466 Changed |= EnforceAny(Small);
467 if (Big.empty())
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
477 // of them does.
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) |
489 berase_if(B, NotFP);
490 } else if (S.empty() || B.empty()) {
491 Changed = !S.empty() || !B.empty();
492 S.clear();
493 B.clear();
494 } else {
495 TP.error("Incompatible types");
496 return Changed;
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 = [&LT](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())
514 return false;
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);
526 if (MinS != S.end())
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
530 // larger than MaxS.
531 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
532 if (MaxS != B.end())
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);
538 if (MinV != S.end())
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
542 // larger than MaxV.
543 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
544 if (MaxV != B.end())
545 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
548 return Changed;
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);
558 if (TP.hasError())
559 return false;
560 bool Changed = false;
562 if (Vec.empty())
563 Changed |= EnforceVector(Vec);
564 if (Elem.empty())
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.
577 for (MVT T : V)
578 VT.insert(T.getVectorElementType());
579 // Collect scalar types from the "element" set.
580 for (MVT T : E)
581 ST.insert(T);
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
588 // type in V.
589 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
592 return Changed;
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);
608 if (TP.hasError())
609 return false;
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())
614 return false;
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
617 // types separate.
618 if (B.isScalableVector() != P.isScalableVector())
619 return false;
620 if (B.getVectorElementType() != P.getVectorElementType())
621 return false;
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)
629 if (IsSubVec(T, I))
630 return false;
631 return true;
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)
638 if (IsSubVec(I, T))
639 return false;
640 return true;
643 bool Changed = false;
645 if (Vec.empty())
646 Changed |= EnforceVector(Vec);
647 if (Sub.empty())
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));
663 return Changed;
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
671 /// (reverse of 2).
672 bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
673 ValidateOnExit _1(V, *this), _2(W, *this);
674 if (TP.hasError())
675 return false;
677 bool Changed = false;
678 if (V.empty())
679 Changed |= EnforceAny(V);
680 if (W.empty())
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;
695 for (MVT T : VS)
696 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
697 for (MVT T : WS)
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));
703 return Changed;
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);
712 if (TP.hasError())
713 return false;
714 bool Changed = false;
715 if (A.empty())
716 Changed |= EnforceAny(A);
717 if (B.empty())
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;
729 for (MVT T : AS)
730 AN.insert(T.getSizeInBits());
731 for (MVT T : BS)
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));
738 return Changed;
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);
747 for (auto &I : VTS)
748 expandOverloads(I.second, LegalTypes);
751 void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
752 const TypeSetByHwMode::SetType &Legal) {
753 std::set<MVT> Ovs;
754 for (MVT T : Out) {
755 if (!T.isOverloaded())
756 continue;
758 Ovs.insert(T);
759 // MachineValueTypeSet allows iteration and erasing.
760 Out.erase(T);
763 for (MVT Ov : Ovs) {
764 switch (Ov.SimpleTy) {
765 case MVT::iPTRAny:
766 Out.insert(MVT::iPTR);
767 return;
768 case MVT::iAny:
769 for (MVT T : MVT::integer_valuetypes())
770 if (Legal.count(T))
771 Out.insert(T);
772 for (MVT T : MVT::integer_vector_valuetypes())
773 if (Legal.count(T))
774 Out.insert(T);
775 return;
776 case MVT::fAny:
777 for (MVT T : MVT::fp_valuetypes())
778 if (Legal.count(T))
779 Out.insert(T);
780 for (MVT T : MVT::fp_vector_valuetypes())
781 if (Legal.count(T))
782 Out.insert(T);
783 return;
784 case MVT::vAny:
785 for (MVT T : MVT::vector_valuetypes())
786 if (Legal.count(T))
787 Out.insert(T);
788 return;
789 case MVT::Any:
790 for (MVT T : MVT::all_valuetypes())
791 if (Legal.count(T))
792 Out.insert(T);
793 return;
794 default:
795 break;
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 &LTS = 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");
810 return LegalCache;
813 #ifndef NDEBUG
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";
820 Infer.TP.dump();
821 llvm_unreachable(nullptr);
824 #endif
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) {
846 assert(
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();
862 if (MemoryVT)
863 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
864 "MemoryVT requires IsLoad or IsStore");
867 if (!isLoad() && !isStore()) {
868 if (isUnindexed())
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "IsUnindexed requires IsLoad or IsStore");
872 Record *ScalarMemoryVT = getScalarMemoryVT();
874 if (ScalarMemoryVT)
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");
883 if (isLoad()) {
884 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
885 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
886 getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
887 getMinAlignment() < 1)
888 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
889 "IsLoad cannot be used by itself");
890 } else {
891 if (isNonExtLoad())
892 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
893 "IsNonExtLoad requires IsLoad");
894 if (isAnyExtLoad())
895 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
896 "IsAnyExtLoad requires IsLoad");
897 if (isSignExtLoad())
898 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
899 "IsSignExtLoad requires IsLoad");
900 if (isZeroExtLoad())
901 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
902 "IsZeroExtLoad requires IsLoad");
905 if (isStore()) {
906 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
907 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
908 getAddressSpaces() == nullptr && getMinAlignment() < 1)
909 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
910 "IsStore cannot be used by itself");
911 } else {
912 if (isNonTruncStore())
913 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
914 "IsNonTruncStore requires IsStore");
915 if (isTruncStore())
916 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
917 "IsTruncStore requires IsStore");
920 if (isAtomic()) {
921 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
922 getAddressSpaces() == nullptr &&
923 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
924 !isAtomicOrderingAcquireRelease() &&
925 !isAtomicOrderingSequentiallyConsistent() &&
926 !isAtomicOrderingAcquireOrStronger() &&
927 !isAtomicOrderingReleaseOrStronger() &&
928 !isAtomicOrderingWeakerThanAcquire() &&
929 !isAtomicOrderingWeakerThanRelease())
930 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
931 "IsAtomic cannot be used by itself");
932 } else {
933 if (isAtomicOrderingMonotonic())
934 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
935 "IsAtomicOrderingMonotonic requires IsAtomic");
936 if (isAtomicOrderingAcquire())
937 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
938 "IsAtomicOrderingAcquire requires IsAtomic");
939 if (isAtomicOrderingRelease())
940 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
941 "IsAtomicOrderingRelease requires IsAtomic");
942 if (isAtomicOrderingAcquireRelease())
943 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
944 "IsAtomicOrderingAcquireRelease requires IsAtomic");
945 if (isAtomicOrderingSequentiallyConsistent())
946 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
947 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
948 if (isAtomicOrderingAcquireOrStronger())
949 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
950 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
951 if (isAtomicOrderingReleaseOrStronger())
952 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
953 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
954 if (isAtomicOrderingWeakerThanAcquire())
955 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
956 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
959 if (isLoad() || isStore() || isAtomic()) {
960 if (ListInit *AddressSpaces = getAddressSpaces()) {
961 Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
962 " if (";
964 bool First = true;
965 for (Init *Val : AddressSpaces->getValues()) {
966 if (First)
967 First = false;
968 else
969 Code += " && ";
971 IntInit *IntVal = dyn_cast<IntInit>(Val);
972 if (!IntVal) {
973 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
974 "AddressSpaces element must be integer");
977 Code += "AddrSpace != " + utostr(IntVal->getValue());
980 Code += ")\nreturn false;\n";
983 int64_t MinAlign = getMinAlignment();
984 if (MinAlign > 0) {
985 Code += "if (cast<MemSDNode>(N)->getAlignment() < ";
986 Code += utostr(MinAlign);
987 Code += ")\nreturn false;\n";
990 Record *MemoryVT = getMemoryVT();
992 if (MemoryVT)
993 Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
994 MemoryVT->getName() + ") return false;\n")
995 .str();
998 if (isAtomic() && isAtomicOrderingMonotonic())
999 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1000 "AtomicOrdering::Monotonic) return false;\n";
1001 if (isAtomic() && isAtomicOrderingAcquire())
1002 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1003 "AtomicOrdering::Acquire) return false;\n";
1004 if (isAtomic() && isAtomicOrderingRelease())
1005 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1006 "AtomicOrdering::Release) return false;\n";
1007 if (isAtomic() && isAtomicOrderingAcquireRelease())
1008 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1009 "AtomicOrdering::AcquireRelease) return false;\n";
1010 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1011 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1012 "AtomicOrdering::SequentiallyConsistent) return false;\n";
1014 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1015 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1016 "return false;\n";
1017 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1018 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1019 "return false;\n";
1021 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1022 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1023 "return false;\n";
1024 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1025 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1026 "return false;\n";
1028 if (isLoad() || isStore()) {
1029 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1031 if (isUnindexed())
1032 Code += ("if (cast<" + SDNodeName +
1033 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1034 "return false;\n")
1035 .str();
1037 if (isLoad()) {
1038 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1039 isZeroExtLoad()) > 1)
1040 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1041 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1042 "IsZeroExtLoad are mutually exclusive");
1043 if (isNonExtLoad())
1044 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1045 "ISD::NON_EXTLOAD) return false;\n";
1046 if (isAnyExtLoad())
1047 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1048 "return false;\n";
1049 if (isSignExtLoad())
1050 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1051 "return false;\n";
1052 if (isZeroExtLoad())
1053 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1054 "return false;\n";
1055 } else {
1056 if ((isNonTruncStore() + isTruncStore()) > 1)
1057 PrintFatalError(
1058 getOrigPatFragRecord()->getRecord()->getLoc(),
1059 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1060 if (isNonTruncStore())
1061 Code +=
1062 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1063 if (isTruncStore())
1064 Code +=
1065 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1068 Record *ScalarMemoryVT = getScalarMemoryVT();
1070 if (ScalarMemoryVT)
1071 Code += ("if (cast<" + SDNodeName +
1072 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1073 ScalarMemoryVT->getName() + ") return false;\n")
1074 .str();
1077 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1079 Code += PredicateCode;
1081 if (PredicateCode.empty() && !Code.empty())
1082 Code += "return true;\n";
1084 return Code;
1087 bool TreePredicateFn::hasImmCode() const {
1088 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1091 std::string TreePredicateFn::getImmCode() const {
1092 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
1095 bool TreePredicateFn::immCodeUsesAPInt() const {
1096 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1099 bool TreePredicateFn::immCodeUsesAPFloat() const {
1100 bool Unset;
1101 // The return value will be false when IsAPFloat is unset.
1102 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1103 Unset);
1106 bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1107 bool Value) const {
1108 bool Unset;
1109 bool Result =
1110 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1111 if (Unset)
1112 return false;
1113 return Result == Value;
1115 bool TreePredicateFn::usesOperands() const {
1116 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1118 bool TreePredicateFn::isLoad() const {
1119 return isPredefinedPredicateEqualTo("IsLoad", true);
1121 bool TreePredicateFn::isStore() const {
1122 return isPredefinedPredicateEqualTo("IsStore", true);
1124 bool TreePredicateFn::isAtomic() const {
1125 return isPredefinedPredicateEqualTo("IsAtomic", true);
1127 bool TreePredicateFn::isUnindexed() const {
1128 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1130 bool TreePredicateFn::isNonExtLoad() const {
1131 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1133 bool TreePredicateFn::isAnyExtLoad() const {
1134 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1136 bool TreePredicateFn::isSignExtLoad() const {
1137 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1139 bool TreePredicateFn::isZeroExtLoad() const {
1140 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1142 bool TreePredicateFn::isNonTruncStore() const {
1143 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1145 bool TreePredicateFn::isTruncStore() const {
1146 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1148 bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1149 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1151 bool TreePredicateFn::isAtomicOrderingAcquire() const {
1152 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1154 bool TreePredicateFn::isAtomicOrderingRelease() const {
1155 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1157 bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1158 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1160 bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1161 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1162 true);
1164 bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1165 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1167 bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1168 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1170 bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1171 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1173 bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1174 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1176 Record *TreePredicateFn::getMemoryVT() const {
1177 Record *R = getOrigPatFragRecord()->getRecord();
1178 if (R->isValueUnset("MemoryVT"))
1179 return nullptr;
1180 return R->getValueAsDef("MemoryVT");
1183 ListInit *TreePredicateFn::getAddressSpaces() const {
1184 Record *R = getOrigPatFragRecord()->getRecord();
1185 if (R->isValueUnset("AddressSpaces"))
1186 return nullptr;
1187 return R->getValueAsListInit("AddressSpaces");
1190 int64_t TreePredicateFn::getMinAlignment() const {
1191 Record *R = getOrigPatFragRecord()->getRecord();
1192 if (R->isValueUnset("MinAlignment"))
1193 return 0;
1194 return R->getValueAsInt("MinAlignment");
1197 Record *TreePredicateFn::getScalarMemoryVT() const {
1198 Record *R = getOrigPatFragRecord()->getRecord();
1199 if (R->isValueUnset("ScalarMemoryVT"))
1200 return nullptr;
1201 return R->getValueAsDef("ScalarMemoryVT");
1203 bool TreePredicateFn::hasGISelPredicateCode() const {
1204 return !PatFragRec->getRecord()
1205 ->getValueAsString("GISelPredicateCode")
1206 .empty();
1208 std::string TreePredicateFn::getGISelPredicateCode() const {
1209 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1212 StringRef TreePredicateFn::getImmType() const {
1213 if (immCodeUsesAPInt())
1214 return "const APInt &";
1215 if (immCodeUsesAPFloat())
1216 return "const APFloat &";
1217 return "int64_t";
1220 StringRef TreePredicateFn::getImmTypeIdentifier() const {
1221 if (immCodeUsesAPInt())
1222 return "APInt";
1223 else if (immCodeUsesAPFloat())
1224 return "APFloat";
1225 return "I64";
1228 /// isAlwaysTrue - Return true if this is a noop predicate.
1229 bool TreePredicateFn::isAlwaysTrue() const {
1230 return !hasPredCode() && !hasImmCode();
1233 /// Return the name to use in the generated code to reference this, this is
1234 /// "Predicate_foo" if from a pattern fragment "foo".
1235 std::string TreePredicateFn::getFnName() const {
1236 return "Predicate_" + PatFragRec->getRecord()->getName().str();
1239 /// getCodeToRunOnSDNode - Return the code for the function body that
1240 /// evaluates this predicate. The argument is expected to be in "Node",
1241 /// not N. This handles casting and conversion to a concrete node type as
1242 /// appropriate.
1243 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
1244 // Handle immediate predicates first.
1245 std::string ImmCode = getImmCode();
1246 if (!ImmCode.empty()) {
1247 if (isLoad())
1248 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1249 "IsLoad cannot be used with ImmLeaf or its subclasses");
1250 if (isStore())
1251 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1252 "IsStore cannot be used with ImmLeaf or its subclasses");
1253 if (isUnindexed())
1254 PrintFatalError(
1255 getOrigPatFragRecord()->getRecord()->getLoc(),
1256 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1257 if (isNonExtLoad())
1258 PrintFatalError(
1259 getOrigPatFragRecord()->getRecord()->getLoc(),
1260 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1261 if (isAnyExtLoad())
1262 PrintFatalError(
1263 getOrigPatFragRecord()->getRecord()->getLoc(),
1264 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1265 if (isSignExtLoad())
1266 PrintFatalError(
1267 getOrigPatFragRecord()->getRecord()->getLoc(),
1268 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1269 if (isZeroExtLoad())
1270 PrintFatalError(
1271 getOrigPatFragRecord()->getRecord()->getLoc(),
1272 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1273 if (isNonTruncStore())
1274 PrintFatalError(
1275 getOrigPatFragRecord()->getRecord()->getLoc(),
1276 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1277 if (isTruncStore())
1278 PrintFatalError(
1279 getOrigPatFragRecord()->getRecord()->getLoc(),
1280 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1281 if (getMemoryVT())
1282 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1283 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1284 if (getScalarMemoryVT())
1285 PrintFatalError(
1286 getOrigPatFragRecord()->getRecord()->getLoc(),
1287 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1289 std::string Result = (" " + getImmType() + " Imm = ").str();
1290 if (immCodeUsesAPFloat())
1291 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1292 else if (immCodeUsesAPInt())
1293 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1294 else
1295 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1296 return Result + ImmCode;
1299 // Handle arbitrary node predicates.
1300 assert(hasPredCode() && "Don't have any predicate code!");
1301 StringRef ClassName;
1302 if (PatFragRec->getOnlyTree()->isLeaf())
1303 ClassName = "SDNode";
1304 else {
1305 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1306 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1308 std::string Result;
1309 if (ClassName == "SDNode")
1310 Result = " SDNode *N = Node;\n";
1311 else
1312 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
1314 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
1317 //===----------------------------------------------------------------------===//
1318 // PatternToMatch implementation
1321 static bool isImmAllOnesAllZerosMatch(const TreePatternNode *P) {
1322 if (!P->isLeaf())
1323 return false;
1324 DefInit *DI = dyn_cast<DefInit>(P->getLeafValue());
1325 if (!DI)
1326 return false;
1328 Record *R = DI->getDef();
1329 return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1332 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1333 /// patterns before small ones. This is used to determine the size of a
1334 /// pattern.
1335 static unsigned getPatternSize(const TreePatternNode *P,
1336 const CodeGenDAGPatterns &CGP) {
1337 unsigned Size = 3; // The node itself.
1338 // If the root node is a ConstantSDNode, increases its size.
1339 // e.g. (set R32:$dst, 0).
1340 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
1341 Size += 2;
1343 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
1344 Size += AM->getComplexity();
1345 // We don't want to count any children twice, so return early.
1346 return Size;
1349 // If this node has some predicate function that must match, it adds to the
1350 // complexity of this node.
1351 if (!P->getPredicateCalls().empty())
1352 ++Size;
1354 // Count children in the count if they are also nodes.
1355 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1356 const TreePatternNode *Child = P->getChild(i);
1357 if (!Child->isLeaf() && Child->getNumTypes()) {
1358 const TypeSetByHwMode &T0 = Child->getExtType(0);
1359 // At this point, all variable type sets should be simple, i.e. only
1360 // have a default mode.
1361 if (T0.getMachineValueType() != MVT::Other) {
1362 Size += getPatternSize(Child, CGP);
1363 continue;
1366 if (Child->isLeaf()) {
1367 if (isa<IntInit>(Child->getLeafValue()))
1368 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1369 else if (Child->getComplexPatternInfo(CGP))
1370 Size += getPatternSize(Child, CGP);
1371 else if (isImmAllOnesAllZerosMatch(Child))
1372 Size += 4; // Matches a build_vector(+3) and a predicate (+1).
1373 else if (!Child->getPredicateCalls().empty())
1374 ++Size;
1378 return Size;
1381 /// Compute the complexity metric for the input pattern. This roughly
1382 /// corresponds to the number of nodes that are covered.
1383 int PatternToMatch::
1384 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1385 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1388 /// getPredicateCheck - Return a single string containing all of this
1389 /// pattern's predicates concatenated with "&&" operators.
1391 std::string PatternToMatch::getPredicateCheck() const {
1392 SmallVector<const Predicate*,4> PredList;
1393 for (const Predicate &P : Predicates) {
1394 if (!P.getCondString().empty())
1395 PredList.push_back(&P);
1397 llvm::sort(PredList, deref<std::less<>>());
1399 std::string Check;
1400 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1401 if (i != 0)
1402 Check += " && ";
1403 Check += '(' + PredList[i]->getCondString() + ')';
1405 return Check;
1408 //===----------------------------------------------------------------------===//
1409 // SDTypeConstraint implementation
1412 SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
1413 OperandNo = R->getValueAsInt("OperandNum");
1415 if (R->isSubClassOf("SDTCisVT")) {
1416 ConstraintType = SDTCisVT;
1417 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1418 for (const auto &P : VVT)
1419 if (P.second == MVT::isVoid)
1420 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1421 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1422 ConstraintType = SDTCisPtrTy;
1423 } else if (R->isSubClassOf("SDTCisInt")) {
1424 ConstraintType = SDTCisInt;
1425 } else if (R->isSubClassOf("SDTCisFP")) {
1426 ConstraintType = SDTCisFP;
1427 } else if (R->isSubClassOf("SDTCisVec")) {
1428 ConstraintType = SDTCisVec;
1429 } else if (R->isSubClassOf("SDTCisSameAs")) {
1430 ConstraintType = SDTCisSameAs;
1431 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1432 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1433 ConstraintType = SDTCisVTSmallerThanOp;
1434 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
1435 R->getValueAsInt("OtherOperandNum");
1436 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1437 ConstraintType = SDTCisOpSmallerThanOp;
1438 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
1439 R->getValueAsInt("BigOperandNum");
1440 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1441 ConstraintType = SDTCisEltOfVec;
1442 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
1443 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1444 ConstraintType = SDTCisSubVecOfVec;
1445 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1446 R->getValueAsInt("OtherOpNum");
1447 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1448 ConstraintType = SDTCVecEltisVT;
1449 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1450 for (const auto &P : VVT) {
1451 MVT T = P.second;
1452 if (T.isVector())
1453 PrintFatalError(R->getLoc(),
1454 "Cannot use vector type as SDTCVecEltisVT");
1455 if (!T.isInteger() && !T.isFloatingPoint())
1456 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1457 "as SDTCVecEltisVT");
1459 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1460 ConstraintType = SDTCisSameNumEltsAs;
1461 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1462 R->getValueAsInt("OtherOperandNum");
1463 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1464 ConstraintType = SDTCisSameSizeAs;
1465 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1466 R->getValueAsInt("OtherOperandNum");
1467 } else {
1468 PrintFatalError(R->getLoc(),
1469 "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1473 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1474 /// N, and the result number in ResNo.
1475 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1476 const SDNodeInfo &NodeInfo,
1477 unsigned &ResNo) {
1478 unsigned NumResults = NodeInfo.getNumResults();
1479 if (OpNo < NumResults) {
1480 ResNo = OpNo;
1481 return N;
1484 OpNo -= NumResults;
1486 if (OpNo >= N->getNumChildren()) {
1487 std::string S;
1488 raw_string_ostream OS(S);
1489 OS << "Invalid operand number in type constraint "
1490 << (OpNo+NumResults) << " ";
1491 N->print(OS);
1492 PrintFatalError(OS.str());
1495 return N->getChild(OpNo);
1498 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1499 /// constraint to the nodes operands. This returns true if it makes a
1500 /// change, false otherwise. If a type contradiction is found, flag an error.
1501 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1502 const SDNodeInfo &NodeInfo,
1503 TreePattern &TP) const {
1504 if (TP.hasError())
1505 return false;
1507 unsigned ResNo = 0; // The result number being referenced.
1508 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
1509 TypeInfer &TI = TP.getInfer();
1511 switch (ConstraintType) {
1512 case SDTCisVT:
1513 // Operand must be a particular type.
1514 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
1515 case SDTCisPtrTy:
1516 // Operand must be same as target pointer type.
1517 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
1518 case SDTCisInt:
1519 // Require it to be one of the legal integer VTs.
1520 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
1521 case SDTCisFP:
1522 // Require it to be one of the legal fp VTs.
1523 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
1524 case SDTCisVec:
1525 // Require it to be one of the legal vector VTs.
1526 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
1527 case SDTCisSameAs: {
1528 unsigned OResNo = 0;
1529 TreePatternNode *OtherNode =
1530 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1531 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1532 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
1534 case SDTCisVTSmallerThanOp: {
1535 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1536 // have an integer type that is smaller than the VT.
1537 if (!NodeToApply->isLeaf() ||
1538 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1539 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1540 ->isSubClassOf("ValueType")) {
1541 TP.error(N->getOperator()->getName() + " expects a VT operand!");
1542 return false;
1544 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1545 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1546 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1547 TypeSetByHwMode TypeListTmp(VVT);
1549 unsigned OResNo = 0;
1550 TreePatternNode *OtherNode =
1551 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1552 OResNo);
1554 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
1556 case SDTCisOpSmallerThanOp: {
1557 unsigned BResNo = 0;
1558 TreePatternNode *BigOperand =
1559 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1560 BResNo);
1561 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1562 BigOperand->getExtType(BResNo));
1564 case SDTCisEltOfVec: {
1565 unsigned VResNo = 0;
1566 TreePatternNode *VecOperand =
1567 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1568 VResNo);
1569 // Filter vector types out of VecOperand that don't have the right element
1570 // type.
1571 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1572 NodeToApply->getExtType(ResNo));
1574 case SDTCisSubVecOfVec: {
1575 unsigned VResNo = 0;
1576 TreePatternNode *BigVecOperand =
1577 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1578 VResNo);
1580 // Filter vector types out of BigVecOperand that don't have the
1581 // right subvector type.
1582 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1583 NodeToApply->getExtType(ResNo));
1585 case SDTCVecEltisVT: {
1586 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
1588 case SDTCisSameNumEltsAs: {
1589 unsigned OResNo = 0;
1590 TreePatternNode *OtherNode =
1591 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1592 N, NodeInfo, OResNo);
1593 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1594 NodeToApply->getExtType(ResNo));
1596 case SDTCisSameSizeAs: {
1597 unsigned OResNo = 0;
1598 TreePatternNode *OtherNode =
1599 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1600 N, NodeInfo, OResNo);
1601 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1602 NodeToApply->getExtType(ResNo));
1605 llvm_unreachable("Invalid ConstraintType!");
1608 // Update the node type to match an instruction operand or result as specified
1609 // in the ins or outs lists on the instruction definition. Return true if the
1610 // type was actually changed.
1611 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1612 Record *Operand,
1613 TreePattern &TP) {
1614 // The 'unknown' operand indicates that types should be inferred from the
1615 // context.
1616 if (Operand->isSubClassOf("unknown_class"))
1617 return false;
1619 // The Operand class specifies a type directly.
1620 if (Operand->isSubClassOf("Operand")) {
1621 Record *R = Operand->getValueAsDef("Type");
1622 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1623 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1626 // PointerLikeRegClass has a type that is determined at runtime.
1627 if (Operand->isSubClassOf("PointerLikeRegClass"))
1628 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1630 // Both RegisterClass and RegisterOperand operands derive their types from a
1631 // register class def.
1632 Record *RC = nullptr;
1633 if (Operand->isSubClassOf("RegisterClass"))
1634 RC = Operand;
1635 else if (Operand->isSubClassOf("RegisterOperand"))
1636 RC = Operand->getValueAsDef("RegClass");
1638 assert(RC && "Unknown operand type");
1639 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1640 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1643 bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1644 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1645 if (!TP.getInfer().isConcrete(Types[i], true))
1646 return true;
1647 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1648 if (getChild(i)->ContainsUnresolvedType(TP))
1649 return true;
1650 return false;
1653 bool TreePatternNode::hasProperTypeByHwMode() const {
1654 for (const TypeSetByHwMode &S : Types)
1655 if (!S.isDefaultOnly())
1656 return true;
1657 for (const TreePatternNodePtr &C : Children)
1658 if (C->hasProperTypeByHwMode())
1659 return true;
1660 return false;
1663 bool TreePatternNode::hasPossibleType() const {
1664 for (const TypeSetByHwMode &S : Types)
1665 if (!S.isPossible())
1666 return false;
1667 for (const TreePatternNodePtr &C : Children)
1668 if (!C->hasPossibleType())
1669 return false;
1670 return true;
1673 bool TreePatternNode::setDefaultMode(unsigned Mode) {
1674 for (TypeSetByHwMode &S : Types) {
1675 S.makeSimple(Mode);
1676 // Check if the selected mode had a type conflict.
1677 if (S.get(DefaultMode).empty())
1678 return false;
1680 for (const TreePatternNodePtr &C : Children)
1681 if (!C->setDefaultMode(Mode))
1682 return false;
1683 return true;
1686 //===----------------------------------------------------------------------===//
1687 // SDNodeInfo implementation
1689 SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
1690 EnumName = R->getValueAsString("Opcode");
1691 SDClassName = R->getValueAsString("SDClass");
1692 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1693 NumResults = TypeProfile->getValueAsInt("NumResults");
1694 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1696 // Parse the properties.
1697 Properties = parseSDPatternOperatorProperties(R);
1699 // Parse the type constraints.
1700 std::vector<Record*> ConstraintList =
1701 TypeProfile->getValueAsListOfDefs("Constraints");
1702 for (Record *R : ConstraintList)
1703 TypeConstraints.emplace_back(R, CGH);
1706 /// getKnownType - If the type constraints on this node imply a fixed type
1707 /// (e.g. all stores return void, etc), then return it as an
1708 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1709 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1710 unsigned NumResults = getNumResults();
1711 assert(NumResults <= 1 &&
1712 "We only work with nodes with zero or one result so far!");
1713 assert(ResNo == 0 && "Only handles single result nodes so far");
1715 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1716 // Make sure that this applies to the correct node result.
1717 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1718 continue;
1720 switch (Constraint.ConstraintType) {
1721 default: break;
1722 case SDTypeConstraint::SDTCisVT:
1723 if (Constraint.VVT.isSimple())
1724 return Constraint.VVT.getSimple().SimpleTy;
1725 break;
1726 case SDTypeConstraint::SDTCisPtrTy:
1727 return MVT::iPTR;
1730 return MVT::Other;
1733 //===----------------------------------------------------------------------===//
1734 // TreePatternNode implementation
1737 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1738 if (Operator->getName() == "set" ||
1739 Operator->getName() == "implicit")
1740 return 0; // All return nothing.
1742 if (Operator->isSubClassOf("Intrinsic"))
1743 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1745 if (Operator->isSubClassOf("SDNode"))
1746 return CDP.getSDNodeInfo(Operator).getNumResults();
1748 if (Operator->isSubClassOf("PatFrags")) {
1749 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1750 // the forward reference case where one pattern fragment references another
1751 // before it is processed.
1752 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1753 // The number of results of a fragment with alternative records is the
1754 // maximum number of results across all alternatives.
1755 unsigned NumResults = 0;
1756 for (auto T : PFRec->getTrees())
1757 NumResults = std::max(NumResults, T->getNumTypes());
1758 return NumResults;
1761 ListInit *LI = Operator->getValueAsListInit("Fragments");
1762 assert(LI && "Invalid Fragment");
1763 unsigned NumResults = 0;
1764 for (Init *I : LI->getValues()) {
1765 Record *Op = nullptr;
1766 if (DagInit *Dag = dyn_cast<DagInit>(I))
1767 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1768 Op = DI->getDef();
1769 assert(Op && "Invalid Fragment");
1770 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1772 return NumResults;
1775 if (Operator->isSubClassOf("Instruction")) {
1776 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1778 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1780 // Subtract any defaulted outputs.
1781 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1782 Record *OperandNode = InstInfo.Operands[i].Rec;
1784 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1785 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1786 --NumDefsToAdd;
1789 // Add on one implicit def if it has a resolvable type.
1790 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1791 ++NumDefsToAdd;
1792 return NumDefsToAdd;
1795 if (Operator->isSubClassOf("SDNodeXForm"))
1796 return 1; // FIXME: Generalize SDNodeXForm
1798 if (Operator->isSubClassOf("ValueType"))
1799 return 1; // A type-cast of one result.
1801 if (Operator->isSubClassOf("ComplexPattern"))
1802 return 1;
1804 errs() << *Operator;
1805 PrintFatalError("Unhandled node in GetNumNodeResults");
1808 void TreePatternNode::print(raw_ostream &OS) const {
1809 if (isLeaf())
1810 OS << *getLeafValue();
1811 else
1812 OS << '(' << getOperator()->getName();
1814 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1815 OS << ':';
1816 getExtType(i).writeToStream(OS);
1819 if (!isLeaf()) {
1820 if (getNumChildren() != 0) {
1821 OS << " ";
1822 getChild(0)->print(OS);
1823 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1824 OS << ", ";
1825 getChild(i)->print(OS);
1828 OS << ")";
1831 for (const TreePredicateCall &Pred : PredicateCalls) {
1832 OS << "<<P:";
1833 if (Pred.Scope)
1834 OS << Pred.Scope << ":";
1835 OS << Pred.Fn.getFnName() << ">>";
1837 if (TransformFn)
1838 OS << "<<X:" << TransformFn->getName() << ">>";
1839 if (!getName().empty())
1840 OS << ":$" << getName();
1842 for (const ScopedName &Name : NamesAsPredicateArg)
1843 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
1845 void TreePatternNode::dump() const {
1846 print(errs());
1849 /// isIsomorphicTo - Return true if this node is recursively
1850 /// isomorphic to the specified node. For this comparison, the node's
1851 /// entire state is considered. The assigned name is ignored, since
1852 /// nodes with differing names are considered isomorphic. However, if
1853 /// the assigned name is present in the dependent variable set, then
1854 /// the assigned name is considered significant and the node is
1855 /// isomorphic if the names match.
1856 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1857 const MultipleUseVarSet &DepVars) const {
1858 if (N == this) return true;
1859 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1860 getPredicateCalls() != N->getPredicateCalls() ||
1861 getTransformFn() != N->getTransformFn())
1862 return false;
1864 if (isLeaf()) {
1865 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1866 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1867 return ((DI->getDef() == NDI->getDef())
1868 && (DepVars.find(getName()) == DepVars.end()
1869 || getName() == N->getName()));
1872 return getLeafValue() == N->getLeafValue();
1875 if (N->getOperator() != getOperator() ||
1876 N->getNumChildren() != getNumChildren()) return false;
1877 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1878 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1879 return false;
1880 return true;
1883 /// clone - Make a copy of this tree and all of its children.
1885 TreePatternNodePtr TreePatternNode::clone() const {
1886 TreePatternNodePtr New;
1887 if (isLeaf()) {
1888 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
1889 } else {
1890 std::vector<TreePatternNodePtr> CChildren;
1891 CChildren.reserve(Children.size());
1892 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1893 CChildren.push_back(getChild(i)->clone());
1894 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
1895 getNumTypes());
1897 New->setName(getName());
1898 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
1899 New->Types = Types;
1900 New->setPredicateCalls(getPredicateCalls());
1901 New->setTransformFn(getTransformFn());
1902 return New;
1905 /// RemoveAllTypes - Recursively strip all the types of this tree.
1906 void TreePatternNode::RemoveAllTypes() {
1907 // Reset to unknown type.
1908 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
1909 if (isLeaf()) return;
1910 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1911 getChild(i)->RemoveAllTypes();
1915 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1916 /// with actual values specified by ArgMap.
1917 void TreePatternNode::SubstituteFormalArguments(
1918 std::map<std::string, TreePatternNodePtr> &ArgMap) {
1919 if (isLeaf()) return;
1921 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1922 TreePatternNode *Child = getChild(i);
1923 if (Child->isLeaf()) {
1924 Init *Val = Child->getLeafValue();
1925 // Note that, when substituting into an output pattern, Val might be an
1926 // UnsetInit.
1927 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1928 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1929 // We found a use of a formal argument, replace it with its value.
1930 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
1931 assert(NewChild && "Couldn't find formal argument!");
1932 assert((Child->getPredicateCalls().empty() ||
1933 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
1934 "Non-empty child predicate clobbered!");
1935 setChild(i, std::move(NewChild));
1937 } else {
1938 getChild(i)->SubstituteFormalArguments(ArgMap);
1944 /// InlinePatternFragments - If this pattern refers to any pattern
1945 /// fragments, return the set of inlined versions (this can be more than
1946 /// one if a PatFrags record has multiple alternatives).
1947 void TreePatternNode::InlinePatternFragments(
1948 TreePatternNodePtr T, TreePattern &TP,
1949 std::vector<TreePatternNodePtr> &OutAlternatives) {
1951 if (TP.hasError())
1952 return;
1954 if (isLeaf()) {
1955 OutAlternatives.push_back(T); // nothing to do.
1956 return;
1959 Record *Op = getOperator();
1961 if (!Op->isSubClassOf("PatFrags")) {
1962 if (getNumChildren() == 0) {
1963 OutAlternatives.push_back(T);
1964 return;
1967 // Recursively inline children nodes.
1968 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1969 ChildAlternatives.resize(getNumChildren());
1970 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1971 TreePatternNodePtr Child = getChildShared(i);
1972 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1973 // If there are no alternatives for any child, there are no
1974 // alternatives for this expression as whole.
1975 if (ChildAlternatives[i].empty())
1976 return;
1978 for (auto NewChild : ChildAlternatives[i])
1979 assert((Child->getPredicateCalls().empty() ||
1980 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
1981 "Non-empty child predicate clobbered!");
1984 // The end result is an all-pairs construction of the resultant pattern.
1985 std::vector<unsigned> Idxs;
1986 Idxs.resize(ChildAlternatives.size());
1987 bool NotDone;
1988 do {
1989 // Create the variant and add it to the output list.
1990 std::vector<TreePatternNodePtr> NewChildren;
1991 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1992 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1993 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
1994 getOperator(), std::move(NewChildren), getNumTypes());
1996 // Copy over properties.
1997 R->setName(getName());
1998 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
1999 R->setPredicateCalls(getPredicateCalls());
2000 R->setTransformFn(getTransformFn());
2001 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2002 R->setType(i, getExtType(i));
2003 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2004 R->setResultIndex(i, getResultIndex(i));
2006 // Register alternative.
2007 OutAlternatives.push_back(R);
2009 // Increment indices to the next permutation by incrementing the
2010 // indices from last index backward, e.g., generate the sequence
2011 // [0, 0], [0, 1], [1, 0], [1, 1].
2012 int IdxsIdx;
2013 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2014 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2015 Idxs[IdxsIdx] = 0;
2016 else
2017 break;
2019 NotDone = (IdxsIdx >= 0);
2020 } while (NotDone);
2022 return;
2025 // Otherwise, we found a reference to a fragment. First, look up its
2026 // TreePattern record.
2027 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
2029 // Verify that we are passing the right number of operands.
2030 if (Frag->getNumArgs() != Children.size()) {
2031 TP.error("'" + Op->getName() + "' fragment requires " +
2032 Twine(Frag->getNumArgs()) + " operands!");
2033 return;
2036 TreePredicateFn PredFn(Frag);
2037 unsigned Scope = 0;
2038 if (TreePredicateFn(Frag).usesOperands())
2039 Scope = TP.getDAGPatterns().allocateScope();
2041 // Compute the map of formal to actual arguments.
2042 std::map<std::string, TreePatternNodePtr> ArgMap;
2043 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
2044 TreePatternNodePtr Child = getChildShared(i);
2045 if (Scope != 0) {
2046 Child = Child->clone();
2047 Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
2049 ArgMap[Frag->getArgName(i)] = Child;
2052 // Loop over all fragment alternatives.
2053 for (auto Alternative : Frag->getTrees()) {
2054 TreePatternNodePtr FragTree = Alternative->clone();
2056 if (!PredFn.isAlwaysTrue())
2057 FragTree->addPredicateCall(PredFn, Scope);
2059 // Resolve formal arguments to their actual value.
2060 if (Frag->getNumArgs())
2061 FragTree->SubstituteFormalArguments(ArgMap);
2063 // Transfer types. Note that the resolved alternative may have fewer
2064 // (but not more) results than the PatFrags node.
2065 FragTree->setName(getName());
2066 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2067 FragTree->UpdateNodeType(i, getExtType(i), TP);
2069 // Transfer in the old predicates.
2070 for (const TreePredicateCall &Pred : getPredicateCalls())
2071 FragTree->addPredicateCall(Pred);
2073 // The fragment we inlined could have recursive inlining that is needed. See
2074 // if there are any pattern fragments in it and inline them as needed.
2075 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
2079 /// getImplicitType - Check to see if the specified record has an implicit
2080 /// type which should be applied to it. This will infer the type of register
2081 /// references from the register file information, for example.
2083 /// When Unnamed is set, return the type of a DAG operand with no name, such as
2084 /// the F8RC register class argument in:
2086 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
2088 /// When Unnamed is false, return the type of a named DAG operand such as the
2089 /// GPR:$src operand above.
2091 static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2092 bool NotRegisters,
2093 bool Unnamed,
2094 TreePattern &TP) {
2095 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2097 // Check to see if this is a register operand.
2098 if (R->isSubClassOf("RegisterOperand")) {
2099 assert(ResNo == 0 && "Regoperand ref only has one result!");
2100 if (NotRegisters)
2101 return TypeSetByHwMode(); // Unknown.
2102 Record *RegClass = R->getValueAsDef("RegClass");
2103 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2104 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
2107 // Check to see if this is a register or a register class.
2108 if (R->isSubClassOf("RegisterClass")) {
2109 assert(ResNo == 0 && "Regclass ref only has one result!");
2110 // An unnamed register class represents itself as an i32 immediate, for
2111 // example on a COPY_TO_REGCLASS instruction.
2112 if (Unnamed)
2113 return TypeSetByHwMode(MVT::i32);
2115 // In a named operand, the register class provides the possible set of
2116 // types.
2117 if (NotRegisters)
2118 return TypeSetByHwMode(); // Unknown.
2119 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2120 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2123 if (R->isSubClassOf("PatFrags")) {
2124 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2125 // Pattern fragment types will be resolved when they are inlined.
2126 return TypeSetByHwMode(); // Unknown.
2129 if (R->isSubClassOf("Register")) {
2130 assert(ResNo == 0 && "Registers only produce one result!");
2131 if (NotRegisters)
2132 return TypeSetByHwMode(); // Unknown.
2133 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2134 return TypeSetByHwMode(T.getRegisterVTs(R));
2137 if (R->isSubClassOf("SubRegIndex")) {
2138 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
2139 return TypeSetByHwMode(MVT::i32);
2142 if (R->isSubClassOf("ValueType")) {
2143 assert(ResNo == 0 && "This node only has one result!");
2144 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2146 // (sext_inreg GPR:$src, i16)
2147 // ~~~
2148 if (Unnamed)
2149 return TypeSetByHwMode(MVT::Other);
2150 // With a name, the ValueType simply provides the type of the named
2151 // variable.
2153 // (sext_inreg i32:$src, i16)
2154 // ~~~~~~~~
2155 if (NotRegisters)
2156 return TypeSetByHwMode(); // Unknown.
2157 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2158 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
2161 if (R->isSubClassOf("CondCode")) {
2162 assert(ResNo == 0 && "This node only has one result!");
2163 // Using a CondCodeSDNode.
2164 return TypeSetByHwMode(MVT::Other);
2167 if (R->isSubClassOf("ComplexPattern")) {
2168 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2169 if (NotRegisters)
2170 return TypeSetByHwMode(); // Unknown.
2171 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
2173 if (R->isSubClassOf("PointerLikeRegClass")) {
2174 assert(ResNo == 0 && "Regclass can only have one result!");
2175 TypeSetByHwMode VTS(MVT::iPTR);
2176 TP.getInfer().expandOverloads(VTS);
2177 return VTS;
2180 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2181 R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
2182 R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
2183 // Placeholder.
2184 return TypeSetByHwMode(); // Unknown.
2187 if (R->isSubClassOf("Operand")) {
2188 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2189 Record *T = R->getValueAsDef("Type");
2190 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2193 TP.error("Unknown node flavor used in pattern: " + R->getName());
2194 return TypeSetByHwMode(MVT::Other);
2198 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2199 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2200 const CodeGenIntrinsic *TreePatternNode::
2201 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2202 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2203 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2204 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2205 return nullptr;
2207 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
2208 return &CDP.getIntrinsicInfo(IID);
2211 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2212 /// return the ComplexPattern information, otherwise return null.
2213 const ComplexPattern *
2214 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2215 Record *Rec;
2216 if (isLeaf()) {
2217 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2218 if (!DI)
2219 return nullptr;
2220 Rec = DI->getDef();
2221 } else
2222 Rec = getOperator();
2224 if (!Rec->isSubClassOf("ComplexPattern"))
2225 return nullptr;
2226 return &CGP.getComplexPattern(Rec);
2229 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2230 // A ComplexPattern specifically declares how many results it fills in.
2231 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2232 return CP->getNumOperands();
2234 // If MIOperandInfo is specified, that gives the count.
2235 if (isLeaf()) {
2236 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2237 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2238 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2239 if (MIOps->getNumArgs())
2240 return MIOps->getNumArgs();
2244 // Otherwise there is just one result.
2245 return 1;
2248 /// NodeHasProperty - Return true if this node has the specified property.
2249 bool TreePatternNode::NodeHasProperty(SDNP Property,
2250 const CodeGenDAGPatterns &CGP) const {
2251 if (isLeaf()) {
2252 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2253 return CP->hasProperty(Property);
2255 return false;
2258 if (Property != SDNPHasChain) {
2259 // The chain proprety is already present on the different intrinsic node
2260 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2261 // on the intrinsic. Anything else is specific to the individual intrinsic.
2262 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2263 return Int->hasProperty(Property);
2266 if (!Operator->isSubClassOf("SDPatternOperator"))
2267 return false;
2269 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2275 /// TreeHasProperty - Return true if any node in this tree has the specified
2276 /// property.
2277 bool TreePatternNode::TreeHasProperty(SDNP Property,
2278 const CodeGenDAGPatterns &CGP) const {
2279 if (NodeHasProperty(Property, CGP))
2280 return true;
2281 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2282 if (getChild(i)->TreeHasProperty(Property, CGP))
2283 return true;
2284 return false;
2287 /// isCommutativeIntrinsic - Return true if the node corresponds to a
2288 /// commutative intrinsic.
2289 bool
2290 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2291 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2292 return Int->isCommutative;
2293 return false;
2296 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2297 if (!N->isLeaf())
2298 return N->getOperator()->isSubClassOf(Class);
2300 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2301 if (DI && DI->getDef()->isSubClassOf(Class))
2302 return true;
2304 return false;
2307 static void emitTooManyOperandsError(TreePattern &TP,
2308 StringRef InstName,
2309 unsigned Expected,
2310 unsigned Actual) {
2311 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2312 " operands but expected only " + Twine(Expected) + "!");
2315 static void emitTooFewOperandsError(TreePattern &TP,
2316 StringRef InstName,
2317 unsigned Actual) {
2318 TP.error("Instruction '" + InstName +
2319 "' expects more than the provided " + Twine(Actual) + " operands!");
2322 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2323 /// this node and its children in the tree. This returns true if it makes a
2324 /// change, false otherwise. If a type contradiction is found, flag an error.
2325 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2326 if (TP.hasError())
2327 return false;
2329 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2330 if (isLeaf()) {
2331 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
2332 // If it's a regclass or something else known, include the type.
2333 bool MadeChange = false;
2334 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2335 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
2336 NotRegisters,
2337 !hasName(), TP), TP);
2338 return MadeChange;
2341 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
2342 assert(Types.size() == 1 && "Invalid IntInit");
2344 // Int inits are always integers. :)
2345 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
2347 if (!TP.getInfer().isConcrete(Types[0], false))
2348 return MadeChange;
2350 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2351 for (auto &P : VVT) {
2352 MVT::SimpleValueType VT = P.second.SimpleTy;
2353 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2354 continue;
2355 unsigned Size = MVT(VT).getSizeInBits();
2356 // Make sure that the value is representable for this type.
2357 if (Size >= 32)
2358 continue;
2359 // Check that the value doesn't use more bits than we have. It must
2360 // either be a sign- or zero-extended equivalent of the original.
2361 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2362 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2363 SignBitAndAbove == 1)
2364 continue;
2366 TP.error("Integer value '" + Twine(II->getValue()) +
2367 "' is out of range for type '" + getEnumName(VT) + "'!");
2368 break;
2370 return MadeChange;
2373 return false;
2376 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2377 bool MadeChange = false;
2379 // Apply the result type to the node.
2380 unsigned NumRetVTs = Int->IS.RetVTs.size();
2381 unsigned NumParamVTs = Int->IS.ParamVTs.size();
2383 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2384 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
2386 if (getNumChildren() != NumParamVTs + 1) {
2387 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2388 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2389 return false;
2392 // Apply type info to the intrinsic ID.
2393 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
2395 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2396 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
2398 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2399 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2400 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
2402 return MadeChange;
2405 if (getOperator()->isSubClassOf("SDNode")) {
2406 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
2408 // Check that the number of operands is sane. Negative operands -> varargs.
2409 if (NI.getNumOperands() >= 0 &&
2410 getNumChildren() != (unsigned)NI.getNumOperands()) {
2411 TP.error(getOperator()->getName() + " node requires exactly " +
2412 Twine(NI.getNumOperands()) + " operands!");
2413 return false;
2416 bool MadeChange = false;
2417 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2418 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2419 MadeChange |= NI.ApplyTypeConstraints(this, TP);
2420 return MadeChange;
2423 if (getOperator()->isSubClassOf("Instruction")) {
2424 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
2425 CodeGenInstruction &InstInfo =
2426 CDP.getTargetInfo().getInstruction(getOperator());
2428 bool MadeChange = false;
2430 // Apply the result types to the node, these come from the things in the
2431 // (outs) list of the instruction.
2432 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2433 Inst.getNumResults());
2434 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2435 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
2437 // If the instruction has implicit defs, we apply the first one as a result.
2438 // FIXME: This sucks, it should apply all implicit defs.
2439 if (!InstInfo.ImplicitDefs.empty()) {
2440 unsigned ResNo = NumResultsToAdd;
2442 // FIXME: Generalize to multiple possible types and multiple possible
2443 // ImplicitDefs.
2444 MVT::SimpleValueType VT =
2445 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
2447 if (VT != MVT::Other)
2448 MadeChange |= UpdateNodeType(ResNo, VT, TP);
2451 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2452 // be the same.
2453 if (getOperator()->getName() == "INSERT_SUBREG") {
2454 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2455 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2456 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
2457 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2458 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2459 // variadic.
2461 unsigned NChild = getNumChildren();
2462 if (NChild < 3) {
2463 TP.error("REG_SEQUENCE requires at least 3 operands!");
2464 return false;
2467 if (NChild % 2 == 0) {
2468 TP.error("REG_SEQUENCE requires an odd number of operands!");
2469 return false;
2472 if (!isOperandClass(getChild(0), "RegisterClass")) {
2473 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2474 return false;
2477 for (unsigned I = 1; I < NChild; I += 2) {
2478 TreePatternNode *SubIdxChild = getChild(I + 1);
2479 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2480 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2481 Twine(I + 1) + "!");
2482 return false;
2487 // If one or more operands with a default value appear at the end of the
2488 // formal operand list for an instruction, we allow them to be overridden
2489 // by optional operands provided in the pattern.
2491 // But if an operand B without a default appears at any point after an
2492 // operand A with a default, then we don't allow A to be overridden,
2493 // because there would be no way to specify whether the next operand in
2494 // the pattern was intended to override A or skip it.
2495 unsigned NonOverridableOperands = Inst.getNumOperands();
2496 while (NonOverridableOperands > 0 &&
2497 CDP.operandHasDefault(Inst.getOperand(NonOverridableOperands-1)))
2498 --NonOverridableOperands;
2500 unsigned ChildNo = 0;
2501 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2502 Record *OperandNode = Inst.getOperand(i);
2504 // If the operand has a default value, do we use it? We must use the
2505 // default if we've run out of children of the pattern DAG to consume,
2506 // or if the operand is followed by a non-defaulted one.
2507 if (CDP.operandHasDefault(OperandNode) &&
2508 (i < NonOverridableOperands || ChildNo >= getNumChildren()))
2509 continue;
2511 // If we have run out of child nodes and there _isn't_ a default
2512 // value we can use for the next operand, give an error.
2513 if (ChildNo >= getNumChildren()) {
2514 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
2515 return false;
2518 TreePatternNode *Child = getChild(ChildNo++);
2519 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
2521 // If the operand has sub-operands, they may be provided by distinct
2522 // child patterns, so attempt to match each sub-operand separately.
2523 if (OperandNode->isSubClassOf("Operand")) {
2524 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2525 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2526 // But don't do that if the whole operand is being provided by
2527 // a single ComplexPattern-related Operand.
2529 if (Child->getNumMIResults(CDP) < NumArgs) {
2530 // Match first sub-operand against the child we already have.
2531 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2532 MadeChange |=
2533 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2535 // And the remaining sub-operands against subsequent children.
2536 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2537 if (ChildNo >= getNumChildren()) {
2538 emitTooFewOperandsError(TP, getOperator()->getName(),
2539 getNumChildren());
2540 return false;
2542 Child = getChild(ChildNo++);
2544 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2545 MadeChange |=
2546 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2548 continue;
2553 // If we didn't match by pieces above, attempt to match the whole
2554 // operand now.
2555 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
2558 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2559 emitTooManyOperandsError(TP, getOperator()->getName(),
2560 ChildNo, getNumChildren());
2561 return false;
2564 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2565 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2566 return MadeChange;
2569 if (getOperator()->isSubClassOf("ComplexPattern")) {
2570 bool MadeChange = false;
2572 for (unsigned i = 0; i < getNumChildren(); ++i)
2573 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2575 return MadeChange;
2578 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2580 // Node transforms always take one operand.
2581 if (getNumChildren() != 1) {
2582 TP.error("Node transform '" + getOperator()->getName() +
2583 "' requires one operand!");
2584 return false;
2587 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
2588 return MadeChange;
2591 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2592 /// RHS of a commutative operation, not the on LHS.
2593 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2594 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2595 return true;
2596 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
2597 return true;
2598 return false;
2602 /// canPatternMatch - If it is impossible for this pattern to match on this
2603 /// target, fill in Reason and return false. Otherwise, return true. This is
2604 /// used as a sanity check for .td files (to prevent people from writing stuff
2605 /// that can never possibly work), and to prevent the pattern permuter from
2606 /// generating stuff that is useless.
2607 bool TreePatternNode::canPatternMatch(std::string &Reason,
2608 const CodeGenDAGPatterns &CDP) {
2609 if (isLeaf()) return true;
2611 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2612 if (!getChild(i)->canPatternMatch(Reason, CDP))
2613 return false;
2615 // If this is an intrinsic, handle cases that would make it not match. For
2616 // example, if an operand is required to be an immediate.
2617 if (getOperator()->isSubClassOf("Intrinsic")) {
2618 // TODO:
2619 return true;
2622 if (getOperator()->isSubClassOf("ComplexPattern"))
2623 return true;
2625 // If this node is a commutative operator, check that the LHS isn't an
2626 // immediate.
2627 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2628 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2629 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2630 // Scan all of the operands of the node and make sure that only the last one
2631 // is a constant node, unless the RHS also is.
2632 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2633 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2634 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2635 if (OnlyOnRHSOfCommutative(getChild(i))) {
2636 Reason="Immediate value must be on the RHS of commutative operators!";
2637 return false;
2642 return true;
2645 //===----------------------------------------------------------------------===//
2646 // TreePattern implementation
2649 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2650 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2651 isInputPattern(isInput), HasError(false),
2652 Infer(*this) {
2653 for (Init *I : RawPat->getValues())
2654 Trees.push_back(ParseTreePattern(I, ""));
2657 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2658 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2659 isInputPattern(isInput), HasError(false),
2660 Infer(*this) {
2661 Trees.push_back(ParseTreePattern(Pat, ""));
2664 TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2665 CodeGenDAGPatterns &cdp)
2666 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2667 Infer(*this) {
2668 Trees.push_back(Pat);
2671 void TreePattern::error(const Twine &Msg) {
2672 if (HasError)
2673 return;
2674 dump();
2675 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2676 HasError = true;
2679 void TreePattern::ComputeNamedNodes() {
2680 for (TreePatternNodePtr &Tree : Trees)
2681 ComputeNamedNodes(Tree.get());
2684 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2685 if (!N->getName().empty())
2686 NamedNodes[N->getName()].push_back(N);
2688 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2689 ComputeNamedNodes(N->getChild(i));
2692 TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2693 StringRef OpName) {
2694 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2695 Record *R = DI->getDef();
2697 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2698 // TreePatternNode of its own. For example:
2699 /// (foo GPR, imm) -> (foo GPR, (imm))
2700 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
2701 return ParseTreePattern(
2702 DagInit::get(DI, nullptr,
2703 std::vector<std::pair<Init*, StringInit*> >()),
2704 OpName);
2706 // Input argument?
2707 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
2708 if (R->getName() == "node" && !OpName.empty()) {
2709 if (OpName.empty())
2710 error("'node' argument requires a name to match with operand list");
2711 Args.push_back(OpName);
2714 Res->setName(OpName);
2715 return Res;
2718 // ?:$name or just $name.
2719 if (isa<UnsetInit>(TheInit)) {
2720 if (OpName.empty())
2721 error("'?' argument requires a name to match with operand list");
2722 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
2723 Args.push_back(OpName);
2724 Res->setName(OpName);
2725 return Res;
2728 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
2729 if (!OpName.empty())
2730 error("Constant int or bit argument should not have a name!");
2731 if (isa<BitInit>(TheInit))
2732 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2733 return std::make_shared<TreePatternNode>(TheInit, 1);
2736 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2737 // Turn this into an IntInit.
2738 Init *II = BI->convertInitializerTo(IntRecTy::get());
2739 if (!II || !isa<IntInit>(II))
2740 error("Bits value must be constants!");
2741 return ParseTreePattern(II, OpName);
2744 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2745 if (!Dag) {
2746 TheInit->print(errs());
2747 error("Pattern has unexpected init kind!");
2749 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2750 if (!OpDef) error("Pattern has unexpected operator type!");
2751 Record *Operator = OpDef->getDef();
2753 if (Operator->isSubClassOf("ValueType")) {
2754 // If the operator is a ValueType, then this must be "type cast" of a leaf
2755 // node.
2756 if (Dag->getNumArgs() != 1)
2757 error("Type cast only takes one operand!");
2759 TreePatternNodePtr New =
2760 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
2762 // Apply the type cast.
2763 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2764 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2765 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
2767 if (!OpName.empty())
2768 error("ValueType cast should not have a name!");
2769 return New;
2772 // Verify that this is something that makes sense for an operator.
2773 if (!Operator->isSubClassOf("PatFrags") &&
2774 !Operator->isSubClassOf("SDNode") &&
2775 !Operator->isSubClassOf("Instruction") &&
2776 !Operator->isSubClassOf("SDNodeXForm") &&
2777 !Operator->isSubClassOf("Intrinsic") &&
2778 !Operator->isSubClassOf("ComplexPattern") &&
2779 Operator->getName() != "set" &&
2780 Operator->getName() != "implicit")
2781 error("Unrecognized node '" + Operator->getName() + "'!");
2783 // Check to see if this is something that is illegal in an input pattern.
2784 if (isInputPattern) {
2785 if (Operator->isSubClassOf("Instruction") ||
2786 Operator->isSubClassOf("SDNodeXForm"))
2787 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2788 } else {
2789 if (Operator->isSubClassOf("Intrinsic"))
2790 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2792 if (Operator->isSubClassOf("SDNode") &&
2793 Operator->getName() != "imm" &&
2794 Operator->getName() != "fpimm" &&
2795 Operator->getName() != "tglobaltlsaddr" &&
2796 Operator->getName() != "tconstpool" &&
2797 Operator->getName() != "tjumptable" &&
2798 Operator->getName() != "tframeindex" &&
2799 Operator->getName() != "texternalsym" &&
2800 Operator->getName() != "tblockaddress" &&
2801 Operator->getName() != "tglobaladdr" &&
2802 Operator->getName() != "bb" &&
2803 Operator->getName() != "vt" &&
2804 Operator->getName() != "mcsym")
2805 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2808 std::vector<TreePatternNodePtr> Children;
2810 // Parse all the operands.
2811 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2812 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2814 // Get the actual number of results before Operator is converted to an intrinsic
2815 // node (which is hard-coded to have either zero or one result).
2816 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2818 // If the operator is an intrinsic, then this is just syntactic sugar for
2819 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2820 // convert the intrinsic name to a number.
2821 if (Operator->isSubClassOf("Intrinsic")) {
2822 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2823 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2825 // If this intrinsic returns void, it must have side-effects and thus a
2826 // chain.
2827 if (Int.IS.RetVTs.empty())
2828 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2829 else if (Int.ModRef != CodeGenIntrinsic::NoMem || Int.hasSideEffects)
2830 // Has side-effects, requires chain.
2831 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2832 else // Otherwise, no chain.
2833 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2835 Children.insert(Children.begin(),
2836 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
2839 if (Operator->isSubClassOf("ComplexPattern")) {
2840 for (unsigned i = 0; i < Children.size(); ++i) {
2841 TreePatternNodePtr Child = Children[i];
2843 if (Child->getName().empty())
2844 error("All arguments to a ComplexPattern must be named");
2846 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2847 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2848 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2849 auto OperandId = std::make_pair(Operator, i);
2850 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2851 if (PrevOp != ComplexPatternOperands.end()) {
2852 if (PrevOp->getValue() != OperandId)
2853 error("All ComplexPattern operands must appear consistently: "
2854 "in the same order in just one ComplexPattern instance.");
2855 } else
2856 ComplexPatternOperands[Child->getName()] = OperandId;
2860 TreePatternNodePtr Result =
2861 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2862 NumResults);
2863 Result->setName(OpName);
2865 if (Dag->getName()) {
2866 assert(Result->getName().empty());
2867 Result->setName(Dag->getNameStr());
2869 return Result;
2872 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2873 /// will never match in favor of something obvious that will. This is here
2874 /// strictly as a convenience to target authors because it allows them to write
2875 /// more type generic things and have useless type casts fold away.
2877 /// This returns true if any change is made.
2878 static bool SimplifyTree(TreePatternNodePtr &N) {
2879 if (N->isLeaf())
2880 return false;
2882 // If we have a bitconvert with a resolved type and if the source and
2883 // destination types are the same, then the bitconvert is useless, remove it.
2884 if (N->getOperator()->getName() == "bitconvert" &&
2885 N->getExtType(0).isValueTypeByHwMode(false) &&
2886 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2887 N->getName().empty()) {
2888 N = N->getChildShared(0);
2889 SimplifyTree(N);
2890 return true;
2893 // Walk all children.
2894 bool MadeChange = false;
2895 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2896 TreePatternNodePtr Child = N->getChildShared(i);
2897 MadeChange |= SimplifyTree(Child);
2898 N->setChild(i, std::move(Child));
2900 return MadeChange;
2905 /// InferAllTypes - Infer/propagate as many types throughout the expression
2906 /// patterns as possible. Return true if all types are inferred, false
2907 /// otherwise. Flags an error if a type contradiction is found.
2908 bool TreePattern::
2909 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2910 if (NamedNodes.empty())
2911 ComputeNamedNodes();
2913 bool MadeChange = true;
2914 while (MadeChange) {
2915 MadeChange = false;
2916 for (TreePatternNodePtr &Tree : Trees) {
2917 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2918 MadeChange |= SimplifyTree(Tree);
2921 // If there are constraints on our named nodes, apply them.
2922 for (auto &Entry : NamedNodes) {
2923 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2925 // If we have input named node types, propagate their types to the named
2926 // values here.
2927 if (InNamedTypes) {
2928 if (!InNamedTypes->count(Entry.getKey())) {
2929 error("Node '" + std::string(Entry.getKey()) +
2930 "' in output pattern but not input pattern");
2931 return true;
2934 const SmallVectorImpl<TreePatternNode*> &InNodes =
2935 InNamedTypes->find(Entry.getKey())->second;
2937 // The input types should be fully resolved by now.
2938 for (TreePatternNode *Node : Nodes) {
2939 // If this node is a register class, and it is the root of the pattern
2940 // then we're mapping something onto an input register. We allow
2941 // changing the type of the input register in this case. This allows
2942 // us to match things like:
2943 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2944 if (Node == Trees[0].get() && Node->isLeaf()) {
2945 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2946 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2947 DI->getDef()->isSubClassOf("RegisterOperand")))
2948 continue;
2951 assert(Node->getNumTypes() == 1 &&
2952 InNodes[0]->getNumTypes() == 1 &&
2953 "FIXME: cannot name multiple result nodes yet");
2954 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2955 *this);
2959 // If there are multiple nodes with the same name, they must all have the
2960 // same type.
2961 if (Entry.second.size() > 1) {
2962 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2963 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2964 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2965 "FIXME: cannot name multiple result nodes yet");
2967 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2968 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2974 bool HasUnresolvedTypes = false;
2975 for (const TreePatternNodePtr &Tree : Trees)
2976 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
2977 return !HasUnresolvedTypes;
2980 void TreePattern::print(raw_ostream &OS) const {
2981 OS << getRecord()->getName();
2982 if (!Args.empty()) {
2983 OS << "(" << Args[0];
2984 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2985 OS << ", " << Args[i];
2986 OS << ")";
2988 OS << ": ";
2990 if (Trees.size() > 1)
2991 OS << "[\n";
2992 for (const TreePatternNodePtr &Tree : Trees) {
2993 OS << "\t";
2994 Tree->print(OS);
2995 OS << "\n";
2998 if (Trees.size() > 1)
2999 OS << "]\n";
3002 void TreePattern::dump() const { print(errs()); }
3004 //===----------------------------------------------------------------------===//
3005 // CodeGenDAGPatterns implementation
3008 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
3009 PatternRewriterFn PatternRewriter)
3010 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
3011 PatternRewriter(PatternRewriter) {
3013 Intrinsics = CodeGenIntrinsicTable(Records, false);
3014 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
3015 ParseNodeInfo();
3016 ParseNodeTransforms();
3017 ParseComplexPatterns();
3018 ParsePatternFragments();
3019 ParseDefaultOperands();
3020 ParseInstructions();
3021 ParsePatternFragments(/*OutFrags*/true);
3022 ParsePatterns();
3024 // Break patterns with parameterized types into a series of patterns,
3025 // where each one has a fixed type and is predicated on the conditions
3026 // of the associated HW mode.
3027 ExpandHwModeBasedTypes();
3029 // Generate variants. For example, commutative patterns can match
3030 // multiple ways. Add them to PatternsToMatch as well.
3031 GenerateVariants();
3033 // Infer instruction flags. For example, we can detect loads,
3034 // stores, and side effects in many cases by examining an
3035 // instruction's pattern.
3036 InferInstructionFlags();
3038 // Verify that instruction flags match the patterns.
3039 VerifyInstructionFlags();
3042 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
3043 Record *N = Records.getDef(Name);
3044 if (!N || !N->isSubClassOf("SDNode"))
3045 PrintFatalError("Error getting SDNode '" + Name + "'!");
3047 return N;
3050 // Parse all of the SDNode definitions for the target, populating SDNodes.
3051 void CodeGenDAGPatterns::ParseNodeInfo() {
3052 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
3053 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3055 while (!Nodes.empty()) {
3056 Record *R = Nodes.back();
3057 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
3058 Nodes.pop_back();
3061 // Get the builtin intrinsic nodes.
3062 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
3063 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
3064 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
3067 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3068 /// map, and emit them to the file as functions.
3069 void CodeGenDAGPatterns::ParseNodeTransforms() {
3070 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
3071 while (!Xforms.empty()) {
3072 Record *XFormNode = Xforms.back();
3073 Record *SDNode = XFormNode->getValueAsDef("Opcode");
3074 StringRef Code = XFormNode->getValueAsString("XFormFunction");
3075 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
3077 Xforms.pop_back();
3081 void CodeGenDAGPatterns::ParseComplexPatterns() {
3082 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3083 while (!AMs.empty()) {
3084 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3085 AMs.pop_back();
3090 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3091 /// file, building up the PatternFragments map. After we've collected them all,
3092 /// inline fragments together as necessary, so that there are no references left
3093 /// inside a pattern fragment to a pattern fragment.
3095 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
3096 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
3098 // First step, parse all of the fragments.
3099 for (Record *Frag : Fragments) {
3100 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3101 continue;
3103 ListInit *LI = Frag->getValueAsListInit("Fragments");
3104 TreePattern *P =
3105 (PatternFragments[Frag] = std::make_unique<TreePattern>(
3106 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
3107 *this)).get();
3109 // Validate the argument list, converting it to set, to discard duplicates.
3110 std::vector<std::string> &Args = P->getArgList();
3111 // Copy the args so we can take StringRefs to them.
3112 auto ArgsCopy = Args;
3113 SmallDenseSet<StringRef, 4> OperandsSet;
3114 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
3116 if (OperandsSet.count(""))
3117 P->error("Cannot have unnamed 'node' values in pattern fragment!");
3119 // Parse the operands list.
3120 DagInit *OpsList = Frag->getValueAsDag("Operands");
3121 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
3122 // Special cases: ops == outs == ins. Different names are used to
3123 // improve readability.
3124 if (!OpsOp ||
3125 (OpsOp->getDef()->getName() != "ops" &&
3126 OpsOp->getDef()->getName() != "outs" &&
3127 OpsOp->getDef()->getName() != "ins"))
3128 P->error("Operands list should start with '(ops ... '!");
3130 // Copy over the arguments.
3131 Args.clear();
3132 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
3133 if (!isa<DefInit>(OpsList->getArg(j)) ||
3134 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
3135 P->error("Operands list should all be 'node' values.");
3136 if (!OpsList->getArgName(j))
3137 P->error("Operands list should have names for each operand!");
3138 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3139 if (!OperandsSet.count(ArgNameStr))
3140 P->error("'" + ArgNameStr +
3141 "' does not occur in pattern or was multiply specified!");
3142 OperandsSet.erase(ArgNameStr);
3143 Args.push_back(ArgNameStr);
3146 if (!OperandsSet.empty())
3147 P->error("Operands list does not contain an entry for operand '" +
3148 *OperandsSet.begin() + "'!");
3150 // If there is a node transformation corresponding to this, keep track of
3151 // it.
3152 Record *Transform = Frag->getValueAsDef("OperandTransform");
3153 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
3154 for (auto T : P->getTrees())
3155 T->setTransformFn(Transform);
3158 // Now that we've parsed all of the tree fragments, do a closure on them so
3159 // that there are not references to PatFrags left inside of them.
3160 for (Record *Frag : Fragments) {
3161 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3162 continue;
3164 TreePattern &ThePat = *PatternFragments[Frag];
3165 ThePat.InlinePatternFragments();
3167 // Infer as many types as possible. Don't worry about it if we don't infer
3168 // all of them, some may depend on the inputs of the pattern. Also, don't
3169 // validate type sets; validation may cause spurious failures e.g. if a
3170 // fragment needs floating-point types but the current target does not have
3171 // any (this is only an error if that fragment is ever used!).
3173 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3174 ThePat.InferAllTypes();
3175 ThePat.resetError();
3178 // If debugging, print out the pattern fragment result.
3179 LLVM_DEBUG(ThePat.dump());
3183 void CodeGenDAGPatterns::ParseDefaultOperands() {
3184 std::vector<Record*> DefaultOps;
3185 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
3187 // Find some SDNode.
3188 assert(!SDNodes.empty() && "No SDNodes parsed?");
3189 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
3191 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3192 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3194 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3195 // SomeSDnode so that we can parse this.
3196 std::vector<std::pair<Init*, StringInit*> > Ops;
3197 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3198 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3199 DefaultInfo->getArgName(op)));
3200 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3202 // Create a TreePattern to parse this.
3203 TreePattern P(DefaultOps[i], DI, false, *this);
3204 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3206 // Copy the operands over into a DAGDefaultOperand.
3207 DAGDefaultOperand DefaultOpInfo;
3209 const TreePatternNodePtr &T = P.getTree(0);
3210 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3211 TreePatternNodePtr TPN = T->getChildShared(op);
3212 while (TPN->ApplyTypeConstraints(P, false))
3213 /* Resolve all types */;
3215 if (TPN->ContainsUnresolvedType(P)) {
3216 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3217 DefaultOps[i]->getName() +
3218 "' doesn't have a concrete type!");
3220 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
3223 // Insert it into the DefaultOperands map so we can find it later.
3224 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3228 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3229 /// instruction input. Return true if this is a real use.
3230 static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3231 std::map<std::string, TreePatternNodePtr> &InstInputs) {
3232 // No name -> not interesting.
3233 if (Pat->getName().empty()) {
3234 if (Pat->isLeaf()) {
3235 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3236 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3237 DI->getDef()->isSubClassOf("RegisterOperand")))
3238 I.error("Input " + DI->getDef()->getName() + " must be named!");
3240 return false;
3243 Record *Rec;
3244 if (Pat->isLeaf()) {
3245 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3246 if (!DI)
3247 I.error("Input $" + Pat->getName() + " must be an identifier!");
3248 Rec = DI->getDef();
3249 } else {
3250 Rec = Pat->getOperator();
3253 // SRCVALUE nodes are ignored.
3254 if (Rec->getName() == "srcvalue")
3255 return false;
3257 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3258 if (!Slot) {
3259 Slot = Pat;
3260 return true;
3262 Record *SlotRec;
3263 if (Slot->isLeaf()) {
3264 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3265 } else {
3266 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3267 SlotRec = Slot->getOperator();
3270 // Ensure that the inputs agree if we've already seen this input.
3271 if (Rec != SlotRec)
3272 I.error("All $" + Pat->getName() + " inputs must agree with each other");
3273 // Ensure that the types can agree as well.
3274 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3275 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
3276 if (Slot->getExtTypes() != Pat->getExtTypes())
3277 I.error("All $" + Pat->getName() + " inputs must agree with each other");
3278 return true;
3281 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3282 /// part of "I", the instruction), computing the set of inputs and outputs of
3283 /// the pattern. Report errors if we see anything naughty.
3284 void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3285 TreePattern &I, TreePatternNodePtr Pat,
3286 std::map<std::string, TreePatternNodePtr> &InstInputs,
3287 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3288 &InstResults,
3289 std::vector<Record *> &InstImpResults) {
3291 // The instruction pattern still has unresolved fragments. For *named*
3292 // nodes we must resolve those here. This may not result in multiple
3293 // alternatives.
3294 if (!Pat->getName().empty()) {
3295 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3296 SrcPattern.InlinePatternFragments();
3297 SrcPattern.InferAllTypes();
3298 Pat = SrcPattern.getOnlyTree();
3301 if (Pat->isLeaf()) {
3302 bool isUse = HandleUse(I, Pat, InstInputs);
3303 if (!isUse && Pat->getTransformFn())
3304 I.error("Cannot specify a transform function for a non-input value!");
3305 return;
3308 if (Pat->getOperator()->getName() == "implicit") {
3309 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3310 TreePatternNode *Dest = Pat->getChild(i);
3311 if (!Dest->isLeaf())
3312 I.error("implicitly defined value should be a register!");
3314 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3315 if (!Val || !Val->getDef()->isSubClassOf("Register"))
3316 I.error("implicitly defined value should be a register!");
3317 InstImpResults.push_back(Val->getDef());
3319 return;
3322 if (Pat->getOperator()->getName() != "set") {
3323 // If this is not a set, verify that the children nodes are not void typed,
3324 // and recurse.
3325 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3326 if (Pat->getChild(i)->getNumTypes() == 0)
3327 I.error("Cannot have void nodes inside of patterns!");
3328 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3329 InstResults, InstImpResults);
3332 // If this is a non-leaf node with no children, treat it basically as if
3333 // it were a leaf. This handles nodes like (imm).
3334 bool isUse = HandleUse(I, Pat, InstInputs);
3336 if (!isUse && Pat->getTransformFn())
3337 I.error("Cannot specify a transform function for a non-input value!");
3338 return;
3341 // Otherwise, this is a set, validate and collect instruction results.
3342 if (Pat->getNumChildren() == 0)
3343 I.error("set requires operands!");
3345 if (Pat->getTransformFn())
3346 I.error("Cannot specify a transform function on a set node!");
3348 // Check the set destinations.
3349 unsigned NumDests = Pat->getNumChildren()-1;
3350 for (unsigned i = 0; i != NumDests; ++i) {
3351 TreePatternNodePtr Dest = Pat->getChildShared(i);
3352 // For set destinations we also must resolve fragments here.
3353 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3354 DestPattern.InlinePatternFragments();
3355 DestPattern.InferAllTypes();
3356 Dest = DestPattern.getOnlyTree();
3358 if (!Dest->isLeaf())
3359 I.error("set destination should be a register!");
3361 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3362 if (!Val) {
3363 I.error("set destination should be a register!");
3364 continue;
3367 if (Val->getDef()->isSubClassOf("RegisterClass") ||
3368 Val->getDef()->isSubClassOf("ValueType") ||
3369 Val->getDef()->isSubClassOf("RegisterOperand") ||
3370 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3371 if (Dest->getName().empty())
3372 I.error("set destination must have a name!");
3373 if (InstResults.count(Dest->getName()))
3374 I.error("cannot set '" + Dest->getName() + "' multiple times");
3375 InstResults[Dest->getName()] = Dest;
3376 } else if (Val->getDef()->isSubClassOf("Register")) {
3377 InstImpResults.push_back(Val->getDef());
3378 } else {
3379 I.error("set destination should be a register!");
3383 // Verify and collect info from the computation.
3384 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3385 InstResults, InstImpResults);
3388 //===----------------------------------------------------------------------===//
3389 // Instruction Analysis
3390 //===----------------------------------------------------------------------===//
3392 class InstAnalyzer {
3393 const CodeGenDAGPatterns &CDP;
3394 public:
3395 bool hasSideEffects;
3396 bool mayStore;
3397 bool mayLoad;
3398 bool isBitcast;
3399 bool isVariadic;
3400 bool hasChain;
3402 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3403 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3404 isBitcast(false), isVariadic(false), hasChain(false) {}
3406 void Analyze(const PatternToMatch &Pat) {
3407 const TreePatternNode *N = Pat.getSrcPattern();
3408 AnalyzeNode(N);
3409 // These properties are detected only on the root node.
3410 isBitcast = IsNodeBitcast(N);
3413 private:
3414 bool IsNodeBitcast(const TreePatternNode *N) const {
3415 if (hasSideEffects || mayLoad || mayStore || isVariadic)
3416 return false;
3418 if (N->isLeaf())
3419 return false;
3420 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
3421 return false;
3423 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
3424 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3425 return false;
3426 return OpInfo.getEnumName() == "ISD::BITCAST";
3429 public:
3430 void AnalyzeNode(const TreePatternNode *N) {
3431 if (N->isLeaf()) {
3432 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
3433 Record *LeafRec = DI->getDef();
3434 // Handle ComplexPattern leaves.
3435 if (LeafRec->isSubClassOf("ComplexPattern")) {
3436 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3437 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3438 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
3439 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
3442 return;
3445 // Analyze children.
3446 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3447 AnalyzeNode(N->getChild(i));
3449 // Notice properties of the node.
3450 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3451 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3452 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3453 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
3454 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
3456 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3457 // If this is an intrinsic, analyze it.
3458 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
3459 mayLoad = true;// These may load memory.
3461 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
3462 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3464 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3465 IntInfo->hasSideEffects)
3466 // ReadWriteMem intrinsics can have other strange effects.
3467 hasSideEffects = true;
3473 static bool InferFromPattern(CodeGenInstruction &InstInfo,
3474 const InstAnalyzer &PatInfo,
3475 Record *PatDef) {
3476 bool Error = false;
3478 // Remember where InstInfo got its flags.
3479 if (InstInfo.hasUndefFlags())
3480 InstInfo.InferredFrom = PatDef;
3482 // Check explicitly set flags for consistency.
3483 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3484 !InstInfo.hasSideEffects_Unset) {
3485 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3486 // the pattern has no side effects. That could be useful for div/rem
3487 // instructions that may trap.
3488 if (!InstInfo.hasSideEffects) {
3489 Error = true;
3490 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3491 Twine(InstInfo.hasSideEffects));
3495 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3496 Error = true;
3497 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3498 Twine(InstInfo.mayStore));
3501 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3502 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3503 // Some targets translate immediates to loads.
3504 if (!InstInfo.mayLoad) {
3505 Error = true;
3506 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3507 Twine(InstInfo.mayLoad));
3511 // Transfer inferred flags.
3512 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3513 InstInfo.mayStore |= PatInfo.mayStore;
3514 InstInfo.mayLoad |= PatInfo.mayLoad;
3516 // These flags are silently added without any verification.
3517 // FIXME: To match historical behavior of TableGen, for now add those flags
3518 // only when we're inferring from the primary instruction pattern.
3519 if (PatDef->isSubClassOf("Instruction")) {
3520 InstInfo.isBitcast |= PatInfo.isBitcast;
3521 InstInfo.hasChain |= PatInfo.hasChain;
3522 InstInfo.hasChain_Inferred = true;
3525 // Don't infer isVariadic. This flag means something different on SDNodes and
3526 // instructions. For example, a CALL SDNode is variadic because it has the
3527 // call arguments as operands, but a CALL instruction is not variadic - it
3528 // has argument registers as implicit, not explicit uses.
3530 return Error;
3533 /// hasNullFragReference - Return true if the DAG has any reference to the
3534 /// null_frag operator.
3535 static bool hasNullFragReference(DagInit *DI) {
3536 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
3537 if (!OpDef) return false;
3538 Record *Operator = OpDef->getDef();
3540 // If this is the null fragment, return true.
3541 if (Operator->getName() == "null_frag") return true;
3542 // If any of the arguments reference the null fragment, return true.
3543 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3544 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
3545 if (Arg && hasNullFragReference(Arg))
3546 return true;
3549 return false;
3552 /// hasNullFragReference - Return true if any DAG in the list references
3553 /// the null_frag operator.
3554 static bool hasNullFragReference(ListInit *LI) {
3555 for (Init *I : LI->getValues()) {
3556 DagInit *DI = dyn_cast<DagInit>(I);
3557 assert(DI && "non-dag in an instruction Pattern list?!");
3558 if (hasNullFragReference(DI))
3559 return true;
3561 return false;
3564 /// Get all the instructions in a tree.
3565 static void
3566 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3567 if (Tree->isLeaf())
3568 return;
3569 if (Tree->getOperator()->isSubClassOf("Instruction"))
3570 Instrs.push_back(Tree->getOperator());
3571 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3572 getInstructionsInTree(Tree->getChild(i), Instrs);
3575 /// Check the class of a pattern leaf node against the instruction operand it
3576 /// represents.
3577 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3578 Record *Leaf) {
3579 if (OI.Rec == Leaf)
3580 return true;
3582 // Allow direct value types to be used in instruction set patterns.
3583 // The type will be checked later.
3584 if (Leaf->isSubClassOf("ValueType"))
3585 return true;
3587 // Patterns can also be ComplexPattern instances.
3588 if (Leaf->isSubClassOf("ComplexPattern"))
3589 return true;
3591 return false;
3594 void CodeGenDAGPatterns::parseInstructionPattern(
3595 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
3597 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3599 // Parse the instruction.
3600 TreePattern I(CGI.TheDef, Pat, true, *this);
3602 // InstInputs - Keep track of all of the inputs of the instruction, along
3603 // with the record they are declared as.
3604 std::map<std::string, TreePatternNodePtr> InstInputs;
3606 // InstResults - Keep track of all the virtual registers that are 'set'
3607 // in the instruction, including what reg class they are.
3608 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3609 InstResults;
3611 std::vector<Record*> InstImpResults;
3613 // Verify that the top-level forms in the instruction are of void type, and
3614 // fill in the InstResults map.
3615 SmallString<32> TypesString;
3616 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3617 TypesString.clear();
3618 TreePatternNodePtr Pat = I.getTree(j);
3619 if (Pat->getNumTypes() != 0) {
3620 raw_svector_ostream OS(TypesString);
3621 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3622 if (k > 0)
3623 OS << ", ";
3624 Pat->getExtType(k).writeToStream(OS);
3626 I.error("Top-level forms in instruction pattern should have"
3627 " void types, has types " +
3628 OS.str());
3631 // Find inputs and outputs, and verify the structure of the uses/defs.
3632 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3633 InstImpResults);
3636 // Now that we have inputs and outputs of the pattern, inspect the operands
3637 // list for the instruction. This determines the order that operands are
3638 // added to the machine instruction the node corresponds to.
3639 unsigned NumResults = InstResults.size();
3641 // Parse the operands list from the (ops) list, validating it.
3642 assert(I.getArgList().empty() && "Args list should still be empty here!");
3644 // Check that all of the results occur first in the list.
3645 std::vector<Record*> Results;
3646 std::vector<unsigned> ResultIndices;
3647 SmallVector<TreePatternNodePtr, 2> ResNodes;
3648 for (unsigned i = 0; i != NumResults; ++i) {
3649 if (i == CGI.Operands.size()) {
3650 const std::string &OpName =
3651 std::find_if(InstResults.begin(), InstResults.end(),
3652 [](const std::pair<std::string, TreePatternNodePtr> &P) {
3653 return P.second;
3655 ->first;
3657 I.error("'" + OpName + "' set but does not appear in operand list!");
3660 const std::string &OpName = CGI.Operands[i].Name;
3662 // Check that it exists in InstResults.
3663 auto InstResultIter = InstResults.find(OpName);
3664 if (InstResultIter == InstResults.end() || !InstResultIter->second)
3665 I.error("Operand $" + OpName + " does not exist in operand list!");
3667 TreePatternNodePtr RNode = InstResultIter->second;
3668 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3669 ResNodes.push_back(std::move(RNode));
3670 if (!R)
3671 I.error("Operand $" + OpName + " should be a set destination: all "
3672 "outputs must occur before inputs in operand list!");
3674 if (!checkOperandClass(CGI.Operands[i], R))
3675 I.error("Operand $" + OpName + " class mismatch!");
3677 // Remember the return type.
3678 Results.push_back(CGI.Operands[i].Rec);
3680 // Remember the result index.
3681 ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3683 // Okay, this one checks out.
3684 InstResultIter->second = nullptr;
3687 // Loop over the inputs next.
3688 std::vector<TreePatternNodePtr> ResultNodeOperands;
3689 std::vector<Record*> Operands;
3690 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3691 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3692 const std::string &OpName = Op.Name;
3693 if (OpName.empty())
3694 I.error("Operand #" + Twine(i) + " in operands list has no name!");
3696 if (!InstInputs.count(OpName)) {
3697 // If this is an operand with a DefaultOps set filled in, we can ignore
3698 // this. When we codegen it, we will do so as always executed.
3699 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3700 // Does it have a non-empty DefaultOps field? If so, ignore this
3701 // operand.
3702 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3703 continue;
3705 I.error("Operand $" + OpName +
3706 " does not appear in the instruction pattern");
3708 TreePatternNodePtr InVal = InstInputs[OpName];
3709 InstInputs.erase(OpName); // It occurred, remove from map.
3711 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3712 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3713 if (!checkOperandClass(Op, InRec))
3714 I.error("Operand $" + OpName + "'s register class disagrees"
3715 " between the operand and pattern");
3717 Operands.push_back(Op.Rec);
3719 // Construct the result for the dest-pattern operand list.
3720 TreePatternNodePtr OpNode = InVal->clone();
3722 // No predicate is useful on the result.
3723 OpNode->clearPredicateCalls();
3725 // Promote the xform function to be an explicit node if set.
3726 if (Record *Xform = OpNode->getTransformFn()) {
3727 OpNode->setTransformFn(nullptr);
3728 std::vector<TreePatternNodePtr> Children;
3729 Children.push_back(OpNode);
3730 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
3731 OpNode->getNumTypes());
3734 ResultNodeOperands.push_back(std::move(OpNode));
3737 if (!InstInputs.empty())
3738 I.error("Input operand $" + InstInputs.begin()->first +
3739 " occurs in pattern but not in operands list!");
3741 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
3742 I.getRecord(), std::move(ResultNodeOperands),
3743 GetNumNodeResults(I.getRecord(), *this));
3744 // Copy fully inferred output node types to instruction result pattern.
3745 for (unsigned i = 0; i != NumResults; ++i) {
3746 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3747 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3748 ResultPattern->setResultIndex(i, ResultIndices[i]);
3751 // FIXME: Assume only the first tree is the pattern. The others are clobber
3752 // nodes.
3753 TreePatternNodePtr Pattern = I.getTree(0);
3754 TreePatternNodePtr SrcPattern;
3755 if (Pattern->getOperator()->getName() == "set") {
3756 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3757 } else{
3758 // Not a set (store or something?)
3759 SrcPattern = Pattern;
3762 // Create and insert the instruction.
3763 // FIXME: InstImpResults should not be part of DAGInstruction.
3764 Record *R = I.getRecord();
3765 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3766 std::forward_as_tuple(Results, Operands, InstImpResults,
3767 SrcPattern, ResultPattern));
3769 LLVM_DEBUG(I.dump());
3772 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3773 /// any fragments involved. This populates the Instructions list with fully
3774 /// resolved instructions.
3775 void CodeGenDAGPatterns::ParseInstructions() {
3776 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3778 for (Record *Instr : Instrs) {
3779 ListInit *LI = nullptr;
3781 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3782 LI = Instr->getValueAsListInit("Pattern");
3784 // If there is no pattern, only collect minimal information about the
3785 // instruction for its operand list. We have to assume that there is one
3786 // result, as we have no detailed info. A pattern which references the
3787 // null_frag operator is as-if no pattern were specified. Normally this
3788 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3789 // null_frag.
3790 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3791 std::vector<Record*> Results;
3792 std::vector<Record*> Operands;
3794 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3796 if (InstInfo.Operands.size() != 0) {
3797 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3798 Results.push_back(InstInfo.Operands[j].Rec);
3800 // The rest are inputs.
3801 for (unsigned j = InstInfo.Operands.NumDefs,
3802 e = InstInfo.Operands.size(); j < e; ++j)
3803 Operands.push_back(InstInfo.Operands[j].Rec);
3806 // Create and insert the instruction.
3807 std::vector<Record*> ImpResults;
3808 Instructions.insert(std::make_pair(Instr,
3809 DAGInstruction(Results, Operands, ImpResults)));
3810 continue; // no pattern.
3813 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3814 parseInstructionPattern(CGI, LI, Instructions);
3817 // If we can, convert the instructions to be patterns that are matched!
3818 for (auto &Entry : Instructions) {
3819 Record *Instr = Entry.first;
3820 DAGInstruction &TheInst = Entry.second;
3821 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3822 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3824 if (SrcPattern && ResultPattern) {
3825 TreePattern Pattern(Instr, SrcPattern, true, *this);
3826 TreePattern Result(Instr, ResultPattern, false, *this);
3827 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3832 typedef std::pair<TreePatternNode *, unsigned> NameRecord;
3834 static void FindNames(TreePatternNode *P,
3835 std::map<std::string, NameRecord> &Names,
3836 TreePattern *PatternTop) {
3837 if (!P->getName().empty()) {
3838 NameRecord &Rec = Names[P->getName()];
3839 // If this is the first instance of the name, remember the node.
3840 if (Rec.second++ == 0)
3841 Rec.first = P;
3842 else if (Rec.first->getExtTypes() != P->getExtTypes())
3843 PatternTop->error("repetition of value: $" + P->getName() +
3844 " where different uses have different types!");
3847 if (!P->isLeaf()) {
3848 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3849 FindNames(P->getChild(i), Names, PatternTop);
3853 std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3854 std::vector<Predicate> Preds;
3855 for (Init *I : L->getValues()) {
3856 if (DefInit *Pred = dyn_cast<DefInit>(I))
3857 Preds.push_back(Pred->getDef());
3858 else
3859 llvm_unreachable("Non-def on the list");
3862 // Sort so that different orders get canonicalized to the same string.
3863 llvm::sort(Preds);
3864 return Preds;
3867 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3868 PatternToMatch &&PTM) {
3869 // Do some sanity checking on the pattern we're about to match.
3870 std::string Reason;
3871 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3872 PrintWarning(Pattern->getRecord()->getLoc(),
3873 Twine("Pattern can never match: ") + Reason);
3874 return;
3877 // If the source pattern's root is a complex pattern, that complex pattern
3878 // must specify the nodes it can potentially match.
3879 if (const ComplexPattern *CP =
3880 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3881 if (CP->getRootNodes().empty())
3882 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3883 " could match");
3886 // Find all of the named values in the input and output, ensure they have the
3887 // same type.
3888 std::map<std::string, NameRecord> SrcNames, DstNames;
3889 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3890 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3892 // Scan all of the named values in the destination pattern, rejecting them if
3893 // they don't exist in the input pattern.
3894 for (const auto &Entry : DstNames) {
3895 if (SrcNames[Entry.first].first == nullptr)
3896 Pattern->error("Pattern has input without matching name in output: $" +
3897 Entry.first);
3900 // Scan all of the named values in the source pattern, rejecting them if the
3901 // name isn't used in the dest, and isn't used to tie two values together.
3902 for (const auto &Entry : SrcNames)
3903 if (DstNames[Entry.first].first == nullptr &&
3904 SrcNames[Entry.first].second == 1)
3905 Pattern->error("Pattern has dead named input: $" + Entry.first);
3907 PatternsToMatch.push_back(PTM);
3910 void CodeGenDAGPatterns::InferInstructionFlags() {
3911 ArrayRef<const CodeGenInstruction*> Instructions =
3912 Target.getInstructionsByEnumValue();
3914 unsigned Errors = 0;
3916 // Try to infer flags from all patterns in PatternToMatch. These include
3917 // both the primary instruction patterns (which always come first) and
3918 // patterns defined outside the instruction.
3919 for (const PatternToMatch &PTM : ptms()) {
3920 // We can only infer from single-instruction patterns, otherwise we won't
3921 // know which instruction should get the flags.
3922 SmallVector<Record*, 8> PatInstrs;
3923 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3924 if (PatInstrs.size() != 1)
3925 continue;
3927 // Get the single instruction.
3928 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3930 // Only infer properties from the first pattern. We'll verify the others.
3931 if (InstInfo.InferredFrom)
3932 continue;
3934 InstAnalyzer PatInfo(*this);
3935 PatInfo.Analyze(PTM);
3936 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3939 if (Errors)
3940 PrintFatalError("pattern conflicts");
3942 // If requested by the target, guess any undefined properties.
3943 if (Target.guessInstructionProperties()) {
3944 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3945 CodeGenInstruction *InstInfo =
3946 const_cast<CodeGenInstruction *>(Instructions[i]);
3947 if (InstInfo->InferredFrom)
3948 continue;
3949 // The mayLoad and mayStore flags default to false.
3950 // Conservatively assume hasSideEffects if it wasn't explicit.
3951 if (InstInfo->hasSideEffects_Unset)
3952 InstInfo->hasSideEffects = true;
3954 return;
3957 // Complain about any flags that are still undefined.
3958 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3959 CodeGenInstruction *InstInfo =
3960 const_cast<CodeGenInstruction *>(Instructions[i]);
3961 if (InstInfo->InferredFrom)
3962 continue;
3963 if (InstInfo->hasSideEffects_Unset)
3964 PrintError(InstInfo->TheDef->getLoc(),
3965 "Can't infer hasSideEffects from patterns");
3966 if (InstInfo->mayStore_Unset)
3967 PrintError(InstInfo->TheDef->getLoc(),
3968 "Can't infer mayStore from patterns");
3969 if (InstInfo->mayLoad_Unset)
3970 PrintError(InstInfo->TheDef->getLoc(),
3971 "Can't infer mayLoad from patterns");
3976 /// Verify instruction flags against pattern node properties.
3977 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3978 unsigned Errors = 0;
3979 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3980 const PatternToMatch &PTM = *I;
3981 SmallVector<Record*, 8> Instrs;
3982 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3983 if (Instrs.empty())
3984 continue;
3986 // Count the number of instructions with each flag set.
3987 unsigned NumSideEffects = 0;
3988 unsigned NumStores = 0;
3989 unsigned NumLoads = 0;
3990 for (const Record *Instr : Instrs) {
3991 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3992 NumSideEffects += InstInfo.hasSideEffects;
3993 NumStores += InstInfo.mayStore;
3994 NumLoads += InstInfo.mayLoad;
3997 // Analyze the source pattern.
3998 InstAnalyzer PatInfo(*this);
3999 PatInfo.Analyze(PTM);
4001 // Collect error messages.
4002 SmallVector<std::string, 4> Msgs;
4004 // Check for missing flags in the output.
4005 // Permit extra flags for now at least.
4006 if (PatInfo.hasSideEffects && !NumSideEffects)
4007 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
4009 // Don't verify store flags on instructions with side effects. At least for
4010 // intrinsics, side effects implies mayStore.
4011 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4012 Msgs.push_back("pattern may store, but mayStore isn't set");
4014 // Similarly, mayStore implies mayLoad on intrinsics.
4015 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4016 Msgs.push_back("pattern may load, but mayLoad isn't set");
4018 // Print error messages.
4019 if (Msgs.empty())
4020 continue;
4021 ++Errors;
4023 for (const std::string &Msg : Msgs)
4024 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
4025 (Instrs.size() == 1 ?
4026 "instruction" : "output instructions"));
4027 // Provide the location of the relevant instruction definitions.
4028 for (const Record *Instr : Instrs) {
4029 if (Instr != PTM.getSrcRecord())
4030 PrintError(Instr->getLoc(), "defined here");
4031 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
4032 if (InstInfo.InferredFrom &&
4033 InstInfo.InferredFrom != InstInfo.TheDef &&
4034 InstInfo.InferredFrom != PTM.getSrcRecord())
4035 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
4038 if (Errors)
4039 PrintFatalError("Errors in DAG patterns");
4042 /// Given a pattern result with an unresolved type, see if we can find one
4043 /// instruction with an unresolved result type. Force this result type to an
4044 /// arbitrary element if it's possible types to converge results.
4045 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
4046 if (N->isLeaf())
4047 return false;
4049 // Analyze children.
4050 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4051 if (ForceArbitraryInstResultType(N->getChild(i), TP))
4052 return true;
4054 if (!N->getOperator()->isSubClassOf("Instruction"))
4055 return false;
4057 // If this type is already concrete or completely unknown we can't do
4058 // anything.
4059 TypeInfer &TI = TP.getInfer();
4060 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
4061 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
4062 continue;
4064 // Otherwise, force its type to an arbitrary choice.
4065 if (TI.forceArbitrary(N->getExtType(i)))
4066 return true;
4069 return false;
4072 // Promote xform function to be an explicit node wherever set.
4073 static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4074 if (Record *Xform = N->getTransformFn()) {
4075 N->setTransformFn(nullptr);
4076 std::vector<TreePatternNodePtr> Children;
4077 Children.push_back(PromoteXForms(N));
4078 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
4079 N->getNumTypes());
4082 if (!N->isLeaf())
4083 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4084 TreePatternNodePtr Child = N->getChildShared(i);
4085 N->setChild(i, PromoteXForms(Child));
4087 return N;
4090 void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
4091 TreePattern &Pattern, TreePattern &Result,
4092 const std::vector<Record *> &InstImpResults) {
4094 // Inline pattern fragments and expand multiple alternatives.
4095 Pattern.InlinePatternFragments();
4096 Result.InlinePatternFragments();
4098 if (Result.getNumTrees() != 1)
4099 Result.error("Cannot use multi-alternative fragments in result pattern!");
4101 // Infer types.
4102 bool IterateInference;
4103 bool InferredAllPatternTypes, InferredAllResultTypes;
4104 do {
4105 // Infer as many types as possible. If we cannot infer all of them, we
4106 // can never do anything with this pattern: report it to the user.
4107 InferredAllPatternTypes =
4108 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4110 // Infer as many types as possible. If we cannot infer all of them, we
4111 // can never do anything with this pattern: report it to the user.
4112 InferredAllResultTypes =
4113 Result.InferAllTypes(&Pattern.getNamedNodesMap());
4115 IterateInference = false;
4117 // Apply the type of the result to the source pattern. This helps us
4118 // resolve cases where the input type is known to be a pointer type (which
4119 // is considered resolved), but the result knows it needs to be 32- or
4120 // 64-bits. Infer the other way for good measure.
4121 for (auto T : Pattern.getTrees())
4122 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4123 T->getNumTypes());
4124 i != e; ++i) {
4125 IterateInference |= T->UpdateNodeType(
4126 i, Result.getOnlyTree()->getExtType(i), Result);
4127 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4128 i, T->getExtType(i), Result);
4131 // If our iteration has converged and the input pattern's types are fully
4132 // resolved but the result pattern is not fully resolved, we may have a
4133 // situation where we have two instructions in the result pattern and
4134 // the instructions require a common register class, but don't care about
4135 // what actual MVT is used. This is actually a bug in our modelling:
4136 // output patterns should have register classes, not MVTs.
4138 // In any case, to handle this, we just go through and disambiguate some
4139 // arbitrary types to the result pattern's nodes.
4140 if (!IterateInference && InferredAllPatternTypes &&
4141 !InferredAllResultTypes)
4142 IterateInference =
4143 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4144 } while (IterateInference);
4146 // Verify that we inferred enough types that we can do something with the
4147 // pattern and result. If these fire the user has to add type casts.
4148 if (!InferredAllPatternTypes)
4149 Pattern.error("Could not infer all types in pattern!");
4150 if (!InferredAllResultTypes) {
4151 Pattern.dump();
4152 Result.error("Could not infer all types in pattern result!");
4155 // Promote xform function to be an explicit node wherever set.
4156 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
4158 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4159 Temp.InferAllTypes();
4161 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4162 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4164 if (PatternRewriter)
4165 PatternRewriter(&Pattern);
4167 // A pattern may end up with an "impossible" type, i.e. a situation
4168 // where all types have been eliminated for some node in this pattern.
4169 // This could occur for intrinsics that only make sense for a specific
4170 // value type, and use a specific register class. If, for some mode,
4171 // that register class does not accept that type, the type inference
4172 // will lead to a contradiction, which is not an error however, but
4173 // a sign that this pattern will simply never match.
4174 if (Temp.getOnlyTree()->hasPossibleType())
4175 for (auto T : Pattern.getTrees())
4176 if (T->hasPossibleType())
4177 AddPatternToMatch(&Pattern,
4178 PatternToMatch(TheDef, makePredList(Preds),
4179 T, Temp.getOnlyTree(),
4180 InstImpResults, Complexity,
4181 TheDef->getID()));
4184 void CodeGenDAGPatterns::ParsePatterns() {
4185 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4187 for (Record *CurPattern : Patterns) {
4188 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
4190 // If the pattern references the null_frag, there's nothing to do.
4191 if (hasNullFragReference(Tree))
4192 continue;
4194 TreePattern Pattern(CurPattern, Tree, true, *this);
4196 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
4197 if (LI->empty()) continue; // no pattern.
4199 // Parse the instruction.
4200 TreePattern Result(CurPattern, LI, false, *this);
4202 if (Result.getNumTrees() != 1)
4203 Result.error("Cannot handle instructions producing instructions "
4204 "with temporaries yet!");
4206 // Validate that the input pattern is correct.
4207 std::map<std::string, TreePatternNodePtr> InstInputs;
4208 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4209 InstResults;
4210 std::vector<Record*> InstImpResults;
4211 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4212 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
4213 InstResults, InstImpResults);
4215 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
4219 static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
4220 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4221 for (const auto &I : VTS)
4222 Modes.insert(I.first);
4224 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4225 collectModes(Modes, N->getChild(i));
4228 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4229 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4230 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4231 std::vector<PatternToMatch> Copy = PatternsToMatch;
4232 PatternsToMatch.clear();
4234 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4235 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4236 TreePatternNodePtr NewDst = P.DstPattern->clone();
4237 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4238 return;
4241 std::vector<Predicate> Preds = P.Predicates;
4242 const std::vector<Predicate> &MC = ModeChecks[Mode];
4243 Preds.insert(Preds.end(), MC.begin(), MC.end());
4244 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4245 std::move(NewDst), P.getDstRegs(),
4246 P.getAddedComplexity(), Record::getNewUID(),
4247 Mode);
4250 for (PatternToMatch &P : Copy) {
4251 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
4252 if (P.SrcPattern->hasProperTypeByHwMode())
4253 SrcP = P.SrcPattern;
4254 if (P.DstPattern->hasProperTypeByHwMode())
4255 DstP = P.DstPattern;
4256 if (!SrcP && !DstP) {
4257 PatternsToMatch.push_back(P);
4258 continue;
4261 std::set<unsigned> Modes;
4262 if (SrcP)
4263 collectModes(Modes, SrcP.get());
4264 if (DstP)
4265 collectModes(Modes, DstP.get());
4267 // The predicate for the default mode needs to be constructed for each
4268 // pattern separately.
4269 // Since not all modes must be present in each pattern, if a mode m is
4270 // absent, then there is no point in constructing a check for m. If such
4271 // a check was created, it would be equivalent to checking the default
4272 // mode, except not all modes' predicates would be a part of the checking
4273 // code. The subsequently generated check for the default mode would then
4274 // have the exact same patterns, but a different predicate code. To avoid
4275 // duplicated patterns with different predicate checks, construct the
4276 // default check as a negation of all predicates that are actually present
4277 // in the source/destination patterns.
4278 std::vector<Predicate> DefaultPred;
4280 for (unsigned M : Modes) {
4281 if (M == DefaultMode)
4282 continue;
4283 if (ModeChecks.find(M) != ModeChecks.end())
4284 continue;
4286 // Fill the map entry for this mode.
4287 const HwMode &HM = CGH.getMode(M);
4288 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4290 // Add negations of the HM's predicates to the default predicate.
4291 DefaultPred.emplace_back(Predicate(HM.Features, false));
4294 for (unsigned M : Modes) {
4295 if (M == DefaultMode)
4296 continue;
4297 AppendPattern(P, M);
4300 bool HasDefault = Modes.count(DefaultMode);
4301 if (HasDefault)
4302 AppendPattern(P, DefaultMode);
4306 /// Dependent variable map for CodeGenDAGPattern variant generation
4307 typedef StringMap<int> DepVarMap;
4309 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4310 if (N->isLeaf()) {
4311 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4312 DepMap[N->getName()]++;
4313 } else {
4314 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4315 FindDepVarsOf(N->getChild(i), DepMap);
4319 /// Find dependent variables within child patterns
4320 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4321 DepVarMap depcounts;
4322 FindDepVarsOf(N, depcounts);
4323 for (const auto &Pair : depcounts) {
4324 if (Pair.getValue() > 1)
4325 DepVars.insert(Pair.getKey());
4329 #ifndef NDEBUG
4330 /// Dump the dependent variable set:
4331 static void DumpDepVars(MultipleUseVarSet &DepVars) {
4332 if (DepVars.empty()) {
4333 LLVM_DEBUG(errs() << "<empty set>");
4334 } else {
4335 LLVM_DEBUG(errs() << "[ ");
4336 for (const auto &DepVar : DepVars) {
4337 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
4339 LLVM_DEBUG(errs() << "]");
4342 #endif
4345 /// CombineChildVariants - Given a bunch of permutations of each child of the
4346 /// 'operator' node, put them together in all possible ways.
4347 static void CombineChildVariants(
4348 TreePatternNodePtr Orig,
4349 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4350 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4351 const MultipleUseVarSet &DepVars) {
4352 // Make sure that each operand has at least one variant to choose from.
4353 for (const auto &Variants : ChildVariants)
4354 if (Variants.empty())
4355 return;
4357 // The end result is an all-pairs construction of the resultant pattern.
4358 std::vector<unsigned> Idxs;
4359 Idxs.resize(ChildVariants.size());
4360 bool NotDone;
4361 do {
4362 #ifndef NDEBUG
4363 LLVM_DEBUG(if (!Idxs.empty()) {
4364 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4365 for (unsigned Idx : Idxs) {
4366 errs() << Idx << " ";
4368 errs() << "]\n";
4370 #endif
4371 // Create the variant and add it to the output list.
4372 std::vector<TreePatternNodePtr> NewChildren;
4373 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4374 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
4375 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
4376 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
4378 // Copy over properties.
4379 R->setName(Orig->getName());
4380 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4381 R->setPredicateCalls(Orig->getPredicateCalls());
4382 R->setTransformFn(Orig->getTransformFn());
4383 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4384 R->setType(i, Orig->getExtType(i));
4386 // If this pattern cannot match, do not include it as a variant.
4387 std::string ErrString;
4388 // Scan to see if this pattern has already been emitted. We can get
4389 // duplication due to things like commuting:
4390 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4391 // which are the same pattern. Ignore the dups.
4392 if (R->canPatternMatch(ErrString, CDP) &&
4393 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
4394 return R->isIsomorphicTo(Variant.get(), DepVars);
4396 OutVariants.push_back(R);
4398 // Increment indices to the next permutation by incrementing the
4399 // indices from last index backward, e.g., generate the sequence
4400 // [0, 0], [0, 1], [1, 0], [1, 1].
4401 int IdxsIdx;
4402 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4403 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4404 Idxs[IdxsIdx] = 0;
4405 else
4406 break;
4408 NotDone = (IdxsIdx >= 0);
4409 } while (NotDone);
4412 /// CombineChildVariants - A helper function for binary operators.
4414 static void CombineChildVariants(TreePatternNodePtr Orig,
4415 const std::vector<TreePatternNodePtr> &LHS,
4416 const std::vector<TreePatternNodePtr> &RHS,
4417 std::vector<TreePatternNodePtr> &OutVariants,
4418 CodeGenDAGPatterns &CDP,
4419 const MultipleUseVarSet &DepVars) {
4420 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4421 ChildVariants.push_back(LHS);
4422 ChildVariants.push_back(RHS);
4423 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4426 static void
4427 GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4428 std::vector<TreePatternNodePtr> &Children) {
4429 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4430 Record *Operator = N->getOperator();
4432 // Only permit raw nodes.
4433 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
4434 N->getTransformFn()) {
4435 Children.push_back(N);
4436 return;
4439 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4440 Children.push_back(N->getChildShared(0));
4441 else
4442 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
4444 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4445 Children.push_back(N->getChildShared(1));
4446 else
4447 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
4450 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4451 /// the (potentially recursive) pattern by using algebraic laws.
4453 static void GenerateVariantsOf(TreePatternNodePtr N,
4454 std::vector<TreePatternNodePtr> &OutVariants,
4455 CodeGenDAGPatterns &CDP,
4456 const MultipleUseVarSet &DepVars) {
4457 // We cannot permute leaves or ComplexPattern uses.
4458 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4459 OutVariants.push_back(N);
4460 return;
4463 // Look up interesting info about the node.
4464 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4466 // If this node is associative, re-associate.
4467 if (NodeInfo.hasProperty(SDNPAssociative)) {
4468 // Re-associate by pulling together all of the linked operators
4469 std::vector<TreePatternNodePtr> MaximalChildren;
4470 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4472 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4473 // permutations.
4474 if (MaximalChildren.size() == 3) {
4475 // Find the variants of all of our maximal children.
4476 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4477 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4478 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4479 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4481 // There are only two ways we can permute the tree:
4482 // (A op B) op C and A op (B op C)
4483 // Within these forms, we can also permute A/B/C.
4485 // Generate legal pair permutations of A/B/C.
4486 std::vector<TreePatternNodePtr> ABVariants;
4487 std::vector<TreePatternNodePtr> BAVariants;
4488 std::vector<TreePatternNodePtr> ACVariants;
4489 std::vector<TreePatternNodePtr> CAVariants;
4490 std::vector<TreePatternNodePtr> BCVariants;
4491 std::vector<TreePatternNodePtr> CBVariants;
4492 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4493 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4494 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4495 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4496 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4497 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4499 // Combine those into the result: (x op x) op x
4500 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4501 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4502 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4503 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4504 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4505 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4507 // Combine those into the result: x op (x op x)
4508 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4509 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4510 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4511 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4512 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4513 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4514 return;
4518 // Compute permutations of all children.
4519 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4520 ChildVariants.resize(N->getNumChildren());
4521 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4522 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
4524 // Build all permutations based on how the children were formed.
4525 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4527 // If this node is commutative, consider the commuted order.
4528 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4529 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
4530 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
4531 "Commutative but doesn't have 2 children!");
4532 // Don't count children which are actually register references.
4533 unsigned NC = 0;
4534 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4535 TreePatternNode *Child = N->getChild(i);
4536 if (Child->isLeaf())
4537 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
4538 Record *RR = DI->getDef();
4539 if (RR->isSubClassOf("Register"))
4540 continue;
4542 NC++;
4544 // Consider the commuted order.
4545 if (isCommIntrinsic) {
4546 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4547 // operands are the commutative operands, and there might be more operands
4548 // after those.
4549 assert(NC >= 3 &&
4550 "Commutative intrinsic should have at least 3 children!");
4551 std::vector<std::vector<TreePatternNodePtr>> Variants;
4552 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4553 Variants.push_back(std::move(ChildVariants[2]));
4554 Variants.push_back(std::move(ChildVariants[1]));
4555 for (unsigned i = 3; i != NC; ++i)
4556 Variants.push_back(std::move(ChildVariants[i]));
4557 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4558 } else if (NC == N->getNumChildren()) {
4559 std::vector<std::vector<TreePatternNodePtr>> Variants;
4560 Variants.push_back(std::move(ChildVariants[1]));
4561 Variants.push_back(std::move(ChildVariants[0]));
4562 for (unsigned i = 2; i != NC; ++i)
4563 Variants.push_back(std::move(ChildVariants[i]));
4564 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4570 // GenerateVariants - Generate variants. For example, commutative patterns can
4571 // match multiple ways. Add them to PatternsToMatch as well.
4572 void CodeGenDAGPatterns::GenerateVariants() {
4573 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4575 // Loop over all of the patterns we've collected, checking to see if we can
4576 // generate variants of the instruction, through the exploitation of
4577 // identities. This permits the target to provide aggressive matching without
4578 // the .td file having to contain tons of variants of instructions.
4580 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4581 // intentionally do not reconsider these. Any variants of added patterns have
4582 // already been added.
4584 const unsigned NumOriginalPatterns = PatternsToMatch.size();
4585 BitVector MatchedPatterns(NumOriginalPatterns);
4586 std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4587 BitVector(NumOriginalPatterns));
4589 typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4590 DepsAndVariants;
4591 std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4593 // Collect patterns with more than one variant.
4594 for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4595 MultipleUseVarSet DepVars;
4596 std::vector<TreePatternNodePtr> Variants;
4597 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
4598 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4599 LLVM_DEBUG(DumpDepVars(DepVars));
4600 LLVM_DEBUG(errs() << "\n");
4601 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4602 *this, DepVars);
4604 assert(!Variants.empty() && "Must create at least original variant!");
4605 if (Variants.size() == 1) // No additional variants for this pattern.
4606 continue;
4608 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4609 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
4611 PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4613 // Cache matching predicates.
4614 if (MatchedPatterns[i])
4615 continue;
4617 const std::vector<Predicate> &Predicates =
4618 PatternsToMatch[i].getPredicates();
4620 BitVector &Matches = MatchedPredicates[i];
4621 MatchedPatterns.set(i);
4622 Matches.set(i);
4624 // Don't test patterns that have already been cached - it won't match.
4625 for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4626 if (!MatchedPatterns[p])
4627 Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4629 // Copy this to all the matching patterns.
4630 for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
4631 if (p != (int)i) {
4632 MatchedPatterns.set(p);
4633 MatchedPredicates[p] = Matches;
4637 for (auto it : PatternsWithVariants) {
4638 unsigned i = it.first;
4639 const MultipleUseVarSet &DepVars = it.second.first;
4640 const std::vector<TreePatternNodePtr> &Variants = it.second.second;
4642 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4643 TreePatternNodePtr Variant = Variants[v];
4644 BitVector &Matches = MatchedPredicates[i];
4646 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4647 errs() << "\n");
4649 // Scan to see if an instruction or explicit pattern already matches this.
4650 bool AlreadyExists = false;
4651 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4652 // Skip if the top level predicates do not match.
4653 if (!Matches[p])
4654 continue;
4655 // Check to see if this variant already exists.
4656 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4657 DepVars)) {
4658 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
4659 AlreadyExists = true;
4660 break;
4663 // If we already have it, ignore the variant.
4664 if (AlreadyExists) continue;
4666 // Otherwise, add it to the list of patterns we have.
4667 PatternsToMatch.push_back(PatternToMatch(
4668 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4669 Variant, PatternsToMatch[i].getDstPatternShared(),
4670 PatternsToMatch[i].getDstRegs(),
4671 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
4672 MatchedPredicates.push_back(Matches);
4674 // Add a new match the same as this pattern.
4675 for (auto &P : MatchedPredicates)
4676 P.push_back(P[i]);
4679 LLVM_DEBUG(errs() << "\n");