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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenDAGPatterns.h"
15#include "CodeGenInstruction.h"
16#include "CodeGenRegisters.h"
17#include "SubtargetFeatureInfo.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/Twine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/InterleavedRange.h"
29#include "llvm/Support/TypeSize.h"
30#include "llvm/TableGen/Error.h"
31#include "llvm/TableGen/Record.h"
32#include <algorithm>
33#include <cstdio>
34#include <iterator>
35#include <set>
36using namespace llvm;
37
38#define DEBUG_TYPE "dag-patterns"
39
40static inline bool isIntegerOrPtr(MVT VT) {
41 return VT.isInteger() || VT == MVT::iPTR;
42}
43static inline bool isFloatingPoint(MVT VT) { return VT.isFloatingPoint(); }
44static inline bool isVector(MVT VT) { return VT.isVector(); }
45static inline bool isScalar(MVT VT) { return !VT.isVector(); }
46
47template <typename Predicate>
48static bool berase_if(MachineValueTypeSet &S, Predicate P) {
49 bool Erased = false;
50 // It is ok to iterate over MachineValueTypeSet and remove elements from it
51 // at the same time.
52 for (MVT T : S) {
53 if (!P(T))
54 continue;
55 Erased = true;
56 S.erase(T);
57 }
58 return Erased;
59}
60
61void MachineValueTypeSet::writeToStream(raw_ostream &OS) const {
62 SmallVector<MVT, 4> Types(begin(), end());
63 array_pod_sort(Start: Types.begin(), End: Types.end());
64
65 OS << '[';
66 ListSeparator LS(" ");
67 for (const MVT &T : Types)
68 OS << LS << ValueTypeByHwMode::getMVTName(T);
69 OS << ']';
70}
71
72// --- TypeSetByHwMode
73
74// This is a parameterized type-set class. For each mode there is a list
75// of types that are currently possible for a given tree node. Type
76// inference will apply to each mode separately.
77
78TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
79 // Take the address space from the first type in the list.
80 if (!VTList.empty())
81 AddrSpace = VTList[0].PtrAddrSpace;
82
83 for (const ValueTypeByHwMode &VVT : VTList)
84 insert(VVT);
85}
86
87bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
88 for (const auto &I : *this) {
89 if (I.second.size() > 1)
90 return false;
91 if (!AllowEmpty && I.second.empty())
92 return false;
93 }
94 return true;
95}
96
97ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode(bool SkipEmpty) const {
98 assert(isValueTypeByHwMode(true) &&
99 "The type set has multiple types for at least one HW mode");
100 ValueTypeByHwMode VVT;
101 VVT.PtrAddrSpace = AddrSpace;
102
103 for (const auto &I : *this) {
104 if (SkipEmpty && I.second.empty())
105 continue;
106 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
107 VVT.insertTypeForMode(Mode: I.first, Type: T);
108 }
109 return VVT;
110}
111
112bool TypeSetByHwMode::isPossible() const {
113 for (const auto &I : *this)
114 if (!I.second.empty())
115 return true;
116 return false;
117}
118
119bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
120 bool Changed = false;
121 bool ContainsDefault = false;
122 MVT DT = MVT::Other;
123
124 for (const auto &P : VVT) {
125 unsigned M = P.first;
126 // Make sure there exists a set for each specific mode from VVT.
127 Changed |= getOrCreate(Mode: M).insert(T: P.second).second;
128 // Cache VVT's default mode.
129 if (DefaultMode == M) {
130 ContainsDefault = true;
131 DT = P.second;
132 }
133 }
134
135 // If VVT has a default mode, add the corresponding type to all
136 // modes in "this" that do not exist in VVT.
137 if (ContainsDefault)
138 for (auto &I : *this)
139 if (!VVT.hasMode(M: I.first))
140 Changed |= I.second.insert(T: DT).second;
141
142 return Changed;
143}
144
145// Constrain the type set to be the intersection with VTS.
146bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
147 bool Changed = false;
148 if (hasDefault()) {
149 for (const auto &I : VTS) {
150 unsigned M = I.first;
151 if (M == DefaultMode || hasMode(M))
152 continue;
153 Map.try_emplace(k: M, args&: Map.at(k: DefaultMode));
154 Changed = true;
155 }
156 }
157
158 for (auto &I : *this) {
159 unsigned M = I.first;
160 SetType &S = I.second;
161 if (VTS.hasMode(M) || VTS.hasDefault()) {
162 Changed |= intersect(Out&: I.second, In: VTS.get(Mode: M));
163 } else if (!S.empty()) {
164 S.clear();
165 Changed = true;
166 }
167 }
168 return Changed;
169}
170
171template <typename Predicate> bool TypeSetByHwMode::constrain(Predicate P) {
172 bool Changed = false;
173 for (auto &I : *this)
174 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
175 return Changed;
176}
177
178template <typename Predicate>
179bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
180 assert(empty());
181 for (const auto &I : VTS) {
182 SetType &S = getOrCreate(Mode: I.first);
183 for (auto J : I.second)
184 if (P(J))
185 S.insert(T: J);
186 }
187 return !empty();
188}
189
190void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
191 SmallVector<unsigned, 4> Modes;
192 Modes.reserve(N: Map.size());
193
194 for (const auto &I : *this)
195 Modes.push_back(Elt: I.first);
196 if (Modes.empty()) {
197 OS << "{}";
198 return;
199 }
200 array_pod_sort(Start: Modes.begin(), End: Modes.end());
201
202 OS << '{';
203 for (unsigned M : Modes) {
204 OS << ' ' << getModeName(Mode: M) << ':';
205 get(Mode: M).writeToStream(OS);
206 }
207 OS << " }";
208}
209
210bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
211 // The isSimple call is much quicker than hasDefault - check this first.
212 bool IsSimple = isSimple();
213 bool VTSIsSimple = VTS.isSimple();
214 if (IsSimple && VTSIsSimple)
215 return getSimple() == VTS.getSimple();
216
217 // Speedup: We have a default if the set is simple.
218 bool HaveDefault = IsSimple || hasDefault();
219 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
220 if (HaveDefault != VTSHaveDefault)
221 return false;
222
223 SmallSet<unsigned, 4> Modes;
224 Modes.insert_range(R: llvm::make_first_range(c: *this));
225 Modes.insert_range(R: llvm::make_first_range(c: VTS));
226
227 if (HaveDefault) {
228 // Both sets have default mode.
229 for (unsigned M : Modes) {
230 if (get(Mode: M) != VTS.get(Mode: M))
231 return false;
232 }
233 } else {
234 // Neither set has default mode.
235 for (unsigned M : Modes) {
236 // If there is no default mode, an empty set is equivalent to not having
237 // the corresponding mode.
238 bool NoModeThis = !hasMode(M) || get(Mode: M).empty();
239 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(Mode: M).empty();
240 if (NoModeThis != NoModeVTS)
241 return false;
242 if (!NoModeThis)
243 if (get(Mode: M) != VTS.get(Mode: M))
244 return false;
245 }
246 }
247
248 return true;
249}
250
251raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineValueTypeSet &T) {
252 T.writeToStream(OS);
253 return OS;
254}
255raw_ostream &llvm::operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
256 T.writeToStream(OS);
257 return OS;
258}
259
260LLVM_DUMP_METHOD
261void TypeSetByHwMode::dump() const { dbgs() << *this << '\n'; }
262
263bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
264 auto IntersectP = [&](std::optional<MVT> WildVT, function_ref<bool(MVT)> P) {
265 // Complement of In within this partition.
266 auto CompIn = [&](MVT T) -> bool { return !In.count(T) && P(T); };
267
268 if (!WildVT)
269 return berase_if(S&: Out, P: CompIn);
270
271 bool OutW = Out.count(T: *WildVT), InW = In.count(T: *WildVT);
272 if (OutW == InW)
273 return berase_if(S&: Out, P: CompIn);
274
275 // Compute the intersection of scalars separately to account for only one
276 // set containing WildVT.
277 // The intersection of WildVT with a set of corresponding types that does
278 // not include WildVT will result in the most specific type:
279 // - WildVT is more specific than any set with two elements or more
280 // - WildVT is less specific than any single type.
281 // For example, for iPTR and scalar integer types
282 // { iPTR } * { i32 } -> { i32 }
283 // { iPTR } * { i32 i64 } -> { iPTR }
284 // and
285 // { iPTR i32 } * { i32 } -> { i32 }
286 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
287 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
288
289 // Looking at just this partition, let In' = elements only in In,
290 // Out' = elements only in Out, and IO = elements common to both. Normally
291 // IO would be returned as the result of the intersection, but we need to
292 // account for WildVT being a "wildcard" of sorts. Since elements in IO are
293 // those that match both sets exactly, they will all belong to the output.
294 // If any of the "leftovers" (i.e. In' or Out') contain WildVT, it means
295 // that the other set doesn't have it, but it could have (1) a more
296 // specific type, or (2) a set of types that is less specific. The
297 // "leftovers" from the other set is what we want to examine more closely.
298
299 auto Leftovers = [&](const SetType &A, const SetType &B) {
300 SetType Diff = A;
301 berase_if(S&: Diff, P: [&](MVT T) { return B.count(T) || !P(T); });
302 return Diff;
303 };
304
305 if (InW) {
306 SetType OutLeftovers = Leftovers(Out, In);
307 if (OutLeftovers.size() < 2) {
308 // WildVT not added to Out. Keep the possible single leftover.
309 return false;
310 }
311 // WildVT replaces the leftovers.
312 berase_if(S&: Out, P: CompIn);
313 Out.insert(T: *WildVT);
314 return true;
315 }
316
317 // OutW == true
318 SetType InLeftovers = Leftovers(In, Out);
319 unsigned SizeOut = Out.size();
320 berase_if(S&: Out, P: CompIn); // This will remove at least the WildVT.
321 if (InLeftovers.size() < 2) {
322 // WildVT deleted from Out. Add back the possible single leftover.
323 Out.insert(S: InLeftovers);
324 return true;
325 }
326
327 // Keep the WildVT in Out.
328 Out.insert(T: *WildVT);
329 // If WildVT was the only element initially removed from Out, then Out
330 // has not changed.
331 return SizeOut != Out.size();
332 };
333
334 // Note: must be non-overlapping
335 using WildPartT = std::pair<MVT, std::function<bool(MVT)>>;
336 static const WildPartT WildParts[] = {
337 {MVT::iPTR, [](MVT T) { return T.isScalarInteger() || T == MVT::iPTR; }},
338 {MVT::cPTR,
339 [](MVT T) { return T.isCheriCapability() || T == MVT::cPTR; }},
340 };
341
342 bool Changed = false;
343 for (const auto &I : WildParts)
344 Changed |= IntersectP(I.first, I.second);
345
346 Changed |= IntersectP(std::nullopt, [&](MVT T) {
347 return !any_of(Range: WildParts, P: [=](const WildPartT &I) { return I.second(T); });
348 });
349
350 return Changed;
351}
352
353bool TypeSetByHwMode::validate() const {
354 if (empty())
355 return true;
356 bool AllEmpty = true;
357 for (const auto &I : *this)
358 AllEmpty &= I.second.empty();
359 return !AllEmpty;
360}
361
362// --- TypeInfer
363
364bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
365 const TypeSetByHwMode &In) const {
366 ValidateOnExit _1(Out, *this);
367 In.validate();
368 if (In.empty() || Out == In || TP.hasError())
369 return false;
370 if (Out.empty()) {
371 Out = In;
372 return true;
373 }
374
375 bool Changed = Out.constrain(VTS: In);
376 if (Changed && Out.empty())
377 TP.error(Msg: "Type contradiction");
378
379 return Changed;
380}
381
382bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
383 ValidateOnExit _1(Out, *this);
384 if (TP.hasError())
385 return false;
386 assert(!Out.empty() && "cannot pick from an empty set");
387
388 bool Changed = false;
389 for (auto &I : Out) {
390 TypeSetByHwMode::SetType &S = I.second;
391 if (S.size() <= 1)
392 continue;
393 MVT T = *S.begin(); // Pick the first element.
394 S.clear();
395 S.insert(T);
396 Changed = true;
397 }
398 return Changed;
399}
400
401bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
402 ValidateOnExit _1(Out, *this);
403 if (TP.hasError())
404 return false;
405 if (!Out.empty())
406 return Out.constrain(P: isIntegerOrPtr);
407
408 return Out.assign_if(VTS: getLegalTypes(), P: isIntegerOrPtr);
409}
410
411bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
412 ValidateOnExit _1(Out, *this);
413 if (TP.hasError())
414 return false;
415 if (!Out.empty())
416 return Out.constrain(P: isFloatingPoint);
417
418 return Out.assign_if(VTS: getLegalTypes(), P: isFloatingPoint);
419}
420
421bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
422 ValidateOnExit _1(Out, *this);
423 if (TP.hasError())
424 return false;
425 if (!Out.empty())
426 return Out.constrain(P: isScalar);
427
428 return Out.assign_if(VTS: getLegalTypes(), P: isScalar);
429}
430
431bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
432 ValidateOnExit _1(Out, *this);
433 if (TP.hasError())
434 return false;
435 if (!Out.empty())
436 return Out.constrain(P: isVector);
437
438 return Out.assign_if(VTS: getLegalTypes(), P: isVector);
439}
440
441bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
442 ValidateOnExit _1(Out, *this);
443 if (TP.hasError() || !Out.empty())
444 return false;
445
446 Out = getLegalTypes();
447 return true;
448}
449
450template <typename Iter, typename Pred, typename Less>
451static Iter min_if(Iter B, Iter E, Pred P, Less L) {
452 if (B == E)
453 return E;
454 Iter Min = E;
455 for (Iter I = B; I != E; ++I) {
456 if (!P(*I))
457 continue;
458 if (Min == E || L(*I, *Min))
459 Min = I;
460 }
461 return Min;
462}
463
464template <typename Iter, typename Pred, typename Less>
465static Iter max_if(Iter B, Iter E, Pred P, Less L) {
466 if (B == E)
467 return E;
468 Iter Max = E;
469 for (Iter I = B; I != E; ++I) {
470 if (!P(*I))
471 continue;
472 if (Max == E || L(*Max, *I))
473 Max = I;
474 }
475 return Max;
476}
477
478/// Make sure that for each type in Small, there exists a larger type in Big.
479bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big,
480 bool SmallIsVT) {
481 ValidateOnExit _1(Small, *this), _2(Big, *this);
482 if (TP.hasError())
483 return false;
484 bool Changed = false;
485
486 assert((!SmallIsVT || !Small.empty()) &&
487 "Small should not be empty for SDTCisVTSmallerThanOp");
488
489 if (Small.empty())
490 Changed |= EnforceAny(Out&: Small);
491 if (Big.empty())
492 Changed |= EnforceAny(Out&: Big);
493
494 assert(Small.hasDefault() && Big.hasDefault());
495
496 SmallVector<unsigned, 4> Modes;
497 union_modes(A: Small, B: Big, Modes);
498
499 // 1. Only allow integer or floating point types and make sure that
500 // both sides are both integer or both floating point.
501 // 2. Make sure that either both sides have vector types, or neither
502 // of them does.
503 for (unsigned M : Modes) {
504 TypeSetByHwMode::SetType &S = Small.get(Mode: M);
505 TypeSetByHwMode::SetType &B = Big.get(Mode: M);
506
507 assert((!SmallIsVT || !S.empty()) && "Expected non-empty type");
508
509 if (any_of(Range&: S, P: isIntegerOrPtr) && any_of(Range&: B, P: isIntegerOrPtr)) {
510 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
511 Changed |= berase_if(S, P: NotInt);
512 Changed |= berase_if(S&: B, P: NotInt);
513 } else if (any_of(Range&: S, P: isFloatingPoint) && any_of(Range&: B, P: isFloatingPoint)) {
514 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
515 Changed |= berase_if(S, P: NotFP);
516 Changed |= berase_if(S&: B, P: NotFP);
517 } else if (SmallIsVT && B.empty()) {
518 // B is empty and since S is a specific VT, it will never be empty. Don't
519 // report this as a change, just clear S and continue. This prevents an
520 // infinite loop.
521 S.clear();
522 } else if (S.empty() || B.empty()) {
523 Changed = !S.empty() || !B.empty();
524 S.clear();
525 B.clear();
526 } else {
527 TP.error(Msg: "Incompatible types");
528 return Changed;
529 }
530
531 if (none_of(Range&: S, P: isVector) || none_of(Range&: B, P: isVector)) {
532 Changed |= berase_if(S, P: isVector);
533 Changed |= berase_if(S&: B, P: isVector);
534 }
535 }
536
537 auto LT = [](MVT A, MVT B) -> bool {
538 // Always treat non-scalable MVTs as smaller than scalable MVTs for the
539 // purposes of ordering.
540 auto ASize = std::tuple(A.isScalableVector(), A.getScalarSizeInBits(),
541 A.getSizeInBits().getKnownMinValue());
542 auto BSize = std::tuple(B.isScalableVector(), B.getScalarSizeInBits(),
543 B.getSizeInBits().getKnownMinValue());
544 return ASize < BSize;
545 };
546 auto SameKindLE = [](MVT A, MVT B) -> bool {
547 // This function is used when removing elements: when a vector is compared
548 // to a non-vector or a scalable vector to any non-scalable MVT, it should
549 // return false (to avoid removal).
550 if (std::tuple(A.isVector(), A.isScalableVector()) !=
551 std::tuple(B.isVector(), B.isScalableVector()))
552 return false;
553
554 return std::tuple(A.getScalarSizeInBits(),
555 A.getSizeInBits().getKnownMinValue()) <=
556 std::tuple(B.getScalarSizeInBits(),
557 B.getSizeInBits().getKnownMinValue());
558 };
559
560 for (unsigned M : Modes) {
561 TypeSetByHwMode::SetType &S = Small.get(Mode: M);
562 TypeSetByHwMode::SetType &B = Big.get(Mode: M);
563 // MinS = min scalar in Small, remove all scalars from Big that are
564 // smaller-or-equal than MinS.
565 auto MinS = min_if(B: S.begin(), E: S.end(), P: isScalar, L: LT);
566 if (MinS != S.end())
567 Changed |=
568 berase_if(S&: B, P: std::bind(f&: SameKindLE, args: std::placeholders::_1, args: *MinS));
569
570 // MaxS = max scalar in Big, remove all scalars from Small that are
571 // larger than MaxS.
572 auto MaxS = max_if(B: B.begin(), E: B.end(), P: isScalar, L: LT);
573 if (MaxS != B.end())
574 Changed |=
575 berase_if(S, P: std::bind(f&: SameKindLE, args: *MaxS, args: std::placeholders::_1));
576
577 // MinV = min vector in Small, remove all vectors from Big that are
578 // smaller-or-equal than MinV.
579 auto MinV = min_if(B: S.begin(), E: S.end(), P: isVector, L: LT);
580 if (MinV != S.end())
581 Changed |=
582 berase_if(S&: B, P: std::bind(f&: SameKindLE, args: std::placeholders::_1, args: *MinV));
583
584 // MaxV = max vector in Big, remove all vectors from Small that are
585 // larger than MaxV.
586 auto MaxV = max_if(B: B.begin(), E: B.end(), P: isVector, L: LT);
587 if (MaxV != B.end())
588 Changed |=
589 berase_if(S, P: std::bind(f&: SameKindLE, args: *MaxV, args: std::placeholders::_1));
590 }
591
592 return Changed;
593}
594
595/// 1. Ensure that for each type T in Vec, T is a vector type, and that
596/// for each type U in Elem, U is a scalar type.
597/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
598/// type T in Vec, such that U is the element type of T.
599bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
600 TypeSetByHwMode &Elem) {
601 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
602 if (TP.hasError())
603 return false;
604 bool Changed = false;
605
606 if (Vec.empty())
607 Changed |= EnforceVector(Out&: Vec);
608 if (Elem.empty())
609 Changed |= EnforceScalar(Out&: Elem);
610
611 SmallVector<unsigned, 4> Modes;
612 union_modes(A: Vec, B: Elem, Modes);
613 for (unsigned M : Modes) {
614 TypeSetByHwMode::SetType &V = Vec.get(Mode: M);
615 TypeSetByHwMode::SetType &E = Elem.get(Mode: M);
616
617 Changed |= berase_if(S&: V, P: isScalar); // Scalar = !vector
618 Changed |= berase_if(S&: E, P: isVector); // Vector = !scalar
619 assert(!V.empty() && !E.empty());
620
621 MachineValueTypeSet VT, ST;
622 // Collect element types from the "vector" set.
623 for (MVT T : V)
624 VT.insert(T: T.getVectorElementType());
625 // Collect scalar types from the "element" set.
626 for (MVT T : E)
627 ST.insert(T);
628
629 // Remove from V all (vector) types whose element type is not in S.
630 Changed |= berase_if(S&: V, P: [&ST](MVT T) -> bool {
631 return !ST.count(T: T.getVectorElementType());
632 });
633 // Remove from E all (scalar) types, for which there is no corresponding
634 // type in V.
635 Changed |= berase_if(S&: E, P: [&VT](MVT T) -> bool { return !VT.count(T); });
636 }
637
638 return Changed;
639}
640
641bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
642 const ValueTypeByHwMode &VVT) {
643 TypeSetByHwMode Tmp(VVT);
644 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
645 return EnforceVectorEltTypeIs(Vec, Elem&: Tmp);
646}
647
648/// Ensure that for each type T in Sub, T is a vector type, and there
649/// exists a type U in Vec such that U is a vector type with the same
650/// element type as T and at least as many elements as T.
651bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
652 TypeSetByHwMode &Sub) {
653 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
654 if (TP.hasError())
655 return false;
656
657 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
658 auto IsSubVec = [](MVT B, MVT P) -> bool {
659 if (!B.isVector() || !P.isVector())
660 return false;
661 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
662 // but until there are obvious use-cases for this, keep the
663 // types separate.
664 if (B.isScalableVector() != P.isScalableVector())
665 return false;
666 if (B.getVectorElementType() != P.getVectorElementType())
667 return false;
668 return B.getVectorMinNumElements() < P.getVectorMinNumElements();
669 };
670
671 /// Return true if S has no element (vector type) that T is a sub-vector of,
672 /// i.e. has the same element type as T and more elements.
673 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
674 for (auto I : S)
675 if (IsSubVec(T, I))
676 return false;
677 return true;
678 };
679
680 /// Return true if S has no element (vector type) that T is a super-vector
681 /// of, i.e. has the same element type as T and fewer elements.
682 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
683 for (auto I : S)
684 if (IsSubVec(I, T))
685 return false;
686 return true;
687 };
688
689 bool Changed = false;
690
691 if (Vec.empty())
692 Changed |= EnforceVector(Out&: Vec);
693 if (Sub.empty())
694 Changed |= EnforceVector(Out&: Sub);
695
696 SmallVector<unsigned, 4> Modes;
697 union_modes(A: Vec, B: Sub, Modes);
698 for (unsigned M : Modes) {
699 TypeSetByHwMode::SetType &S = Sub.get(Mode: M);
700 TypeSetByHwMode::SetType &V = Vec.get(Mode: M);
701
702 Changed |= berase_if(S, P: isScalar);
703
704 // Erase all types from S that are not sub-vectors of a type in V.
705 Changed |= berase_if(S, P: std::bind(f&: NoSubV, args&: V, args: std::placeholders::_1));
706
707 // Erase all types from V that are not super-vectors of a type in S.
708 Changed |= berase_if(S&: V, P: std::bind(f&: NoSupV, args&: S, args: std::placeholders::_1));
709 }
710
711 return Changed;
712}
713
714/// 1. Ensure that V has a scalar type iff W has a scalar type.
715/// 2. Ensure that for each vector type T in V, there exists a vector
716/// type U in W, such that T and U have the same number of elements.
717/// 3. Ensure that for each vector type U in W, there exists a vector
718/// type T in V, such that T and U have the same number of elements
719/// (reverse of 2).
720bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
721 ValidateOnExit _1(V, *this), _2(W, *this);
722 if (TP.hasError())
723 return false;
724
725 bool Changed = false;
726 if (V.empty())
727 Changed |= EnforceAny(Out&: V);
728 if (W.empty())
729 Changed |= EnforceAny(Out&: W);
730
731 // An actual vector type cannot have 0 elements, so we can treat scalars
732 // as zero-length vectors. This way both vectors and scalars can be
733 // processed identically.
734 auto NoLength = [](const SmallDenseSet<ElementCount> &Lengths,
735 MVT T) -> bool {
736 return !Lengths.contains(V: T.isVector() ? T.getVectorElementCount()
737 : ElementCount());
738 };
739
740 SmallVector<unsigned, 4> Modes;
741 union_modes(A: V, B: W, Modes);
742 for (unsigned M : Modes) {
743 TypeSetByHwMode::SetType &VS = V.get(Mode: M);
744 TypeSetByHwMode::SetType &WS = W.get(Mode: M);
745
746 SmallDenseSet<ElementCount> VN, WN;
747 for (MVT T : VS)
748 VN.insert(V: T.isVector() ? T.getVectorElementCount() : ElementCount());
749 for (MVT T : WS)
750 WN.insert(V: T.isVector() ? T.getVectorElementCount() : ElementCount());
751
752 Changed |= berase_if(S&: VS, P: std::bind(f&: NoLength, args&: WN, args: std::placeholders::_1));
753 Changed |= berase_if(S&: WS, P: std::bind(f&: NoLength, args&: VN, args: std::placeholders::_1));
754 }
755 return Changed;
756}
757
758namespace {
759struct TypeSizeComparator {
760 bool operator()(const TypeSize &LHS, const TypeSize &RHS) const {
761 return std::tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
762 std::tuple(RHS.isScalable(), RHS.getKnownMinValue());
763 }
764};
765} // end anonymous namespace
766
767/// 1. Ensure that for each type T in A, there exists a type U in B,
768/// such that T and U have equal size in bits.
769/// 2. Ensure that for each type U in B, there exists a type T in A
770/// such that T and U have equal size in bits (reverse of 1).
771bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
772 ValidateOnExit _1(A, *this), _2(B, *this);
773 if (TP.hasError())
774 return false;
775 bool Changed = false;
776 if (A.empty())
777 Changed |= EnforceAny(Out&: A);
778 if (B.empty())
779 Changed |= EnforceAny(Out&: B);
780
781 using TypeSizeSet = SmallSet<TypeSize, 2, TypeSizeComparator>;
782
783 auto NoSize = [](const TypeSizeSet &Sizes, MVT T) -> bool {
784 return !Sizes.contains(V: T.getSizeInBits());
785 };
786
787 SmallVector<unsigned, 4> Modes;
788 union_modes(A, B, Modes);
789 for (unsigned M : Modes) {
790 TypeSetByHwMode::SetType &AS = A.get(Mode: M);
791 TypeSetByHwMode::SetType &BS = B.get(Mode: M);
792 TypeSizeSet AN, BN;
793
794 for (MVT T : AS)
795 AN.insert(V: T.getSizeInBits());
796 for (MVT T : BS)
797 BN.insert(V: T.getSizeInBits());
798
799 Changed |= berase_if(S&: AS, P: std::bind(f&: NoSize, args&: BN, args: std::placeholders::_1));
800 Changed |= berase_if(S&: BS, P: std::bind(f&: NoSize, args&: AN, args: std::placeholders::_1));
801 }
802
803 return Changed;
804}
805
806void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) const {
807 ValidateOnExit _1(VTS, *this);
808 const TypeSetByHwMode &Legal = getLegalTypes();
809 assert(Legal.isSimple() && "Default-mode only expected");
810 const TypeSetByHwMode::SetType &LegalTypes = Legal.getSimple();
811
812 for (auto &I : VTS)
813 expandOverloads(Out&: I.second, Legal: LegalTypes);
814}
815
816void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
817 const TypeSetByHwMode::SetType &Legal) const {
818 if (Out.count(T: MVT::pAny)) {
819 Out.erase(T: MVT::pAny);
820 Out.insert(T: MVT::iPTR);
821 for (MVT T : MVT::cheri_capability_valuetypes()) {
822 if (Legal.count(T))
823 Out.insert(T: MVT::cPTR);
824 }
825 } else if (Out.count(T: MVT::iAny)) {
826 Out.erase(T: MVT::iAny);
827 for (MVT T : MVT::integer_valuetypes())
828 if (Legal.count(T))
829 Out.insert(T);
830 for (MVT T : MVT::integer_fixedlen_vector_valuetypes())
831 if (Legal.count(T))
832 Out.insert(T);
833 for (MVT T : MVT::integer_scalable_vector_valuetypes())
834 if (Legal.count(T))
835 Out.insert(T);
836 } else if (Out.count(T: MVT::fAny)) {
837 Out.erase(T: MVT::fAny);
838 for (MVT T : MVT::fp_valuetypes())
839 if (Legal.count(T))
840 Out.insert(T);
841 for (MVT T : MVT::fp_fixedlen_vector_valuetypes())
842 if (Legal.count(T))
843 Out.insert(T);
844 for (MVT T : MVT::fp_scalable_vector_valuetypes())
845 if (Legal.count(T))
846 Out.insert(T);
847 } else if (Out.count(T: MVT::vAny)) {
848 Out.erase(T: MVT::vAny);
849 for (MVT T : MVT::vector_valuetypes())
850 if (Legal.count(T))
851 Out.insert(T);
852 } else if (Out.count(T: MVT::Any)) {
853 Out.erase(T: MVT::Any);
854 for (MVT T : MVT::all_valuetypes())
855 if (Legal.count(T))
856 Out.insert(T);
857 }
858}
859
860const TypeSetByHwMode &TypeInfer::getLegalTypes() const {
861 if (!LegalTypesCached) {
862 TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(Mode: DefaultMode);
863 // Stuff all types from all modes into the default mode.
864 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
865 for (const auto &I : LTS)
866 LegalTypes.insert(S: I.second);
867 LegalTypesCached = true;
868 }
869 assert(LegalCache.isSimple() && "Default-mode only expected");
870 return LegalCache;
871}
872
873TypeInfer::ValidateOnExit::~ValidateOnExit() {
874 if (Infer.Validate && !VTS.validate()) {
875#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
876 errs() << "Type set is empty for each HW mode:\n"
877 "possible type contradiction in the pattern below "
878 "(use -print-records with llvm-tblgen to see all "
879 "expanded records).\n";
880 Infer.TP.dump();
881 errs() << "Generated from record:\n";
882 Infer.TP.getRecord()->dump();
883#endif
884 PrintFatalError(ErrorLoc: Infer.TP.getRecord()->getLoc(),
885 Msg: "Type set is empty for each HW mode in '" +
886 Infer.TP.getRecord()->getName() + "'");
887 }
888}
889
890//===----------------------------------------------------------------------===//
891// ScopedName Implementation
892//===----------------------------------------------------------------------===//
893
894bool ScopedName::operator==(const ScopedName &o) const {
895 return Scope == o.Scope && Identifier == o.Identifier;
896}
897
898bool ScopedName::operator!=(const ScopedName &o) const { return !(*this == o); }
899
900//===----------------------------------------------------------------------===//
901// TreePredicateFn Implementation
902//===----------------------------------------------------------------------===//
903
904/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
905TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
906 assert(
907 (!hasPredCode() || !hasImmCode()) &&
908 ".td file corrupt: can't have a node predicate *and* an imm predicate");
909
910 if (hasGISelPredicateCode() && hasGISelLeafPredicateCode())
911 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
912 Msg: ".td file corrupt: can't have GISelPredicateCode *and* "
913 "GISelLeafPredicateCode");
914}
915
916bool TreePredicateFn::hasPredCode() const {
917 return isLoad() || isStore() || isAtomic() || hasNoUse() || hasOneUse() ||
918 !PatFragRec->getRecord()->getValueAsString(FieldName: "PredicateCode").empty();
919}
920
921std::string TreePredicateFn::getPredCode() const {
922 std::string Code;
923
924 if (!isLoad() && !isStore() && !isAtomic() && getMemoryVT())
925 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
926 Msg: "MemoryVT requires IsLoad or IsStore or IsAtomic");
927
928 if (!isLoad() && !isStore()) {
929 if (isUnindexed())
930 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
931 Msg: "IsUnindexed requires IsLoad or IsStore");
932
933 if (getScalarMemoryVT())
934 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
935 Msg: "ScalarMemoryVT requires IsLoad or IsStore");
936 }
937
938 if (isLoad() + isStore() + isAtomic() > 1)
939 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
940 Msg: "IsLoad, IsStore, and IsAtomic are mutually exclusive");
941
942 if (isLoad()) {
943 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
944 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
945 getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
946 getMinAlignment() < 1)
947 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
948 Msg: "IsLoad cannot be used by itself");
949 } else if (!isAtomic()) {
950 if (isNonExtLoad())
951 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
952 Msg: "IsNonExtLoad requires IsLoad or IsAtomic");
953 if (isAnyExtLoad())
954 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
955 Msg: "IsAnyExtLoad requires IsLoad or IsAtomic");
956 if (isSignExtLoad())
957 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
958 Msg: "IsSignExtLoad requires IsLoad or IsAtomic");
959 if (isZeroExtLoad())
960 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
961 Msg: "IsZeroExtLoad requires IsLoad or IsAtomic");
962 }
963
964 if (isStore()) {
965 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
966 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
967 getAddressSpaces() == nullptr && getMinAlignment() < 1)
968 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
969 Msg: "IsStore cannot be used by itself");
970 } else {
971 if (isNonTruncStore())
972 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
973 Msg: "IsNonTruncStore requires IsStore");
974 if (isTruncStore())
975 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
976 Msg: "IsTruncStore requires IsStore");
977 }
978
979 if (isAtomic()) {
980 if (getMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
981 // FIXME: Should atomic loads be IsLoad, IsAtomic, or both?
982 !isNonExtLoad() && !isAnyExtLoad() && !isZeroExtLoad() &&
983 !isSignExtLoad() && !isAtomicOrderingMonotonic() &&
984 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
985 !isAtomicOrderingAcquireRelease() &&
986 !isAtomicOrderingSequentiallyConsistent() &&
987 !isAtomicOrderingAcquireOrStronger() &&
988 !isAtomicOrderingReleaseOrStronger() &&
989 !isAtomicOrderingWeakerThanAcquire() &&
990 !isAtomicOrderingWeakerThanRelease())
991 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
992 Msg: "IsAtomic cannot be used by itself");
993 } else {
994 if (isAtomicOrderingMonotonic())
995 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
996 Msg: "IsAtomicOrderingMonotonic requires IsAtomic");
997 if (isAtomicOrderingAcquire())
998 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
999 Msg: "IsAtomicOrderingAcquire requires IsAtomic");
1000 if (isAtomicOrderingRelease())
1001 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1002 Msg: "IsAtomicOrderingRelease requires IsAtomic");
1003 if (isAtomicOrderingAcquireRelease())
1004 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1005 Msg: "IsAtomicOrderingAcquireRelease requires IsAtomic");
1006 if (isAtomicOrderingSequentiallyConsistent())
1007 PrintFatalError(
1008 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1009 Msg: "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
1010 if (isAtomicOrderingAcquireOrStronger())
1011 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1012 Msg: "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
1013 if (isAtomicOrderingReleaseOrStronger())
1014 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1015 Msg: "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
1016 if (isAtomicOrderingWeakerThanAcquire())
1017 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1018 Msg: "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
1019 }
1020
1021 if (isLoad() || isStore() || isAtomic()) {
1022 if (const ListInit *AddressSpaces = getAddressSpaces()) {
1023 Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
1024 " if (";
1025
1026 ListSeparator LS(" && ");
1027 for (const Init *Val : AddressSpaces->getElements()) {
1028 Code += LS;
1029
1030 const IntInit *IntVal = dyn_cast<IntInit>(Val);
1031 if (!IntVal) {
1032 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1033 Msg: "AddressSpaces element must be integer");
1034 }
1035
1036 Code += "AddrSpace != " + utostr(X: IntVal->getValue());
1037 }
1038
1039 Code += ")\nreturn false;\n";
1040 }
1041
1042 int64_t MinAlign = getMinAlignment();
1043 if (MinAlign > 0) {
1044 Code += "if (cast<MemSDNode>(N)->getAlign() < Align(";
1045 Code += utostr(X: MinAlign);
1046 Code += "))\nreturn false;\n";
1047 }
1048
1049 if (const Record *MemoryVT = getMemoryVT())
1050 Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
1051 MemoryVT->getName() + ") return false;\n")
1052 .str();
1053 }
1054
1055 if (isAtomic() && isAtomicOrderingMonotonic())
1056 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1057 "AtomicOrdering::Monotonic) return false;\n";
1058 if (isAtomic() && isAtomicOrderingAcquire())
1059 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1060 "AtomicOrdering::Acquire) return false;\n";
1061 if (isAtomic() && isAtomicOrderingRelease())
1062 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1063 "AtomicOrdering::Release) return false;\n";
1064 if (isAtomic() && isAtomicOrderingAcquireRelease())
1065 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1066 "AtomicOrdering::AcquireRelease) return false;\n";
1067 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1068 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1069 "AtomicOrdering::SequentiallyConsistent) return false;\n";
1070
1071 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1072 Code +=
1073 "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1074 "return false;\n";
1075 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1076 Code +=
1077 "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1078 "return false;\n";
1079
1080 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1081 Code +=
1082 "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1083 "return false;\n";
1084 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1085 Code +=
1086 "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1087 "return false;\n";
1088
1089 if (isAtomic()) {
1090 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() + isZeroExtLoad()) >
1091 1)
1092 PrintFatalError(
1093 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1094 Msg: "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and IsZeroExtLoad are "
1095 "mutually exclusive");
1096
1097 if (isNonExtLoad())
1098 Code += "if (cast<AtomicSDNode>(N)->getExtensionType() != "
1099 "ISD::NON_EXTLOAD) return false;\n";
1100 if (isAnyExtLoad())
1101 Code += "if (cast<AtomicSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1102 "return false;\n";
1103 if (isSignExtLoad())
1104 Code += "if (cast<AtomicSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1105 "return false;\n";
1106 if (isZeroExtLoad())
1107 Code += "if (cast<AtomicSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1108 "return false;\n";
1109 }
1110
1111 if (isLoad() || isStore()) {
1112 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1113
1114 if (isUnindexed())
1115 Code += ("if (cast<" + SDNodeName +
1116 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1117 "return false;\n")
1118 .str();
1119
1120 if (isLoad()) {
1121 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1122 isZeroExtLoad()) > 1)
1123 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1124 Msg: "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1125 "IsZeroExtLoad are mutually exclusive");
1126 if (isNonExtLoad())
1127 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1128 "ISD::NON_EXTLOAD) return false;\n";
1129 if (isAnyExtLoad())
1130 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1131 "return false;\n";
1132 if (isSignExtLoad())
1133 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1134 "return false;\n";
1135 if (isZeroExtLoad())
1136 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1137 "return false;\n";
1138 } else {
1139 if ((isNonTruncStore() + isTruncStore()) > 1)
1140 PrintFatalError(
1141 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1142 Msg: "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1143 if (isNonTruncStore())
1144 Code +=
1145 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1146 if (isTruncStore())
1147 Code +=
1148 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1149 }
1150
1151 if (const Record *ScalarMemoryVT = getScalarMemoryVT())
1152 Code += ("if (cast<" + SDNodeName +
1153 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1154 ScalarMemoryVT->getName() + ") return false;\n")
1155 .str();
1156 }
1157
1158 if (hasNoUse())
1159 Code += "if (N->hasAnyUseOfValue(0)) return false;\n";
1160 if (hasOneUse())
1161 Code += "if (!N->hasNUsesOfValue(1, 0)) return false;\n";
1162
1163 std::string PredicateCode =
1164 PatFragRec->getRecord()->getValueAsString(FieldName: "PredicateCode").str();
1165
1166 Code += PredicateCode;
1167
1168 if (PredicateCode.empty() && !Code.empty())
1169 Code += "return true;\n";
1170
1171 return Code;
1172}
1173
1174bool TreePredicateFn::hasImmCode() const {
1175 return !PatFragRec->getRecord()->getValueAsString(FieldName: "ImmediateCode").empty();
1176}
1177
1178std::string TreePredicateFn::getImmCode() const {
1179 return PatFragRec->getRecord()->getValueAsString(FieldName: "ImmediateCode").str();
1180}
1181
1182bool TreePredicateFn::immCodeUsesAPInt() const {
1183 return getOrigPatFragRecord()->getRecord()->getValueAsBit(FieldName: "IsAPInt");
1184}
1185
1186bool TreePredicateFn::immCodeUsesAPFloat() const {
1187 bool Unset;
1188 // The return value will be false when IsAPFloat is unset.
1189 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(FieldName: "IsAPFloat",
1190 Unset);
1191}
1192
1193bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1194 bool Value) const {
1195 bool Unset;
1196 bool Result =
1197 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(FieldName: Field, Unset);
1198 if (Unset)
1199 return false;
1200 return Result == Value;
1201}
1202bool TreePredicateFn::usesOperands() const {
1203 return isPredefinedPredicateEqualTo(Field: "PredicateCodeUsesOperands", Value: true);
1204}
1205bool TreePredicateFn::hasNoUse() const {
1206 return isPredefinedPredicateEqualTo(Field: "HasNoUse", Value: true);
1207}
1208bool TreePredicateFn::hasOneUse() const {
1209 return isPredefinedPredicateEqualTo(Field: "HasOneUse", Value: true);
1210}
1211bool TreePredicateFn::isLoad() const {
1212 return isPredefinedPredicateEqualTo(Field: "IsLoad", Value: true);
1213}
1214bool TreePredicateFn::isStore() const {
1215 return isPredefinedPredicateEqualTo(Field: "IsStore", Value: true);
1216}
1217bool TreePredicateFn::isAtomic() const {
1218 return isPredefinedPredicateEqualTo(Field: "IsAtomic", Value: true);
1219}
1220bool TreePredicateFn::isUnindexed() const {
1221 return isPredefinedPredicateEqualTo(Field: "IsUnindexed", Value: true);
1222}
1223bool TreePredicateFn::isNonExtLoad() const {
1224 return isPredefinedPredicateEqualTo(Field: "IsNonExtLoad", Value: true);
1225}
1226bool TreePredicateFn::isAnyExtLoad() const {
1227 return isPredefinedPredicateEqualTo(Field: "IsAnyExtLoad", Value: true);
1228}
1229bool TreePredicateFn::isSignExtLoad() const {
1230 return isPredefinedPredicateEqualTo(Field: "IsSignExtLoad", Value: true);
1231}
1232bool TreePredicateFn::isZeroExtLoad() const {
1233 return isPredefinedPredicateEqualTo(Field: "IsZeroExtLoad", Value: true);
1234}
1235bool TreePredicateFn::isNonTruncStore() const {
1236 return isPredefinedPredicateEqualTo(Field: "IsTruncStore", Value: false);
1237}
1238bool TreePredicateFn::isTruncStore() const {
1239 return isPredefinedPredicateEqualTo(Field: "IsTruncStore", Value: true);
1240}
1241bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1242 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingMonotonic", Value: true);
1243}
1244bool TreePredicateFn::isAtomicOrderingAcquire() const {
1245 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingAcquire", Value: true);
1246}
1247bool TreePredicateFn::isAtomicOrderingRelease() const {
1248 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingRelease", Value: true);
1249}
1250bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1251 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingAcquireRelease", Value: true);
1252}
1253bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1254 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingSequentiallyConsistent",
1255 Value: true);
1256}
1257bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1258 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingAcquireOrStronger",
1259 Value: true);
1260}
1261bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1262 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingAcquireOrStronger",
1263 Value: false);
1264}
1265bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1266 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingReleaseOrStronger",
1267 Value: true);
1268}
1269bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1270 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingReleaseOrStronger",
1271 Value: false);
1272}
1273const Record *TreePredicateFn::getMemoryVT() const {
1274 const Record *R = getOrigPatFragRecord()->getRecord();
1275 if (R->isValueUnset(FieldName: "MemoryVT"))
1276 return nullptr;
1277 return R->getValueAsDef(FieldName: "MemoryVT");
1278}
1279
1280const ListInit *TreePredicateFn::getAddressSpaces() const {
1281 const Record *R = getOrigPatFragRecord()->getRecord();
1282 if (R->isValueUnset(FieldName: "AddressSpaces"))
1283 return nullptr;
1284 return R->getValueAsListInit(FieldName: "AddressSpaces");
1285}
1286
1287int64_t TreePredicateFn::getMinAlignment() const {
1288 const Record *R = getOrigPatFragRecord()->getRecord();
1289 if (R->isValueUnset(FieldName: "MinAlignment"))
1290 return 0;
1291 return R->getValueAsInt(FieldName: "MinAlignment");
1292}
1293
1294const Record *TreePredicateFn::getScalarMemoryVT() const {
1295 const Record *R = getOrigPatFragRecord()->getRecord();
1296 if (R->isValueUnset(FieldName: "ScalarMemoryVT"))
1297 return nullptr;
1298 return R->getValueAsDef(FieldName: "ScalarMemoryVT");
1299}
1300
1301bool TreePredicateFn::hasGISelPredicateCode() const {
1302 return !PatFragRec->getRecord()
1303 ->getValueAsString(FieldName: "GISelPredicateCode")
1304 .empty();
1305}
1306
1307std::string TreePredicateFn::getGISelPredicateCode() const {
1308 return PatFragRec->getRecord()->getValueAsString(FieldName: "GISelPredicateCode").str();
1309}
1310
1311bool TreePredicateFn::hasGISelLeafPredicateCode() const {
1312 return PatFragRec->getRecord()
1313 ->getValueAsOptionalString(FieldName: "GISelLeafPredicateCode")
1314 .has_value();
1315}
1316
1317std::string TreePredicateFn::getGISelLeafPredicateCode() const {
1318 return PatFragRec->getRecord()
1319 ->getValueAsOptionalString(FieldName: "GISelLeafPredicateCode")
1320 .value_or(u: StringRef())
1321 .str();
1322}
1323
1324StringRef TreePredicateFn::getImmType() const {
1325 if (immCodeUsesAPInt())
1326 return "const APInt &";
1327 if (immCodeUsesAPFloat())
1328 return "const APFloat &";
1329 return "int64_t";
1330}
1331
1332StringRef TreePredicateFn::getImmTypeIdentifier() const {
1333 if (immCodeUsesAPInt())
1334 return "APInt";
1335 if (immCodeUsesAPFloat())
1336 return "APFloat";
1337 return "I64";
1338}
1339
1340/// isAlwaysTrue - Return true if this is a noop predicate.
1341bool TreePredicateFn::isAlwaysTrue() const {
1342 return !hasPredCode() && !hasImmCode();
1343}
1344
1345/// Return the name to use in the generated code to reference this, this is
1346/// "Predicate_foo" if from a pattern fragment "foo".
1347std::string TreePredicateFn::getFnName() const {
1348 return "Predicate_" + PatFragRec->getRecord()->getName().str();
1349}
1350
1351/// getCodeToRunOnSDNode - Return the code for the function body that
1352/// evaluates this predicate. The argument is expected to be in "Node",
1353/// not N. This handles casting and conversion to a concrete node type as
1354/// appropriate.
1355std::string TreePredicateFn::getCodeToRunOnSDNode() const {
1356 // Handle immediate predicates first.
1357 std::string ImmCode = getImmCode();
1358 if (!ImmCode.empty()) {
1359 if (isLoad())
1360 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1361 Msg: "IsLoad cannot be used with ImmLeaf or its subclasses");
1362 if (isStore())
1363 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1364 Msg: "IsStore cannot be used with ImmLeaf or its subclasses");
1365 if (isUnindexed())
1366 PrintFatalError(
1367 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1368 Msg: "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1369 if (isNonExtLoad())
1370 PrintFatalError(
1371 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1372 Msg: "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1373 if (isAnyExtLoad())
1374 PrintFatalError(
1375 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1376 Msg: "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1377 if (isSignExtLoad())
1378 PrintFatalError(
1379 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1380 Msg: "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1381 if (isZeroExtLoad())
1382 PrintFatalError(
1383 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1384 Msg: "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1385 if (isNonTruncStore())
1386 PrintFatalError(
1387 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1388 Msg: "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1389 if (isTruncStore())
1390 PrintFatalError(
1391 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1392 Msg: "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1393 if (getMemoryVT())
1394 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1395 Msg: "MemoryVT cannot be used with ImmLeaf or its subclasses");
1396 if (getScalarMemoryVT())
1397 PrintFatalError(
1398 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1399 Msg: "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1400
1401 std::string Result = (" " + getImmType() + " Imm = ").str();
1402 if (immCodeUsesAPFloat())
1403 Result += "cast<ConstantFPSDNode>(Op.getNode())->getValueAPF();\n";
1404 else if (immCodeUsesAPInt())
1405 Result += "Op->getAsAPIntVal();\n";
1406 else
1407 Result += "cast<ConstantSDNode>(Op.getNode())->getSExtValue();\n";
1408 return Result + ImmCode;
1409 }
1410
1411 // Handle arbitrary node predicates.
1412 assert(hasPredCode() && "Don't have any predicate code!");
1413
1414 // If this is using PatFrags, there are multiple trees to search. They should
1415 // all have the same class. FIXME: Is there a way to find a common
1416 // superclass?
1417 StringRef ClassName;
1418 for (const auto &Tree : PatFragRec->getTrees()) {
1419 StringRef TreeClassName;
1420 if (Tree->isLeaf())
1421 TreeClassName = "SDNode";
1422 else {
1423 const Record *Op = Tree->getOperator();
1424 const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(R: Op);
1425 TreeClassName = Info.getSDClassName();
1426 }
1427
1428 if (ClassName.empty())
1429 ClassName = TreeClassName;
1430 else if (ClassName != TreeClassName) {
1431 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1432 Msg: "PatFrags trees do not have consistent class");
1433 }
1434 }
1435
1436 std::string Result;
1437 if (ClassName == "SDNode")
1438 Result = " SDNode *N = Op.getNode();\n";
1439 else
1440 Result = " auto *N = cast<" + ClassName.str() + ">(Op.getNode());\n";
1441
1442 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
1443}
1444
1445//===----------------------------------------------------------------------===//
1446// PatternToMatch implementation
1447//
1448
1449static bool isImmAllOnesAllZerosMatch(const TreePatternNode &P) {
1450 if (!P.isLeaf())
1451 return false;
1452 const DefInit *DI = dyn_cast<DefInit>(Val: P.getLeafValue());
1453 if (!DI)
1454 return false;
1455
1456 const Record *R = DI->getDef();
1457 return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1458}
1459
1460/// getPatternSize - Return the 'size' of this pattern. We want to match large
1461/// patterns before small ones. This is used to determine the size of a
1462/// pattern.
1463static unsigned getPatternSize(const TreePatternNode &P,
1464 const CodeGenDAGPatterns &CGP) {
1465 unsigned Size = 3; // The node itself.
1466 // If the root node is a ConstantSDNode, increases its size.
1467 // e.g. (set R32:$dst, 0).
1468 if (P.isLeaf() && isa<IntInit>(Val: P.getLeafValue()))
1469 Size += 2;
1470
1471 if (const ComplexPattern *AM = P.getComplexPatternInfo(CGP)) {
1472 Size += AM->getComplexity();
1473 // We don't want to count any children twice, so return early.
1474 return Size;
1475 }
1476
1477 // If this node has some predicate function that must match, it adds to the
1478 // complexity of this node.
1479 if (!P.getPredicateCalls().empty())
1480 ++Size;
1481
1482 // Count children in the count if they are also nodes.
1483 for (const TreePatternNode &Child : P.children()) {
1484 if (!Child.isLeaf() && Child.getNumTypes()) {
1485 // FIXME: Can we assume non-simple VTs should be counted?
1486 auto VVT = Child.getType(ResNo: 0);
1487 if (llvm::any_of(Range&: VVT, P: [](auto &P) { return P.second != MVT::Other; })) {
1488 Size += getPatternSize(P: Child, CGP);
1489 continue;
1490 }
1491 }
1492 if (Child.isLeaf()) {
1493 if (isa<IntInit>(Val: Child.getLeafValue()))
1494 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1495 else if (Child.getComplexPatternInfo(CGP))
1496 Size += getPatternSize(P: Child, CGP);
1497 else if (isImmAllOnesAllZerosMatch(P: Child))
1498 Size += 4; // Matches a build_vector(+3) and a predicate (+1).
1499 else if (!Child.getPredicateCalls().empty())
1500 ++Size;
1501 }
1502 }
1503
1504 return Size;
1505}
1506
1507/// Compute the complexity metric for the input pattern. This roughly
1508/// corresponds to the number of nodes that are covered.
1509int PatternToMatch::getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1510 return getPatternSize(P: getSrcPattern(), CGP) + getAddedComplexity();
1511}
1512
1513void PatternToMatch::getPredicateRecords(
1514 SmallVectorImpl<const Record *> &PredicateRecs) const {
1515 for (const Init *I : Predicates->getElements()) {
1516 if (const DefInit *Pred = dyn_cast<DefInit>(Val: I)) {
1517 const Record *Def = Pred->getDef();
1518 if (!Def->isSubClassOf(Name: "Predicate")) {
1519#ifndef NDEBUG
1520 Def->dump();
1521#endif
1522 llvm_unreachable("Unknown predicate type!");
1523 }
1524 PredicateRecs.push_back(Elt: Def);
1525 }
1526 }
1527 // Sort so that different orders get canonicalized to the same string.
1528 llvm::sort(C&: PredicateRecs, Comp: LessRecord());
1529 // Remove duplicate predicates.
1530 PredicateRecs.erase(CS: llvm::unique(R&: PredicateRecs), CE: PredicateRecs.end());
1531}
1532
1533/// getPredicateCheck - Return a single string containing all of this
1534/// pattern's predicates concatenated with "&&" operators.
1535///
1536std::string PatternToMatch::getPredicateCheck() const {
1537 SmallVector<const Record *, 4> PredicateRecs;
1538 getPredicateRecords(PredicateRecs);
1539
1540 SmallString<128> PredicateCheck;
1541 raw_svector_ostream OS(PredicateCheck);
1542 ListSeparator LS(" && ");
1543 for (const Record *Pred : PredicateRecs) {
1544 StringRef CondString = Pred->getValueAsString(FieldName: "CondString");
1545 if (CondString.empty())
1546 continue;
1547 OS << LS << '(' << CondString << ')';
1548 }
1549
1550 if (!HwModeFeatures.empty())
1551 OS << LS << HwModeFeatures;
1552
1553 return std::string(PredicateCheck);
1554}
1555
1556//===----------------------------------------------------------------------===//
1557// SDTypeConstraint implementation
1558//
1559
1560SDTypeConstraint::SDTypeConstraint(const Record *R, const CodeGenHwModes &CGH) {
1561 OperandNo = R->getValueAsInt(FieldName: "OperandNum");
1562
1563 if (R->isSubClassOf(Name: "SDTCisVT")) {
1564 ConstraintType = SDTCisVT;
1565 VVT = getValueTypeByHwMode(Rec: R->getValueAsDef(FieldName: "VT"), CGH);
1566 for (const auto &P : VVT)
1567 if (P.second == MVT::isVoid)
1568 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "Cannot use 'Void' as type to SDTCisVT");
1569 } else if (R->isSubClassOf(Name: "SDTCisPtrTy")) {
1570 ConstraintType = SDTCisPtrTy;
1571 } else if (R->isSubClassOf(Name: "SDTCisInt")) {
1572 ConstraintType = SDTCisInt;
1573 } else if (R->isSubClassOf(Name: "SDTCisFP")) {
1574 ConstraintType = SDTCisFP;
1575 } else if (R->isSubClassOf(Name: "SDTCisVec")) {
1576 ConstraintType = SDTCisVec;
1577 } else if (R->isSubClassOf(Name: "SDTCisSameAs")) {
1578 ConstraintType = SDTCisSameAs;
1579 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOperandNum");
1580 } else if (R->isSubClassOf(Name: "SDTCisVTSmallerThanOp")) {
1581 ConstraintType = SDTCisVTSmallerThanOp;
1582 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOperandNum");
1583 } else if (R->isSubClassOf(Name: "SDTCisOpSmallerThanOp")) {
1584 ConstraintType = SDTCisOpSmallerThanOp;
1585 OtherOperandNo = R->getValueAsInt(FieldName: "BigOperandNum");
1586 } else if (R->isSubClassOf(Name: "SDTCisEltOfVec")) {
1587 ConstraintType = SDTCisEltOfVec;
1588 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOpNum");
1589 } else if (R->isSubClassOf(Name: "SDTCisSubVecOfVec")) {
1590 ConstraintType = SDTCisSubVecOfVec;
1591 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOpNum");
1592 } else if (R->isSubClassOf(Name: "SDTCVecEltisVT")) {
1593 ConstraintType = SDTCVecEltisVT;
1594 VVT = getValueTypeByHwMode(Rec: R->getValueAsDef(FieldName: "VT"), CGH);
1595 for (const auto &P : VVT) {
1596 MVT T = P.second;
1597 if (T.isVector())
1598 PrintFatalError(ErrorLoc: R->getLoc(),
1599 Msg: "Cannot use vector type as SDTCVecEltisVT");
1600 if (!T.isInteger() && !T.isFloatingPoint())
1601 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "Must use integer or floating point type "
1602 "as SDTCVecEltisVT");
1603 }
1604 } else if (R->isSubClassOf(Name: "SDTCisSameNumEltsAs")) {
1605 ConstraintType = SDTCisSameNumEltsAs;
1606 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOperandNum");
1607 } else if (R->isSubClassOf(Name: "SDTCisSameSizeAs")) {
1608 ConstraintType = SDTCisSameSizeAs;
1609 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOperandNum");
1610 } else {
1611 PrintFatalError(ErrorLoc: R->getLoc(),
1612 Msg: "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1613 }
1614}
1615
1616/// getOperandNum - Return the node corresponding to operand #OpNo in tree
1617/// N, and the result number in ResNo.
1618static TreePatternNode &getOperandNum(unsigned OpNo, TreePatternNode &N,
1619 const SDNodeInfo &NodeInfo,
1620 unsigned &ResNo) {
1621 unsigned NumResults = NodeInfo.getNumResults();
1622 if (OpNo < NumResults) {
1623 ResNo = OpNo;
1624 return N;
1625 }
1626
1627 OpNo -= NumResults;
1628
1629 if (OpNo >= N.getNumChildren()) {
1630 PrintFatalError(PrintMsg: [&N, OpNo, NumResults](raw_ostream &OS) {
1631 OS << "Invalid operand number in type constraint " << (OpNo + NumResults);
1632 N.print(OS);
1633 });
1634 }
1635 return N.getChild(N: OpNo);
1636}
1637
1638/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1639/// constraint to the nodes operands. This returns true if it makes a
1640/// change, false otherwise. If a type contradiction is found, flag an error.
1641bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode &N,
1642 const SDNodeInfo &NodeInfo,
1643 TreePattern &TP) const {
1644 if (TP.hasError())
1645 return false;
1646
1647 unsigned ResNo = 0; // The result number being referenced.
1648 TreePatternNode &NodeToApply = getOperandNum(OpNo: OperandNo, N, NodeInfo, ResNo);
1649 TypeInfer &TI = TP.getInfer();
1650
1651 switch (ConstraintType) {
1652 case SDTCisVT:
1653 // Operand must be a particular type.
1654 return NodeToApply.UpdateNodeType(ResNo, InTy: VVT, TP);
1655 case SDTCisPtrTy: {
1656 // Operand must be a legal pointer (iPTR, or possibly cPTR) type.
1657 const TypeSetByHwMode &PtrTys = TP.getDAGPatterns().getLegalPtrTypes();
1658 return NodeToApply.UpdateNodeType(ResNo, InTy: PtrTys, TP);
1659 }
1660 case SDTCisInt:
1661 // Require it to be one of the legal integer VTs.
1662 return TI.EnforceInteger(Out&: NodeToApply.getExtType(ResNo));
1663 case SDTCisFP:
1664 // Require it to be one of the legal fp VTs.
1665 return TI.EnforceFloatingPoint(Out&: NodeToApply.getExtType(ResNo));
1666 case SDTCisVec:
1667 // Require it to be one of the legal vector VTs.
1668 return TI.EnforceVector(Out&: NodeToApply.getExtType(ResNo));
1669 case SDTCisSameAs: {
1670 unsigned OResNo = 0;
1671 TreePatternNode &OtherNode =
1672 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: OResNo);
1673 return (int)NodeToApply.UpdateNodeType(ResNo, InTy: OtherNode.getExtType(ResNo: OResNo),
1674 TP) |
1675 (int)OtherNode.UpdateNodeType(ResNo: OResNo, InTy: NodeToApply.getExtType(ResNo),
1676 TP);
1677 }
1678 case SDTCisVTSmallerThanOp: {
1679 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1680 // have an integer type that is smaller than the VT.
1681 if (!NodeToApply.isLeaf() || !isa<DefInit>(Val: NodeToApply.getLeafValue()) ||
1682 !cast<DefInit>(Val: NodeToApply.getLeafValue())
1683 ->getDef()
1684 ->isSubClassOf(Name: "ValueType")) {
1685 TP.error(Msg: N.getOperator()->getName() + " expects a VT operand!");
1686 return false;
1687 }
1688 const DefInit *DI = cast<DefInit>(Val: NodeToApply.getLeafValue());
1689 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1690 auto VVT = getValueTypeByHwMode(Rec: DI->getDef(), CGH: T.getHwModes());
1691 TypeSetByHwMode TypeListTmp(VVT);
1692
1693 unsigned OResNo = 0;
1694 TreePatternNode &OtherNode =
1695 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: OResNo);
1696
1697 return TI.EnforceSmallerThan(Small&: TypeListTmp, Big&: OtherNode.getExtType(ResNo: OResNo),
1698 /*SmallIsVT*/ true);
1699 }
1700 case SDTCisOpSmallerThanOp: {
1701 unsigned BResNo = 0;
1702 TreePatternNode &BigOperand =
1703 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: BResNo);
1704 return TI.EnforceSmallerThan(Small&: NodeToApply.getExtType(ResNo),
1705 Big&: BigOperand.getExtType(ResNo: BResNo));
1706 }
1707 case SDTCisEltOfVec: {
1708 unsigned VResNo = 0;
1709 TreePatternNode &VecOperand =
1710 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: VResNo);
1711 // Filter vector types out of VecOperand that don't have the right element
1712 // type.
1713 return TI.EnforceVectorEltTypeIs(Vec&: VecOperand.getExtType(ResNo: VResNo),
1714 Elem&: NodeToApply.getExtType(ResNo));
1715 }
1716 case SDTCisSubVecOfVec: {
1717 unsigned VResNo = 0;
1718 TreePatternNode &BigVecOperand =
1719 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: VResNo);
1720
1721 // Filter vector types out of BigVecOperand that don't have the
1722 // right subvector type.
1723 return TI.EnforceVectorSubVectorTypeIs(Vec&: BigVecOperand.getExtType(ResNo: VResNo),
1724 Sub&: NodeToApply.getExtType(ResNo));
1725 }
1726 case SDTCVecEltisVT: {
1727 return TI.EnforceVectorEltTypeIs(Vec&: NodeToApply.getExtType(ResNo), VVT);
1728 }
1729 case SDTCisSameNumEltsAs: {
1730 unsigned OResNo = 0;
1731 TreePatternNode &OtherNode =
1732 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: OResNo);
1733 return TI.EnforceSameNumElts(V&: OtherNode.getExtType(ResNo: OResNo),
1734 W&: NodeToApply.getExtType(ResNo));
1735 }
1736 case SDTCisSameSizeAs: {
1737 unsigned OResNo = 0;
1738 TreePatternNode &OtherNode =
1739 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: OResNo);
1740 return TI.EnforceSameSize(A&: OtherNode.getExtType(ResNo: OResNo),
1741 B&: NodeToApply.getExtType(ResNo));
1742 }
1743 }
1744 llvm_unreachable("Invalid ConstraintType!");
1745}
1746
1747bool llvm::operator==(const SDTypeConstraint &LHS,
1748 const SDTypeConstraint &RHS) {
1749 if (std::tie(args: LHS.OperandNo, args: LHS.ConstraintType) !=
1750 std::tie(args: RHS.OperandNo, args: RHS.ConstraintType))
1751 return false;
1752 switch (LHS.ConstraintType) {
1753 case SDTypeConstraint::SDTCisVT:
1754 case SDTypeConstraint::SDTCVecEltisVT:
1755 return LHS.VVT == RHS.VVT;
1756 case SDTypeConstraint::SDTCisPtrTy:
1757 case SDTypeConstraint::SDTCisInt:
1758 case SDTypeConstraint::SDTCisFP:
1759 case SDTypeConstraint::SDTCisVec:
1760 break;
1761 case SDTypeConstraint::SDTCisSameAs:
1762 case SDTypeConstraint::SDTCisVTSmallerThanOp:
1763 case SDTypeConstraint::SDTCisOpSmallerThanOp:
1764 case SDTypeConstraint::SDTCisEltOfVec:
1765 case SDTypeConstraint::SDTCisSubVecOfVec:
1766 case SDTypeConstraint::SDTCisSameNumEltsAs:
1767 case SDTypeConstraint::SDTCisSameSizeAs:
1768 return LHS.OtherOperandNo == RHS.OtherOperandNo;
1769 }
1770 return true;
1771}
1772
1773bool llvm::operator<(const SDTypeConstraint &LHS, const SDTypeConstraint &RHS) {
1774 if (std::tie(args: LHS.OperandNo, args: LHS.ConstraintType) !=
1775 std::tie(args: RHS.OperandNo, args: RHS.ConstraintType))
1776 return std::tie(args: LHS.OperandNo, args: LHS.ConstraintType) <
1777 std::tie(args: RHS.OperandNo, args: RHS.ConstraintType);
1778 switch (LHS.ConstraintType) {
1779 case SDTypeConstraint::SDTCisVT:
1780 case SDTypeConstraint::SDTCVecEltisVT:
1781 return LHS.VVT < RHS.VVT;
1782 case SDTypeConstraint::SDTCisPtrTy:
1783 case SDTypeConstraint::SDTCisInt:
1784 case SDTypeConstraint::SDTCisFP:
1785 case SDTypeConstraint::SDTCisVec:
1786 break;
1787 case SDTypeConstraint::SDTCisSameAs:
1788 case SDTypeConstraint::SDTCisVTSmallerThanOp:
1789 case SDTypeConstraint::SDTCisOpSmallerThanOp:
1790 case SDTypeConstraint::SDTCisEltOfVec:
1791 case SDTypeConstraint::SDTCisSubVecOfVec:
1792 case SDTypeConstraint::SDTCisSameNumEltsAs:
1793 case SDTypeConstraint::SDTCisSameSizeAs:
1794 return LHS.OtherOperandNo < RHS.OtherOperandNo;
1795 }
1796 return false;
1797}
1798
1799/// RegClassByHwMode acts like ValueTypeByHwMode, taking the type of the
1800/// register class from the active mode.
1801static TypeSetByHwMode getTypeForRegClassByHwMode(const CodeGenTarget &T,
1802 const Record *R,
1803 ArrayRef<SMLoc> Loc) {
1804 TypeSetByHwMode TypeSet;
1805 RegClassByHwMode Helper(R, T.getRegBank());
1806
1807 for (auto [ModeID, RegClass] : Helper) {
1808 ArrayRef<ValueTypeByHwMode> RegClassVTs = RegClass->getValueTypes();
1809 MachineValueTypeSet &ModeTypeSet = TypeSet.getOrCreate(Mode: ModeID);
1810 for (const ValueTypeByHwMode &VT : RegClassVTs) {
1811 if (!VT.hasMode(M: ModeID) && !VT.hasDefault()) {
1812 PrintError(ErrorLoc: R->getLoc(), Msg: "Could not resolve VT for Mode " +
1813 T.getHwModes().getModeName(Id: ModeID, IncludeDefault: true));
1814 if (VT.getRecord())
1815 PrintNote(NoteLoc: VT.getRecord()->getLoc(), Msg: "ValueTypeByHwMode " +
1816 VT.getRecord()->getName() +
1817 " defined here");
1818 PrintFatalNote(ErrorLoc: Loc, Msg: "pattern instantiated here");
1819 continue;
1820 }
1821 ModeTypeSet.insert(T: VT.getType(Mode: ModeID));
1822 }
1823 }
1824
1825 return TypeSet;
1826}
1827
1828// Update the node type to match an instruction operand or result as specified
1829// in the ins or outs lists on the instruction definition. Return true if the
1830// type was actually changed.
1831bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1832 const Record *Operand,
1833 TreePattern &TP) {
1834 // The 'unknown' operand indicates that types should be inferred from the
1835 // context.
1836 if (Operand->isSubClassOf(Name: "unknown_class"))
1837 return false;
1838
1839 // The Operand class specifies a type directly.
1840 if (Operand->isSubClassOf(Name: "Operand")) {
1841 const Record *R = Operand->getValueAsDef(FieldName: "Type");
1842 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1843 return UpdateNodeType(ResNo, InTy: getValueTypeByHwMode(Rec: R, CGH: T.getHwModes()), TP);
1844 }
1845
1846 // Both RegisterClass and RegisterOperand operands derive their types from a
1847 // register class def.
1848 const Record *RC = nullptr;
1849 if (Operand->isSubClassOf(Name: "RegisterClassLike"))
1850 RC = Operand;
1851 else if (Operand->isSubClassOf(Name: "RegisterOperand"))
1852 RC = Operand->getValueAsDef(FieldName: "RegClass");
1853
1854 if (!RC) {
1855 TP.error(Msg: "cannot update node type from unknown operand!");
1856 return false;
1857 }
1858
1859 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1860 if (RC->isSubClassOf(Name: "RegClassByHwMode"))
1861 return UpdateNodeType(
1862 ResNo, InTy: getTypeForRegClassByHwMode(T: Tgt, R: RC, Loc: TP.getRecord()->getLoc()),
1863 TP);
1864
1865 return UpdateNodeType(ResNo, InTy: Tgt.getRegisterClass(R: RC).getValueTypes(), TP);
1866}
1867
1868bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1869 for (const TypeSetByHwMode &Type : Types)
1870 if (!Type.isValueTypeByHwMode(/*AllowEmpty=*/true))
1871 return true;
1872 for (const TreePatternNode &Child : children())
1873 if (Child.ContainsUnresolvedType(TP))
1874 return true;
1875 return false;
1876}
1877
1878bool TreePatternNode::hasProperTypeByHwMode() const {
1879 for (const TypeSetByHwMode &S : Types)
1880 if (!S.isSimple())
1881 return true;
1882 for (const TreePatternNodePtr &C : Children)
1883 if (C->hasProperTypeByHwMode())
1884 return true;
1885 return false;
1886}
1887
1888bool TreePatternNode::hasPossibleType() const {
1889 for (const TypeSetByHwMode &S : Types)
1890 if (!S.isPossible())
1891 return false;
1892 for (const TreePatternNodePtr &C : Children)
1893 if (!C->hasPossibleType())
1894 return false;
1895 return true;
1896}
1897
1898bool TreePatternNode::setDefaultMode(unsigned Mode) {
1899 for (TypeSetByHwMode &S : Types) {
1900 S.makeSimple(Mode);
1901 // Check if the selected mode had a type conflict.
1902 if (S.get(Mode: DefaultMode).empty())
1903 return false;
1904 }
1905 for (const TreePatternNodePtr &C : Children)
1906 if (!C->setDefaultMode(Mode))
1907 return false;
1908 return true;
1909}
1910
1911//===----------------------------------------------------------------------===//
1912// SDNodeInfo implementation
1913//
1914SDNodeInfo::SDNodeInfo(const Record *R, const CodeGenHwModes &CGH) : Def(R) {
1915 EnumName = R->getValueAsString(FieldName: "Opcode");
1916 SDClassName = R->getValueAsString(FieldName: "SDClass");
1917 const Record *TypeProfile = R->getValueAsDef(FieldName: "TypeProfile");
1918 NumResults = TypeProfile->getValueAsInt(FieldName: "NumResults");
1919 NumOperands = TypeProfile->getValueAsInt(FieldName: "NumOperands");
1920
1921 // Parse the properties.
1922 Properties = parseSDPatternOperatorProperties(R);
1923 IsStrictFP = R->getValueAsBit(FieldName: "IsStrictFP");
1924
1925 std::optional<int64_t> MaybeTSFlags =
1926 R->getValueAsBitsInit(FieldName: "TSFlags")->convertInitializerToInt();
1927 if (!MaybeTSFlags)
1928 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "Invalid TSFlags");
1929 assert(isUInt<32>(*MaybeTSFlags) && "TSFlags bit width out of sync");
1930 TSFlags = *MaybeTSFlags;
1931
1932 // Parse the type constraints.
1933 for (const Record *R : TypeProfile->getValueAsListOfDefs(FieldName: "Constraints"))
1934 TypeConstraints.emplace_back(args&: R, args: CGH);
1935}
1936
1937/// getKnownType - If the type constraints on this node imply a fixed type
1938/// (e.g. all stores return void, etc), then return it as an
1939/// MVT. Otherwise, return EEVT::Other.
1940MVT SDNodeInfo::getKnownType(unsigned ResNo) const {
1941 unsigned NumResults = getNumResults();
1942 assert(NumResults <= 1 &&
1943 "We only work with nodes with zero or one result so far!");
1944 assert(ResNo == 0 && "Only handles single result nodes so far");
1945
1946 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1947 // Make sure that this applies to the correct node result.
1948 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1949 continue;
1950
1951 switch (Constraint.ConstraintType) {
1952 default:
1953 break;
1954 case SDTypeConstraint::SDTCisVT:
1955 if (Constraint.VVT.isSimple())
1956 return Constraint.VVT.getSimple().SimpleTy;
1957 break;
1958 case SDTypeConstraint::SDTCisPtrTy:
1959 return MVT::iPTR;
1960 }
1961 }
1962 return MVT::Other;
1963}
1964
1965//===----------------------------------------------------------------------===//
1966// TreePatternNode implementation
1967//
1968
1969static unsigned GetNumNodeResults(const Record *Operator,
1970 CodeGenDAGPatterns &CDP) {
1971 if (Operator->getName() == "set")
1972 return 0; // All return nothing.
1973
1974 if (Operator->isSubClassOf(Name: "Intrinsic"))
1975 return CDP.getIntrinsic(R: Operator).IS.RetTys.size();
1976
1977 if (Operator->isSubClassOf(Name: "SDNode"))
1978 return CDP.getSDNodeInfo(R: Operator).getNumResults();
1979
1980 if (Operator->isSubClassOf(Name: "PatFrags")) {
1981 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1982 // the forward reference case where one pattern fragment references another
1983 // before it is processed.
1984 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(R: Operator)) {
1985 // The number of results of a fragment with alternative records is the
1986 // maximum number of results across all alternatives.
1987 unsigned NumResults = 0;
1988 for (const auto &T : PFRec->getTrees())
1989 NumResults = std::max(a: NumResults, b: T->getNumTypes());
1990 return NumResults;
1991 }
1992
1993 const ListInit *LI = Operator->getValueAsListInit(FieldName: "Fragments");
1994 assert(LI && "Invalid Fragment");
1995 unsigned NumResults = 0;
1996 for (const Init *I : LI->getElements()) {
1997 const Record *Op = nullptr;
1998 if (const DagInit *Dag = dyn_cast<DagInit>(Val: I))
1999 if (const DefInit *DI = dyn_cast<DefInit>(Val: Dag->getOperator()))
2000 Op = DI->getDef();
2001 assert(Op && "Invalid Fragment");
2002 NumResults = std::max(a: NumResults, b: GetNumNodeResults(Operator: Op, CDP));
2003 }
2004 return NumResults;
2005 }
2006
2007 if (Operator->isSubClassOf(Name: "Instruction")) {
2008 const CodeGenInstruction &InstInfo =
2009 CDP.getTargetInfo().getInstruction(InstRec: Operator);
2010
2011 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
2012
2013 // Subtract any defaulted outputs.
2014 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
2015 const Record *OperandNode = InstInfo.Operands[i].Rec;
2016
2017 if (OperandNode->isSubClassOf(Name: "OperandWithDefaultOps") &&
2018 !CDP.getDefaultOperand(R: OperandNode).DefaultOps.empty())
2019 --NumDefsToAdd;
2020 }
2021
2022 // Add on one implicit def if it has a resolvable type.
2023 if (InstInfo.HasOneImplicitDefWithKnownVT(TargetInfo: CDP.getTargetInfo()) !=
2024 MVT::Other)
2025 ++NumDefsToAdd;
2026 return NumDefsToAdd;
2027 }
2028
2029 if (Operator->isSubClassOf(Name: "SDNodeXForm"))
2030 return 1; // FIXME: Generalize SDNodeXForm
2031
2032 if (Operator->isSubClassOf(Name: "ValueType"))
2033 return 1; // A type-cast of one result.
2034
2035 if (Operator->isSubClassOf(Name: "ComplexPattern"))
2036 return 1;
2037
2038 errs() << *Operator;
2039 PrintFatalError(Msg: "Unhandled node in GetNumNodeResults");
2040}
2041
2042void TreePatternNode::print(raw_ostream &OS) const {
2043 if (isLeaf())
2044 OS << *getLeafValue();
2045 else
2046 OS << '(' << getOperator()->getName();
2047
2048 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
2049 OS << ':';
2050 getExtType(ResNo: i).writeToStream(OS);
2051 }
2052
2053 if (!isLeaf()) {
2054 if (getNumChildren() != 0) {
2055 OS << " ";
2056 ListSeparator LS;
2057 for (const TreePatternNode &Child : children()) {
2058 OS << LS;
2059 Child.print(OS);
2060 }
2061 }
2062 OS << ")";
2063 }
2064
2065 for (const TreePredicateCall &Pred : PredicateCalls) {
2066 OS << "<<P:";
2067 if (Pred.Scope)
2068 OS << Pred.Scope << ":";
2069 OS << Pred.Fn.getFnName() << ">>";
2070 }
2071 if (TransformFn)
2072 OS << "<<X:" << TransformFn->getName() << ">>";
2073 if (!getName().empty())
2074 OS << ":$" << getName();
2075
2076 for (const ScopedName &Name : NamesAsPredicateArg)
2077 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
2078}
2079void TreePatternNode::dump() const {
2080 print(OS&: dbgs());
2081 dbgs() << '\n';
2082}
2083
2084/// isIsomorphicTo - Return true if this node is recursively
2085/// isomorphic to the specified node. For this comparison, the node's
2086/// entire state is considered. The assigned name is ignored, since
2087/// nodes with differing names are considered isomorphic. However, if
2088/// the assigned name is present in the dependent variable set, then
2089/// the assigned name is considered significant and the node is
2090/// isomorphic if the names match.
2091bool TreePatternNode::isIsomorphicTo(const TreePatternNode &N,
2092 const MultipleUseVarSet &DepVars) const {
2093 if (&N == this)
2094 return true;
2095 if (N.isLeaf() != isLeaf())
2096 return false;
2097
2098 // Check operator of non-leaves early since it can be cheaper than checking
2099 // types.
2100 if (!isLeaf())
2101 if (N.getOperator() != getOperator() ||
2102 N.getNumChildren() != getNumChildren())
2103 return false;
2104
2105 if (getExtTypes() != N.getExtTypes() ||
2106 getPredicateCalls() != N.getPredicateCalls() ||
2107 getTransformFn() != N.getTransformFn())
2108 return false;
2109
2110 if (isLeaf()) {
2111 if (const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue())) {
2112 if (const DefInit *NDI = dyn_cast<DefInit>(Val: N.getLeafValue())) {
2113 return ((DI->getDef() == NDI->getDef()) &&
2114 (!DepVars.contains(key: getName()) || getName() == N.getName()));
2115 }
2116 }
2117 return getLeafValue() == N.getLeafValue();
2118 }
2119
2120 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2121 if (!getChild(N: i).isIsomorphicTo(N: N.getChild(N: i), DepVars))
2122 return false;
2123 return true;
2124}
2125
2126/// clone - Make a copy of this tree and all of its children.
2127///
2128TreePatternNodePtr TreePatternNode::clone() const {
2129 TreePatternNodePtr New;
2130 if (isLeaf()) {
2131 New = makeIntrusiveRefCnt<TreePatternNode>(A: getLeafValue(), A: getNumTypes());
2132 } else {
2133 std::vector<TreePatternNodePtr> CChildren;
2134 CChildren.reserve(n: Children.size());
2135 for (const TreePatternNode &Child : children())
2136 CChildren.push_back(x: Child.clone());
2137 New = makeIntrusiveRefCnt<TreePatternNode>(
2138 A: getOperator(), A: std::move(CChildren), A: getNumTypes());
2139 }
2140 New->setName(getName());
2141 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
2142 New->Types = Types;
2143 New->setPredicateCalls(getPredicateCalls());
2144 New->setGISelFlagsRecord(getGISelFlagsRecord());
2145 New->setTransformFn(getTransformFn());
2146 return New;
2147}
2148
2149/// RemoveAllTypes - Recursively strip all the types of this tree.
2150void TreePatternNode::RemoveAllTypes() {
2151 // Reset to unknown type.
2152 llvm::fill(Range&: Types, Value: TypeSetByHwMode());
2153 if (isLeaf())
2154 return;
2155 for (TreePatternNode &Child : children())
2156 Child.RemoveAllTypes();
2157}
2158
2159/// SubstituteFormalArguments - Replace the formal arguments in this tree
2160/// with actual values specified by ArgMap.
2161void TreePatternNode::SubstituteFormalArguments(
2162 std::map<StringRef, TreePatternNodePtr> &ArgMap) {
2163 if (isLeaf())
2164 return;
2165
2166 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2167 TreePatternNode &Child = getChild(N: i);
2168 if (Child.isLeaf()) {
2169 const Init *Val = Child.getLeafValue();
2170 // Note that, when substituting into an output pattern, Val might be an
2171 // UnsetInit.
2172 if (isa<UnsetInit>(Val) ||
2173 (isa<DefInit>(Val) &&
2174 cast<DefInit>(Val)->getDef()->getName() == "node")) {
2175 // We found a use of a formal argument, replace it with its value.
2176 TreePatternNodePtr NewChild = ArgMap[Child.getName()];
2177 assert(NewChild && "Couldn't find formal argument!");
2178 assert((Child.getPredicateCalls().empty() ||
2179 NewChild->getPredicateCalls() == Child.getPredicateCalls()) &&
2180 "Non-empty child predicate clobbered!");
2181 setChild(i, N: std::move(NewChild));
2182 }
2183 } else {
2184 getChild(N: i).SubstituteFormalArguments(ArgMap);
2185 }
2186 }
2187}
2188
2189/// InlinePatternFragments - If this pattern refers to any pattern
2190/// fragments, return the set of inlined versions (this can be more than
2191/// one if a PatFrags record has multiple alternatives).
2192void TreePatternNode::InlinePatternFragments(
2193 TreePattern &TP, std::vector<TreePatternNodePtr> &OutAlternatives) {
2194
2195 if (TP.hasError())
2196 return;
2197
2198 if (isLeaf()) {
2199 OutAlternatives.push_back(x: this); // nothing to do.
2200 return;
2201 }
2202
2203 const Record *Op = getOperator();
2204
2205 if (!Op->isSubClassOf(Name: "PatFrags")) {
2206 if (getNumChildren() == 0) {
2207 OutAlternatives.push_back(x: this);
2208 return;
2209 }
2210
2211 // Recursively inline children nodes.
2212 std::vector<std::vector<TreePatternNodePtr>> ChildAlternatives(
2213 getNumChildren());
2214 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2215 TreePatternNodePtr Child = getChildShared(N: i);
2216 Child->InlinePatternFragments(TP, OutAlternatives&: ChildAlternatives[i]);
2217 // If there are no alternatives for any child, there are no
2218 // alternatives for this expression as whole.
2219 if (ChildAlternatives[i].empty())
2220 return;
2221
2222 assert((Child->getPredicateCalls().empty() ||
2223 llvm::all_of(ChildAlternatives[i],
2224 [&](const TreePatternNodePtr &NewChild) {
2225 return NewChild->getPredicateCalls() ==
2226 Child->getPredicateCalls();
2227 })) &&
2228 "Non-empty child predicate clobbered!");
2229 }
2230
2231 // The end result is an all-pairs construction of the resultant pattern.
2232 std::vector<unsigned> Idxs(ChildAlternatives.size());
2233 bool NotDone;
2234 do {
2235 // Create the variant and add it to the output list.
2236 std::vector<TreePatternNodePtr> NewChildren;
2237 NewChildren.reserve(n: ChildAlternatives.size());
2238 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
2239 NewChildren.push_back(x: ChildAlternatives[i][Idxs[i]]);
2240 TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
2241 A: getOperator(), A: std::move(NewChildren), A: getNumTypes());
2242
2243 // Copy over properties.
2244 R->setName(getName());
2245 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
2246 R->setPredicateCalls(getPredicateCalls());
2247 R->setGISelFlagsRecord(getGISelFlagsRecord());
2248 R->setTransformFn(getTransformFn());
2249 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2250 R->setType(ResNo: i, T: getExtType(ResNo: i));
2251 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2252 R->setResultIndex(ResNo: i, RI: getResultIndex(ResNo: i));
2253
2254 // Register alternative.
2255 OutAlternatives.push_back(x: R);
2256
2257 // Increment indices to the next permutation by incrementing the
2258 // indices from last index backward, e.g., generate the sequence
2259 // [0, 0], [0, 1], [1, 0], [1, 1].
2260 int IdxsIdx;
2261 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2262 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2263 Idxs[IdxsIdx] = 0;
2264 else
2265 break;
2266 }
2267 NotDone = (IdxsIdx >= 0);
2268 } while (NotDone);
2269
2270 return;
2271 }
2272
2273 // Otherwise, we found a reference to a fragment. First, look up its
2274 // TreePattern record.
2275 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(R: Op);
2276
2277 // Verify that we are passing the right number of operands.
2278 if (Frag->getNumArgs() != getNumChildren()) {
2279 TP.error(Msg: "'" + Op->getName() + "' fragment requires " +
2280 Twine(Frag->getNumArgs()) + " operands!");
2281 return;
2282 }
2283
2284 TreePredicateFn PredFn(Frag);
2285 unsigned Scope = 0;
2286 if (TreePredicateFn(Frag).usesOperands())
2287 Scope = TP.getDAGPatterns().allocateScope();
2288
2289 // Compute the map of formal to actual arguments.
2290 std::map<StringRef, TreePatternNodePtr> ArgMap;
2291 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
2292 TreePatternNodePtr Child = getChildShared(N: i);
2293 if (Scope != 0) {
2294 Child = Child->clone();
2295 Child->addNameAsPredicateArg(N: ScopedName(Scope, Frag->getArgName(i)));
2296 }
2297 ArgMap[Frag->getArgName(i)] = Child;
2298 }
2299
2300 // Loop over all fragment alternatives.
2301 for (const auto &Alternative : Frag->getTrees()) {
2302 TreePatternNodePtr FragTree = Alternative->clone();
2303
2304 if (!PredFn.isAlwaysTrue())
2305 FragTree->addPredicateCall(Fn: PredFn, Scope);
2306
2307 // Resolve formal arguments to their actual value.
2308 if (Frag->getNumArgs())
2309 FragTree->SubstituteFormalArguments(ArgMap);
2310
2311 // Transfer types. Note that the resolved alternative may have fewer
2312 // (but not more) results than the PatFrags node.
2313 FragTree->setName(getName());
2314 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2315 FragTree->UpdateNodeType(ResNo: i, InTy: getExtType(ResNo: i), TP);
2316
2317 if (Op->isSubClassOf(Name: "GISelFlags"))
2318 FragTree->setGISelFlagsRecord(Op);
2319
2320 // Transfer in the old predicates.
2321 for (const TreePredicateCall &Pred : getPredicateCalls())
2322 FragTree->addPredicateCall(Call: Pred);
2323
2324 // The fragment we inlined could have recursive inlining that is needed. See
2325 // if there are any pattern fragments in it and inline them as needed.
2326 FragTree->InlinePatternFragments(TP, OutAlternatives);
2327 }
2328}
2329
2330/// getImplicitType - Check to see if the specified record has an implicit
2331/// type which should be applied to it. This will infer the type of register
2332/// references from the register file information, for example.
2333///
2334/// When Unnamed is set, return the type of a DAG operand with no name, such as
2335/// the F8RC register class argument in:
2336///
2337/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2338///
2339/// When Unnamed is false, return the type of a named DAG operand such as the
2340/// GPR:$src operand above.
2341///
2342static TypeSetByHwMode getImplicitType(const Record *R, unsigned ResNo,
2343 bool NotRegisters, bool Unnamed,
2344 TreePattern &TP) {
2345 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2346
2347 // Check to see if this is a register operand.
2348 if (R->isSubClassOf(Name: "RegisterOperand")) {
2349 assert(ResNo == 0 && "Regoperand ref only has one result!");
2350 if (NotRegisters)
2351 return TypeSetByHwMode(); // Unknown.
2352 const Record *RegClass = R->getValueAsDef(FieldName: "RegClass");
2353 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2354
2355 if (RegClass->isSubClassOf(Name: "RegClassByHwMode"))
2356 return getTypeForRegClassByHwMode(T, R: RegClass, Loc: TP.getRecord()->getLoc());
2357
2358 return TypeSetByHwMode(T.getRegisterClass(R: RegClass).getValueTypes());
2359 }
2360
2361 // Check to see if this is a register or a register class.
2362 if (R->isSubClassOf(Name: "RegisterClass")) {
2363 assert(ResNo == 0 && "Regclass ref only has one result!");
2364 // An unnamed register class represents itself as an i32 immediate, for
2365 // example on a COPY_TO_REGCLASS instruction.
2366 if (Unnamed)
2367 return TypeSetByHwMode(MVT::i32);
2368
2369 // In a named operand, the register class provides the possible set of
2370 // types.
2371 if (NotRegisters)
2372 return TypeSetByHwMode(); // Unknown.
2373 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2374 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2375 }
2376
2377 if (R->isSubClassOf(Name: "RegClassByHwMode")) {
2378 if (NotRegisters)
2379 return TypeSetByHwMode(); // Unknown.
2380 const CodeGenTarget &T = CDP.getTargetInfo();
2381 return getTypeForRegClassByHwMode(T, R, Loc: TP.getRecord()->getLoc());
2382 }
2383
2384 if (R->isSubClassOf(Name: "PatFrags")) {
2385 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2386 // Pattern fragment types will be resolved when they are inlined.
2387 return TypeSetByHwMode(); // Unknown.
2388 }
2389
2390 if (R->isSubClassOf(Name: "Register")) {
2391 assert(ResNo == 0 && "Registers only produce one result!");
2392 if (NotRegisters)
2393 return TypeSetByHwMode(); // Unknown.
2394 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2395 return TypeSetByHwMode(T.getRegisterVTs(R));
2396 }
2397
2398 if (R->isSubClassOf(Name: "SubRegIndex")) {
2399 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
2400 return TypeSetByHwMode(MVT::i32);
2401 }
2402
2403 if (R->isSubClassOf(Name: "ValueType")) {
2404 assert(ResNo == 0 && "This node only has one result!");
2405 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2406 //
2407 // (sext_inreg GPR:$src, i16)
2408 // ~~~
2409 if (Unnamed)
2410 return TypeSetByHwMode(MVT::Other);
2411 // With a name, the ValueType simply provides the type of the named
2412 // variable.
2413 //
2414 // (sext_inreg i32:$src, i16)
2415 // ~~~~~~~~
2416 if (NotRegisters)
2417 return TypeSetByHwMode(); // Unknown.
2418 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2419 return TypeSetByHwMode(getValueTypeByHwMode(Rec: R, CGH));
2420 }
2421
2422 if (R->isSubClassOf(Name: "CondCode")) {
2423 assert(ResNo == 0 && "This node only has one result!");
2424 // Using a CondCodeSDNode.
2425 return TypeSetByHwMode(MVT::Other);
2426 }
2427
2428 if (R->isSubClassOf(Name: "ComplexPattern")) {
2429 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2430 if (NotRegisters)
2431 return TypeSetByHwMode(); // Unknown.
2432 const Record *T = CDP.getComplexPattern(R).getValueType();
2433 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2434 return TypeSetByHwMode(getValueTypeByHwMode(Rec: T, CGH));
2435 }
2436
2437 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2438 R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
2439 R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
2440 // Placeholder.
2441 return TypeSetByHwMode(); // Unknown.
2442 }
2443
2444 if (R->isSubClassOf(Name: "Operand")) {
2445 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2446 const Record *T = R->getValueAsDef(FieldName: "Type");
2447 return TypeSetByHwMode(getValueTypeByHwMode(Rec: T, CGH));
2448 }
2449
2450 TP.error(Msg: "Unknown node flavor used in pattern: " + R->getName());
2451 return TypeSetByHwMode(MVT::Other);
2452}
2453
2454/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2455/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2456const CodeGenIntrinsic *
2457TreePatternNode::getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2458 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2459 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2460 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2461 return nullptr;
2462
2463 unsigned IID = cast<IntInit>(Val: getChild(N: 0).getLeafValue())->getValue();
2464 return &CDP.getIntrinsicInfo(IID);
2465}
2466
2467/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2468/// return the ComplexPattern information, otherwise return null.
2469const ComplexPattern *
2470TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2471 const Record *Rec;
2472 if (isLeaf()) {
2473 const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue());
2474 if (!DI)
2475 return nullptr;
2476 Rec = DI->getDef();
2477 } else {
2478 Rec = getOperator();
2479 }
2480
2481 if (!Rec->isSubClassOf(Name: "ComplexPattern"))
2482 return nullptr;
2483 return &CGP.getComplexPattern(R: Rec);
2484}
2485
2486unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2487 // A ComplexPattern specifically declares how many results it fills in.
2488 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2489 return CP->getNumOperands();
2490
2491 // If MIOperandInfo is specified, that gives the count.
2492 if (isLeaf()) {
2493 const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue());
2494 if (DI && DI->getDef()->isSubClassOf(Name: "Operand")) {
2495 const DagInit *MIOps = DI->getDef()->getValueAsDag(FieldName: "MIOperandInfo");
2496 if (MIOps->getNumArgs())
2497 return MIOps->getNumArgs();
2498 }
2499 }
2500
2501 // Otherwise there is just one result.
2502 return 1;
2503}
2504
2505/// NodeHasProperty - Return true if this node has the specified property.
2506bool TreePatternNode::NodeHasProperty(SDNP Property,
2507 const CodeGenDAGPatterns &CGP) const {
2508 if (isLeaf()) {
2509 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2510 return CP->hasProperty(Prop: Property);
2511
2512 return false;
2513 }
2514
2515 if (Property != SDNPHasChain) {
2516 // The chain proprety is already present on the different intrinsic node
2517 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2518 // on the intrinsic. Anything else is specific to the individual intrinsic.
2519 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP: CGP))
2520 return Int->hasProperty(Prop: Property);
2521 }
2522
2523 if (!getOperator()->isSubClassOf(Name: "SDPatternOperator"))
2524 return false;
2525
2526 return CGP.getSDNodeInfo(R: getOperator()).hasProperty(Prop: Property);
2527}
2528
2529/// TreeHasProperty - Return true if any node in this tree has the specified
2530/// property.
2531bool TreePatternNode::TreeHasProperty(SDNP Property,
2532 const CodeGenDAGPatterns &CGP) const {
2533 if (NodeHasProperty(Property, CGP))
2534 return true;
2535 for (const TreePatternNode &Child : children())
2536 if (Child.TreeHasProperty(Property, CGP))
2537 return true;
2538 return false;
2539}
2540
2541/// isCommutativeIntrinsic - Return true if the node corresponds to a
2542/// commutative intrinsic.
2543bool TreePatternNode::isCommutativeIntrinsic(
2544 const CodeGenDAGPatterns &CDP) const {
2545 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2546 return Int->isCommutative;
2547 return false;
2548}
2549
2550static bool isOperandClass(const TreePatternNode &N, StringRef Class) {
2551 if (!N.isLeaf())
2552 return N.getOperator()->isSubClassOf(Name: Class);
2553
2554 const DefInit *DI = dyn_cast<DefInit>(Val: N.getLeafValue());
2555 if (DI && DI->getDef()->isSubClassOf(Name: Class))
2556 return true;
2557
2558 return false;
2559}
2560
2561static void emitTooManyOperandsError(TreePattern &TP, StringRef InstName,
2562 unsigned Expected, unsigned Actual) {
2563 TP.error(Msg: "Instruction '" + InstName + "' was provided " + Twine(Actual) +
2564 " operands but expected only " + Twine(Expected) + "!");
2565}
2566
2567static void emitTooFewOperandsError(TreePattern &TP, StringRef InstName,
2568 unsigned Actual) {
2569 TP.error(Msg: "Instruction '" + InstName + "' expects more than the provided " +
2570 Twine(Actual) + " operands!");
2571}
2572
2573/// ApplyTypeConstraints - Apply all of the type constraints relevant to
2574/// this node and its children in the tree. This returns true if it makes a
2575/// change, false otherwise. If a type contradiction is found, flag an error.
2576bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2577 if (TP.hasError())
2578 return false;
2579
2580 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2581 if (isLeaf()) {
2582 if (const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue())) {
2583 // If it's a regclass or something else known, include the type.
2584 bool MadeChange = false;
2585 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2586 MadeChange |= UpdateNodeType(
2587 ResNo: i, InTy: getImplicitType(R: DI->getDef(), ResNo: i, NotRegisters, Unnamed: !hasName(), TP),
2588 TP);
2589 return MadeChange;
2590 }
2591
2592 if (const IntInit *II = dyn_cast<IntInit>(Val: getLeafValue())) {
2593 assert(Types.size() == 1 && "Invalid IntInit");
2594
2595 // Int inits are always integers. :)
2596 bool MadeChange = TP.getInfer().EnforceInteger(Out&: Types[0]);
2597
2598 if (!Types[0].isValueTypeByHwMode(/*AllowEmpty=*/false))
2599 return MadeChange;
2600
2601 ValueTypeByHwMode VVT = Types[0].getValueTypeByHwMode();
2602 for (auto &P : VVT) {
2603 MVT VT = P.second;
2604 // Can only check for types of a known size
2605 if (VT == MVT::iPTR)
2606 continue;
2607
2608 // Check that the value doesn't use more bits than we have. It must
2609 // either be a sign- or zero-extended equivalent of the original.
2610 unsigned Width = VT.getFixedSizeInBits();
2611 int64_t Val = II->getValue();
2612 if (!isIntN(N: Width, x: Val) && !isUIntN(N: Width, x: Val)) {
2613 TP.error(Msg: "Integer value '" + Twine(Val) +
2614 "' is out of range for type '" + getEnumName(T: VT) + "'!");
2615 break;
2616 }
2617 }
2618 return MadeChange;
2619 }
2620
2621 return false;
2622 }
2623
2624 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2625 bool MadeChange = false;
2626
2627 // Apply the result type to the node.
2628 unsigned NumRetVTs = Int->IS.RetTys.size();
2629 unsigned NumParamVTs = Int->IS.ParamTys.size();
2630
2631 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2632 MadeChange |= UpdateNodeType(
2633 ResNo: i, InTy: getValueType(Rec: Int->IS.RetTys[i]->getValueAsDef(FieldName: "VT")), TP);
2634
2635 if (getNumChildren() != NumParamVTs + 1) {
2636 TP.error(Msg: "Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2637 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2638 return false;
2639 }
2640
2641 // Apply type info to the intrinsic ID.
2642 MadeChange |= getChild(N: 0).UpdateNodeType(ResNo: 0, InTy: MVT::iPTR, TP);
2643
2644 for (unsigned i = 0, e = getNumChildren() - 1; i != e; ++i) {
2645 MadeChange |= getChild(N: i + 1).ApplyTypeConstraints(TP, NotRegisters);
2646
2647 MVT OpVT = getValueType(Rec: Int->IS.ParamTys[i]->getValueAsDef(FieldName: "VT"));
2648 assert(getChild(i + 1).getNumTypes() == 1 && "Unhandled case");
2649 MadeChange |= getChild(N: i + 1).UpdateNodeType(ResNo: 0, InTy: OpVT, TP);
2650 }
2651 return MadeChange;
2652 }
2653
2654 if (getOperator()->isSubClassOf(Name: "SDNode")) {
2655 const SDNodeInfo &NI = CDP.getSDNodeInfo(R: getOperator());
2656
2657 // Check that the number of operands is sane. Negative operands -> varargs.
2658 if (NI.getNumOperands() >= 0 &&
2659 getNumChildren() != (unsigned)NI.getNumOperands()) {
2660 TP.error(Msg: getOperator()->getName() + " node requires exactly " +
2661 Twine(NI.getNumOperands()) + " operands!");
2662 return false;
2663 }
2664
2665 bool MadeChange = false;
2666 for (TreePatternNode &Child : children())
2667 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2668 MadeChange |= NI.ApplyTypeConstraints(N&: *this, TP);
2669 return MadeChange;
2670 }
2671
2672 if (getOperator()->isSubClassOf(Name: "Instruction")) {
2673 const DAGInstruction &Inst = CDP.getInstruction(R: getOperator());
2674 const CodeGenInstruction &InstInfo =
2675 CDP.getTargetInfo().getInstruction(InstRec: getOperator());
2676
2677 bool MadeChange = false;
2678
2679 // Apply the result types to the node, these come from the things in the
2680 // (outs) list of the instruction.
2681 unsigned NumResultsToAdd =
2682 std::min(a: InstInfo.Operands.NumDefs, b: Inst.getNumResults());
2683 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2684 MadeChange |= UpdateNodeTypeFromInst(ResNo, Operand: Inst.getResult(RN: ResNo), TP);
2685
2686 // If the instruction has implicit defs, we apply the first one as a result.
2687 // FIXME: This sucks, it should apply all implicit defs.
2688 if (!InstInfo.ImplicitDefs.empty()) {
2689 unsigned ResNo = NumResultsToAdd;
2690
2691 // FIXME: Generalize to multiple possible types and multiple possible
2692 // ImplicitDefs.
2693 MVT VT = InstInfo.HasOneImplicitDefWithKnownVT(TargetInfo: CDP.getTargetInfo());
2694
2695 if (VT != MVT::Other)
2696 MadeChange |= UpdateNodeType(ResNo, InTy: VT, TP);
2697 }
2698
2699 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2700 // be the same.
2701 if (getOperator()->getName() == "INSERT_SUBREG") {
2702 assert(getChild(0).getNumTypes() == 1 && "FIXME: Unhandled");
2703 MadeChange |= UpdateNodeType(ResNo: 0, InTy: getChild(N: 0).getExtType(ResNo: 0), TP);
2704 MadeChange |= getChild(N: 0).UpdateNodeType(ResNo: 0, InTy: getExtType(ResNo: 0), TP);
2705 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2706 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2707 // variadic.
2708
2709 unsigned NChild = getNumChildren();
2710 if (NChild < 3) {
2711 TP.error(Msg: "REG_SEQUENCE requires at least 3 operands!");
2712 return false;
2713 }
2714
2715 if (NChild % 2 == 0) {
2716 TP.error(Msg: "REG_SEQUENCE requires an odd number of operands!");
2717 return false;
2718 }
2719
2720 if (!isOperandClass(N: getChild(N: 0), Class: "RegisterClass")) {
2721 TP.error(Msg: "REG_SEQUENCE requires a RegisterClass for first operand!");
2722 return false;
2723 }
2724
2725 for (unsigned I = 1; I < NChild; I += 2) {
2726 TreePatternNode &SubIdxChild = getChild(N: I + 1);
2727 if (!isOperandClass(N: SubIdxChild, Class: "SubRegIndex")) {
2728 TP.error(Msg: "REG_SEQUENCE requires a SubRegIndex for operand " +
2729 Twine(I + 1) + "!");
2730 return false;
2731 }
2732 }
2733 }
2734
2735 unsigned NumResults = Inst.getNumResults();
2736 unsigned NumFixedOperands = InstInfo.Operands.size();
2737
2738 // If one or more operands with a default value appear at the end of the
2739 // formal operand list for an instruction, we allow them to be overridden
2740 // by optional operands provided in the pattern.
2741 //
2742 // But if an operand B without a default appears at any point after an
2743 // operand A with a default, then we don't allow A to be overridden,
2744 // because there would be no way to specify whether the next operand in
2745 // the pattern was intended to override A or skip it.
2746 unsigned NonOverridableOperands = NumFixedOperands;
2747 while (NonOverridableOperands > NumResults &&
2748 CDP.operandHasDefault(
2749 Op: InstInfo.Operands[NonOverridableOperands - 1].Rec))
2750 --NonOverridableOperands;
2751
2752 unsigned ChildNo = 0;
2753 assert(NumResults <= NumFixedOperands);
2754 for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {
2755 const Record *OperandNode = InstInfo.Operands[i].Rec;
2756
2757 // If the operand has a default value, do we use it? We must use the
2758 // default if we've run out of children of the pattern DAG to consume,
2759 // or if the operand is followed by a non-defaulted one.
2760 if (CDP.operandHasDefault(Op: OperandNode) &&
2761 (i < NonOverridableOperands || ChildNo >= getNumChildren()))
2762 continue;
2763
2764 // If we have run out of child nodes and there _isn't_ a default
2765 // value we can use for the next operand, give an error.
2766 if (ChildNo >= getNumChildren()) {
2767 emitTooFewOperandsError(TP, InstName: getOperator()->getName(), Actual: getNumChildren());
2768 return false;
2769 }
2770
2771 TreePatternNode *Child = &getChild(N: ChildNo++);
2772 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
2773
2774 // If the operand has sub-operands, they may be provided by distinct
2775 // child patterns, so attempt to match each sub-operand separately.
2776 if (OperandNode->isSubClassOf(Name: "Operand")) {
2777 const DagInit *MIOpInfo = OperandNode->getValueAsDag(FieldName: "MIOperandInfo");
2778 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2779 // But don't do that if the whole operand is being provided by
2780 // a single ComplexPattern-related Operand.
2781
2782 if (Child->getNumMIResults(CGP: CDP) < NumArgs) {
2783 // Match first sub-operand against the child we already have.
2784 const Record *SubRec = cast<DefInit>(Val: MIOpInfo->getArg(Num: 0))->getDef();
2785 MadeChange |= Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: SubRec, TP);
2786
2787 // And the remaining sub-operands against subsequent children.
2788 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2789 if (ChildNo >= getNumChildren()) {
2790 emitTooFewOperandsError(TP, InstName: getOperator()->getName(),
2791 Actual: getNumChildren());
2792 return false;
2793 }
2794 Child = &getChild(N: ChildNo++);
2795
2796 SubRec = cast<DefInit>(Val: MIOpInfo->getArg(Num: Arg))->getDef();
2797 MadeChange |=
2798 Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: SubRec, TP);
2799 }
2800 continue;
2801 }
2802 }
2803 }
2804
2805 // If we didn't match by pieces above, attempt to match the whole
2806 // operand now.
2807 MadeChange |= Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: OperandNode, TP);
2808 }
2809
2810 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2811 emitTooManyOperandsError(TP, InstName: getOperator()->getName(), Expected: ChildNo,
2812 Actual: getNumChildren());
2813 return false;
2814 }
2815
2816 for (TreePatternNode &Child : children())
2817 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2818 return MadeChange;
2819 }
2820
2821 if (getOperator()->isSubClassOf(Name: "ComplexPattern")) {
2822 bool MadeChange = false;
2823
2824 if (!NotRegisters) {
2825 assert(Types.size() == 1 && "ComplexPatterns only produce one result!");
2826 const Record *T = CDP.getComplexPattern(R: getOperator()).getValueType();
2827 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2828 const ValueTypeByHwMode VVT = getValueTypeByHwMode(Rec: T, CGH);
2829 // TODO: AArch64 and AMDGPU use ComplexPattern<untyped, ...> and then
2830 // exclusively use those as non-leaf nodes with explicit type casts, so
2831 // for backwards compatibility we do no inference in that case. This is
2832 // not supported when the ComplexPattern is used as a leaf value,
2833 // however; this inconsistency should be resolved, either by adding this
2834 // case there or by altering the backends to not do this (e.g. using Any
2835 // instead may work).
2836 if (!VVT.isSimple() || VVT.getSimple() != MVT::Untyped)
2837 MadeChange |= UpdateNodeType(ResNo: 0, InTy: VVT, TP);
2838 }
2839
2840 for (TreePatternNode &Child : children())
2841 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2842
2843 return MadeChange;
2844 }
2845
2846 if (!getOperator()->isSubClassOf(Name: "SDNodeXForm")) {
2847 TP.error(Msg: "unknown node type '" + getOperator()->getName() +
2848 "' in input pattern");
2849 return false;
2850 }
2851
2852 // Node transforms always take one operand.
2853 if (getNumChildren() != 1) {
2854 TP.error(Msg: "Node transform '" + getOperator()->getName() +
2855 "' requires one operand!");
2856 return false;
2857 }
2858
2859 bool MadeChange = getChild(N: 0).ApplyTypeConstraints(TP, NotRegisters);
2860 return MadeChange;
2861}
2862
2863/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2864/// RHS of a commutative operation, not the on LHS.
2865static bool OnlyOnRHSOfCommutative(const TreePatternNode &N) {
2866 if (!N.isLeaf() && N.getOperator()->getName() == "imm")
2867 return true;
2868 if (N.isLeaf() && isa<IntInit>(Val: N.getLeafValue()))
2869 return true;
2870 if (isImmAllOnesAllZerosMatch(P: N))
2871 return true;
2872 return false;
2873}
2874
2875/// canPatternMatch - If it is impossible for this pattern to match on this
2876/// target, fill in Reason and return false. Otherwise, return true. This is
2877/// used as a sanity check for .td files (to prevent people from writing stuff
2878/// that can never possibly work), and to prevent the pattern permuter from
2879/// generating stuff that is useless.
2880bool TreePatternNode::canPatternMatch(std::string &Reason,
2881 const CodeGenDAGPatterns &CDP) const {
2882 if (isLeaf())
2883 return true;
2884
2885 for (const TreePatternNode &Child : children())
2886 if (!Child.canPatternMatch(Reason, CDP))
2887 return false;
2888
2889 // If this is an intrinsic, handle cases that would make it not match. For
2890 // example, if an operand is required to be an immediate.
2891 if (getOperator()->isSubClassOf(Name: "Intrinsic")) {
2892 // TODO:
2893 return true;
2894 }
2895
2896 if (getOperator()->isSubClassOf(Name: "ComplexPattern"))
2897 return true;
2898
2899 // If this node is a commutative operator, check that the LHS isn't an
2900 // immediate.
2901 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(R: getOperator());
2902 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2903 if (NodeInfo.hasProperty(Prop: SDNPCommutative) || isCommIntrinsic) {
2904 // Scan all of the operands of the node and make sure that only the last one
2905 // is a constant node, unless the RHS also is.
2906 if (!OnlyOnRHSOfCommutative(N: getChild(N: getNumChildren() - 1))) {
2907 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2908 for (unsigned i = Skip, e = getNumChildren() - 1; i != e; ++i)
2909 if (OnlyOnRHSOfCommutative(N: getChild(N: i))) {
2910 Reason =
2911 "Immediate value must be on the RHS of commutative operators!";
2912 return false;
2913 }
2914 }
2915 }
2916
2917 return true;
2918}
2919
2920//===----------------------------------------------------------------------===//
2921// TreePattern implementation
2922//
2923
2924TreePattern::TreePattern(const Record *TheRec, const ListInit *RawPat,
2925 bool isInput, CodeGenDAGPatterns &cdp)
2926 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2927 Infer(*this) {
2928 for (const Init *I : RawPat->getElements()) {
2929 TreePatternNodePtr Node = ParseTreePattern(DI: I, OpName: "");
2930 if (!Node)
2931 return;
2932 Trees.push_back(x: Node);
2933 }
2934}
2935
2936TreePattern::TreePattern(const Record *TheRec, const DagInit *Pat, bool isInput,
2937 CodeGenDAGPatterns &cdp)
2938 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2939 Infer(*this) {
2940 TreePatternNodePtr Node = ParseTreePattern(DI: Pat, OpName: "");
2941 if (!Node)
2942 return;
2943 Trees.push_back(x: Node);
2944}
2945
2946TreePattern::TreePattern(const Record *TheRec, ArrayRef<const Init *> Args,
2947 ArrayRef<const StringInit *> ArgNames, bool isInput,
2948 CodeGenDAGPatterns &cdp)
2949 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2950 Infer(*this) {
2951 Trees.push_back(x: ParseRootlessTreePattern(Args, ArgNames));
2952}
2953
2954TreePattern::TreePattern(const Record *TheRec, TreePatternNodePtr Pat,
2955 bool isInput, CodeGenDAGPatterns &cdp)
2956 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2957 Infer(*this) {
2958 Trees.push_back(x: Pat);
2959}
2960
2961void TreePattern::error(const Twine &Msg) {
2962 if (HasError)
2963 return;
2964 dump();
2965 PrintError(ErrorLoc: TheRecord->getLoc(), Msg: "In " + TheRecord->getName() + ": " + Msg);
2966 HasError = true;
2967}
2968
2969void TreePattern::ComputeNamedNodes() {
2970 for (TreePatternNodePtr &Tree : Trees)
2971 ComputeNamedNodes(N&: *Tree);
2972}
2973
2974void TreePattern::ComputeNamedNodes(TreePatternNode &N) {
2975 if (!N.getName().empty())
2976 NamedNodes[N.getName()].push_back(Elt: &N);
2977
2978 for (TreePatternNode &Child : N.children())
2979 ComputeNamedNodes(N&: Child);
2980}
2981
2982TreePatternNodePtr
2983TreePattern::ParseRootlessTreePattern(ArrayRef<const Init *> Args,
2984 ArrayRef<const StringInit *> ArgNames) {
2985 std::vector<TreePatternNodePtr> Children;
2986
2987 for (auto [Arg, ArgName] : llvm::zip_equal(t&: Args, u&: ArgNames)) {
2988 StringRef NameStr = ArgName ? ArgName->getValue() : "";
2989 Children.push_back(x: ParseTreePattern(DI: Arg, OpName: NameStr));
2990 }
2991
2992 return makeIntrusiveRefCnt<TreePatternNode>(A: nullptr, A: std::move(Children), A: 1);
2993}
2994
2995TreePatternNodePtr TreePattern::ParseTreePattern(const Init *TheInit,
2996 StringRef OpName) {
2997 RecordKeeper &RK = TheInit->getRecordKeeper();
2998 // Here, we are creating new records (BitsInit->InitInit), so const_cast
2999 // TheInit back to non-const pointer.
3000 if (const DefInit *DI = dyn_cast<DefInit>(Val: TheInit)) {
3001 const Record *R = DI->getDef();
3002
3003 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
3004 // TreePatternNode of its own. For example:
3005 /// (foo GPR, imm) -> (foo GPR, (imm))
3006 if (R->isSubClassOf(Name: "SDNode") || R->isSubClassOf(Name: "PatFrags"))
3007 return ParseTreePattern(TheInit: DagInit::get(V: DI, ArgAndNames: {}), OpName);
3008
3009 // Input argument?
3010 TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(A&: DI, A: 1);
3011 if (R->getName() == "node" && !OpName.empty()) {
3012 if (OpName.empty())
3013 error(Msg: "'node' argument requires a name to match with operand list");
3014 Args.push_back(x: OpName.str());
3015 }
3016
3017 Res->setName(OpName);
3018 return Res;
3019 }
3020
3021 // ?:$name or just $name.
3022 if (isa<UnsetInit>(Val: TheInit)) {
3023 if (OpName.empty())
3024 error(Msg: "'?' argument requires a name to match with operand list");
3025 TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(A&: TheInit, A: 1);
3026 Args.push_back(x: OpName.str());
3027 Res->setName(OpName);
3028 return Res;
3029 }
3030
3031 if (isa<IntInit>(Val: TheInit) || isa<BitInit>(Val: TheInit)) {
3032 if (!OpName.empty())
3033 error(Msg: "Constant int or bit argument should not have a name!");
3034 if (isa<BitInit>(Val: TheInit))
3035 TheInit = TheInit->convertInitializerTo(Ty: IntRecTy::get(RK));
3036 return makeIntrusiveRefCnt<TreePatternNode>(A&: TheInit, A: 1);
3037 }
3038
3039 if (const BitsInit *BI = dyn_cast<BitsInit>(Val: TheInit)) {
3040 // Turn this into an IntInit.
3041 const Init *II = BI->convertInitializerTo(Ty: IntRecTy::get(RK));
3042 if (!II || !isa<IntInit>(Val: II))
3043 error(Msg: "Bits value must be constants!");
3044 return II ? ParseTreePattern(TheInit: II, OpName) : nullptr;
3045 }
3046
3047 const DagInit *Dag = dyn_cast<DagInit>(Val: TheInit);
3048 if (!Dag) {
3049 TheInit->print(OS&: errs());
3050 error(Msg: "Pattern has unexpected init kind!");
3051 return nullptr;
3052 }
3053
3054 auto ParseCastOperand = [this](const DagInit *Dag,
3055 StringRef OpName) -> TreePatternNodePtr {
3056 if (Dag->getNumArgs() != 1) {
3057 error(Msg: "Type cast only takes one operand!");
3058 return nullptr;
3059 }
3060
3061 if (!OpName.empty()) {
3062 error(Msg: "Type cast should not have a name!");
3063 return nullptr;
3064 }
3065
3066 return ParseTreePattern(TheInit: Dag->getArg(Num: 0), OpName: Dag->getArgNameStr(Num: 0));
3067 };
3068
3069 if (const ListInit *LI = dyn_cast<ListInit>(Val: Dag->getOperator())) {
3070 // If the operator is a list (of value types), then this must be "type cast"
3071 // of a leaf node with multiple results.
3072 TreePatternNodePtr New = ParseCastOperand(Dag, OpName);
3073 if (!New)
3074 return nullptr;
3075
3076 size_t NumTypes = New->getNumTypes();
3077 if (LI->empty() || LI->size() != NumTypes)
3078 error(Msg: "Invalid number of type casts!");
3079
3080 // Apply the type casts.
3081 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
3082 for (unsigned i = 0; i < std::min(a: NumTypes, b: LI->size()); ++i)
3083 New->UpdateNodeType(
3084 ResNo: i, InTy: getValueTypeByHwMode(Rec: LI->getElementAsRecord(Idx: i), CGH), TP&: *this);
3085
3086 return New;
3087 }
3088
3089 const DefInit *OpDef = dyn_cast<DefInit>(Val: Dag->getOperator());
3090 if (!OpDef) {
3091 error(Msg: "Pattern has unexpected operator type!");
3092 return nullptr;
3093 }
3094 const Record *Operator = OpDef->getDef();
3095
3096 if (Operator->isSubClassOf(Name: "ValueType")) {
3097 // If the operator is a ValueType, then this must be "type cast" of a leaf
3098 // node.
3099 TreePatternNodePtr New = ParseCastOperand(Dag, OpName);
3100 if (!New)
3101 return nullptr;
3102
3103 if (New->getNumTypes() != 1)
3104 error(Msg: "ValueType cast can only have one type!");
3105
3106 // Apply the type cast.
3107 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
3108 New->UpdateNodeType(ResNo: 0, InTy: getValueTypeByHwMode(Rec: Operator, CGH), TP&: *this);
3109
3110 return New;
3111 }
3112
3113 // Verify that this is something that makes sense for an operator.
3114 if (!Operator->isSubClassOf(Name: "PatFrags") &&
3115 !Operator->isSubClassOf(Name: "SDNode") &&
3116 !Operator->isSubClassOf(Name: "Instruction") &&
3117 !Operator->isSubClassOf(Name: "SDNodeXForm") &&
3118 !Operator->isSubClassOf(Name: "Intrinsic") &&
3119 !Operator->isSubClassOf(Name: "ComplexPattern") && Operator->getName() != "set")
3120 error(Msg: "Unrecognized node '" + Operator->getName() + "'!");
3121
3122 // Check to see if this is something that is illegal in an input pattern.
3123 if (isInputPattern) {
3124 if (Operator->isSubClassOf(Name: "Instruction") ||
3125 Operator->isSubClassOf(Name: "SDNodeXForm"))
3126 error(Msg: "Cannot use '" + Operator->getName() + "' in an input pattern!");
3127 } else {
3128 if (Operator->isSubClassOf(Name: "Intrinsic"))
3129 error(Msg: "Cannot use '" + Operator->getName() + "' in an output pattern!");
3130
3131 if (Operator->isSubClassOf(Name: "SDNode") && Operator->getName() != "imm" &&
3132 Operator->getName() != "timm" && Operator->getName() != "fpimm" &&
3133 Operator->getName() != "tglobaltlsaddr" &&
3134 Operator->getName() != "tconstpool" &&
3135 Operator->getName() != "tjumptable" &&
3136 Operator->getName() != "tframeindex" &&
3137 Operator->getName() != "texternalsym" &&
3138 Operator->getName() != "tblockaddress" &&
3139 Operator->getName() != "tglobaladdr" && Operator->getName() != "bb" &&
3140 Operator->getName() != "vt" && Operator->getName() != "mcsym")
3141 error(Msg: "Cannot use '" + Operator->getName() + "' in an output pattern!");
3142 }
3143
3144 std::vector<TreePatternNodePtr> Children;
3145
3146 // Parse all the operands.
3147 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
3148 TreePatternNodePtr Child =
3149 ParseTreePattern(TheInit: Dag->getArg(Num: i), OpName: Dag->getArgNameStr(Num: i));
3150 if (!Child)
3151 return nullptr;
3152 Children.push_back(x: Child);
3153 }
3154
3155 // Get the actual number of results before Operator is converted to an
3156 // intrinsic node (which is hard-coded to have either zero or one result).
3157 unsigned NumResults = GetNumNodeResults(Operator, CDP);
3158
3159 // If the operator is an intrinsic, then this is just syntactic sugar for
3160 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
3161 // convert the intrinsic name to a number.
3162 if (Operator->isSubClassOf(Name: "Intrinsic")) {
3163 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(R: Operator);
3164 unsigned IID = getDAGPatterns().getIntrinsicID(R: Operator) + 1;
3165
3166 // If this intrinsic returns void, it must have side-effects and thus a
3167 // chain.
3168 if (Int.IS.RetTys.empty())
3169 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
3170 else if (!Int.ME.doesNotAccessMemory() || Int.hasSideEffects)
3171 // Has side-effects, requires chain.
3172 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
3173 else // Otherwise, no chain.
3174 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
3175
3176 Children.insert(position: Children.begin(), x: makeIntrusiveRefCnt<TreePatternNode>(
3177 A: IntInit::get(RK, V: IID), A: 1));
3178 }
3179
3180 if (Operator->isSubClassOf(Name: "ComplexPattern")) {
3181 for (unsigned i = 0; i < Children.size(); ++i) {
3182 TreePatternNodePtr Child = Children[i];
3183
3184 if (Child->getName().empty())
3185 error(Msg: "All arguments to a ComplexPattern must be named");
3186
3187 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
3188 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
3189 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
3190 auto OperandId = std::pair(Operator, i);
3191 auto [PrevOp, Inserted] =
3192 ComplexPatternOperands.try_emplace(Key: Child->getName(), Args&: OperandId);
3193 if (!Inserted && PrevOp->getValue() != OperandId) {
3194 error(Msg: "All ComplexPattern operands must appear consistently: "
3195 "in the same order in just one ComplexPattern instance.");
3196 }
3197 }
3198 }
3199
3200 TreePatternNodePtr Result = makeIntrusiveRefCnt<TreePatternNode>(
3201 A&: Operator, A: std::move(Children), A&: NumResults);
3202 Result->setName(OpName);
3203
3204 if (Dag->getName()) {
3205 assert(Result->getName().empty());
3206 Result->setName(Dag->getNameStr());
3207 }
3208 return Result;
3209}
3210
3211/// SimplifyTree - See if we can simplify this tree to eliminate something that
3212/// will never match in favor of something obvious that will. This is here
3213/// strictly as a convenience to target authors because it allows them to write
3214/// more type generic things and have useless type casts fold away.
3215///
3216/// This returns true if any change is made.
3217static bool SimplifyTree(TreePatternNodePtr &N) {
3218 if (N->isLeaf())
3219 return false;
3220
3221 // If we have a bitconvert with a resolved type and if the source and
3222 // destination types are the same, then the bitconvert is useless, remove it.
3223 //
3224 // We make an exception if the types are completely empty. This can come up
3225 // when the pattern being simplified is in the Fragments list of a PatFrags,
3226 // so that the operand is just an untyped "node". In that situation we leave
3227 // bitconverts unsimplified, and simplify them later once the fragment is
3228 // expanded into its true context.
3229 if (N->getOperator()->getName() == "bitconvert" &&
3230 N->getExtType(ResNo: 0).isValueTypeByHwMode(AllowEmpty: false) &&
3231 !N->getExtType(ResNo: 0).empty() &&
3232 N->getExtType(ResNo: 0) == N->getChild(N: 0).getExtType(ResNo: 0) &&
3233 N->getName().empty()) {
3234 if (!N->getPredicateCalls().empty()) {
3235 std::string Str;
3236 raw_string_ostream OS(Str);
3237 OS << *N
3238 << "\n trivial bitconvert node should not have predicate calls\n";
3239 PrintFatalError(Msg: Str);
3240 return false;
3241 }
3242 N = N->getChildShared(N: 0);
3243 SimplifyTree(N);
3244 return true;
3245 }
3246
3247 // Walk all children.
3248 bool MadeChange = false;
3249 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3250 MadeChange |= SimplifyTree(N&: N->getChildSharedPtr(N: i));
3251
3252 return MadeChange;
3253}
3254
3255/// InferAllTypes - Infer/propagate as many types throughout the expression
3256/// patterns as possible. Return true if all types are inferred, false
3257/// otherwise. Flags an error if a type contradiction is found.
3258bool TreePattern::InferAllTypes(
3259 const StringMap<SmallVector<TreePatternNode *, 1>> *InNamedTypes) {
3260 if (NamedNodes.empty())
3261 ComputeNamedNodes();
3262
3263 bool MadeChange = true;
3264 while (MadeChange) {
3265 MadeChange = false;
3266 for (TreePatternNodePtr &Tree : Trees) {
3267 MadeChange |= Tree->ApplyTypeConstraints(TP&: *this, NotRegisters: false);
3268 MadeChange |= SimplifyTree(N&: Tree);
3269 }
3270
3271 // If there are constraints on our named nodes, apply them.
3272 for (auto &Entry : NamedNodes) {
3273 SmallVectorImpl<TreePatternNode *> &Nodes = Entry.second;
3274
3275 // If we have input named node types, propagate their types to the named
3276 // values here.
3277 if (InNamedTypes) {
3278 auto InIter = InNamedTypes->find(Key: Entry.getKey());
3279 if (InIter == InNamedTypes->end()) {
3280 error(Msg: "Node '" + Entry.getKey().str() +
3281 "' in output pattern but not input pattern");
3282 return true;
3283 }
3284
3285 ArrayRef<TreePatternNode *> InNodes = InIter->second;
3286
3287 // The input types should be fully resolved by now.
3288 for (TreePatternNode *Node : Nodes) {
3289 // If this node is a register class, and it is the root of the pattern
3290 // then we're mapping something onto an input register. We allow
3291 // changing the type of the input register in this case. This allows
3292 // us to match things like:
3293 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
3294 if (Node == Trees[0].get() && Node->isLeaf()) {
3295 const DefInit *DI = dyn_cast<DefInit>(Val: Node->getLeafValue());
3296 if (DI && (DI->getDef()->isSubClassOf(Name: "RegisterClass") ||
3297 DI->getDef()->isSubClassOf(Name: "RegisterOperand")))
3298 continue;
3299 }
3300
3301 assert(Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 &&
3302 "FIXME: cannot name multiple result nodes yet");
3303 MadeChange |=
3304 Node->UpdateNodeType(ResNo: 0, InTy: InNodes[0]->getExtType(ResNo: 0), TP&: *this);
3305 }
3306 }
3307
3308 // If there are multiple nodes with the same name, they must all have the
3309 // same type.
3310 if (Entry.second.size() > 1) {
3311 for (unsigned i = 0, e = Nodes.size() - 1; i != e; ++i) {
3312 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i + 1];
3313 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
3314 "FIXME: cannot name multiple result nodes yet");
3315
3316 MadeChange |= N1->UpdateNodeType(ResNo: 0, InTy: N2->getExtType(ResNo: 0), TP&: *this);
3317 MadeChange |= N2->UpdateNodeType(ResNo: 0, InTy: N1->getExtType(ResNo: 0), TP&: *this);
3318 }
3319 }
3320 }
3321 }
3322
3323 bool HasUnresolvedTypes = false;
3324 for (const TreePatternNodePtr &Tree : Trees)
3325 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(TP&: *this);
3326 return !HasUnresolvedTypes;
3327}
3328
3329void TreePattern::print(raw_ostream &OS) const {
3330 OS << getRecord()->getName();
3331 if (!Args.empty())
3332 OS << '(' << llvm::interleaved(R: Args) << ')';
3333 OS << ": ";
3334
3335 if (Trees.size() > 1)
3336 OS << "[\n";
3337 for (const TreePatternNodePtr &Tree : Trees) {
3338 OS << "\t";
3339 Tree->print(OS);
3340 OS << "\n";
3341 }
3342
3343 if (Trees.size() > 1)
3344 OS << "]\n";
3345}
3346
3347void TreePattern::dump() const { print(OS&: dbgs()); }
3348
3349//===----------------------------------------------------------------------===//
3350// CodeGenDAGPatterns implementation
3351//
3352
3353CodeGenDAGPatterns::CodeGenDAGPatterns(const RecordKeeper &R, bool ExpandHwMode)
3354 : Records(R), Target(R), Intrinsics(R),
3355 LegalVTS(Target.getLegalValueTypes()),
3356 LegalPtrVTS(ComputeLegalPtrTypes()) {
3357 ParseNodeInfo();
3358 ParseNodeTransforms();
3359 ParseComplexPatterns();
3360 ParsePatternFragments();
3361 ParseDefaultOperands();
3362 ParseInstructions();
3363 ParsePatternFragments(/*OutFrags*/ true);
3364 ParsePatterns();
3365
3366 // Generate variants. For example, commutative patterns can match
3367 // multiple ways. Add them to PatternsToMatch as well.
3368 GenerateVariants();
3369
3370 // Break patterns with parameterized types into a series of patterns,
3371 // where each one has a fixed type and is predicated on the conditions
3372 // of the associated HW mode.
3373 if (ExpandHwMode)
3374 ExpandHwModeBasedTypes();
3375
3376 // Infer instruction flags. For example, we can detect loads,
3377 // stores, and side effects in many cases by examining an
3378 // instruction's pattern.
3379 InferInstructionFlags();
3380
3381 // Verify that instruction flags match the patterns.
3382 VerifyInstructionFlags();
3383}
3384
3385const Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {
3386 const Record *N = Records.getDef(Name);
3387 if (!N || !N->isSubClassOf(Name: "SDNode"))
3388 PrintFatalError(Msg: "Error getting SDNode '" + Name + "'!");
3389 return N;
3390}
3391
3392// Compute the subset of iPTR and cPTR legal for each mode, coalescing into the
3393// default mode where possible to avoid predicate explosion.
3394TypeSetByHwMode CodeGenDAGPatterns::ComputeLegalPtrTypes() const {
3395 auto LegalPtrsForSet = [](const MachineValueTypeSet &In) {
3396 MachineValueTypeSet Out;
3397 Out.insert(T: MVT::iPTR);
3398 for (MVT T : MVT::cheri_capability_valuetypes()) {
3399 if (In.count(T)) {
3400 Out.insert(T: MVT::cPTR);
3401 break;
3402 }
3403 }
3404 return Out;
3405 };
3406
3407 const TypeSetByHwMode &LegalTypes = getLegalTypes();
3408 MachineValueTypeSet LegalPtrsDefault =
3409 LegalPtrsForSet(LegalTypes.get(Mode: DefaultMode));
3410
3411 TypeSetByHwMode LegalPtrTypes;
3412 for (const auto &I : LegalTypes) {
3413 MachineValueTypeSet S = LegalPtrsForSet(I.second);
3414 if (I.first != DefaultMode && S == LegalPtrsDefault)
3415 continue;
3416 LegalPtrTypes.getOrCreate(Mode: I.first).insert(S);
3417 }
3418
3419 return LegalPtrTypes;
3420}
3421
3422// Parse all of the SDNode definitions for the target, populating SDNodes.
3423void CodeGenDAGPatterns::ParseNodeInfo() {
3424 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3425
3426 for (const Record *R : reverse(C: Records.getAllDerivedDefinitions(ClassName: "SDNode")))
3427 SDNodes.try_emplace(k: R, args: SDNodeInfo(R, CGH));
3428
3429 // Get the builtin intrinsic nodes.
3430 intrinsic_void_sdnode = getSDNodeNamed(Name: "intrinsic_void");
3431 intrinsic_w_chain_sdnode = getSDNodeNamed(Name: "intrinsic_w_chain");
3432 intrinsic_wo_chain_sdnode = getSDNodeNamed(Name: "intrinsic_wo_chain");
3433}
3434
3435/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3436/// map, and emit them to the file as functions.
3437void CodeGenDAGPatterns::ParseNodeTransforms() {
3438 for (const Record *XFormNode :
3439 reverse(C: Records.getAllDerivedDefinitions(ClassName: "SDNodeXForm"))) {
3440 const Record *SDNode = XFormNode->getValueAsDef(FieldName: "Opcode");
3441 StringRef Code = XFormNode->getValueAsString(FieldName: "XFormFunction");
3442 SDNodeXForms.try_emplace(k: XFormNode, args: NodeXForm(SDNode, Code.str()));
3443 }
3444}
3445
3446void CodeGenDAGPatterns::ParseComplexPatterns() {
3447 for (const Record *R :
3448 reverse(C: Records.getAllDerivedDefinitions(ClassName: "ComplexPattern")))
3449 ComplexPatterns.try_emplace(k: R, args&: R);
3450}
3451
3452/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3453/// file, building up the PatternFragments map. After we've collected them all,
3454/// inline fragments together as necessary, so that there are no references left
3455/// inside a pattern fragment to a pattern fragment.
3456///
3457void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
3458 // First step, parse all of the fragments.
3459 ArrayRef<const Record *> Fragments =
3460 Records.getAllDerivedDefinitions(ClassName: "PatFrags");
3461 for (const Record *Frag : Fragments) {
3462 if (OutFrags != Frag->isSubClassOf(Name: "OutPatFrag"))
3463 continue;
3464
3465 const ListInit *LI = Frag->getValueAsListInit(FieldName: "Fragments");
3466 TreePattern *P = (PatternFragments[Frag] = std::make_unique<TreePattern>(
3467 args&: Frag, args&: LI, args: !Frag->isSubClassOf(Name: "OutPatFrag"), args&: *this))
3468 .get();
3469
3470 // Validate the argument list, converting it to set, to discard duplicates.
3471 std::vector<std::string> &Args = P->getArgList();
3472 // Copy the args so we can take StringRefs to them.
3473 auto ArgsCopy = Args;
3474 SmallDenseSet<StringRef, 4> OperandsSet(llvm::from_range, ArgsCopy);
3475
3476 if (OperandsSet.contains(V: ""))
3477 P->error(Msg: "Cannot have unnamed 'node' values in pattern fragment!");
3478
3479 // Parse the operands list.
3480 const DagInit *OpsList = Frag->getValueAsDag(FieldName: "Operands");
3481 const DefInit *OpsOp = dyn_cast<DefInit>(Val: OpsList->getOperator());
3482 // Special cases: ops == outs == ins. Different names are used to
3483 // improve readability.
3484 if (!OpsOp || (OpsOp->getDef()->getName() != "ops" &&
3485 OpsOp->getDef()->getName() != "outs" &&
3486 OpsOp->getDef()->getName() != "ins"))
3487 P->error(Msg: "Operands list should start with '(ops ... '!");
3488
3489 // Copy over the arguments.
3490 Args.clear();
3491 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
3492 if (!isa<DefInit>(Val: OpsList->getArg(Num: j)) ||
3493 cast<DefInit>(Val: OpsList->getArg(Num: j))->getDef()->getName() != "node")
3494 P->error(Msg: "Operands list should all be 'node' values.");
3495 if (!OpsList->getArgName(Num: j))
3496 P->error(Msg: "Operands list should have names for each operand!");
3497 StringRef ArgNameStr = OpsList->getArgNameStr(Num: j);
3498 if (!OperandsSet.erase(V: ArgNameStr))
3499 P->error(Msg: "'" + ArgNameStr +
3500 "' does not occur in pattern or was multiply specified!");
3501 Args.push_back(x: ArgNameStr.str());
3502 }
3503
3504 if (!OperandsSet.empty())
3505 P->error(Msg: "Operands list does not contain an entry for operand '" +
3506 *OperandsSet.begin() + "'!");
3507
3508 // If there is a node transformation corresponding to this, keep track of
3509 // it.
3510 const Record *Transform = Frag->getValueAsDef(FieldName: "OperandTransform");
3511 if (!getSDNodeTransform(R: Transform).second.empty()) // not noop xform?
3512 for (const auto &T : P->getTrees())
3513 T->setTransformFn(Transform);
3514 }
3515
3516 // Now that we've parsed all of the tree fragments, do a closure on them so
3517 // that there are not references to PatFrags left inside of them.
3518 for (const Record *Frag : Fragments) {
3519 if (OutFrags != Frag->isSubClassOf(Name: "OutPatFrag"))
3520 continue;
3521
3522 TreePattern &ThePat = *PatternFragments[Frag];
3523 ThePat.InlinePatternFragments();
3524
3525 // Infer as many types as possible. Don't worry about it if we don't infer
3526 // all of them, some may depend on the inputs of the pattern. Also, don't
3527 // validate type sets; validation may cause spurious failures e.g. if a
3528 // fragment needs floating-point types but the current target does not have
3529 // any (this is only an error if that fragment is ever used!).
3530 {
3531 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3532 ThePat.InferAllTypes();
3533 ThePat.resetError();
3534 }
3535
3536 // If debugging, print out the pattern fragment result.
3537 LLVM_DEBUG(ThePat.dump());
3538 }
3539}
3540
3541void CodeGenDAGPatterns::ParseDefaultOperands() {
3542 ArrayRef<const Record *> DefaultOps =
3543 Records.getAllDerivedDefinitions(ClassName: "OperandWithDefaultOps");
3544
3545 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3546 const DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag(FieldName: "DefaultOps");
3547
3548 // Create a TreePattern to parse this.
3549 TreePattern P(DefaultOps[i], DefaultInfo->getArgs(),
3550 DefaultInfo->getArgNames(), false, *this);
3551 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3552
3553 // Copy the operands over into a DAGDefaultOperand.
3554 DAGDefaultOperand DefaultOpInfo;
3555
3556 const TreePatternNodePtr &T = P.getTree(i: 0);
3557 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3558 TreePatternNodePtr TPN = T->getChildShared(N: op);
3559 while (TPN->ApplyTypeConstraints(TP&: P, NotRegisters: false))
3560 /* Resolve all types */;
3561
3562 if (TPN->ContainsUnresolvedType(TP&: P)) {
3563 PrintFatalError(Msg: "Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3564 DefaultOps[i]->getName() +
3565 "' doesn't have a concrete type!");
3566 }
3567 DefaultOpInfo.DefaultOps.push_back(x: std::move(TPN));
3568 }
3569
3570 // Insert it into the DefaultOperands map so we can find it later.
3571 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3572 }
3573}
3574
3575/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3576/// instruction input. Return true if this is a real use.
3577static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3578 std::map<StringRef, TreePatternNodePtr> &InstInputs) {
3579 // No name -> not interesting.
3580 if (Pat->getName().empty()) {
3581 if (Pat->isLeaf()) {
3582 const DefInit *DI = dyn_cast<DefInit>(Val: Pat->getLeafValue());
3583 if (DI && (DI->getDef()->isSubClassOf(Name: "RegisterClass") ||
3584 DI->getDef()->isSubClassOf(Name: "RegisterOperand")))
3585 I.error(Msg: "Input " + DI->getDef()->getName() + " must be named!");
3586 }
3587 return false;
3588 }
3589
3590 const Record *Rec;
3591 if (Pat->isLeaf()) {
3592 const DefInit *DI = dyn_cast<DefInit>(Val: Pat->getLeafValue());
3593 if (!DI) {
3594 I.error(Msg: "Input $" + Pat->getName() + " must be an identifier!");
3595 return false;
3596 }
3597 Rec = DI->getDef();
3598 } else {
3599 Rec = Pat->getOperator();
3600 }
3601
3602 // SRCVALUE nodes are ignored.
3603 if (Rec->getName() == "srcvalue")
3604 return false;
3605
3606 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3607 if (!Slot) {
3608 Slot = Pat;
3609 return true;
3610 }
3611 const Record *SlotRec;
3612 if (Slot->isLeaf()) {
3613 SlotRec = cast<DefInit>(Val: Slot->getLeafValue())->getDef();
3614 } else {
3615 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3616 SlotRec = Slot->getOperator();
3617 }
3618
3619 // Ensure that the inputs agree if we've already seen this input.
3620 if (Rec != SlotRec)
3621 I.error(Msg: "All $" + Pat->getName() + " inputs must agree with each other");
3622 // Ensure that the types can agree as well.
3623 Slot->UpdateNodeType(ResNo: 0, InTy: Pat->getExtType(ResNo: 0), TP&: I);
3624 Pat->UpdateNodeType(ResNo: 0, InTy: Slot->getExtType(ResNo: 0), TP&: I);
3625 if (Slot->getExtTypes() != Pat->getExtTypes())
3626 I.error(Msg: "All $" + Pat->getName() + " inputs must agree with each other");
3627 return true;
3628}
3629
3630/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3631/// part of "I", the instruction), computing the set of inputs and outputs of
3632/// the pattern. Report errors if we see anything naughty.
3633void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3634 TreePattern &I, TreePatternNodePtr Pat, InstInputsTy &InstInputs,
3635 InstResultsTy &InstResults, std::vector<const Record *> &InstImpResults) {
3636 // The instruction pattern still has unresolved fragments. For *named*
3637 // nodes we must resolve those here. This may not result in multiple
3638 // alternatives.
3639 if (!Pat->getName().empty()) {
3640 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3641 SrcPattern.InlinePatternFragments();
3642 SrcPattern.InferAllTypes();
3643 Pat = SrcPattern.getOnlyTree();
3644 }
3645
3646 if (Pat->isLeaf()) {
3647 bool isUse = HandleUse(I, Pat, InstInputs);
3648 if (!isUse && Pat->getTransformFn())
3649 I.error(Msg: "Cannot specify a transform function for a non-input value!");
3650 return;
3651 }
3652
3653 if (Pat->getOperator()->getName() != "set") {
3654 // If this is not a set, verify that the children nodes are not void typed,
3655 // and recurse.
3656 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3657 if (Pat->getChild(N: i).getNumTypes() == 0)
3658 I.error(Msg: "Cannot have void nodes inside of patterns!");
3659 FindPatternInputsAndOutputs(I, Pat: Pat->getChildShared(N: i), InstInputs,
3660 InstResults, InstImpResults);
3661 }
3662
3663 // If this is a non-leaf node with no children, treat it basically as if
3664 // it were a leaf. This handles nodes like (imm).
3665 bool isUse = HandleUse(I, Pat, InstInputs);
3666
3667 if (!isUse && Pat->getTransformFn())
3668 I.error(Msg: "Cannot specify a transform function for a non-input value!");
3669 return;
3670 }
3671
3672 // Otherwise, this is a set, validate and collect instruction results.
3673 if (Pat->getNumChildren() == 0)
3674 I.error(Msg: "set requires operands!");
3675
3676 if (Pat->getTransformFn())
3677 I.error(Msg: "Cannot specify a transform function on a set node!");
3678
3679 // Check the set destinations.
3680 unsigned NumDests = Pat->getNumChildren() - 1;
3681 for (unsigned i = 0; i != NumDests; ++i) {
3682 TreePatternNodePtr Dest = Pat->getChildShared(N: i);
3683 // For set destinations we also must resolve fragments here.
3684 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3685 DestPattern.InlinePatternFragments();
3686 DestPattern.InferAllTypes();
3687 Dest = DestPattern.getOnlyTree();
3688
3689 if (!Dest->isLeaf())
3690 I.error(Msg: "set destination should be a register!");
3691
3692 const DefInit *Val = dyn_cast<DefInit>(Val: Dest->getLeafValue());
3693 if (!Val) {
3694 I.error(Msg: "set destination should be a register!");
3695 continue;
3696 }
3697
3698 if (Val->getDef()->isSubClassOf(Name: "RegisterClassLike") ||
3699 Val->getDef()->isSubClassOf(Name: "ValueType") ||
3700 Val->getDef()->isSubClassOf(Name: "RegisterOperand")) {
3701 if (Dest->getName().empty())
3702 I.error(Msg: "set destination must have a name!");
3703 if (!InstResults.insert_or_assign(Key: Dest->getName(), Val&: Dest).second)
3704 I.error(Msg: "cannot set '" + Dest->getName() + "' multiple times");
3705 } else if (Val->getDef()->isSubClassOf(Name: "Register")) {
3706 InstImpResults.push_back(x: Val->getDef());
3707 } else {
3708 I.error(Msg: "set destination should be a register!");
3709 }
3710 }
3711
3712 // Verify and collect info from the computation.
3713 FindPatternInputsAndOutputs(I, Pat: Pat->getChildShared(N: NumDests), InstInputs,
3714 InstResults, InstImpResults);
3715}
3716
3717//===----------------------------------------------------------------------===//
3718// Instruction Analysis
3719//===----------------------------------------------------------------------===//
3720
3721class InstAnalyzer {
3722 const CodeGenDAGPatterns &CDP;
3723
3724public:
3725 bool hasSideEffects = false;
3726 bool mayStore = false;
3727 bool mayLoad = false;
3728 bool isBitcast = false;
3729 bool isVariadic = false;
3730 bool hasChain = false;
3731
3732 InstAnalyzer(const CodeGenDAGPatterns &cdp) : CDP(cdp) {}
3733
3734 void Analyze(const PatternToMatch &Pat) {
3735 const TreePatternNode &N = Pat.getSrcPattern();
3736 AnalyzeNode(N);
3737 // These properties are detected only on the root node.
3738 isBitcast = IsNodeBitcast(N);
3739 }
3740
3741private:
3742 bool IsNodeBitcast(const TreePatternNode &N) const {
3743 if (hasSideEffects || mayLoad || mayStore || isVariadic)
3744 return false;
3745
3746 if (N.isLeaf())
3747 return false;
3748 if (N.getNumChildren() != 1 || !N.getChild(N: 0).isLeaf())
3749 return false;
3750
3751 if (N.getOperator()->isSubClassOf(Name: "ComplexPattern"))
3752 return false;
3753
3754 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(R: N.getOperator());
3755 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3756 return false;
3757 return OpInfo.getEnumName() == "ISD::BITCAST";
3758 }
3759
3760public:
3761 void AnalyzeNode(const TreePatternNode &N) {
3762 if (N.isLeaf()) {
3763 if (const DefInit *DI = dyn_cast<DefInit>(Val: N.getLeafValue())) {
3764 const Record *LeafRec = DI->getDef();
3765 // Handle ComplexPattern leaves.
3766 if (LeafRec->isSubClassOf(Name: "ComplexPattern")) {
3767 const ComplexPattern &CP = CDP.getComplexPattern(R: LeafRec);
3768 if (CP.hasProperty(Prop: SDNPMayStore))
3769 mayStore = true;
3770 if (CP.hasProperty(Prop: SDNPMayLoad))
3771 mayLoad = true;
3772 if (CP.hasProperty(Prop: SDNPSideEffect))
3773 hasSideEffects = true;
3774 }
3775 }
3776 return;
3777 }
3778
3779 // Analyze children.
3780 for (const TreePatternNode &Child : N.children())
3781 AnalyzeNode(N: Child);
3782
3783 // Notice properties of the node.
3784 if (N.NodeHasProperty(Property: SDNPMayStore, CGP: CDP))
3785 mayStore = true;
3786 if (N.NodeHasProperty(Property: SDNPMayLoad, CGP: CDP))
3787 mayLoad = true;
3788 if (N.NodeHasProperty(Property: SDNPSideEffect, CGP: CDP))
3789 hasSideEffects = true;
3790 if (N.NodeHasProperty(Property: SDNPVariadic, CGP: CDP))
3791 isVariadic = true;
3792 if (N.NodeHasProperty(Property: SDNPHasChain, CGP: CDP))
3793 hasChain = true;
3794
3795 if (const CodeGenIntrinsic *IntInfo = N.getIntrinsicInfo(CDP)) {
3796 ModRefInfo MR = IntInfo->ME.getModRef();
3797 // If this is an intrinsic, analyze it.
3798 if (isRefSet(MRI: MR))
3799 mayLoad = true; // These may load memory.
3800
3801 if (isModSet(MRI: MR))
3802 mayStore = true; // Intrinsics that can write to memory are 'mayStore'.
3803
3804 // Consider intrinsics that don't specify any restrictions on memory
3805 // effects as having a side-effect.
3806 if (IntInfo->ME == MemoryEffects::unknown() || IntInfo->hasSideEffects)
3807 hasSideEffects = true;
3808 }
3809 }
3810};
3811
3812static bool InferFromPattern(CodeGenInstruction &InstInfo,
3813 const InstAnalyzer &PatInfo,
3814 const Record *PatDef) {
3815 bool Error = false;
3816
3817 // Remember where InstInfo got its flags.
3818 if (InstInfo.hasUndefFlags())
3819 InstInfo.InferredFrom = PatDef;
3820
3821 // Check explicitly set flags for consistency.
3822 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3823 !InstInfo.hasSideEffects_Unset) {
3824 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3825 // the pattern has no side effects. That could be useful for div/rem
3826 // instructions that may trap.
3827 if (!InstInfo.hasSideEffects) {
3828 Error = true;
3829 PrintError(ErrorLoc: PatDef->getLoc(), Msg: "Pattern doesn't match hasSideEffects = " +
3830 Twine(InstInfo.hasSideEffects));
3831 }
3832 }
3833
3834 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3835 Error = true;
3836 PrintError(ErrorLoc: PatDef->getLoc(),
3837 Msg: "Pattern doesn't match mayStore = " + Twine(InstInfo.mayStore));
3838 }
3839
3840 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3841 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3842 // Some targets translate immediates to loads.
3843 if (!InstInfo.mayLoad) {
3844 Error = true;
3845 PrintError(ErrorLoc: PatDef->getLoc(),
3846 Msg: "Pattern doesn't match mayLoad = " + Twine(InstInfo.mayLoad));
3847 }
3848 }
3849
3850 // Transfer inferred flags.
3851 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3852 InstInfo.mayStore |= PatInfo.mayStore;
3853 InstInfo.mayLoad |= PatInfo.mayLoad;
3854
3855 // These flags are silently added without any verification.
3856 // FIXME: To match historical behavior of TableGen, for now add those flags
3857 // only when we're inferring from the primary instruction pattern.
3858 if (PatDef->isSubClassOf(Name: "Instruction")) {
3859 InstInfo.isBitcast |= PatInfo.isBitcast;
3860 InstInfo.hasChain |= PatInfo.hasChain;
3861 InstInfo.hasChain_Inferred = true;
3862 }
3863
3864 // Don't infer isVariadic. This flag means something different on SDNodes and
3865 // instructions. For example, a CALL SDNode is variadic because it has the
3866 // call arguments as operands, but a CALL instruction is not variadic - it
3867 // has argument registers as implicit, not explicit uses.
3868
3869 return Error;
3870}
3871
3872/// hasNullFragReference - Return true if the DAG has any reference to the
3873/// null_frag operator.
3874static bool hasNullFragReference(const DagInit *DI) {
3875 const DefInit *OpDef = dyn_cast<DefInit>(Val: DI->getOperator());
3876 if (!OpDef)
3877 return false;
3878 const Record *Operator = OpDef->getDef();
3879
3880 // If this is the null fragment, return true.
3881 if (Operator->getName() == "null_frag")
3882 return true;
3883 // If any of the arguments reference the null fragment, return true.
3884 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3885 if (auto Arg = dyn_cast<DefInit>(Val: DI->getArg(Num: i)))
3886 if (Arg->getDef()->getName() == "null_frag")
3887 return true;
3888 const DagInit *Arg = dyn_cast<DagInit>(Val: DI->getArg(Num: i));
3889 if (Arg && hasNullFragReference(DI: Arg))
3890 return true;
3891 }
3892
3893 return false;
3894}
3895
3896/// hasNullFragReference - Return true if any DAG in the list references
3897/// the null_frag operator.
3898static bool hasNullFragReference(const ListInit *LI) {
3899 for (const Init *I : LI->getElements()) {
3900 const DagInit *DI = dyn_cast<DagInit>(Val: I);
3901 assert(DI && "non-dag in an instruction Pattern list?!");
3902 if (hasNullFragReference(DI))
3903 return true;
3904 }
3905 return false;
3906}
3907
3908/// Get all the instructions in a tree.
3909static void getInstructionsInTree(TreePatternNode &Tree,
3910 SmallVectorImpl<const Record *> &Instrs) {
3911 if (Tree.isLeaf())
3912 return;
3913 if (Tree.getOperator()->isSubClassOf(Name: "Instruction"))
3914 Instrs.push_back(Elt: Tree.getOperator());
3915 for (TreePatternNode &Child : Tree.children())
3916 getInstructionsInTree(Tree&: Child, Instrs);
3917}
3918
3919/// Check the class of a pattern leaf node against the instruction operand it
3920/// represents.
3921static bool checkOperandClass(const CGIOperandList::OperandInfo &OI,
3922 const Record *Leaf) {
3923 if (OI.Rec == Leaf)
3924 return true;
3925
3926 // Allow direct value types to be used in instruction set patterns.
3927 // The type will be checked later.
3928 if (Leaf->isSubClassOf(Name: "ValueType"))
3929 return true;
3930
3931 // Patterns can also be ComplexPattern instances.
3932 if (Leaf->isSubClassOf(Name: "ComplexPattern"))
3933 return true;
3934
3935 return false;
3936}
3937
3938void CodeGenDAGPatterns::parseInstructionPattern(const CodeGenInstruction &CGI,
3939 const ListInit *Pat,
3940 DAGInstMap &DAGInsts) {
3941
3942 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3943
3944 // Parse the instruction.
3945 TreePattern I(CGI.TheDef, Pat, true, *this);
3946
3947 // InstInputs - Keep track of all of the inputs of the instruction, along
3948 // with the record they are declared as.
3949 std::map<StringRef, TreePatternNodePtr> InstInputs;
3950
3951 // InstResults - Keep track of all the virtual registers that are 'set'
3952 // in the instruction, including what reg class they are.
3953 MapVector<StringRef, TreePatternNodePtr, std::map<StringRef, unsigned>>
3954 InstResults;
3955
3956 std::vector<const Record *> InstImpResults;
3957
3958 // Verify that the top-level forms in the instruction are of void type, and
3959 // fill in the InstResults map.
3960 SmallString<32> TypesString;
3961 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3962 TypesString.clear();
3963 TreePatternNodePtr Pat = I.getTree(i: j);
3964 if (Pat->getNumTypes() != 0) {
3965 raw_svector_ostream OS(TypesString);
3966 ListSeparator LS;
3967 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3968 OS << LS;
3969 Pat->getExtType(ResNo: k).writeToStream(OS);
3970 }
3971 I.error(Msg: "Top-level forms in instruction pattern should have"
3972 " void types, has types " +
3973 OS.str());
3974 }
3975
3976 // Find inputs and outputs, and verify the structure of the uses/defs.
3977 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3978 InstImpResults);
3979 }
3980
3981 // Now that we have inputs and outputs of the pattern, inspect the operands
3982 // list for the instruction. This determines the order that operands are
3983 // added to the machine instruction the node corresponds to.
3984 unsigned NumResults = InstResults.size();
3985
3986 // Parse the operands list from the (ops) list, validating it.
3987 assert(I.getArgList().empty() && "Args list should still be empty here!");
3988
3989 // Check that all of the results occur first in the list.
3990 std::vector<const Record *> Results;
3991 std::vector<unsigned> ResultIndices;
3992 SmallVector<TreePatternNodePtr, 2> ResNodes;
3993 for (unsigned i = 0; i != NumResults; ++i) {
3994 if (i == CGI.Operands.size()) {
3995 StringRef OpName =
3996 llvm::find_if(Range&: InstResults,
3997 P: [](const std::pair<StringRef, TreePatternNodePtr> &P) {
3998 return P.second;
3999 })
4000 ->first;
4001
4002 I.error(Msg: "'" + OpName + "' set but does not appear in operand list!");
4003 }
4004
4005 StringRef OpName = CGI.Operands[i].Name;
4006
4007 // Check that it exists in InstResults.
4008 auto InstResultIter = InstResults.find(Key: OpName);
4009 if (InstResultIter == InstResults.end() || !InstResultIter->second)
4010 I.error(Msg: "Operand $" + OpName + " does not exist in operand list!");
4011
4012 TreePatternNodePtr RNode = InstResultIter->second;
4013 const Record *R = cast<DefInit>(Val: RNode->getLeafValue())->getDef();
4014 ResNodes.push_back(Elt: std::move(RNode));
4015 if (!R)
4016 I.error(Msg: "Operand $" + OpName +
4017 " should be a set destination: all "
4018 "outputs must occur before inputs in operand list!");
4019
4020 if (!checkOperandClass(OI: CGI.Operands[i], Leaf: R))
4021 I.error(Msg: "Operand $" + OpName + " class mismatch!");
4022
4023 // Remember the return type.
4024 Results.push_back(x: CGI.Operands[i].Rec);
4025
4026 // Remember the result index.
4027 ResultIndices.push_back(x: std::distance(first: InstResults.begin(), last: InstResultIter));
4028
4029 // Okay, this one checks out.
4030 InstResultIter->second = nullptr;
4031 }
4032
4033 // Loop over the inputs next.
4034 std::vector<TreePatternNodePtr> ResultNodeOperands;
4035 std::vector<const Record *> Operands;
4036 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
4037 const CGIOperandList::OperandInfo &Op = CGI.Operands[i];
4038 StringRef OpName = Op.Name;
4039 if (OpName.empty()) {
4040 I.error(Msg: "Operand #" + Twine(i) + " in operands list has no name!");
4041 continue;
4042 }
4043
4044 auto InIter = InstInputs.find(x: OpName);
4045 if (InIter == InstInputs.end()) {
4046 // If this is an operand with a DefaultOps set filled in, we can ignore
4047 // this. When we codegen it, we will do so as always executed.
4048 if (Op.Rec->isSubClassOf(Name: "OperandWithDefaultOps")) {
4049 // Does it have a non-empty DefaultOps field? If so, ignore this
4050 // operand.
4051 if (!getDefaultOperand(R: Op.Rec).DefaultOps.empty())
4052 continue;
4053 }
4054 I.error(Msg: "Operand $" + OpName +
4055 " does not appear in the instruction pattern");
4056 continue;
4057 }
4058 TreePatternNodePtr InVal = InIter->second;
4059 InstInputs.erase(position: InIter); // It occurred, remove from map.
4060
4061 if (InVal->isLeaf() && isa<DefInit>(Val: InVal->getLeafValue())) {
4062 const Record *InRec = cast<DefInit>(Val: InVal->getLeafValue())->getDef();
4063 if (!checkOperandClass(OI: Op, Leaf: InRec)) {
4064 I.error(Msg: "Operand $" + OpName +
4065 "'s register class disagrees"
4066 " between the operand and pattern");
4067 continue;
4068 }
4069 }
4070 Operands.push_back(x: Op.Rec);
4071
4072 // Construct the result for the dest-pattern operand list.
4073 TreePatternNodePtr OpNode = InVal->clone();
4074
4075 // No predicate is useful on the result.
4076 OpNode->clearPredicateCalls();
4077
4078 // Promote the xform function to be an explicit node if set.
4079 if (const Record *Xform = OpNode->getTransformFn()) {
4080 OpNode->setTransformFn(nullptr);
4081 std::vector<TreePatternNodePtr> Children;
4082 Children.push_back(x: OpNode);
4083 OpNode = makeIntrusiveRefCnt<TreePatternNode>(A&: Xform, A: std::move(Children),
4084 A: OpNode->getNumTypes());
4085 }
4086
4087 ResultNodeOperands.push_back(x: std::move(OpNode));
4088 }
4089
4090 if (!InstInputs.empty())
4091 I.error(Msg: "Input operand $" + InstInputs.begin()->first +
4092 " occurs in pattern but not in operands list!");
4093
4094 TreePatternNodePtr ResultPattern = makeIntrusiveRefCnt<TreePatternNode>(
4095 A: I.getRecord(), A: std::move(ResultNodeOperands),
4096 A: GetNumNodeResults(Operator: I.getRecord(), CDP&: *this));
4097 // Copy fully inferred output node types to instruction result pattern.
4098 for (unsigned i = 0; i != NumResults; ++i) {
4099 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
4100 ResultPattern->setType(ResNo: i, T: ResNodes[i]->getExtType(ResNo: 0));
4101 ResultPattern->setResultIndex(ResNo: i, RI: ResultIndices[i]);
4102 }
4103
4104 // FIXME: Assume only the first tree is the pattern. The others are clobber
4105 // nodes.
4106 TreePatternNodePtr Pattern = I.getTree(i: 0);
4107 TreePatternNodePtr SrcPattern;
4108 if (Pattern->getOperator()->getName() == "set") {
4109 SrcPattern = Pattern->getChild(N: Pattern->getNumChildren() - 1).clone();
4110 } else {
4111 // Not a set (store or something?)
4112 SrcPattern = Pattern;
4113 }
4114
4115 // Create and insert the instruction.
4116 // FIXME: InstImpResults should not be part of DAGInstruction.
4117 DAGInsts.try_emplace(k: I.getRecord(), args: std::move(Results), args: std::move(Operands),
4118 args: std::move(InstImpResults), args&: SrcPattern, args&: ResultPattern);
4119
4120 LLVM_DEBUG(I.dump());
4121}
4122
4123/// ParseInstructions - Parse all of the instructions, inlining and resolving
4124/// any fragments involved. This populates the Instructions list with fully
4125/// resolved instructions.
4126void CodeGenDAGPatterns::ParseInstructions() {
4127 for (const Record *Instr : Records.getAllDerivedDefinitions(ClassName: "Instruction")) {
4128 const ListInit *LI = nullptr;
4129
4130 if (isa<ListInit>(Val: Instr->getValueInit(FieldName: "Pattern")))
4131 LI = Instr->getValueAsListInit(FieldName: "Pattern");
4132
4133 // If there is no pattern, only collect minimal information about the
4134 // instruction for its operand list. We have to assume that there is one
4135 // result, as we have no detailed info. A pattern which references the
4136 // null_frag operator is as-if no pattern were specified. Normally this
4137 // is from a multiclass expansion w/ a SDPatternOperator passed in as
4138 // null_frag.
4139 if (!LI || LI->empty() || hasNullFragReference(LI)) {
4140 std::vector<const Record *> Results;
4141 std::vector<const Record *> Operands;
4142
4143 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4144
4145 if (InstInfo.Operands.size() != 0) {
4146 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
4147 Results.push_back(x: InstInfo.Operands[j].Rec);
4148
4149 // The rest are inputs.
4150 for (unsigned j = InstInfo.Operands.NumDefs,
4151 e = InstInfo.Operands.size();
4152 j < e; ++j)
4153 Operands.push_back(x: InstInfo.Operands[j].Rec);
4154 }
4155
4156 // Create and insert the instruction.
4157 Instructions.try_emplace(k: Instr, args: std::move(Results), args: std::move(Operands),
4158 args: std::vector<const Record *>());
4159 continue; // no pattern.
4160 }
4161
4162 const CodeGenInstruction &CGI = Target.getInstruction(InstRec: Instr);
4163 parseInstructionPattern(CGI, Pat: LI, DAGInsts&: Instructions);
4164 }
4165
4166 // If we can, convert the instructions to be patterns that are matched!
4167 for (const auto &[Instr, TheInst] : Instructions) {
4168 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
4169 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
4170
4171 if (SrcPattern && ResultPattern) {
4172 TreePattern Pattern(Instr, SrcPattern, true, *this);
4173 TreePattern Result(Instr, ResultPattern, false, *this);
4174 ParseOnePattern(TheDef: Instr, Pattern, Result, InstImpResults: TheInst.getImpResults());
4175 }
4176 }
4177}
4178
4179using NameRecord = std::pair<TreePatternNode *, unsigned>;
4180
4181static void FindNames(TreePatternNode &P,
4182 std::map<StringRef, NameRecord> &Names,
4183 TreePattern *PatternTop) {
4184 if (!P.getName().empty()) {
4185 NameRecord &Rec = Names[P.getName()];
4186 // If this is the first instance of the name, remember the node.
4187 if (Rec.second++ == 0)
4188 Rec.first = &P;
4189 else if (Rec.first->getExtTypes() != P.getExtTypes())
4190 PatternTop->error(Msg: "repetition of value: $" + P.getName() +
4191 " where different uses have different types!");
4192 }
4193
4194 if (!P.isLeaf()) {
4195 for (TreePatternNode &Child : P.children())
4196 FindNames(P&: Child, Names, PatternTop);
4197 }
4198}
4199
4200void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
4201 PatternToMatch &&PTM) {
4202 // Do some sanity checking on the pattern we're about to match.
4203 std::string Reason;
4204 if (!PTM.getSrcPattern().canPatternMatch(Reason, CDP: *this)) {
4205 PrintWarning(WarningLoc: Pattern->getRecord()->getLoc(),
4206 Msg: Twine("Pattern can never match: ") + Reason);
4207 return;
4208 }
4209
4210 // If the source pattern's root is a complex pattern, that complex pattern
4211 // must specify the nodes it can potentially match.
4212 if (const ComplexPattern *CP =
4213 PTM.getSrcPattern().getComplexPatternInfo(CGP: *this))
4214 if (CP->getRootNodes().empty())
4215 Pattern->error(Msg: "ComplexPattern at root must specify list of opcodes it"
4216 " could match");
4217
4218 // Find all of the named values in the input and output, ensure they have the
4219 // same type.
4220 std::map<StringRef, NameRecord> SrcNames, DstNames;
4221 FindNames(P&: PTM.getSrcPattern(), Names&: SrcNames, PatternTop: Pattern);
4222 FindNames(P&: PTM.getDstPattern(), Names&: DstNames, PatternTop: Pattern);
4223
4224 // Scan all of the named values in the destination pattern, rejecting them if
4225 // they don't exist in the input pattern.
4226 for (const auto &Entry : DstNames) {
4227 if (SrcNames[Entry.first].first == nullptr)
4228 Pattern->error(Msg: "Pattern has input without matching name in output: $" +
4229 Entry.first);
4230 }
4231
4232 // Scan all of the named values in the source pattern, rejecting them if the
4233 // name isn't used in the dest, and isn't used to tie two values together.
4234 for (const auto &Entry : SrcNames)
4235 if (DstNames[Entry.first].first == nullptr &&
4236 SrcNames[Entry.first].second == 1)
4237 Pattern->error(Msg: "Pattern has dead named input: $" + Entry.first);
4238
4239 PatternsToMatch.push_back(x: std::move(PTM));
4240}
4241
4242void CodeGenDAGPatterns::InferInstructionFlags() {
4243 ArrayRef<const CodeGenInstruction *> Instructions = Target.getInstructions();
4244
4245 unsigned Errors = 0;
4246
4247 // Try to infer flags from all patterns in PatternToMatch. These include
4248 // both the primary instruction patterns (which always come first) and
4249 // patterns defined outside the instruction.
4250 for (const PatternToMatch &PTM : ptms()) {
4251 // We can only infer from single-instruction patterns, otherwise we won't
4252 // know which instruction should get the flags.
4253 SmallVector<const Record *, 8> PatInstrs;
4254 getInstructionsInTree(Tree&: PTM.getDstPattern(), Instrs&: PatInstrs);
4255 if (PatInstrs.size() != 1)
4256 continue;
4257
4258 // Get the single instruction.
4259 CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: PatInstrs.front());
4260
4261 // Only infer properties from the first pattern. We'll verify the others.
4262 if (InstInfo.InferredFrom)
4263 continue;
4264
4265 InstAnalyzer PatInfo(*this);
4266 PatInfo.Analyze(Pat: PTM);
4267 Errors += InferFromPattern(InstInfo, PatInfo, PatDef: PTM.getSrcRecord());
4268 }
4269
4270 if (Errors)
4271 PrintFatalError(Msg: "pattern conflicts");
4272
4273 // If requested by the target, guess any undefined properties.
4274 if (Target.guessInstructionProperties()) {
4275 for (const CodeGenInstruction *InstInfo : Instructions) {
4276 if (InstInfo->InferredFrom)
4277 continue;
4278 // The mayLoad and mayStore flags default to false.
4279 // Conservatively assume hasSideEffects if it wasn't explicit.
4280 if (InstInfo->hasSideEffects_Unset)
4281 const_cast<CodeGenInstruction *>(InstInfo)->hasSideEffects = true;
4282 }
4283 return;
4284 }
4285
4286 // Complain about any flags that are still undefined.
4287 for (const CodeGenInstruction *InstInfo : Instructions) {
4288 if (InstInfo->InferredFrom)
4289 continue;
4290 if (InstInfo->hasSideEffects_Unset)
4291 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4292 Msg: "Can't infer hasSideEffects from patterns");
4293 if (InstInfo->mayStore_Unset)
4294 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4295 Msg: "Can't infer mayStore from patterns");
4296 if (InstInfo->mayLoad_Unset)
4297 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4298 Msg: "Can't infer mayLoad from patterns");
4299 }
4300}
4301
4302/// Verify instruction flags against pattern node properties.
4303void CodeGenDAGPatterns::VerifyInstructionFlags() {
4304 unsigned Errors = 0;
4305 for (const PatternToMatch &PTM : ptms()) {
4306 SmallVector<const Record *, 8> Instrs;
4307 getInstructionsInTree(Tree&: PTM.getDstPattern(), Instrs);
4308 if (Instrs.empty())
4309 continue;
4310
4311 // Count the number of instructions with each flag set.
4312 unsigned NumSideEffects = 0;
4313 unsigned NumStores = 0;
4314 unsigned NumLoads = 0;
4315 for (const Record *Instr : Instrs) {
4316 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4317 NumSideEffects += InstInfo.hasSideEffects;
4318 NumStores += InstInfo.mayStore;
4319 NumLoads += InstInfo.mayLoad;
4320 }
4321
4322 // Analyze the source pattern.
4323 InstAnalyzer PatInfo(*this);
4324 PatInfo.Analyze(Pat: PTM);
4325
4326 // Collect error messages.
4327 SmallVector<std::string, 4> Msgs;
4328
4329 // Check for missing flags in the output.
4330 // Permit extra flags for now at least.
4331 if (PatInfo.hasSideEffects && !NumSideEffects)
4332 Msgs.push_back(Elt: "pattern has side effects, but hasSideEffects isn't set");
4333
4334 // Don't verify store flags on instructions with side effects. At least for
4335 // intrinsics, side effects implies mayStore.
4336 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4337 Msgs.push_back(Elt: "pattern may store, but mayStore isn't set");
4338
4339 // Similarly, mayStore implies mayLoad on intrinsics.
4340 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4341 Msgs.push_back(Elt: "pattern may load, but mayLoad isn't set");
4342
4343 // Print error messages.
4344 if (Msgs.empty())
4345 continue;
4346 ++Errors;
4347
4348 for (const std::string &Msg : Msgs)
4349 PrintError(
4350 ErrorLoc: PTM.getSrcRecord()->getLoc(),
4351 Msg: Twine(Msg) + " on the " +
4352 (Instrs.size() == 1 ? "instruction" : "output instructions"));
4353 // Provide the location of the relevant instruction definitions.
4354 for (const Record *Instr : Instrs) {
4355 if (Instr != PTM.getSrcRecord())
4356 PrintError(ErrorLoc: Instr->getLoc(), Msg: "defined here");
4357 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4358 if (InstInfo.InferredFrom && InstInfo.InferredFrom != InstInfo.TheDef &&
4359 InstInfo.InferredFrom != PTM.getSrcRecord())
4360 PrintError(ErrorLoc: InstInfo.InferredFrom->getLoc(), Msg: "inferred from pattern");
4361 }
4362 }
4363 if (Errors)
4364 PrintFatalError(Msg: "Errors in DAG patterns");
4365}
4366
4367/// Given a pattern result with an unresolved type, see if we can find one
4368/// instruction with an unresolved result type. Force this result type to an
4369/// arbitrary element if it's possible types to converge results.
4370static bool ForceArbitraryInstResultType(TreePatternNode &N, TreePattern &TP) {
4371 if (N.isLeaf())
4372 return false;
4373
4374 // Analyze children.
4375 for (TreePatternNode &Child : N.children())
4376 if (ForceArbitraryInstResultType(N&: Child, TP))
4377 return true;
4378
4379 if (!N.getOperator()->isSubClassOf(Name: "Instruction"))
4380 return false;
4381
4382 // If this type is already concrete or completely unknown we can't do
4383 // anything.
4384 TypeInfer &TI = TP.getInfer();
4385 for (unsigned i = 0, e = N.getNumTypes(); i != e; ++i) {
4386 if (N.getExtType(ResNo: i).empty() ||
4387 N.getExtType(ResNo: i).isValueTypeByHwMode(/*AllowEmpty=*/false))
4388 continue;
4389
4390 // Otherwise, force its type to an arbitrary choice.
4391 if (TI.forceArbitrary(Out&: N.getExtType(ResNo: i)))
4392 return true;
4393 }
4394
4395 return false;
4396}
4397
4398// Promote xform function to be an explicit node wherever set.
4399static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4400 if (const Record *Xform = N->getTransformFn()) {
4401 N->setTransformFn(nullptr);
4402 std::vector<TreePatternNodePtr> Children;
4403 Children.push_back(x: PromoteXForms(N));
4404 return makeIntrusiveRefCnt<TreePatternNode>(A&: Xform, A: std::move(Children),
4405 A: N->getNumTypes());
4406 }
4407
4408 if (!N->isLeaf())
4409 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4410 TreePatternNodePtr Child = N->getChildShared(N: i);
4411 N->setChild(i, N: PromoteXForms(N: Child));
4412 }
4413 return N;
4414}
4415
4416void CodeGenDAGPatterns::ParseOnePattern(
4417 const Record *TheDef, TreePattern &Pattern, TreePattern &Result,
4418 ArrayRef<const Record *> InstImpResults, bool ShouldIgnore) {
4419 // Inline pattern fragments and expand multiple alternatives.
4420 Pattern.InlinePatternFragments();
4421 Result.InlinePatternFragments();
4422
4423 if (Result.getNumTrees() != 1) {
4424 Result.error(Msg: "Cannot use multi-alternative fragments in result pattern!");
4425 return;
4426 }
4427
4428 // Infer types.
4429 bool IterateInference;
4430 bool InferredAllPatternTypes, InferredAllResultTypes;
4431 do {
4432 // Infer as many types as possible. If we cannot infer all of them, we
4433 // can never do anything with this pattern: report it to the user.
4434 InferredAllPatternTypes =
4435 Pattern.InferAllTypes(InNamedTypes: &Pattern.getNamedNodesMap());
4436
4437 // Infer as many types as possible. If we cannot infer all of them, we
4438 // can never do anything with this pattern: report it to the user.
4439 InferredAllResultTypes = Result.InferAllTypes(InNamedTypes: &Pattern.getNamedNodesMap());
4440
4441 IterateInference = false;
4442
4443 // Apply the type of the result to the source pattern. This helps us
4444 // resolve cases where the input type is known to be a pointer type (which
4445 // is considered resolved), but the result knows it needs to be 32- or
4446 // 64-bits. Infer the other way for good measure.
4447 for (const auto &T : Pattern.getTrees())
4448 for (unsigned i = 0, e = std::min(a: Result.getOnlyTree()->getNumTypes(),
4449 b: T->getNumTypes());
4450 i != e; ++i) {
4451 IterateInference |=
4452 T->UpdateNodeType(ResNo: i, InTy: Result.getOnlyTree()->getExtType(ResNo: i), TP&: Result);
4453 IterateInference |=
4454 Result.getOnlyTree()->UpdateNodeType(ResNo: i, InTy: T->getExtType(ResNo: i), TP&: Result);
4455 }
4456
4457 // If our iteration has converged and the input pattern's types are fully
4458 // resolved but the result pattern is not fully resolved, we may have a
4459 // situation where we have two instructions in the result pattern and
4460 // the instructions require a common register class, but don't care about
4461 // what actual MVT is used. This is actually a bug in our modelling:
4462 // output patterns should have register classes, not MVTs.
4463 //
4464 // In any case, to handle this, we just go through and disambiguate some
4465 // arbitrary types to the result pattern's nodes.
4466 if (!IterateInference && InferredAllPatternTypes && !InferredAllResultTypes)
4467 IterateInference =
4468 ForceArbitraryInstResultType(N&: *Result.getTree(i: 0), TP&: Result);
4469 } while (IterateInference);
4470
4471 // Verify that we inferred enough types that we can do something with the
4472 // pattern and result. If these fire the user has to add type casts.
4473 if (!InferredAllPatternTypes)
4474 Pattern.error(Msg: "Could not infer all types in pattern!");
4475 if (!InferredAllResultTypes) {
4476 Pattern.dump();
4477 Result.error(Msg: "Could not infer all types in pattern result!");
4478 }
4479
4480 // Promote xform function to be an explicit node wherever set.
4481 TreePatternNodePtr DstShared = PromoteXForms(N: Result.getOnlyTree());
4482
4483 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4484 Temp.InferAllTypes();
4485
4486 const ListInit *Preds = TheDef->getValueAsListInit(FieldName: "Predicates");
4487 int Complexity = TheDef->getValueAsInt(FieldName: "AddedComplexity");
4488
4489 // A pattern may end up with an "impossible" type, i.e. a situation
4490 // where all types have been eliminated for some node in this pattern.
4491 // This could occur for intrinsics that only make sense for a specific
4492 // value type, and use a specific register class. If, for some mode,
4493 // that register class does not accept that type, the type inference
4494 // will lead to a contradiction, which is not an error however, but
4495 // a sign that this pattern will simply never match.
4496 if (Temp.getOnlyTree()->hasPossibleType()) {
4497 for (const auto &T : Pattern.getTrees()) {
4498 if (T->hasPossibleType())
4499 AddPatternToMatch(Pattern: &Pattern,
4500 PTM: PatternToMatch(TheDef, Preds, T, Temp.getOnlyTree(),
4501 InstImpResults, Complexity,
4502 TheDef->getID(), ShouldIgnore));
4503 }
4504 } else {
4505 // Show a message about a dropped pattern with some info to make it
4506 // easier to identify it in the .td files.
4507 LLVM_DEBUG({
4508 dbgs() << "Dropping: ";
4509 Pattern.dump();
4510 Temp.getOnlyTree()->dump();
4511 dbgs() << "\n";
4512 });
4513 }
4514}
4515
4516void CodeGenDAGPatterns::ParsePatterns() {
4517 for (const Record *CurPattern : Records.getAllDerivedDefinitions(ClassName: "Pattern")) {
4518 const DagInit *Tree = CurPattern->getValueAsDag(FieldName: "PatternToMatch");
4519
4520 // If the pattern references the null_frag, there's nothing to do.
4521 if (hasNullFragReference(DI: Tree))
4522 continue;
4523
4524 TreePattern Pattern(CurPattern, Tree, true, *this);
4525
4526 const ListInit *LI = CurPattern->getValueAsListInit(FieldName: "ResultInstrs");
4527 if (LI->empty())
4528 continue; // no pattern.
4529
4530 // Parse the instruction.
4531 TreePattern Result(CurPattern, LI, false, *this);
4532
4533 if (Result.getNumTrees() != 1)
4534 Result.error(Msg: "Cannot handle instructions producing instructions "
4535 "with temporaries yet!");
4536
4537 // Validate that the input pattern is correct.
4538 InstInputsTy InstInputs;
4539 InstResultsTy InstResults;
4540 std::vector<const Record *> InstImpResults;
4541 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4542 FindPatternInputsAndOutputs(I&: Pattern, Pat: Pattern.getTree(i: j), InstInputs,
4543 InstResults, InstImpResults);
4544
4545 ParseOnePattern(TheDef: CurPattern, Pattern, Result, InstImpResults,
4546 ShouldIgnore: CurPattern->getValueAsBit(FieldName: "GISelShouldIgnore"));
4547 }
4548}
4549
4550static void collectModes(std::set<unsigned> &Modes, const TreePatternNode &N) {
4551 for (const TypeSetByHwMode &VTS : N.getExtTypes())
4552 for (const auto &I : VTS)
4553 Modes.insert(x: I.first);
4554
4555 for (const TreePatternNode &Child : N.children())
4556 collectModes(Modes, N: Child);
4557}
4558
4559void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4560 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4561 if (CGH.getNumModeIds() == 1)
4562 return;
4563
4564 std::vector<PatternToMatch> Copy;
4565 PatternsToMatch.swap(x&: Copy);
4566
4567 auto AppendPattern = [this](PatternToMatch &P, unsigned Mode,
4568 StringRef Check) {
4569 TreePatternNodePtr NewSrc = P.getSrcPattern().clone();
4570 TreePatternNodePtr NewDst = P.getDstPattern().clone();
4571 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4572 return;
4573 }
4574
4575 PatternsToMatch.emplace_back(args: P.getSrcRecord(), args: P.getPredicates(),
4576 args: std::move(NewSrc), args: std::move(NewDst),
4577 args: P.getDstRegs(), args: P.getAddedComplexity(),
4578 args: getNewUID(), args: P.getGISelShouldIgnore(), args&: Check);
4579 };
4580
4581 for (PatternToMatch &P : Copy) {
4582 const TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4583 if (P.getSrcPattern().hasProperTypeByHwMode())
4584 SrcP = &P.getSrcPattern();
4585 if (P.getDstPattern().hasProperTypeByHwMode())
4586 DstP = &P.getDstPattern();
4587 if (!SrcP && !DstP) {
4588 PatternsToMatch.push_back(x: P);
4589 continue;
4590 }
4591
4592 std::set<unsigned> Modes;
4593 if (SrcP)
4594 collectModes(Modes, N: *SrcP);
4595 if (DstP)
4596 collectModes(Modes, N: *DstP);
4597
4598 // The predicate for the default mode needs to be constructed for each
4599 // pattern separately.
4600 // Since not all modes must be present in each pattern, if a mode m is
4601 // absent, then there is no point in constructing a check for m. If such
4602 // a check was created, it would be equivalent to checking the default
4603 // mode, except not all modes' predicates would be a part of the checking
4604 // code. The subsequently generated check for the default mode would then
4605 // have the exact same patterns, but a different predicate code. To avoid
4606 // duplicated patterns with different predicate checks, construct the
4607 // default check as a negation of all predicates that are actually present
4608 // in the source/destination patterns.
4609 SmallString<128> DefaultCheck;
4610
4611 for (unsigned M : Modes) {
4612 if (M == DefaultMode)
4613 continue;
4614
4615 // Fill the map entry for this mode.
4616 const HwMode &HM = CGH.getMode(Id: M);
4617
4618 SmallString<128> PredicateCheck;
4619 raw_svector_ostream PS(PredicateCheck);
4620 SubtargetFeatureInfo::emitPredicateCheck(OS&: PS, Predicates: HM.Predicates);
4621 AppendPattern(P, M, PredicateCheck);
4622
4623 // Add negations of the HM's predicates to the default predicate.
4624 if (!DefaultCheck.empty())
4625 DefaultCheck += " && ";
4626 DefaultCheck += "!(";
4627 DefaultCheck.append(RHS: PredicateCheck);
4628 DefaultCheck += ")";
4629 }
4630
4631 bool HasDefault = Modes.count(x: DefaultMode);
4632 if (HasDefault)
4633 AppendPattern(P, DefaultMode, DefaultCheck);
4634 }
4635}
4636
4637/// Dependent variable map for CodeGenDAGPattern variant generation
4638using DepVarMap = StringMap<int>;
4639
4640static void FindDepVarsOf(TreePatternNode &N, DepVarMap &DepMap) {
4641 if (N.isLeaf()) {
4642 if (N.hasName() && isa<DefInit>(Val: N.getLeafValue()))
4643 DepMap[N.getName()]++;
4644 } else {
4645 for (TreePatternNode &Child : N.children())
4646 FindDepVarsOf(N&: Child, DepMap);
4647 }
4648}
4649
4650/// Find dependent variables within child patterns
4651static void FindDepVars(TreePatternNode &N, MultipleUseVarSet &DepVars) {
4652 DepVarMap depcounts;
4653 FindDepVarsOf(N, DepMap&: depcounts);
4654 for (const auto &Pair : depcounts) {
4655 if (Pair.getValue() > 1)
4656 DepVars.insert(key: Pair.getKey());
4657 }
4658}
4659
4660#ifndef NDEBUG
4661/// Dump the dependent variable set:
4662static void DumpDepVars(MultipleUseVarSet &DepVars) {
4663 if (DepVars.empty()) {
4664 LLVM_DEBUG(dbgs() << "<empty set>");
4665 } else {
4666 LLVM_DEBUG(dbgs() << "[ ");
4667 for (const auto &DepVar : DepVars) {
4668 LLVM_DEBUG(dbgs() << DepVar.getKey() << " ");
4669 }
4670 LLVM_DEBUG(dbgs() << "]");
4671 }
4672}
4673#endif
4674
4675/// CombineChildVariants - Given a bunch of permutations of each child of the
4676/// 'operator' node, put them together in all possible ways.
4677static void CombineChildVariants(
4678 TreePatternNodePtr Orig,
4679 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4680 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4681 const MultipleUseVarSet &DepVars) {
4682 // Make sure that each operand has at least one variant to choose from.
4683 for (const auto &Variants : ChildVariants)
4684 if (Variants.empty())
4685 return;
4686
4687 // The end result is an all-pairs construction of the resultant pattern.
4688 std::vector<unsigned> Idxs(ChildVariants.size());
4689 bool NotDone;
4690 do {
4691#ifndef NDEBUG
4692 LLVM_DEBUG(if (!Idxs.empty()) {
4693 dbgs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4694 for (unsigned Idx : Idxs) {
4695 dbgs() << Idx << " ";
4696 }
4697 dbgs() << "]\n";
4698 });
4699#endif
4700 // Create the variant and add it to the output list.
4701 std::vector<TreePatternNodePtr> NewChildren;
4702 NewChildren.reserve(n: ChildVariants.size());
4703 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4704 NewChildren.push_back(x: ChildVariants[i][Idxs[i]]);
4705 TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
4706 A: Orig->getOperator(), A: std::move(NewChildren), A: Orig->getNumTypes());
4707
4708 // Copy over properties.
4709 R->setName(Orig->getName());
4710 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4711 R->setPredicateCalls(Orig->getPredicateCalls());
4712 R->setGISelFlagsRecord(Orig->getGISelFlagsRecord());
4713 R->setTransformFn(Orig->getTransformFn());
4714 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4715 R->setType(ResNo: i, T: Orig->getExtType(ResNo: i));
4716
4717 // If this pattern cannot match, do not include it as a variant.
4718 std::string ErrString;
4719 // Scan to see if this pattern has already been emitted. We can get
4720 // duplication due to things like commuting:
4721 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4722 // which are the same pattern. Ignore the dups.
4723 if (R->canPatternMatch(Reason&: ErrString, CDP) &&
4724 none_of(Range&: OutVariants, P: [&](TreePatternNodePtr Variant) {
4725 return R->isIsomorphicTo(N: *Variant, DepVars);
4726 }))
4727 OutVariants.push_back(x: R);
4728
4729 // Increment indices to the next permutation by incrementing the
4730 // indices from last index backward, e.g., generate the sequence
4731 // [0, 0], [0, 1], [1, 0], [1, 1].
4732 int IdxsIdx;
4733 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4734 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4735 Idxs[IdxsIdx] = 0;
4736 else
4737 break;
4738 }
4739 NotDone = (IdxsIdx >= 0);
4740 } while (NotDone);
4741}
4742
4743/// CombineChildVariants - A helper function for binary operators.
4744///
4745static void CombineChildVariants(TreePatternNodePtr Orig,
4746 const std::vector<TreePatternNodePtr> &LHS,
4747 const std::vector<TreePatternNodePtr> &RHS,
4748 std::vector<TreePatternNodePtr> &OutVariants,
4749 CodeGenDAGPatterns &CDP,
4750 const MultipleUseVarSet &DepVars) {
4751 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4752 ChildVariants.push_back(x: LHS);
4753 ChildVariants.push_back(x: RHS);
4754 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4755}
4756
4757static void
4758GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4759 std::vector<TreePatternNodePtr> &Children) {
4760 assert(N->getNumChildren() == 2 &&
4761 "Associative but doesn't have 2 children!");
4762 const Record *Operator = N->getOperator();
4763
4764 // Only permit raw nodes.
4765 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
4766 N->getTransformFn()) {
4767 Children.push_back(x: N);
4768 return;
4769 }
4770
4771 if (N->getChild(N: 0).isLeaf() || N->getChild(N: 0).getOperator() != Operator)
4772 Children.push_back(x: N->getChildShared(N: 0));
4773 else
4774 GatherChildrenOfAssociativeOpcode(N: N->getChildShared(N: 0), Children);
4775
4776 if (N->getChild(N: 1).isLeaf() || N->getChild(N: 1).getOperator() != Operator)
4777 Children.push_back(x: N->getChildShared(N: 1));
4778 else
4779 GatherChildrenOfAssociativeOpcode(N: N->getChildShared(N: 1), Children);
4780}
4781
4782/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4783/// the (potentially recursive) pattern by using algebraic laws.
4784///
4785static void GenerateVariantsOf(TreePatternNodePtr N,
4786 std::vector<TreePatternNodePtr> &OutVariants,
4787 CodeGenDAGPatterns &CDP,
4788 const MultipleUseVarSet &DepVars) {
4789 // We cannot permute leaves or ComplexPattern uses.
4790 if (N->isLeaf() || N->getOperator()->isSubClassOf(Name: "ComplexPattern")) {
4791 OutVariants.push_back(x: N);
4792 return;
4793 }
4794
4795 // Look up interesting info about the node.
4796 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(R: N->getOperator());
4797
4798 // If this node is associative, re-associate.
4799 if (NodeInfo.hasProperty(Prop: SDNPAssociative)) {
4800 // Re-associate by pulling together all of the linked operators
4801 std::vector<TreePatternNodePtr> MaximalChildren;
4802 GatherChildrenOfAssociativeOpcode(N, Children&: MaximalChildren);
4803
4804 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4805 // permutations.
4806 if (MaximalChildren.size() == 3) {
4807 // Find the variants of all of our maximal children.
4808 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4809 GenerateVariantsOf(N: MaximalChildren[0], OutVariants&: AVariants, CDP, DepVars);
4810 GenerateVariantsOf(N: MaximalChildren[1], OutVariants&: BVariants, CDP, DepVars);
4811 GenerateVariantsOf(N: MaximalChildren[2], OutVariants&: CVariants, CDP, DepVars);
4812
4813 // There are only two ways we can permute the tree:
4814 // (A op B) op C and A op (B op C)
4815 // Within these forms, we can also permute A/B/C.
4816
4817 // Generate legal pair permutations of A/B/C.
4818 std::vector<TreePatternNodePtr> ABVariants;
4819 std::vector<TreePatternNodePtr> BAVariants;
4820 std::vector<TreePatternNodePtr> ACVariants;
4821 std::vector<TreePatternNodePtr> CAVariants;
4822 std::vector<TreePatternNodePtr> BCVariants;
4823 std::vector<TreePatternNodePtr> CBVariants;
4824 CombineChildVariants(Orig: N, LHS: AVariants, RHS: BVariants, OutVariants&: ABVariants, CDP, DepVars);
4825 CombineChildVariants(Orig: N, LHS: BVariants, RHS: AVariants, OutVariants&: BAVariants, CDP, DepVars);
4826 CombineChildVariants(Orig: N, LHS: AVariants, RHS: CVariants, OutVariants&: ACVariants, CDP, DepVars);
4827 CombineChildVariants(Orig: N, LHS: CVariants, RHS: AVariants, OutVariants&: CAVariants, CDP, DepVars);
4828 CombineChildVariants(Orig: N, LHS: BVariants, RHS: CVariants, OutVariants&: BCVariants, CDP, DepVars);
4829 CombineChildVariants(Orig: N, LHS: CVariants, RHS: BVariants, OutVariants&: CBVariants, CDP, DepVars);
4830
4831 // Combine those into the result: (x op x) op x
4832 CombineChildVariants(Orig: N, LHS: ABVariants, RHS: CVariants, OutVariants, CDP, DepVars);
4833 CombineChildVariants(Orig: N, LHS: BAVariants, RHS: CVariants, OutVariants, CDP, DepVars);
4834 CombineChildVariants(Orig: N, LHS: ACVariants, RHS: BVariants, OutVariants, CDP, DepVars);
4835 CombineChildVariants(Orig: N, LHS: CAVariants, RHS: BVariants, OutVariants, CDP, DepVars);
4836 CombineChildVariants(Orig: N, LHS: BCVariants, RHS: AVariants, OutVariants, CDP, DepVars);
4837 CombineChildVariants(Orig: N, LHS: CBVariants, RHS: AVariants, OutVariants, CDP, DepVars);
4838
4839 // Combine those into the result: x op (x op x)
4840 CombineChildVariants(Orig: N, LHS: CVariants, RHS: ABVariants, OutVariants, CDP, DepVars);
4841 CombineChildVariants(Orig: N, LHS: CVariants, RHS: BAVariants, OutVariants, CDP, DepVars);
4842 CombineChildVariants(Orig: N, LHS: BVariants, RHS: ACVariants, OutVariants, CDP, DepVars);
4843 CombineChildVariants(Orig: N, LHS: BVariants, RHS: CAVariants, OutVariants, CDP, DepVars);
4844 CombineChildVariants(Orig: N, LHS: AVariants, RHS: BCVariants, OutVariants, CDP, DepVars);
4845 CombineChildVariants(Orig: N, LHS: AVariants, RHS: CBVariants, OutVariants, CDP, DepVars);
4846 return;
4847 }
4848 }
4849
4850 // Compute permutations of all children.
4851 std::vector<std::vector<TreePatternNodePtr>> ChildVariants(
4852 N->getNumChildren());
4853 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4854 GenerateVariantsOf(N: N->getChildShared(N: i), OutVariants&: ChildVariants[i], CDP, DepVars);
4855
4856 // Build all permutations based on how the children were formed.
4857 CombineChildVariants(Orig: N, ChildVariants, OutVariants, CDP, DepVars);
4858
4859 // If this node is commutative, consider the commuted order.
4860 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4861 if (NodeInfo.hasProperty(Prop: SDNPCommutative) || isCommIntrinsic) {
4862 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
4863 assert(N->getNumChildren() >= (2 + Skip) &&
4864 "Commutative but doesn't have 2 children!");
4865 // Don't allow commuting children which are actually register references.
4866 bool NoRegisters = true;
4867 unsigned i = 0 + Skip;
4868 unsigned e = 2 + Skip;
4869 for (; i != e; ++i) {
4870 TreePatternNode &Child = N->getChild(N: i);
4871 if (Child.isLeaf())
4872 if (const DefInit *DI = dyn_cast<DefInit>(Val: Child.getLeafValue())) {
4873 const Record *RR = DI->getDef();
4874 if (RR->isSubClassOf(Name: "Register"))
4875 NoRegisters = false;
4876 }
4877 }
4878 // Consider the commuted order.
4879 if (NoRegisters) {
4880 // Swap the first two operands after the intrinsic id, if present.
4881 unsigned i = isCommIntrinsic ? 1 : 0;
4882 std::swap(x&: ChildVariants[i], y&: ChildVariants[i + 1]);
4883 CombineChildVariants(Orig: N, ChildVariants, OutVariants, CDP, DepVars);
4884 }
4885 }
4886}
4887
4888// GenerateVariants - Generate variants. For example, commutative patterns can
4889// match multiple ways. Add them to PatternsToMatch as well.
4890void CodeGenDAGPatterns::GenerateVariants() {
4891 LLVM_DEBUG(dbgs() << "Generating instruction variants.\n");
4892
4893 // Loop over all of the patterns we've collected, checking to see if we can
4894 // generate variants of the instruction, through the exploitation of
4895 // identities. This permits the target to provide aggressive matching without
4896 // the .td file having to contain tons of variants of instructions.
4897 //
4898 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4899 // intentionally do not reconsider these. Any variants of added patterns have
4900 // already been added.
4901 //
4902 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4903 MultipleUseVarSet DepVars;
4904 std::vector<TreePatternNodePtr> Variants;
4905 FindDepVars(N&: PatternsToMatch[i].getSrcPattern(), DepVars);
4906 LLVM_DEBUG(dbgs() << "Dependent/multiply used variables: ");
4907 LLVM_DEBUG(DumpDepVars(DepVars));
4908 LLVM_DEBUG(dbgs() << "\n");
4909 GenerateVariantsOf(N: PatternsToMatch[i].getSrcPatternShared(), OutVariants&: Variants,
4910 CDP&: *this, DepVars);
4911
4912 assert(PatternsToMatch[i].getHwModeFeatures().empty() &&
4913 "HwModes should not have been expanded yet!");
4914
4915 assert(!Variants.empty() && "Must create at least original variant!");
4916 if (Variants.size() == 1) // No additional variants for this pattern.
4917 continue;
4918
4919 LLVM_DEBUG(dbgs() << "FOUND VARIANTS OF: ";
4920 PatternsToMatch[i].getSrcPattern().dump(); dbgs() << "\n");
4921
4922 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4923 TreePatternNodePtr Variant = Variants[v];
4924
4925 LLVM_DEBUG(dbgs() << " VAR#" << v << ": "; Variant->dump();
4926 dbgs() << "\n");
4927
4928 // Scan to see if an instruction or explicit pattern already matches this.
4929 bool AlreadyExists = false;
4930 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4931 // Skip if the top level predicates do not match.
4932 if ((i != p) && (PatternsToMatch[i].getPredicates() !=
4933 PatternsToMatch[p].getPredicates()))
4934 continue;
4935 // Check to see if this variant already exists.
4936 if (Variant->isIsomorphicTo(N: PatternsToMatch[p].getSrcPattern(),
4937 DepVars)) {
4938 LLVM_DEBUG(dbgs() << " *** ALREADY EXISTS, ignoring variant.\n");
4939 AlreadyExists = true;
4940 break;
4941 }
4942 }
4943 // If we already have it, ignore the variant.
4944 if (AlreadyExists)
4945 continue;
4946
4947 // Otherwise, add it to the list of patterns we have.
4948 PatternsToMatch.emplace_back(
4949 args: PatternsToMatch[i].getSrcRecord(), args: PatternsToMatch[i].getPredicates(),
4950 args&: Variant, args: PatternsToMatch[i].getDstPatternShared(),
4951 args: PatternsToMatch[i].getDstRegs(),
4952 args: PatternsToMatch[i].getAddedComplexity(), args: getNewUID(),
4953 args: PatternsToMatch[i].getGISelShouldIgnore(),
4954 args: PatternsToMatch[i].getHwModeFeatures());
4955 }
4956
4957 LLVM_DEBUG(dbgs() << "\n");
4958 }
4959}
4960
4961unsigned CodeGenDAGPatterns::getNewUID() {
4962 RecordKeeper &MutableRC = const_cast<RecordKeeper &>(Records);
4963 return Record::getNewUID(RK&: MutableRC);
4964}
4965