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 { print(OS&: errs()); }
2080
2081/// isIsomorphicTo - Return true if this node is recursively
2082/// isomorphic to the specified node. For this comparison, the node's
2083/// entire state is considered. The assigned name is ignored, since
2084/// nodes with differing names are considered isomorphic. However, if
2085/// the assigned name is present in the dependent variable set, then
2086/// the assigned name is considered significant and the node is
2087/// isomorphic if the names match.
2088bool TreePatternNode::isIsomorphicTo(const TreePatternNode &N,
2089 const MultipleUseVarSet &DepVars) const {
2090 if (&N == this)
2091 return true;
2092 if (N.isLeaf() != isLeaf())
2093 return false;
2094
2095 // Check operator of non-leaves early since it can be cheaper than checking
2096 // types.
2097 if (!isLeaf())
2098 if (N.getOperator() != getOperator() ||
2099 N.getNumChildren() != getNumChildren())
2100 return false;
2101
2102 if (getExtTypes() != N.getExtTypes() ||
2103 getPredicateCalls() != N.getPredicateCalls() ||
2104 getTransformFn() != N.getTransformFn())
2105 return false;
2106
2107 if (isLeaf()) {
2108 if (const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue())) {
2109 if (const DefInit *NDI = dyn_cast<DefInit>(Val: N.getLeafValue())) {
2110 return ((DI->getDef() == NDI->getDef()) &&
2111 (!DepVars.contains(key: getName()) || getName() == N.getName()));
2112 }
2113 }
2114 return getLeafValue() == N.getLeafValue();
2115 }
2116
2117 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2118 if (!getChild(N: i).isIsomorphicTo(N: N.getChild(N: i), DepVars))
2119 return false;
2120 return true;
2121}
2122
2123/// clone - Make a copy of this tree and all of its children.
2124///
2125TreePatternNodePtr TreePatternNode::clone() const {
2126 TreePatternNodePtr New;
2127 if (isLeaf()) {
2128 New = makeIntrusiveRefCnt<TreePatternNode>(A: getLeafValue(), A: getNumTypes());
2129 } else {
2130 std::vector<TreePatternNodePtr> CChildren;
2131 CChildren.reserve(n: Children.size());
2132 for (const TreePatternNode &Child : children())
2133 CChildren.push_back(x: Child.clone());
2134 New = makeIntrusiveRefCnt<TreePatternNode>(
2135 A: getOperator(), A: std::move(CChildren), A: getNumTypes());
2136 }
2137 New->setName(getName());
2138 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
2139 New->Types = Types;
2140 New->setPredicateCalls(getPredicateCalls());
2141 New->setGISelFlagsRecord(getGISelFlagsRecord());
2142 New->setTransformFn(getTransformFn());
2143 return New;
2144}
2145
2146/// RemoveAllTypes - Recursively strip all the types of this tree.
2147void TreePatternNode::RemoveAllTypes() {
2148 // Reset to unknown type.
2149 llvm::fill(Range&: Types, Value: TypeSetByHwMode());
2150 if (isLeaf())
2151 return;
2152 for (TreePatternNode &Child : children())
2153 Child.RemoveAllTypes();
2154}
2155
2156/// SubstituteFormalArguments - Replace the formal arguments in this tree
2157/// with actual values specified by ArgMap.
2158void TreePatternNode::SubstituteFormalArguments(
2159 std::map<StringRef, TreePatternNodePtr> &ArgMap) {
2160 if (isLeaf())
2161 return;
2162
2163 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2164 TreePatternNode &Child = getChild(N: i);
2165 if (Child.isLeaf()) {
2166 const Init *Val = Child.getLeafValue();
2167 // Note that, when substituting into an output pattern, Val might be an
2168 // UnsetInit.
2169 if (isa<UnsetInit>(Val) ||
2170 (isa<DefInit>(Val) &&
2171 cast<DefInit>(Val)->getDef()->getName() == "node")) {
2172 // We found a use of a formal argument, replace it with its value.
2173 TreePatternNodePtr NewChild = ArgMap[Child.getName()];
2174 assert(NewChild && "Couldn't find formal argument!");
2175 assert((Child.getPredicateCalls().empty() ||
2176 NewChild->getPredicateCalls() == Child.getPredicateCalls()) &&
2177 "Non-empty child predicate clobbered!");
2178 setChild(i, N: std::move(NewChild));
2179 }
2180 } else {
2181 getChild(N: i).SubstituteFormalArguments(ArgMap);
2182 }
2183 }
2184}
2185
2186/// InlinePatternFragments - If this pattern refers to any pattern
2187/// fragments, return the set of inlined versions (this can be more than
2188/// one if a PatFrags record has multiple alternatives).
2189void TreePatternNode::InlinePatternFragments(
2190 TreePattern &TP, std::vector<TreePatternNodePtr> &OutAlternatives) {
2191
2192 if (TP.hasError())
2193 return;
2194
2195 if (isLeaf()) {
2196 OutAlternatives.push_back(x: this); // nothing to do.
2197 return;
2198 }
2199
2200 const Record *Op = getOperator();
2201
2202 if (!Op->isSubClassOf(Name: "PatFrags")) {
2203 if (getNumChildren() == 0) {
2204 OutAlternatives.push_back(x: this);
2205 return;
2206 }
2207
2208 // Recursively inline children nodes.
2209 std::vector<std::vector<TreePatternNodePtr>> ChildAlternatives(
2210 getNumChildren());
2211 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2212 TreePatternNodePtr Child = getChildShared(N: i);
2213 Child->InlinePatternFragments(TP, OutAlternatives&: ChildAlternatives[i]);
2214 // If there are no alternatives for any child, there are no
2215 // alternatives for this expression as whole.
2216 if (ChildAlternatives[i].empty())
2217 return;
2218
2219 assert((Child->getPredicateCalls().empty() ||
2220 llvm::all_of(ChildAlternatives[i],
2221 [&](const TreePatternNodePtr &NewChild) {
2222 return NewChild->getPredicateCalls() ==
2223 Child->getPredicateCalls();
2224 })) &&
2225 "Non-empty child predicate clobbered!");
2226 }
2227
2228 // The end result is an all-pairs construction of the resultant pattern.
2229 std::vector<unsigned> Idxs(ChildAlternatives.size());
2230 bool NotDone;
2231 do {
2232 // Create the variant and add it to the output list.
2233 std::vector<TreePatternNodePtr> NewChildren;
2234 NewChildren.reserve(n: ChildAlternatives.size());
2235 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
2236 NewChildren.push_back(x: ChildAlternatives[i][Idxs[i]]);
2237 TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
2238 A: getOperator(), A: std::move(NewChildren), A: getNumTypes());
2239
2240 // Copy over properties.
2241 R->setName(getName());
2242 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
2243 R->setPredicateCalls(getPredicateCalls());
2244 R->setGISelFlagsRecord(getGISelFlagsRecord());
2245 R->setTransformFn(getTransformFn());
2246 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2247 R->setType(ResNo: i, T: getExtType(ResNo: i));
2248 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2249 R->setResultIndex(ResNo: i, RI: getResultIndex(ResNo: i));
2250
2251 // Register alternative.
2252 OutAlternatives.push_back(x: R);
2253
2254 // Increment indices to the next permutation by incrementing the
2255 // indices from last index backward, e.g., generate the sequence
2256 // [0, 0], [0, 1], [1, 0], [1, 1].
2257 int IdxsIdx;
2258 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2259 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2260 Idxs[IdxsIdx] = 0;
2261 else
2262 break;
2263 }
2264 NotDone = (IdxsIdx >= 0);
2265 } while (NotDone);
2266
2267 return;
2268 }
2269
2270 // Otherwise, we found a reference to a fragment. First, look up its
2271 // TreePattern record.
2272 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(R: Op);
2273
2274 // Verify that we are passing the right number of operands.
2275 if (Frag->getNumArgs() != getNumChildren()) {
2276 TP.error(Msg: "'" + Op->getName() + "' fragment requires " +
2277 Twine(Frag->getNumArgs()) + " operands!");
2278 return;
2279 }
2280
2281 TreePredicateFn PredFn(Frag);
2282 unsigned Scope = 0;
2283 if (TreePredicateFn(Frag).usesOperands())
2284 Scope = TP.getDAGPatterns().allocateScope();
2285
2286 // Compute the map of formal to actual arguments.
2287 std::map<StringRef, TreePatternNodePtr> ArgMap;
2288 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
2289 TreePatternNodePtr Child = getChildShared(N: i);
2290 if (Scope != 0) {
2291 Child = Child->clone();
2292 Child->addNameAsPredicateArg(N: ScopedName(Scope, Frag->getArgName(i)));
2293 }
2294 ArgMap[Frag->getArgName(i)] = Child;
2295 }
2296
2297 // Loop over all fragment alternatives.
2298 for (const auto &Alternative : Frag->getTrees()) {
2299 TreePatternNodePtr FragTree = Alternative->clone();
2300
2301 if (!PredFn.isAlwaysTrue())
2302 FragTree->addPredicateCall(Fn: PredFn, Scope);
2303
2304 // Resolve formal arguments to their actual value.
2305 if (Frag->getNumArgs())
2306 FragTree->SubstituteFormalArguments(ArgMap);
2307
2308 // Transfer types. Note that the resolved alternative may have fewer
2309 // (but not more) results than the PatFrags node.
2310 FragTree->setName(getName());
2311 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2312 FragTree->UpdateNodeType(ResNo: i, InTy: getExtType(ResNo: i), TP);
2313
2314 if (Op->isSubClassOf(Name: "GISelFlags"))
2315 FragTree->setGISelFlagsRecord(Op);
2316
2317 // Transfer in the old predicates.
2318 for (const TreePredicateCall &Pred : getPredicateCalls())
2319 FragTree->addPredicateCall(Call: Pred);
2320
2321 // The fragment we inlined could have recursive inlining that is needed. See
2322 // if there are any pattern fragments in it and inline them as needed.
2323 FragTree->InlinePatternFragments(TP, OutAlternatives);
2324 }
2325}
2326
2327/// getImplicitType - Check to see if the specified record has an implicit
2328/// type which should be applied to it. This will infer the type of register
2329/// references from the register file information, for example.
2330///
2331/// When Unnamed is set, return the type of a DAG operand with no name, such as
2332/// the F8RC register class argument in:
2333///
2334/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2335///
2336/// When Unnamed is false, return the type of a named DAG operand such as the
2337/// GPR:$src operand above.
2338///
2339static TypeSetByHwMode getImplicitType(const Record *R, unsigned ResNo,
2340 bool NotRegisters, bool Unnamed,
2341 TreePattern &TP) {
2342 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2343
2344 // Check to see if this is a register operand.
2345 if (R->isSubClassOf(Name: "RegisterOperand")) {
2346 assert(ResNo == 0 && "Regoperand ref only has one result!");
2347 if (NotRegisters)
2348 return TypeSetByHwMode(); // Unknown.
2349 const Record *RegClass = R->getValueAsDef(FieldName: "RegClass");
2350 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2351
2352 if (RegClass->isSubClassOf(Name: "RegClassByHwMode"))
2353 return getTypeForRegClassByHwMode(T, R: RegClass, Loc: TP.getRecord()->getLoc());
2354
2355 return TypeSetByHwMode(T.getRegisterClass(R: RegClass).getValueTypes());
2356 }
2357
2358 // Check to see if this is a register or a register class.
2359 if (R->isSubClassOf(Name: "RegisterClass")) {
2360 assert(ResNo == 0 && "Regclass ref only has one result!");
2361 // An unnamed register class represents itself as an i32 immediate, for
2362 // example on a COPY_TO_REGCLASS instruction.
2363 if (Unnamed)
2364 return TypeSetByHwMode(MVT::i32);
2365
2366 // In a named operand, the register class provides the possible set of
2367 // types.
2368 if (NotRegisters)
2369 return TypeSetByHwMode(); // Unknown.
2370 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2371 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2372 }
2373
2374 if (R->isSubClassOf(Name: "RegClassByHwMode")) {
2375 if (NotRegisters)
2376 return TypeSetByHwMode(); // Unknown.
2377 const CodeGenTarget &T = CDP.getTargetInfo();
2378 return getTypeForRegClassByHwMode(T, R, Loc: TP.getRecord()->getLoc());
2379 }
2380
2381 if (R->isSubClassOf(Name: "PatFrags")) {
2382 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2383 // Pattern fragment types will be resolved when they are inlined.
2384 return TypeSetByHwMode(); // Unknown.
2385 }
2386
2387 if (R->isSubClassOf(Name: "Register")) {
2388 assert(ResNo == 0 && "Registers only produce one result!");
2389 if (NotRegisters)
2390 return TypeSetByHwMode(); // Unknown.
2391 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2392 return TypeSetByHwMode(T.getRegisterVTs(R));
2393 }
2394
2395 if (R->isSubClassOf(Name: "SubRegIndex")) {
2396 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
2397 return TypeSetByHwMode(MVT::i32);
2398 }
2399
2400 if (R->isSubClassOf(Name: "ValueType")) {
2401 assert(ResNo == 0 && "This node only has one result!");
2402 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2403 //
2404 // (sext_inreg GPR:$src, i16)
2405 // ~~~
2406 if (Unnamed)
2407 return TypeSetByHwMode(MVT::Other);
2408 // With a name, the ValueType simply provides the type of the named
2409 // variable.
2410 //
2411 // (sext_inreg i32:$src, i16)
2412 // ~~~~~~~~
2413 if (NotRegisters)
2414 return TypeSetByHwMode(); // Unknown.
2415 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2416 return TypeSetByHwMode(getValueTypeByHwMode(Rec: R, CGH));
2417 }
2418
2419 if (R->isSubClassOf(Name: "CondCode")) {
2420 assert(ResNo == 0 && "This node only has one result!");
2421 // Using a CondCodeSDNode.
2422 return TypeSetByHwMode(MVT::Other);
2423 }
2424
2425 if (R->isSubClassOf(Name: "ComplexPattern")) {
2426 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2427 if (NotRegisters)
2428 return TypeSetByHwMode(); // Unknown.
2429 const Record *T = CDP.getComplexPattern(R).getValueType();
2430 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2431 return TypeSetByHwMode(getValueTypeByHwMode(Rec: T, CGH));
2432 }
2433
2434 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2435 R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
2436 R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
2437 // Placeholder.
2438 return TypeSetByHwMode(); // Unknown.
2439 }
2440
2441 if (R->isSubClassOf(Name: "Operand")) {
2442 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2443 const Record *T = R->getValueAsDef(FieldName: "Type");
2444 return TypeSetByHwMode(getValueTypeByHwMode(Rec: T, CGH));
2445 }
2446
2447 TP.error(Msg: "Unknown node flavor used in pattern: " + R->getName());
2448 return TypeSetByHwMode(MVT::Other);
2449}
2450
2451/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2452/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2453const CodeGenIntrinsic *
2454TreePatternNode::getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2455 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2456 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2457 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2458 return nullptr;
2459
2460 unsigned IID = cast<IntInit>(Val: getChild(N: 0).getLeafValue())->getValue();
2461 return &CDP.getIntrinsicInfo(IID);
2462}
2463
2464/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2465/// return the ComplexPattern information, otherwise return null.
2466const ComplexPattern *
2467TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2468 const Record *Rec;
2469 if (isLeaf()) {
2470 const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue());
2471 if (!DI)
2472 return nullptr;
2473 Rec = DI->getDef();
2474 } else {
2475 Rec = getOperator();
2476 }
2477
2478 if (!Rec->isSubClassOf(Name: "ComplexPattern"))
2479 return nullptr;
2480 return &CGP.getComplexPattern(R: Rec);
2481}
2482
2483unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2484 // A ComplexPattern specifically declares how many results it fills in.
2485 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2486 return CP->getNumOperands();
2487
2488 // If MIOperandInfo is specified, that gives the count.
2489 if (isLeaf()) {
2490 const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue());
2491 if (DI && DI->getDef()->isSubClassOf(Name: "Operand")) {
2492 const DagInit *MIOps = DI->getDef()->getValueAsDag(FieldName: "MIOperandInfo");
2493 if (MIOps->getNumArgs())
2494 return MIOps->getNumArgs();
2495 }
2496 }
2497
2498 // Otherwise there is just one result.
2499 return 1;
2500}
2501
2502/// NodeHasProperty - Return true if this node has the specified property.
2503bool TreePatternNode::NodeHasProperty(SDNP Property,
2504 const CodeGenDAGPatterns &CGP) const {
2505 if (isLeaf()) {
2506 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2507 return CP->hasProperty(Prop: Property);
2508
2509 return false;
2510 }
2511
2512 if (Property != SDNPHasChain) {
2513 // The chain proprety is already present on the different intrinsic node
2514 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2515 // on the intrinsic. Anything else is specific to the individual intrinsic.
2516 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP: CGP))
2517 return Int->hasProperty(Prop: Property);
2518 }
2519
2520 if (!getOperator()->isSubClassOf(Name: "SDPatternOperator"))
2521 return false;
2522
2523 return CGP.getSDNodeInfo(R: getOperator()).hasProperty(Prop: Property);
2524}
2525
2526/// TreeHasProperty - Return true if any node in this tree has the specified
2527/// property.
2528bool TreePatternNode::TreeHasProperty(SDNP Property,
2529 const CodeGenDAGPatterns &CGP) const {
2530 if (NodeHasProperty(Property, CGP))
2531 return true;
2532 for (const TreePatternNode &Child : children())
2533 if (Child.TreeHasProperty(Property, CGP))
2534 return true;
2535 return false;
2536}
2537
2538/// isCommutativeIntrinsic - Return true if the node corresponds to a
2539/// commutative intrinsic.
2540bool TreePatternNode::isCommutativeIntrinsic(
2541 const CodeGenDAGPatterns &CDP) const {
2542 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2543 return Int->isCommutative;
2544 return false;
2545}
2546
2547static bool isOperandClass(const TreePatternNode &N, StringRef Class) {
2548 if (!N.isLeaf())
2549 return N.getOperator()->isSubClassOf(Name: Class);
2550
2551 const DefInit *DI = dyn_cast<DefInit>(Val: N.getLeafValue());
2552 if (DI && DI->getDef()->isSubClassOf(Name: Class))
2553 return true;
2554
2555 return false;
2556}
2557
2558static void emitTooManyOperandsError(TreePattern &TP, StringRef InstName,
2559 unsigned Expected, unsigned Actual) {
2560 TP.error(Msg: "Instruction '" + InstName + "' was provided " + Twine(Actual) +
2561 " operands but expected only " + Twine(Expected) + "!");
2562}
2563
2564static void emitTooFewOperandsError(TreePattern &TP, StringRef InstName,
2565 unsigned Actual) {
2566 TP.error(Msg: "Instruction '" + InstName + "' expects more than the provided " +
2567 Twine(Actual) + " operands!");
2568}
2569
2570/// ApplyTypeConstraints - Apply all of the type constraints relevant to
2571/// this node and its children in the tree. This returns true if it makes a
2572/// change, false otherwise. If a type contradiction is found, flag an error.
2573bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2574 if (TP.hasError())
2575 return false;
2576
2577 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2578 if (isLeaf()) {
2579 if (const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue())) {
2580 // If it's a regclass or something else known, include the type.
2581 bool MadeChange = false;
2582 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2583 MadeChange |= UpdateNodeType(
2584 ResNo: i, InTy: getImplicitType(R: DI->getDef(), ResNo: i, NotRegisters, Unnamed: !hasName(), TP),
2585 TP);
2586 return MadeChange;
2587 }
2588
2589 if (const IntInit *II = dyn_cast<IntInit>(Val: getLeafValue())) {
2590 assert(Types.size() == 1 && "Invalid IntInit");
2591
2592 // Int inits are always integers. :)
2593 bool MadeChange = TP.getInfer().EnforceInteger(Out&: Types[0]);
2594
2595 if (!Types[0].isValueTypeByHwMode(/*AllowEmpty=*/false))
2596 return MadeChange;
2597
2598 ValueTypeByHwMode VVT = Types[0].getValueTypeByHwMode();
2599 for (auto &P : VVT) {
2600 MVT VT = P.second;
2601 // Can only check for types of a known size
2602 if (VT == MVT::iPTR)
2603 continue;
2604
2605 // Check that the value doesn't use more bits than we have. It must
2606 // either be a sign- or zero-extended equivalent of the original.
2607 unsigned Width = VT.getFixedSizeInBits();
2608 int64_t Val = II->getValue();
2609 if (!isIntN(N: Width, x: Val) && !isUIntN(N: Width, x: Val)) {
2610 TP.error(Msg: "Integer value '" + Twine(Val) +
2611 "' is out of range for type '" + getEnumName(T: VT) + "'!");
2612 break;
2613 }
2614 }
2615 return MadeChange;
2616 }
2617
2618 return false;
2619 }
2620
2621 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2622 bool MadeChange = false;
2623
2624 // Apply the result type to the node.
2625 unsigned NumRetVTs = Int->IS.RetTys.size();
2626 unsigned NumParamVTs = Int->IS.ParamTys.size();
2627
2628 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2629 MadeChange |= UpdateNodeType(
2630 ResNo: i, InTy: getValueType(Rec: Int->IS.RetTys[i]->getValueAsDef(FieldName: "VT")), TP);
2631
2632 if (getNumChildren() != NumParamVTs + 1) {
2633 TP.error(Msg: "Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2634 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2635 return false;
2636 }
2637
2638 // Apply type info to the intrinsic ID.
2639 MadeChange |= getChild(N: 0).UpdateNodeType(ResNo: 0, InTy: MVT::iPTR, TP);
2640
2641 for (unsigned i = 0, e = getNumChildren() - 1; i != e; ++i) {
2642 MadeChange |= getChild(N: i + 1).ApplyTypeConstraints(TP, NotRegisters);
2643
2644 MVT OpVT = getValueType(Rec: Int->IS.ParamTys[i]->getValueAsDef(FieldName: "VT"));
2645 assert(getChild(i + 1).getNumTypes() == 1 && "Unhandled case");
2646 MadeChange |= getChild(N: i + 1).UpdateNodeType(ResNo: 0, InTy: OpVT, TP);
2647 }
2648 return MadeChange;
2649 }
2650
2651 if (getOperator()->isSubClassOf(Name: "SDNode")) {
2652 const SDNodeInfo &NI = CDP.getSDNodeInfo(R: getOperator());
2653
2654 // Check that the number of operands is sane. Negative operands -> varargs.
2655 if (NI.getNumOperands() >= 0 &&
2656 getNumChildren() != (unsigned)NI.getNumOperands()) {
2657 TP.error(Msg: getOperator()->getName() + " node requires exactly " +
2658 Twine(NI.getNumOperands()) + " operands!");
2659 return false;
2660 }
2661
2662 bool MadeChange = false;
2663 for (TreePatternNode &Child : children())
2664 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2665 MadeChange |= NI.ApplyTypeConstraints(N&: *this, TP);
2666 return MadeChange;
2667 }
2668
2669 if (getOperator()->isSubClassOf(Name: "Instruction")) {
2670 const DAGInstruction &Inst = CDP.getInstruction(R: getOperator());
2671 const CodeGenInstruction &InstInfo =
2672 CDP.getTargetInfo().getInstruction(InstRec: getOperator());
2673
2674 bool MadeChange = false;
2675
2676 // Apply the result types to the node, these come from the things in the
2677 // (outs) list of the instruction.
2678 unsigned NumResultsToAdd =
2679 std::min(a: InstInfo.Operands.NumDefs, b: Inst.getNumResults());
2680 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2681 MadeChange |= UpdateNodeTypeFromInst(ResNo, Operand: Inst.getResult(RN: ResNo), TP);
2682
2683 // If the instruction has implicit defs, we apply the first one as a result.
2684 // FIXME: This sucks, it should apply all implicit defs.
2685 if (!InstInfo.ImplicitDefs.empty()) {
2686 unsigned ResNo = NumResultsToAdd;
2687
2688 // FIXME: Generalize to multiple possible types and multiple possible
2689 // ImplicitDefs.
2690 MVT VT = InstInfo.HasOneImplicitDefWithKnownVT(TargetInfo: CDP.getTargetInfo());
2691
2692 if (VT != MVT::Other)
2693 MadeChange |= UpdateNodeType(ResNo, InTy: VT, TP);
2694 }
2695
2696 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2697 // be the same.
2698 if (getOperator()->getName() == "INSERT_SUBREG") {
2699 assert(getChild(0).getNumTypes() == 1 && "FIXME: Unhandled");
2700 MadeChange |= UpdateNodeType(ResNo: 0, InTy: getChild(N: 0).getExtType(ResNo: 0), TP);
2701 MadeChange |= getChild(N: 0).UpdateNodeType(ResNo: 0, InTy: getExtType(ResNo: 0), TP);
2702 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2703 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2704 // variadic.
2705
2706 unsigned NChild = getNumChildren();
2707 if (NChild < 3) {
2708 TP.error(Msg: "REG_SEQUENCE requires at least 3 operands!");
2709 return false;
2710 }
2711
2712 if (NChild % 2 == 0) {
2713 TP.error(Msg: "REG_SEQUENCE requires an odd number of operands!");
2714 return false;
2715 }
2716
2717 if (!isOperandClass(N: getChild(N: 0), Class: "RegisterClass")) {
2718 TP.error(Msg: "REG_SEQUENCE requires a RegisterClass for first operand!");
2719 return false;
2720 }
2721
2722 for (unsigned I = 1; I < NChild; I += 2) {
2723 TreePatternNode &SubIdxChild = getChild(N: I + 1);
2724 if (!isOperandClass(N: SubIdxChild, Class: "SubRegIndex")) {
2725 TP.error(Msg: "REG_SEQUENCE requires a SubRegIndex for operand " +
2726 Twine(I + 1) + "!");
2727 return false;
2728 }
2729 }
2730 }
2731
2732 unsigned NumResults = Inst.getNumResults();
2733 unsigned NumFixedOperands = InstInfo.Operands.size();
2734
2735 // If one or more operands with a default value appear at the end of the
2736 // formal operand list for an instruction, we allow them to be overridden
2737 // by optional operands provided in the pattern.
2738 //
2739 // But if an operand B without a default appears at any point after an
2740 // operand A with a default, then we don't allow A to be overridden,
2741 // because there would be no way to specify whether the next operand in
2742 // the pattern was intended to override A or skip it.
2743 unsigned NonOverridableOperands = NumFixedOperands;
2744 while (NonOverridableOperands > NumResults &&
2745 CDP.operandHasDefault(
2746 Op: InstInfo.Operands[NonOverridableOperands - 1].Rec))
2747 --NonOverridableOperands;
2748
2749 unsigned ChildNo = 0;
2750 assert(NumResults <= NumFixedOperands);
2751 for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {
2752 const Record *OperandNode = InstInfo.Operands[i].Rec;
2753
2754 // If the operand has a default value, do we use it? We must use the
2755 // default if we've run out of children of the pattern DAG to consume,
2756 // or if the operand is followed by a non-defaulted one.
2757 if (CDP.operandHasDefault(Op: OperandNode) &&
2758 (i < NonOverridableOperands || ChildNo >= getNumChildren()))
2759 continue;
2760
2761 // If we have run out of child nodes and there _isn't_ a default
2762 // value we can use for the next operand, give an error.
2763 if (ChildNo >= getNumChildren()) {
2764 emitTooFewOperandsError(TP, InstName: getOperator()->getName(), Actual: getNumChildren());
2765 return false;
2766 }
2767
2768 TreePatternNode *Child = &getChild(N: ChildNo++);
2769 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
2770
2771 // If the operand has sub-operands, they may be provided by distinct
2772 // child patterns, so attempt to match each sub-operand separately.
2773 if (OperandNode->isSubClassOf(Name: "Operand")) {
2774 const DagInit *MIOpInfo = OperandNode->getValueAsDag(FieldName: "MIOperandInfo");
2775 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2776 // But don't do that if the whole operand is being provided by
2777 // a single ComplexPattern-related Operand.
2778
2779 if (Child->getNumMIResults(CGP: CDP) < NumArgs) {
2780 // Match first sub-operand against the child we already have.
2781 const Record *SubRec = cast<DefInit>(Val: MIOpInfo->getArg(Num: 0))->getDef();
2782 MadeChange |= Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: SubRec, TP);
2783
2784 // And the remaining sub-operands against subsequent children.
2785 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2786 if (ChildNo >= getNumChildren()) {
2787 emitTooFewOperandsError(TP, InstName: getOperator()->getName(),
2788 Actual: getNumChildren());
2789 return false;
2790 }
2791 Child = &getChild(N: ChildNo++);
2792
2793 SubRec = cast<DefInit>(Val: MIOpInfo->getArg(Num: Arg))->getDef();
2794 MadeChange |=
2795 Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: SubRec, TP);
2796 }
2797 continue;
2798 }
2799 }
2800 }
2801
2802 // If we didn't match by pieces above, attempt to match the whole
2803 // operand now.
2804 MadeChange |= Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: OperandNode, TP);
2805 }
2806
2807 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2808 emitTooManyOperandsError(TP, InstName: getOperator()->getName(), Expected: ChildNo,
2809 Actual: getNumChildren());
2810 return false;
2811 }
2812
2813 for (TreePatternNode &Child : children())
2814 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2815 return MadeChange;
2816 }
2817
2818 if (getOperator()->isSubClassOf(Name: "ComplexPattern")) {
2819 bool MadeChange = false;
2820
2821 if (!NotRegisters) {
2822 assert(Types.size() == 1 && "ComplexPatterns only produce one result!");
2823 const Record *T = CDP.getComplexPattern(R: getOperator()).getValueType();
2824 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2825 const ValueTypeByHwMode VVT = getValueTypeByHwMode(Rec: T, CGH);
2826 // TODO: AArch64 and AMDGPU use ComplexPattern<untyped, ...> and then
2827 // exclusively use those as non-leaf nodes with explicit type casts, so
2828 // for backwards compatibility we do no inference in that case. This is
2829 // not supported when the ComplexPattern is used as a leaf value,
2830 // however; this inconsistency should be resolved, either by adding this
2831 // case there or by altering the backends to not do this (e.g. using Any
2832 // instead may work).
2833 if (!VVT.isSimple() || VVT.getSimple() != MVT::Untyped)
2834 MadeChange |= UpdateNodeType(ResNo: 0, InTy: VVT, TP);
2835 }
2836
2837 for (TreePatternNode &Child : children())
2838 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2839
2840 return MadeChange;
2841 }
2842
2843 if (!getOperator()->isSubClassOf(Name: "SDNodeXForm")) {
2844 TP.error(Msg: "unknown node type '" + getOperator()->getName() +
2845 "' in input pattern");
2846 return false;
2847 }
2848
2849 // Node transforms always take one operand.
2850 if (getNumChildren() != 1) {
2851 TP.error(Msg: "Node transform '" + getOperator()->getName() +
2852 "' requires one operand!");
2853 return false;
2854 }
2855
2856 bool MadeChange = getChild(N: 0).ApplyTypeConstraints(TP, NotRegisters);
2857 return MadeChange;
2858}
2859
2860/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2861/// RHS of a commutative operation, not the on LHS.
2862static bool OnlyOnRHSOfCommutative(const TreePatternNode &N) {
2863 if (!N.isLeaf() && N.getOperator()->getName() == "imm")
2864 return true;
2865 if (N.isLeaf() && isa<IntInit>(Val: N.getLeafValue()))
2866 return true;
2867 if (isImmAllOnesAllZerosMatch(P: N))
2868 return true;
2869 return false;
2870}
2871
2872/// canPatternMatch - If it is impossible for this pattern to match on this
2873/// target, fill in Reason and return false. Otherwise, return true. This is
2874/// used as a sanity check for .td files (to prevent people from writing stuff
2875/// that can never possibly work), and to prevent the pattern permuter from
2876/// generating stuff that is useless.
2877bool TreePatternNode::canPatternMatch(std::string &Reason,
2878 const CodeGenDAGPatterns &CDP) const {
2879 if (isLeaf())
2880 return true;
2881
2882 for (const TreePatternNode &Child : children())
2883 if (!Child.canPatternMatch(Reason, CDP))
2884 return false;
2885
2886 // If this is an intrinsic, handle cases that would make it not match. For
2887 // example, if an operand is required to be an immediate.
2888 if (getOperator()->isSubClassOf(Name: "Intrinsic")) {
2889 // TODO:
2890 return true;
2891 }
2892
2893 if (getOperator()->isSubClassOf(Name: "ComplexPattern"))
2894 return true;
2895
2896 // If this node is a commutative operator, check that the LHS isn't an
2897 // immediate.
2898 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(R: getOperator());
2899 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2900 if (NodeInfo.hasProperty(Prop: SDNPCommutative) || isCommIntrinsic) {
2901 // Scan all of the operands of the node and make sure that only the last one
2902 // is a constant node, unless the RHS also is.
2903 if (!OnlyOnRHSOfCommutative(N: getChild(N: getNumChildren() - 1))) {
2904 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2905 for (unsigned i = Skip, e = getNumChildren() - 1; i != e; ++i)
2906 if (OnlyOnRHSOfCommutative(N: getChild(N: i))) {
2907 Reason =
2908 "Immediate value must be on the RHS of commutative operators!";
2909 return false;
2910 }
2911 }
2912 }
2913
2914 return true;
2915}
2916
2917//===----------------------------------------------------------------------===//
2918// TreePattern implementation
2919//
2920
2921TreePattern::TreePattern(const Record *TheRec, const ListInit *RawPat,
2922 bool isInput, CodeGenDAGPatterns &cdp)
2923 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2924 Infer(*this) {
2925 for (const Init *I : RawPat->getElements()) {
2926 TreePatternNodePtr Node = ParseTreePattern(DI: I, OpName: "");
2927 if (!Node)
2928 return;
2929 Trees.push_back(x: Node);
2930 }
2931}
2932
2933TreePattern::TreePattern(const Record *TheRec, const DagInit *Pat, bool isInput,
2934 CodeGenDAGPatterns &cdp)
2935 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2936 Infer(*this) {
2937 TreePatternNodePtr Node = ParseTreePattern(DI: Pat, OpName: "");
2938 if (!Node)
2939 return;
2940 Trees.push_back(x: Node);
2941}
2942
2943TreePattern::TreePattern(const Record *TheRec, ArrayRef<const Init *> Args,
2944 ArrayRef<const StringInit *> ArgNames, bool isInput,
2945 CodeGenDAGPatterns &cdp)
2946 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2947 Infer(*this) {
2948 Trees.push_back(x: ParseRootlessTreePattern(Args, ArgNames));
2949}
2950
2951TreePattern::TreePattern(const Record *TheRec, TreePatternNodePtr Pat,
2952 bool isInput, CodeGenDAGPatterns &cdp)
2953 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2954 Infer(*this) {
2955 Trees.push_back(x: Pat);
2956}
2957
2958void TreePattern::error(const Twine &Msg) {
2959 if (HasError)
2960 return;
2961 dump();
2962 PrintError(ErrorLoc: TheRecord->getLoc(), Msg: "In " + TheRecord->getName() + ": " + Msg);
2963 HasError = true;
2964}
2965
2966void TreePattern::ComputeNamedNodes() {
2967 for (TreePatternNodePtr &Tree : Trees)
2968 ComputeNamedNodes(N&: *Tree);
2969}
2970
2971void TreePattern::ComputeNamedNodes(TreePatternNode &N) {
2972 if (!N.getName().empty())
2973 NamedNodes[N.getName()].push_back(Elt: &N);
2974
2975 for (TreePatternNode &Child : N.children())
2976 ComputeNamedNodes(N&: Child);
2977}
2978
2979TreePatternNodePtr
2980TreePattern::ParseRootlessTreePattern(ArrayRef<const Init *> Args,
2981 ArrayRef<const StringInit *> ArgNames) {
2982 std::vector<TreePatternNodePtr> Children;
2983
2984 for (auto [Arg, ArgName] : llvm::zip_equal(t&: Args, u&: ArgNames)) {
2985 StringRef NameStr = ArgName ? ArgName->getValue() : "";
2986 Children.push_back(x: ParseTreePattern(DI: Arg, OpName: NameStr));
2987 }
2988
2989 return makeIntrusiveRefCnt<TreePatternNode>(A: nullptr, A: std::move(Children), A: 1);
2990}
2991
2992TreePatternNodePtr TreePattern::ParseTreePattern(const Init *TheInit,
2993 StringRef OpName) {
2994 RecordKeeper &RK = TheInit->getRecordKeeper();
2995 // Here, we are creating new records (BitsInit->InitInit), so const_cast
2996 // TheInit back to non-const pointer.
2997 if (const DefInit *DI = dyn_cast<DefInit>(Val: TheInit)) {
2998 const Record *R = DI->getDef();
2999
3000 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
3001 // TreePatternNode of its own. For example:
3002 /// (foo GPR, imm) -> (foo GPR, (imm))
3003 if (R->isSubClassOf(Name: "SDNode") || R->isSubClassOf(Name: "PatFrags"))
3004 return ParseTreePattern(TheInit: DagInit::get(V: DI, ArgAndNames: {}), OpName);
3005
3006 // Input argument?
3007 TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(A&: DI, A: 1);
3008 if (R->getName() == "node" && !OpName.empty()) {
3009 if (OpName.empty())
3010 error(Msg: "'node' argument requires a name to match with operand list");
3011 Args.push_back(x: OpName.str());
3012 }
3013
3014 Res->setName(OpName);
3015 return Res;
3016 }
3017
3018 // ?:$name or just $name.
3019 if (isa<UnsetInit>(Val: TheInit)) {
3020 if (OpName.empty())
3021 error(Msg: "'?' argument requires a name to match with operand list");
3022 TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(A&: TheInit, A: 1);
3023 Args.push_back(x: OpName.str());
3024 Res->setName(OpName);
3025 return Res;
3026 }
3027
3028 if (isa<IntInit>(Val: TheInit) || isa<BitInit>(Val: TheInit)) {
3029 if (!OpName.empty())
3030 error(Msg: "Constant int or bit argument should not have a name!");
3031 if (isa<BitInit>(Val: TheInit))
3032 TheInit = TheInit->convertInitializerTo(Ty: IntRecTy::get(RK));
3033 return makeIntrusiveRefCnt<TreePatternNode>(A&: TheInit, A: 1);
3034 }
3035
3036 if (const BitsInit *BI = dyn_cast<BitsInit>(Val: TheInit)) {
3037 // Turn this into an IntInit.
3038 const Init *II = BI->convertInitializerTo(Ty: IntRecTy::get(RK));
3039 if (!II || !isa<IntInit>(Val: II))
3040 error(Msg: "Bits value must be constants!");
3041 return II ? ParseTreePattern(TheInit: II, OpName) : nullptr;
3042 }
3043
3044 const DagInit *Dag = dyn_cast<DagInit>(Val: TheInit);
3045 if (!Dag) {
3046 TheInit->print(OS&: errs());
3047 error(Msg: "Pattern has unexpected init kind!");
3048 return nullptr;
3049 }
3050
3051 auto ParseCastOperand = [this](const DagInit *Dag,
3052 StringRef OpName) -> TreePatternNodePtr {
3053 if (Dag->getNumArgs() != 1) {
3054 error(Msg: "Type cast only takes one operand!");
3055 return nullptr;
3056 }
3057
3058 if (!OpName.empty()) {
3059 error(Msg: "Type cast should not have a name!");
3060 return nullptr;
3061 }
3062
3063 return ParseTreePattern(TheInit: Dag->getArg(Num: 0), OpName: Dag->getArgNameStr(Num: 0));
3064 };
3065
3066 if (const ListInit *LI = dyn_cast<ListInit>(Val: Dag->getOperator())) {
3067 // If the operator is a list (of value types), then this must be "type cast"
3068 // of a leaf node with multiple results.
3069 TreePatternNodePtr New = ParseCastOperand(Dag, OpName);
3070 if (!New)
3071 return nullptr;
3072
3073 size_t NumTypes = New->getNumTypes();
3074 if (LI->empty() || LI->size() != NumTypes)
3075 error(Msg: "Invalid number of type casts!");
3076
3077 // Apply the type casts.
3078 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
3079 for (unsigned i = 0; i < std::min(a: NumTypes, b: LI->size()); ++i)
3080 New->UpdateNodeType(
3081 ResNo: i, InTy: getValueTypeByHwMode(Rec: LI->getElementAsRecord(Idx: i), CGH), TP&: *this);
3082
3083 return New;
3084 }
3085
3086 const DefInit *OpDef = dyn_cast<DefInit>(Val: Dag->getOperator());
3087 if (!OpDef) {
3088 error(Msg: "Pattern has unexpected operator type!");
3089 return nullptr;
3090 }
3091 const Record *Operator = OpDef->getDef();
3092
3093 if (Operator->isSubClassOf(Name: "ValueType")) {
3094 // If the operator is a ValueType, then this must be "type cast" of a leaf
3095 // node.
3096 TreePatternNodePtr New = ParseCastOperand(Dag, OpName);
3097 if (!New)
3098 return nullptr;
3099
3100 if (New->getNumTypes() != 1)
3101 error(Msg: "ValueType cast can only have one type!");
3102
3103 // Apply the type cast.
3104 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
3105 New->UpdateNodeType(ResNo: 0, InTy: getValueTypeByHwMode(Rec: Operator, CGH), TP&: *this);
3106
3107 return New;
3108 }
3109
3110 // Verify that this is something that makes sense for an operator.
3111 if (!Operator->isSubClassOf(Name: "PatFrags") &&
3112 !Operator->isSubClassOf(Name: "SDNode") &&
3113 !Operator->isSubClassOf(Name: "Instruction") &&
3114 !Operator->isSubClassOf(Name: "SDNodeXForm") &&
3115 !Operator->isSubClassOf(Name: "Intrinsic") &&
3116 !Operator->isSubClassOf(Name: "ComplexPattern") && Operator->getName() != "set")
3117 error(Msg: "Unrecognized node '" + Operator->getName() + "'!");
3118
3119 // Check to see if this is something that is illegal in an input pattern.
3120 if (isInputPattern) {
3121 if (Operator->isSubClassOf(Name: "Instruction") ||
3122 Operator->isSubClassOf(Name: "SDNodeXForm"))
3123 error(Msg: "Cannot use '" + Operator->getName() + "' in an input pattern!");
3124 } else {
3125 if (Operator->isSubClassOf(Name: "Intrinsic"))
3126 error(Msg: "Cannot use '" + Operator->getName() + "' in an output pattern!");
3127
3128 if (Operator->isSubClassOf(Name: "SDNode") && Operator->getName() != "imm" &&
3129 Operator->getName() != "timm" && Operator->getName() != "fpimm" &&
3130 Operator->getName() != "tglobaltlsaddr" &&
3131 Operator->getName() != "tconstpool" &&
3132 Operator->getName() != "tjumptable" &&
3133 Operator->getName() != "tframeindex" &&
3134 Operator->getName() != "texternalsym" &&
3135 Operator->getName() != "tblockaddress" &&
3136 Operator->getName() != "tglobaladdr" && Operator->getName() != "bb" &&
3137 Operator->getName() != "vt" && Operator->getName() != "mcsym")
3138 error(Msg: "Cannot use '" + Operator->getName() + "' in an output pattern!");
3139 }
3140
3141 std::vector<TreePatternNodePtr> Children;
3142
3143 // Parse all the operands.
3144 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
3145 TreePatternNodePtr Child =
3146 ParseTreePattern(TheInit: Dag->getArg(Num: i), OpName: Dag->getArgNameStr(Num: i));
3147 if (!Child)
3148 return nullptr;
3149 Children.push_back(x: Child);
3150 }
3151
3152 // Get the actual number of results before Operator is converted to an
3153 // intrinsic node (which is hard-coded to have either zero or one result).
3154 unsigned NumResults = GetNumNodeResults(Operator, CDP);
3155
3156 // If the operator is an intrinsic, then this is just syntactic sugar for
3157 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
3158 // convert the intrinsic name to a number.
3159 if (Operator->isSubClassOf(Name: "Intrinsic")) {
3160 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(R: Operator);
3161 unsigned IID = getDAGPatterns().getIntrinsicID(R: Operator) + 1;
3162
3163 // If this intrinsic returns void, it must have side-effects and thus a
3164 // chain.
3165 if (Int.IS.RetTys.empty())
3166 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
3167 else if (!Int.ME.doesNotAccessMemory() || Int.hasSideEffects)
3168 // Has side-effects, requires chain.
3169 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
3170 else // Otherwise, no chain.
3171 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
3172
3173 Children.insert(position: Children.begin(), x: makeIntrusiveRefCnt<TreePatternNode>(
3174 A: IntInit::get(RK, V: IID), A: 1));
3175 }
3176
3177 if (Operator->isSubClassOf(Name: "ComplexPattern")) {
3178 for (unsigned i = 0; i < Children.size(); ++i) {
3179 TreePatternNodePtr Child = Children[i];
3180
3181 if (Child->getName().empty())
3182 error(Msg: "All arguments to a ComplexPattern must be named");
3183
3184 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
3185 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
3186 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
3187 auto OperandId = std::pair(Operator, i);
3188 auto [PrevOp, Inserted] =
3189 ComplexPatternOperands.try_emplace(Key: Child->getName(), Args&: OperandId);
3190 if (!Inserted && PrevOp->getValue() != OperandId) {
3191 error(Msg: "All ComplexPattern operands must appear consistently: "
3192 "in the same order in just one ComplexPattern instance.");
3193 }
3194 }
3195 }
3196
3197 TreePatternNodePtr Result = makeIntrusiveRefCnt<TreePatternNode>(
3198 A&: Operator, A: std::move(Children), A&: NumResults);
3199 Result->setName(OpName);
3200
3201 if (Dag->getName()) {
3202 assert(Result->getName().empty());
3203 Result->setName(Dag->getNameStr());
3204 }
3205 return Result;
3206}
3207
3208/// SimplifyTree - See if we can simplify this tree to eliminate something that
3209/// will never match in favor of something obvious that will. This is here
3210/// strictly as a convenience to target authors because it allows them to write
3211/// more type generic things and have useless type casts fold away.
3212///
3213/// This returns true if any change is made.
3214static bool SimplifyTree(TreePatternNodePtr &N) {
3215 if (N->isLeaf())
3216 return false;
3217
3218 // If we have a bitconvert with a resolved type and if the source and
3219 // destination types are the same, then the bitconvert is useless, remove it.
3220 //
3221 // We make an exception if the types are completely empty. This can come up
3222 // when the pattern being simplified is in the Fragments list of a PatFrags,
3223 // so that the operand is just an untyped "node". In that situation we leave
3224 // bitconverts unsimplified, and simplify them later once the fragment is
3225 // expanded into its true context.
3226 if (N->getOperator()->getName() == "bitconvert" &&
3227 N->getExtType(ResNo: 0).isValueTypeByHwMode(AllowEmpty: false) &&
3228 !N->getExtType(ResNo: 0).empty() &&
3229 N->getExtType(ResNo: 0) == N->getChild(N: 0).getExtType(ResNo: 0) &&
3230 N->getName().empty()) {
3231 if (!N->getPredicateCalls().empty()) {
3232 std::string Str;
3233 raw_string_ostream OS(Str);
3234 OS << *N
3235 << "\n trivial bitconvert node should not have predicate calls\n";
3236 PrintFatalError(Msg: Str);
3237 return false;
3238 }
3239 N = N->getChildShared(N: 0);
3240 SimplifyTree(N);
3241 return true;
3242 }
3243
3244 // Walk all children.
3245 bool MadeChange = false;
3246 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3247 MadeChange |= SimplifyTree(N&: N->getChildSharedPtr(N: i));
3248
3249 return MadeChange;
3250}
3251
3252/// InferAllTypes - Infer/propagate as many types throughout the expression
3253/// patterns as possible. Return true if all types are inferred, false
3254/// otherwise. Flags an error if a type contradiction is found.
3255bool TreePattern::InferAllTypes(
3256 const StringMap<SmallVector<TreePatternNode *, 1>> *InNamedTypes) {
3257 if (NamedNodes.empty())
3258 ComputeNamedNodes();
3259
3260 bool MadeChange = true;
3261 while (MadeChange) {
3262 MadeChange = false;
3263 for (TreePatternNodePtr &Tree : Trees) {
3264 MadeChange |= Tree->ApplyTypeConstraints(TP&: *this, NotRegisters: false);
3265 MadeChange |= SimplifyTree(N&: Tree);
3266 }
3267
3268 // If there are constraints on our named nodes, apply them.
3269 for (auto &Entry : NamedNodes) {
3270 SmallVectorImpl<TreePatternNode *> &Nodes = Entry.second;
3271
3272 // If we have input named node types, propagate their types to the named
3273 // values here.
3274 if (InNamedTypes) {
3275 auto InIter = InNamedTypes->find(Key: Entry.getKey());
3276 if (InIter == InNamedTypes->end()) {
3277 error(Msg: "Node '" + Entry.getKey().str() +
3278 "' in output pattern but not input pattern");
3279 return true;
3280 }
3281
3282 ArrayRef<TreePatternNode *> InNodes = InIter->second;
3283
3284 // The input types should be fully resolved by now.
3285 for (TreePatternNode *Node : Nodes) {
3286 // If this node is a register class, and it is the root of the pattern
3287 // then we're mapping something onto an input register. We allow
3288 // changing the type of the input register in this case. This allows
3289 // us to match things like:
3290 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
3291 if (Node == Trees[0].get() && Node->isLeaf()) {
3292 const DefInit *DI = dyn_cast<DefInit>(Val: Node->getLeafValue());
3293 if (DI && (DI->getDef()->isSubClassOf(Name: "RegisterClass") ||
3294 DI->getDef()->isSubClassOf(Name: "RegisterOperand")))
3295 continue;
3296 }
3297
3298 assert(Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 &&
3299 "FIXME: cannot name multiple result nodes yet");
3300 MadeChange |=
3301 Node->UpdateNodeType(ResNo: 0, InTy: InNodes[0]->getExtType(ResNo: 0), TP&: *this);
3302 }
3303 }
3304
3305 // If there are multiple nodes with the same name, they must all have the
3306 // same type.
3307 if (Entry.second.size() > 1) {
3308 for (unsigned i = 0, e = Nodes.size() - 1; i != e; ++i) {
3309 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i + 1];
3310 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
3311 "FIXME: cannot name multiple result nodes yet");
3312
3313 MadeChange |= N1->UpdateNodeType(ResNo: 0, InTy: N2->getExtType(ResNo: 0), TP&: *this);
3314 MadeChange |= N2->UpdateNodeType(ResNo: 0, InTy: N1->getExtType(ResNo: 0), TP&: *this);
3315 }
3316 }
3317 }
3318 }
3319
3320 bool HasUnresolvedTypes = false;
3321 for (const TreePatternNodePtr &Tree : Trees)
3322 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(TP&: *this);
3323 return !HasUnresolvedTypes;
3324}
3325
3326void TreePattern::print(raw_ostream &OS) const {
3327 OS << getRecord()->getName();
3328 if (!Args.empty())
3329 OS << '(' << llvm::interleaved(R: Args) << ')';
3330 OS << ": ";
3331
3332 if (Trees.size() > 1)
3333 OS << "[\n";
3334 for (const TreePatternNodePtr &Tree : Trees) {
3335 OS << "\t";
3336 Tree->print(OS);
3337 OS << "\n";
3338 }
3339
3340 if (Trees.size() > 1)
3341 OS << "]\n";
3342}
3343
3344void TreePattern::dump() const { print(OS&: errs()); }
3345
3346//===----------------------------------------------------------------------===//
3347// CodeGenDAGPatterns implementation
3348//
3349
3350CodeGenDAGPatterns::CodeGenDAGPatterns(const RecordKeeper &R, bool ExpandHwMode)
3351 : Records(R), Target(R), Intrinsics(R),
3352 LegalVTS(Target.getLegalValueTypes()),
3353 LegalPtrVTS(ComputeLegalPtrTypes()) {
3354 ParseNodeInfo();
3355 ParseNodeTransforms();
3356 ParseComplexPatterns();
3357 ParsePatternFragments();
3358 ParseDefaultOperands();
3359 ParseInstructions();
3360 ParsePatternFragments(/*OutFrags*/ true);
3361 ParsePatterns();
3362
3363 // Generate variants. For example, commutative patterns can match
3364 // multiple ways. Add them to PatternsToMatch as well.
3365 GenerateVariants();
3366
3367 // Break patterns with parameterized types into a series of patterns,
3368 // where each one has a fixed type and is predicated on the conditions
3369 // of the associated HW mode.
3370 if (ExpandHwMode)
3371 ExpandHwModeBasedTypes();
3372
3373 // Infer instruction flags. For example, we can detect loads,
3374 // stores, and side effects in many cases by examining an
3375 // instruction's pattern.
3376 InferInstructionFlags();
3377
3378 // Verify that instruction flags match the patterns.
3379 VerifyInstructionFlags();
3380}
3381
3382const Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {
3383 const Record *N = Records.getDef(Name);
3384 if (!N || !N->isSubClassOf(Name: "SDNode"))
3385 PrintFatalError(Msg: "Error getting SDNode '" + Name + "'!");
3386 return N;
3387}
3388
3389// Compute the subset of iPTR and cPTR legal for each mode, coalescing into the
3390// default mode where possible to avoid predicate explosion.
3391TypeSetByHwMode CodeGenDAGPatterns::ComputeLegalPtrTypes() const {
3392 auto LegalPtrsForSet = [](const MachineValueTypeSet &In) {
3393 MachineValueTypeSet Out;
3394 Out.insert(T: MVT::iPTR);
3395 for (MVT T : MVT::cheri_capability_valuetypes()) {
3396 if (In.count(T)) {
3397 Out.insert(T: MVT::cPTR);
3398 break;
3399 }
3400 }
3401 return Out;
3402 };
3403
3404 const TypeSetByHwMode &LegalTypes = getLegalTypes();
3405 MachineValueTypeSet LegalPtrsDefault =
3406 LegalPtrsForSet(LegalTypes.get(Mode: DefaultMode));
3407
3408 TypeSetByHwMode LegalPtrTypes;
3409 for (const auto &I : LegalTypes) {
3410 MachineValueTypeSet S = LegalPtrsForSet(I.second);
3411 if (I.first != DefaultMode && S == LegalPtrsDefault)
3412 continue;
3413 LegalPtrTypes.getOrCreate(Mode: I.first).insert(S);
3414 }
3415
3416 return LegalPtrTypes;
3417}
3418
3419// Parse all of the SDNode definitions for the target, populating SDNodes.
3420void CodeGenDAGPatterns::ParseNodeInfo() {
3421 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3422
3423 for (const Record *R : reverse(C: Records.getAllDerivedDefinitions(ClassName: "SDNode")))
3424 SDNodes.try_emplace(k: R, args: SDNodeInfo(R, CGH));
3425
3426 // Get the builtin intrinsic nodes.
3427 intrinsic_void_sdnode = getSDNodeNamed(Name: "intrinsic_void");
3428 intrinsic_w_chain_sdnode = getSDNodeNamed(Name: "intrinsic_w_chain");
3429 intrinsic_wo_chain_sdnode = getSDNodeNamed(Name: "intrinsic_wo_chain");
3430}
3431
3432/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3433/// map, and emit them to the file as functions.
3434void CodeGenDAGPatterns::ParseNodeTransforms() {
3435 for (const Record *XFormNode :
3436 reverse(C: Records.getAllDerivedDefinitions(ClassName: "SDNodeXForm"))) {
3437 const Record *SDNode = XFormNode->getValueAsDef(FieldName: "Opcode");
3438 StringRef Code = XFormNode->getValueAsString(FieldName: "XFormFunction");
3439 SDNodeXForms.try_emplace(k: XFormNode, args: NodeXForm(SDNode, Code.str()));
3440 }
3441}
3442
3443void CodeGenDAGPatterns::ParseComplexPatterns() {
3444 for (const Record *R :
3445 reverse(C: Records.getAllDerivedDefinitions(ClassName: "ComplexPattern")))
3446 ComplexPatterns.try_emplace(k: R, args&: R);
3447}
3448
3449/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3450/// file, building up the PatternFragments map. After we've collected them all,
3451/// inline fragments together as necessary, so that there are no references left
3452/// inside a pattern fragment to a pattern fragment.
3453///
3454void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
3455 // First step, parse all of the fragments.
3456 ArrayRef<const Record *> Fragments =
3457 Records.getAllDerivedDefinitions(ClassName: "PatFrags");
3458 for (const Record *Frag : Fragments) {
3459 if (OutFrags != Frag->isSubClassOf(Name: "OutPatFrag"))
3460 continue;
3461
3462 const ListInit *LI = Frag->getValueAsListInit(FieldName: "Fragments");
3463 TreePattern *P = (PatternFragments[Frag] = std::make_unique<TreePattern>(
3464 args&: Frag, args&: LI, args: !Frag->isSubClassOf(Name: "OutPatFrag"), args&: *this))
3465 .get();
3466
3467 // Validate the argument list, converting it to set, to discard duplicates.
3468 std::vector<std::string> &Args = P->getArgList();
3469 // Copy the args so we can take StringRefs to them.
3470 auto ArgsCopy = Args;
3471 SmallDenseSet<StringRef, 4> OperandsSet(llvm::from_range, ArgsCopy);
3472
3473 if (OperandsSet.contains(V: ""))
3474 P->error(Msg: "Cannot have unnamed 'node' values in pattern fragment!");
3475
3476 // Parse the operands list.
3477 const DagInit *OpsList = Frag->getValueAsDag(FieldName: "Operands");
3478 const DefInit *OpsOp = dyn_cast<DefInit>(Val: OpsList->getOperator());
3479 // Special cases: ops == outs == ins. Different names are used to
3480 // improve readability.
3481 if (!OpsOp || (OpsOp->getDef()->getName() != "ops" &&
3482 OpsOp->getDef()->getName() != "outs" &&
3483 OpsOp->getDef()->getName() != "ins"))
3484 P->error(Msg: "Operands list should start with '(ops ... '!");
3485
3486 // Copy over the arguments.
3487 Args.clear();
3488 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
3489 if (!isa<DefInit>(Val: OpsList->getArg(Num: j)) ||
3490 cast<DefInit>(Val: OpsList->getArg(Num: j))->getDef()->getName() != "node")
3491 P->error(Msg: "Operands list should all be 'node' values.");
3492 if (!OpsList->getArgName(Num: j))
3493 P->error(Msg: "Operands list should have names for each operand!");
3494 StringRef ArgNameStr = OpsList->getArgNameStr(Num: j);
3495 if (!OperandsSet.erase(V: ArgNameStr))
3496 P->error(Msg: "'" + ArgNameStr +
3497 "' does not occur in pattern or was multiply specified!");
3498 Args.push_back(x: ArgNameStr.str());
3499 }
3500
3501 if (!OperandsSet.empty())
3502 P->error(Msg: "Operands list does not contain an entry for operand '" +
3503 *OperandsSet.begin() + "'!");
3504
3505 // If there is a node transformation corresponding to this, keep track of
3506 // it.
3507 const Record *Transform = Frag->getValueAsDef(FieldName: "OperandTransform");
3508 if (!getSDNodeTransform(R: Transform).second.empty()) // not noop xform?
3509 for (const auto &T : P->getTrees())
3510 T->setTransformFn(Transform);
3511 }
3512
3513 // Now that we've parsed all of the tree fragments, do a closure on them so
3514 // that there are not references to PatFrags left inside of them.
3515 for (const Record *Frag : Fragments) {
3516 if (OutFrags != Frag->isSubClassOf(Name: "OutPatFrag"))
3517 continue;
3518
3519 TreePattern &ThePat = *PatternFragments[Frag];
3520 ThePat.InlinePatternFragments();
3521
3522 // Infer as many types as possible. Don't worry about it if we don't infer
3523 // all of them, some may depend on the inputs of the pattern. Also, don't
3524 // validate type sets; validation may cause spurious failures e.g. if a
3525 // fragment needs floating-point types but the current target does not have
3526 // any (this is only an error if that fragment is ever used!).
3527 {
3528 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3529 ThePat.InferAllTypes();
3530 ThePat.resetError();
3531 }
3532
3533 // If debugging, print out the pattern fragment result.
3534 LLVM_DEBUG(ThePat.dump());
3535 }
3536}
3537
3538void CodeGenDAGPatterns::ParseDefaultOperands() {
3539 ArrayRef<const Record *> DefaultOps =
3540 Records.getAllDerivedDefinitions(ClassName: "OperandWithDefaultOps");
3541
3542 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3543 const DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag(FieldName: "DefaultOps");
3544
3545 // Create a TreePattern to parse this.
3546 TreePattern P(DefaultOps[i], DefaultInfo->getArgs(),
3547 DefaultInfo->getArgNames(), false, *this);
3548 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3549
3550 // Copy the operands over into a DAGDefaultOperand.
3551 DAGDefaultOperand DefaultOpInfo;
3552
3553 const TreePatternNodePtr &T = P.getTree(i: 0);
3554 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3555 TreePatternNodePtr TPN = T->getChildShared(N: op);
3556 while (TPN->ApplyTypeConstraints(TP&: P, NotRegisters: false))
3557 /* Resolve all types */;
3558
3559 if (TPN->ContainsUnresolvedType(TP&: P)) {
3560 PrintFatalError(Msg: "Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3561 DefaultOps[i]->getName() +
3562 "' doesn't have a concrete type!");
3563 }
3564 DefaultOpInfo.DefaultOps.push_back(x: std::move(TPN));
3565 }
3566
3567 // Insert it into the DefaultOperands map so we can find it later.
3568 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3569 }
3570}
3571
3572/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3573/// instruction input. Return true if this is a real use.
3574static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3575 std::map<StringRef, TreePatternNodePtr> &InstInputs) {
3576 // No name -> not interesting.
3577 if (Pat->getName().empty()) {
3578 if (Pat->isLeaf()) {
3579 const DefInit *DI = dyn_cast<DefInit>(Val: Pat->getLeafValue());
3580 if (DI && (DI->getDef()->isSubClassOf(Name: "RegisterClass") ||
3581 DI->getDef()->isSubClassOf(Name: "RegisterOperand")))
3582 I.error(Msg: "Input " + DI->getDef()->getName() + " must be named!");
3583 }
3584 return false;
3585 }
3586
3587 const Record *Rec;
3588 if (Pat->isLeaf()) {
3589 const DefInit *DI = dyn_cast<DefInit>(Val: Pat->getLeafValue());
3590 if (!DI) {
3591 I.error(Msg: "Input $" + Pat->getName() + " must be an identifier!");
3592 return false;
3593 }
3594 Rec = DI->getDef();
3595 } else {
3596 Rec = Pat->getOperator();
3597 }
3598
3599 // SRCVALUE nodes are ignored.
3600 if (Rec->getName() == "srcvalue")
3601 return false;
3602
3603 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3604 if (!Slot) {
3605 Slot = Pat;
3606 return true;
3607 }
3608 const Record *SlotRec;
3609 if (Slot->isLeaf()) {
3610 SlotRec = cast<DefInit>(Val: Slot->getLeafValue())->getDef();
3611 } else {
3612 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3613 SlotRec = Slot->getOperator();
3614 }
3615
3616 // Ensure that the inputs agree if we've already seen this input.
3617 if (Rec != SlotRec)
3618 I.error(Msg: "All $" + Pat->getName() + " inputs must agree with each other");
3619 // Ensure that the types can agree as well.
3620 Slot->UpdateNodeType(ResNo: 0, InTy: Pat->getExtType(ResNo: 0), TP&: I);
3621 Pat->UpdateNodeType(ResNo: 0, InTy: Slot->getExtType(ResNo: 0), TP&: I);
3622 if (Slot->getExtTypes() != Pat->getExtTypes())
3623 I.error(Msg: "All $" + Pat->getName() + " inputs must agree with each other");
3624 return true;
3625}
3626
3627/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3628/// part of "I", the instruction), computing the set of inputs and outputs of
3629/// the pattern. Report errors if we see anything naughty.
3630void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3631 TreePattern &I, TreePatternNodePtr Pat, InstInputsTy &InstInputs,
3632 InstResultsTy &InstResults, std::vector<const Record *> &InstImpResults) {
3633 // The instruction pattern still has unresolved fragments. For *named*
3634 // nodes we must resolve those here. This may not result in multiple
3635 // alternatives.
3636 if (!Pat->getName().empty()) {
3637 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3638 SrcPattern.InlinePatternFragments();
3639 SrcPattern.InferAllTypes();
3640 Pat = SrcPattern.getOnlyTree();
3641 }
3642
3643 if (Pat->isLeaf()) {
3644 bool isUse = HandleUse(I, Pat, InstInputs);
3645 if (!isUse && Pat->getTransformFn())
3646 I.error(Msg: "Cannot specify a transform function for a non-input value!");
3647 return;
3648 }
3649
3650 if (Pat->getOperator()->getName() != "set") {
3651 // If this is not a set, verify that the children nodes are not void typed,
3652 // and recurse.
3653 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3654 if (Pat->getChild(N: i).getNumTypes() == 0)
3655 I.error(Msg: "Cannot have void nodes inside of patterns!");
3656 FindPatternInputsAndOutputs(I, Pat: Pat->getChildShared(N: i), InstInputs,
3657 InstResults, InstImpResults);
3658 }
3659
3660 // If this is a non-leaf node with no children, treat it basically as if
3661 // it were a leaf. This handles nodes like (imm).
3662 bool isUse = HandleUse(I, Pat, InstInputs);
3663
3664 if (!isUse && Pat->getTransformFn())
3665 I.error(Msg: "Cannot specify a transform function for a non-input value!");
3666 return;
3667 }
3668
3669 // Otherwise, this is a set, validate and collect instruction results.
3670 if (Pat->getNumChildren() == 0)
3671 I.error(Msg: "set requires operands!");
3672
3673 if (Pat->getTransformFn())
3674 I.error(Msg: "Cannot specify a transform function on a set node!");
3675
3676 // Check the set destinations.
3677 unsigned NumDests = Pat->getNumChildren() - 1;
3678 for (unsigned i = 0; i != NumDests; ++i) {
3679 TreePatternNodePtr Dest = Pat->getChildShared(N: i);
3680 // For set destinations we also must resolve fragments here.
3681 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3682 DestPattern.InlinePatternFragments();
3683 DestPattern.InferAllTypes();
3684 Dest = DestPattern.getOnlyTree();
3685
3686 if (!Dest->isLeaf())
3687 I.error(Msg: "set destination should be a register!");
3688
3689 const DefInit *Val = dyn_cast<DefInit>(Val: Dest->getLeafValue());
3690 if (!Val) {
3691 I.error(Msg: "set destination should be a register!");
3692 continue;
3693 }
3694
3695 if (Val->getDef()->isSubClassOf(Name: "RegisterClassLike") ||
3696 Val->getDef()->isSubClassOf(Name: "ValueType") ||
3697 Val->getDef()->isSubClassOf(Name: "RegisterOperand")) {
3698 if (Dest->getName().empty())
3699 I.error(Msg: "set destination must have a name!");
3700 if (!InstResults.insert_or_assign(Key: Dest->getName(), Val&: Dest).second)
3701 I.error(Msg: "cannot set '" + Dest->getName() + "' multiple times");
3702 } else if (Val->getDef()->isSubClassOf(Name: "Register")) {
3703 InstImpResults.push_back(x: Val->getDef());
3704 } else {
3705 I.error(Msg: "set destination should be a register!");
3706 }
3707 }
3708
3709 // Verify and collect info from the computation.
3710 FindPatternInputsAndOutputs(I, Pat: Pat->getChildShared(N: NumDests), InstInputs,
3711 InstResults, InstImpResults);
3712}
3713
3714//===----------------------------------------------------------------------===//
3715// Instruction Analysis
3716//===----------------------------------------------------------------------===//
3717
3718class InstAnalyzer {
3719 const CodeGenDAGPatterns &CDP;
3720
3721public:
3722 bool hasSideEffects = false;
3723 bool mayStore = false;
3724 bool mayLoad = false;
3725 bool isBitcast = false;
3726 bool isVariadic = false;
3727 bool hasChain = false;
3728
3729 InstAnalyzer(const CodeGenDAGPatterns &cdp) : CDP(cdp) {}
3730
3731 void Analyze(const PatternToMatch &Pat) {
3732 const TreePatternNode &N = Pat.getSrcPattern();
3733 AnalyzeNode(N);
3734 // These properties are detected only on the root node.
3735 isBitcast = IsNodeBitcast(N);
3736 }
3737
3738private:
3739 bool IsNodeBitcast(const TreePatternNode &N) const {
3740 if (hasSideEffects || mayLoad || mayStore || isVariadic)
3741 return false;
3742
3743 if (N.isLeaf())
3744 return false;
3745 if (N.getNumChildren() != 1 || !N.getChild(N: 0).isLeaf())
3746 return false;
3747
3748 if (N.getOperator()->isSubClassOf(Name: "ComplexPattern"))
3749 return false;
3750
3751 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(R: N.getOperator());
3752 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3753 return false;
3754 return OpInfo.getEnumName() == "ISD::BITCAST";
3755 }
3756
3757public:
3758 void AnalyzeNode(const TreePatternNode &N) {
3759 if (N.isLeaf()) {
3760 if (const DefInit *DI = dyn_cast<DefInit>(Val: N.getLeafValue())) {
3761 const Record *LeafRec = DI->getDef();
3762 // Handle ComplexPattern leaves.
3763 if (LeafRec->isSubClassOf(Name: "ComplexPattern")) {
3764 const ComplexPattern &CP = CDP.getComplexPattern(R: LeafRec);
3765 if (CP.hasProperty(Prop: SDNPMayStore))
3766 mayStore = true;
3767 if (CP.hasProperty(Prop: SDNPMayLoad))
3768 mayLoad = true;
3769 if (CP.hasProperty(Prop: SDNPSideEffect))
3770 hasSideEffects = true;
3771 }
3772 }
3773 return;
3774 }
3775
3776 // Analyze children.
3777 for (const TreePatternNode &Child : N.children())
3778 AnalyzeNode(N: Child);
3779
3780 // Notice properties of the node.
3781 if (N.NodeHasProperty(Property: SDNPMayStore, CGP: CDP))
3782 mayStore = true;
3783 if (N.NodeHasProperty(Property: SDNPMayLoad, CGP: CDP))
3784 mayLoad = true;
3785 if (N.NodeHasProperty(Property: SDNPSideEffect, CGP: CDP))
3786 hasSideEffects = true;
3787 if (N.NodeHasProperty(Property: SDNPVariadic, CGP: CDP))
3788 isVariadic = true;
3789 if (N.NodeHasProperty(Property: SDNPHasChain, CGP: CDP))
3790 hasChain = true;
3791
3792 if (const CodeGenIntrinsic *IntInfo = N.getIntrinsicInfo(CDP)) {
3793 ModRefInfo MR = IntInfo->ME.getModRef();
3794 // If this is an intrinsic, analyze it.
3795 if (isRefSet(MRI: MR))
3796 mayLoad = true; // These may load memory.
3797
3798 if (isModSet(MRI: MR))
3799 mayStore = true; // Intrinsics that can write to memory are 'mayStore'.
3800
3801 // Consider intrinsics that don't specify any restrictions on memory
3802 // effects as having a side-effect.
3803 if (IntInfo->ME == MemoryEffects::unknown() || IntInfo->hasSideEffects)
3804 hasSideEffects = true;
3805 }
3806 }
3807};
3808
3809static bool InferFromPattern(CodeGenInstruction &InstInfo,
3810 const InstAnalyzer &PatInfo,
3811 const Record *PatDef) {
3812 bool Error = false;
3813
3814 // Remember where InstInfo got its flags.
3815 if (InstInfo.hasUndefFlags())
3816 InstInfo.InferredFrom = PatDef;
3817
3818 // Check explicitly set flags for consistency.
3819 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3820 !InstInfo.hasSideEffects_Unset) {
3821 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3822 // the pattern has no side effects. That could be useful for div/rem
3823 // instructions that may trap.
3824 if (!InstInfo.hasSideEffects) {
3825 Error = true;
3826 PrintError(ErrorLoc: PatDef->getLoc(), Msg: "Pattern doesn't match hasSideEffects = " +
3827 Twine(InstInfo.hasSideEffects));
3828 }
3829 }
3830
3831 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3832 Error = true;
3833 PrintError(ErrorLoc: PatDef->getLoc(),
3834 Msg: "Pattern doesn't match mayStore = " + Twine(InstInfo.mayStore));
3835 }
3836
3837 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3838 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3839 // Some targets translate immediates to loads.
3840 if (!InstInfo.mayLoad) {
3841 Error = true;
3842 PrintError(ErrorLoc: PatDef->getLoc(),
3843 Msg: "Pattern doesn't match mayLoad = " + Twine(InstInfo.mayLoad));
3844 }
3845 }
3846
3847 // Transfer inferred flags.
3848 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3849 InstInfo.mayStore |= PatInfo.mayStore;
3850 InstInfo.mayLoad |= PatInfo.mayLoad;
3851
3852 // These flags are silently added without any verification.
3853 // FIXME: To match historical behavior of TableGen, for now add those flags
3854 // only when we're inferring from the primary instruction pattern.
3855 if (PatDef->isSubClassOf(Name: "Instruction")) {
3856 InstInfo.isBitcast |= PatInfo.isBitcast;
3857 InstInfo.hasChain |= PatInfo.hasChain;
3858 InstInfo.hasChain_Inferred = true;
3859 }
3860
3861 // Don't infer isVariadic. This flag means something different on SDNodes and
3862 // instructions. For example, a CALL SDNode is variadic because it has the
3863 // call arguments as operands, but a CALL instruction is not variadic - it
3864 // has argument registers as implicit, not explicit uses.
3865
3866 return Error;
3867}
3868
3869/// hasNullFragReference - Return true if the DAG has any reference to the
3870/// null_frag operator.
3871static bool hasNullFragReference(const DagInit *DI) {
3872 const DefInit *OpDef = dyn_cast<DefInit>(Val: DI->getOperator());
3873 if (!OpDef)
3874 return false;
3875 const Record *Operator = OpDef->getDef();
3876
3877 // If this is the null fragment, return true.
3878 if (Operator->getName() == "null_frag")
3879 return true;
3880 // If any of the arguments reference the null fragment, return true.
3881 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3882 if (auto Arg = dyn_cast<DefInit>(Val: DI->getArg(Num: i)))
3883 if (Arg->getDef()->getName() == "null_frag")
3884 return true;
3885 const DagInit *Arg = dyn_cast<DagInit>(Val: DI->getArg(Num: i));
3886 if (Arg && hasNullFragReference(DI: Arg))
3887 return true;
3888 }
3889
3890 return false;
3891}
3892
3893/// hasNullFragReference - Return true if any DAG in the list references
3894/// the null_frag operator.
3895static bool hasNullFragReference(const ListInit *LI) {
3896 for (const Init *I : LI->getElements()) {
3897 const DagInit *DI = dyn_cast<DagInit>(Val: I);
3898 assert(DI && "non-dag in an instruction Pattern list?!");
3899 if (hasNullFragReference(DI))
3900 return true;
3901 }
3902 return false;
3903}
3904
3905/// Get all the instructions in a tree.
3906static void getInstructionsInTree(TreePatternNode &Tree,
3907 SmallVectorImpl<const Record *> &Instrs) {
3908 if (Tree.isLeaf())
3909 return;
3910 if (Tree.getOperator()->isSubClassOf(Name: "Instruction"))
3911 Instrs.push_back(Elt: Tree.getOperator());
3912 for (TreePatternNode &Child : Tree.children())
3913 getInstructionsInTree(Tree&: Child, Instrs);
3914}
3915
3916/// Check the class of a pattern leaf node against the instruction operand it
3917/// represents.
3918static bool checkOperandClass(const CGIOperandList::OperandInfo &OI,
3919 const Record *Leaf) {
3920 if (OI.Rec == Leaf)
3921 return true;
3922
3923 // Allow direct value types to be used in instruction set patterns.
3924 // The type will be checked later.
3925 if (Leaf->isSubClassOf(Name: "ValueType"))
3926 return true;
3927
3928 // Patterns can also be ComplexPattern instances.
3929 if (Leaf->isSubClassOf(Name: "ComplexPattern"))
3930 return true;
3931
3932 return false;
3933}
3934
3935void CodeGenDAGPatterns::parseInstructionPattern(const CodeGenInstruction &CGI,
3936 const ListInit *Pat,
3937 DAGInstMap &DAGInsts) {
3938
3939 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3940
3941 // Parse the instruction.
3942 TreePattern I(CGI.TheDef, Pat, true, *this);
3943
3944 // InstInputs - Keep track of all of the inputs of the instruction, along
3945 // with the record they are declared as.
3946 std::map<StringRef, TreePatternNodePtr> InstInputs;
3947
3948 // InstResults - Keep track of all the virtual registers that are 'set'
3949 // in the instruction, including what reg class they are.
3950 MapVector<StringRef, TreePatternNodePtr, std::map<StringRef, unsigned>>
3951 InstResults;
3952
3953 std::vector<const Record *> InstImpResults;
3954
3955 // Verify that the top-level forms in the instruction are of void type, and
3956 // fill in the InstResults map.
3957 SmallString<32> TypesString;
3958 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3959 TypesString.clear();
3960 TreePatternNodePtr Pat = I.getTree(i: j);
3961 if (Pat->getNumTypes() != 0) {
3962 raw_svector_ostream OS(TypesString);
3963 ListSeparator LS;
3964 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3965 OS << LS;
3966 Pat->getExtType(ResNo: k).writeToStream(OS);
3967 }
3968 I.error(Msg: "Top-level forms in instruction pattern should have"
3969 " void types, has types " +
3970 OS.str());
3971 }
3972
3973 // Find inputs and outputs, and verify the structure of the uses/defs.
3974 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3975 InstImpResults);
3976 }
3977
3978 // Now that we have inputs and outputs of the pattern, inspect the operands
3979 // list for the instruction. This determines the order that operands are
3980 // added to the machine instruction the node corresponds to.
3981 unsigned NumResults = InstResults.size();
3982
3983 // Parse the operands list from the (ops) list, validating it.
3984 assert(I.getArgList().empty() && "Args list should still be empty here!");
3985
3986 // Check that all of the results occur first in the list.
3987 std::vector<const Record *> Results;
3988 std::vector<unsigned> ResultIndices;
3989 SmallVector<TreePatternNodePtr, 2> ResNodes;
3990 for (unsigned i = 0; i != NumResults; ++i) {
3991 if (i == CGI.Operands.size()) {
3992 StringRef OpName =
3993 llvm::find_if(Range&: InstResults,
3994 P: [](const std::pair<StringRef, TreePatternNodePtr> &P) {
3995 return P.second;
3996 })
3997 ->first;
3998
3999 I.error(Msg: "'" + OpName + "' set but does not appear in operand list!");
4000 }
4001
4002 StringRef OpName = CGI.Operands[i].Name;
4003
4004 // Check that it exists in InstResults.
4005 auto InstResultIter = InstResults.find(Key: OpName);
4006 if (InstResultIter == InstResults.end() || !InstResultIter->second)
4007 I.error(Msg: "Operand $" + OpName + " does not exist in operand list!");
4008
4009 TreePatternNodePtr RNode = InstResultIter->second;
4010 const Record *R = cast<DefInit>(Val: RNode->getLeafValue())->getDef();
4011 ResNodes.push_back(Elt: std::move(RNode));
4012 if (!R)
4013 I.error(Msg: "Operand $" + OpName +
4014 " should be a set destination: all "
4015 "outputs must occur before inputs in operand list!");
4016
4017 if (!checkOperandClass(OI: CGI.Operands[i], Leaf: R))
4018 I.error(Msg: "Operand $" + OpName + " class mismatch!");
4019
4020 // Remember the return type.
4021 Results.push_back(x: CGI.Operands[i].Rec);
4022
4023 // Remember the result index.
4024 ResultIndices.push_back(x: std::distance(first: InstResults.begin(), last: InstResultIter));
4025
4026 // Okay, this one checks out.
4027 InstResultIter->second = nullptr;
4028 }
4029
4030 // Loop over the inputs next.
4031 std::vector<TreePatternNodePtr> ResultNodeOperands;
4032 std::vector<const Record *> Operands;
4033 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
4034 const CGIOperandList::OperandInfo &Op = CGI.Operands[i];
4035 StringRef OpName = Op.Name;
4036 if (OpName.empty()) {
4037 I.error(Msg: "Operand #" + Twine(i) + " in operands list has no name!");
4038 continue;
4039 }
4040
4041 auto InIter = InstInputs.find(x: OpName);
4042 if (InIter == InstInputs.end()) {
4043 // If this is an operand with a DefaultOps set filled in, we can ignore
4044 // this. When we codegen it, we will do so as always executed.
4045 if (Op.Rec->isSubClassOf(Name: "OperandWithDefaultOps")) {
4046 // Does it have a non-empty DefaultOps field? If so, ignore this
4047 // operand.
4048 if (!getDefaultOperand(R: Op.Rec).DefaultOps.empty())
4049 continue;
4050 }
4051 I.error(Msg: "Operand $" + OpName +
4052 " does not appear in the instruction pattern");
4053 continue;
4054 }
4055 TreePatternNodePtr InVal = InIter->second;
4056 InstInputs.erase(position: InIter); // It occurred, remove from map.
4057
4058 if (InVal->isLeaf() && isa<DefInit>(Val: InVal->getLeafValue())) {
4059 const Record *InRec = cast<DefInit>(Val: InVal->getLeafValue())->getDef();
4060 if (!checkOperandClass(OI: Op, Leaf: InRec)) {
4061 I.error(Msg: "Operand $" + OpName +
4062 "'s register class disagrees"
4063 " between the operand and pattern");
4064 continue;
4065 }
4066 }
4067 Operands.push_back(x: Op.Rec);
4068
4069 // Construct the result for the dest-pattern operand list.
4070 TreePatternNodePtr OpNode = InVal->clone();
4071
4072 // No predicate is useful on the result.
4073 OpNode->clearPredicateCalls();
4074
4075 // Promote the xform function to be an explicit node if set.
4076 if (const Record *Xform = OpNode->getTransformFn()) {
4077 OpNode->setTransformFn(nullptr);
4078 std::vector<TreePatternNodePtr> Children;
4079 Children.push_back(x: OpNode);
4080 OpNode = makeIntrusiveRefCnt<TreePatternNode>(A&: Xform, A: std::move(Children),
4081 A: OpNode->getNumTypes());
4082 }
4083
4084 ResultNodeOperands.push_back(x: std::move(OpNode));
4085 }
4086
4087 if (!InstInputs.empty())
4088 I.error(Msg: "Input operand $" + InstInputs.begin()->first +
4089 " occurs in pattern but not in operands list!");
4090
4091 TreePatternNodePtr ResultPattern = makeIntrusiveRefCnt<TreePatternNode>(
4092 A: I.getRecord(), A: std::move(ResultNodeOperands),
4093 A: GetNumNodeResults(Operator: I.getRecord(), CDP&: *this));
4094 // Copy fully inferred output node types to instruction result pattern.
4095 for (unsigned i = 0; i != NumResults; ++i) {
4096 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
4097 ResultPattern->setType(ResNo: i, T: ResNodes[i]->getExtType(ResNo: 0));
4098 ResultPattern->setResultIndex(ResNo: i, RI: ResultIndices[i]);
4099 }
4100
4101 // FIXME: Assume only the first tree is the pattern. The others are clobber
4102 // nodes.
4103 TreePatternNodePtr Pattern = I.getTree(i: 0);
4104 TreePatternNodePtr SrcPattern;
4105 if (Pattern->getOperator()->getName() == "set") {
4106 SrcPattern = Pattern->getChild(N: Pattern->getNumChildren() - 1).clone();
4107 } else {
4108 // Not a set (store or something?)
4109 SrcPattern = Pattern;
4110 }
4111
4112 // Create and insert the instruction.
4113 // FIXME: InstImpResults should not be part of DAGInstruction.
4114 DAGInsts.try_emplace(k: I.getRecord(), args: std::move(Results), args: std::move(Operands),
4115 args: std::move(InstImpResults), args&: SrcPattern, args&: ResultPattern);
4116
4117 LLVM_DEBUG(I.dump());
4118}
4119
4120/// ParseInstructions - Parse all of the instructions, inlining and resolving
4121/// any fragments involved. This populates the Instructions list with fully
4122/// resolved instructions.
4123void CodeGenDAGPatterns::ParseInstructions() {
4124 for (const Record *Instr : Records.getAllDerivedDefinitions(ClassName: "Instruction")) {
4125 const ListInit *LI = nullptr;
4126
4127 if (isa<ListInit>(Val: Instr->getValueInit(FieldName: "Pattern")))
4128 LI = Instr->getValueAsListInit(FieldName: "Pattern");
4129
4130 // If there is no pattern, only collect minimal information about the
4131 // instruction for its operand list. We have to assume that there is one
4132 // result, as we have no detailed info. A pattern which references the
4133 // null_frag operator is as-if no pattern were specified. Normally this
4134 // is from a multiclass expansion w/ a SDPatternOperator passed in as
4135 // null_frag.
4136 if (!LI || LI->empty() || hasNullFragReference(LI)) {
4137 std::vector<const Record *> Results;
4138 std::vector<const Record *> Operands;
4139
4140 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4141
4142 if (InstInfo.Operands.size() != 0) {
4143 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
4144 Results.push_back(x: InstInfo.Operands[j].Rec);
4145
4146 // The rest are inputs.
4147 for (unsigned j = InstInfo.Operands.NumDefs,
4148 e = InstInfo.Operands.size();
4149 j < e; ++j)
4150 Operands.push_back(x: InstInfo.Operands[j].Rec);
4151 }
4152
4153 // Create and insert the instruction.
4154 Instructions.try_emplace(k: Instr, args: std::move(Results), args: std::move(Operands),
4155 args: std::vector<const Record *>());
4156 continue; // no pattern.
4157 }
4158
4159 const CodeGenInstruction &CGI = Target.getInstruction(InstRec: Instr);
4160 parseInstructionPattern(CGI, Pat: LI, DAGInsts&: Instructions);
4161 }
4162
4163 // If we can, convert the instructions to be patterns that are matched!
4164 for (const auto &[Instr, TheInst] : Instructions) {
4165 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
4166 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
4167
4168 if (SrcPattern && ResultPattern) {
4169 TreePattern Pattern(Instr, SrcPattern, true, *this);
4170 TreePattern Result(Instr, ResultPattern, false, *this);
4171 ParseOnePattern(TheDef: Instr, Pattern, Result, InstImpResults: TheInst.getImpResults());
4172 }
4173 }
4174}
4175
4176using NameRecord = std::pair<TreePatternNode *, unsigned>;
4177
4178static void FindNames(TreePatternNode &P,
4179 std::map<StringRef, NameRecord> &Names,
4180 TreePattern *PatternTop) {
4181 if (!P.getName().empty()) {
4182 NameRecord &Rec = Names[P.getName()];
4183 // If this is the first instance of the name, remember the node.
4184 if (Rec.second++ == 0)
4185 Rec.first = &P;
4186 else if (Rec.first->getExtTypes() != P.getExtTypes())
4187 PatternTop->error(Msg: "repetition of value: $" + P.getName() +
4188 " where different uses have different types!");
4189 }
4190
4191 if (!P.isLeaf()) {
4192 for (TreePatternNode &Child : P.children())
4193 FindNames(P&: Child, Names, PatternTop);
4194 }
4195}
4196
4197void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
4198 PatternToMatch &&PTM) {
4199 // Do some sanity checking on the pattern we're about to match.
4200 std::string Reason;
4201 if (!PTM.getSrcPattern().canPatternMatch(Reason, CDP: *this)) {
4202 PrintWarning(WarningLoc: Pattern->getRecord()->getLoc(),
4203 Msg: Twine("Pattern can never match: ") + Reason);
4204 return;
4205 }
4206
4207 // If the source pattern's root is a complex pattern, that complex pattern
4208 // must specify the nodes it can potentially match.
4209 if (const ComplexPattern *CP =
4210 PTM.getSrcPattern().getComplexPatternInfo(CGP: *this))
4211 if (CP->getRootNodes().empty())
4212 Pattern->error(Msg: "ComplexPattern at root must specify list of opcodes it"
4213 " could match");
4214
4215 // Find all of the named values in the input and output, ensure they have the
4216 // same type.
4217 std::map<StringRef, NameRecord> SrcNames, DstNames;
4218 FindNames(P&: PTM.getSrcPattern(), Names&: SrcNames, PatternTop: Pattern);
4219 FindNames(P&: PTM.getDstPattern(), Names&: DstNames, PatternTop: Pattern);
4220
4221 // Scan all of the named values in the destination pattern, rejecting them if
4222 // they don't exist in the input pattern.
4223 for (const auto &Entry : DstNames) {
4224 if (SrcNames[Entry.first].first == nullptr)
4225 Pattern->error(Msg: "Pattern has input without matching name in output: $" +
4226 Entry.first);
4227 }
4228
4229 // Scan all of the named values in the source pattern, rejecting them if the
4230 // name isn't used in the dest, and isn't used to tie two values together.
4231 for (const auto &Entry : SrcNames)
4232 if (DstNames[Entry.first].first == nullptr &&
4233 SrcNames[Entry.first].second == 1)
4234 Pattern->error(Msg: "Pattern has dead named input: $" + Entry.first);
4235
4236 PatternsToMatch.push_back(x: std::move(PTM));
4237}
4238
4239void CodeGenDAGPatterns::InferInstructionFlags() {
4240 ArrayRef<const CodeGenInstruction *> Instructions = Target.getInstructions();
4241
4242 unsigned Errors = 0;
4243
4244 // Try to infer flags from all patterns in PatternToMatch. These include
4245 // both the primary instruction patterns (which always come first) and
4246 // patterns defined outside the instruction.
4247 for (const PatternToMatch &PTM : ptms()) {
4248 // We can only infer from single-instruction patterns, otherwise we won't
4249 // know which instruction should get the flags.
4250 SmallVector<const Record *, 8> PatInstrs;
4251 getInstructionsInTree(Tree&: PTM.getDstPattern(), Instrs&: PatInstrs);
4252 if (PatInstrs.size() != 1)
4253 continue;
4254
4255 // Get the single instruction.
4256 CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: PatInstrs.front());
4257
4258 // Only infer properties from the first pattern. We'll verify the others.
4259 if (InstInfo.InferredFrom)
4260 continue;
4261
4262 InstAnalyzer PatInfo(*this);
4263 PatInfo.Analyze(Pat: PTM);
4264 Errors += InferFromPattern(InstInfo, PatInfo, PatDef: PTM.getSrcRecord());
4265 }
4266
4267 if (Errors)
4268 PrintFatalError(Msg: "pattern conflicts");
4269
4270 // If requested by the target, guess any undefined properties.
4271 if (Target.guessInstructionProperties()) {
4272 for (const CodeGenInstruction *InstInfo : Instructions) {
4273 if (InstInfo->InferredFrom)
4274 continue;
4275 // The mayLoad and mayStore flags default to false.
4276 // Conservatively assume hasSideEffects if it wasn't explicit.
4277 if (InstInfo->hasSideEffects_Unset)
4278 const_cast<CodeGenInstruction *>(InstInfo)->hasSideEffects = true;
4279 }
4280 return;
4281 }
4282
4283 // Complain about any flags that are still undefined.
4284 for (const CodeGenInstruction *InstInfo : Instructions) {
4285 if (InstInfo->InferredFrom)
4286 continue;
4287 if (InstInfo->hasSideEffects_Unset)
4288 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4289 Msg: "Can't infer hasSideEffects from patterns");
4290 if (InstInfo->mayStore_Unset)
4291 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4292 Msg: "Can't infer mayStore from patterns");
4293 if (InstInfo->mayLoad_Unset)
4294 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4295 Msg: "Can't infer mayLoad from patterns");
4296 }
4297}
4298
4299/// Verify instruction flags against pattern node properties.
4300void CodeGenDAGPatterns::VerifyInstructionFlags() {
4301 unsigned Errors = 0;
4302 for (const PatternToMatch &PTM : ptms()) {
4303 SmallVector<const Record *, 8> Instrs;
4304 getInstructionsInTree(Tree&: PTM.getDstPattern(), Instrs);
4305 if (Instrs.empty())
4306 continue;
4307
4308 // Count the number of instructions with each flag set.
4309 unsigned NumSideEffects = 0;
4310 unsigned NumStores = 0;
4311 unsigned NumLoads = 0;
4312 for (const Record *Instr : Instrs) {
4313 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4314 NumSideEffects += InstInfo.hasSideEffects;
4315 NumStores += InstInfo.mayStore;
4316 NumLoads += InstInfo.mayLoad;
4317 }
4318
4319 // Analyze the source pattern.
4320 InstAnalyzer PatInfo(*this);
4321 PatInfo.Analyze(Pat: PTM);
4322
4323 // Collect error messages.
4324 SmallVector<std::string, 4> Msgs;
4325
4326 // Check for missing flags in the output.
4327 // Permit extra flags for now at least.
4328 if (PatInfo.hasSideEffects && !NumSideEffects)
4329 Msgs.push_back(Elt: "pattern has side effects, but hasSideEffects isn't set");
4330
4331 // Don't verify store flags on instructions with side effects. At least for
4332 // intrinsics, side effects implies mayStore.
4333 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4334 Msgs.push_back(Elt: "pattern may store, but mayStore isn't set");
4335
4336 // Similarly, mayStore implies mayLoad on intrinsics.
4337 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4338 Msgs.push_back(Elt: "pattern may load, but mayLoad isn't set");
4339
4340 // Print error messages.
4341 if (Msgs.empty())
4342 continue;
4343 ++Errors;
4344
4345 for (const std::string &Msg : Msgs)
4346 PrintError(
4347 ErrorLoc: PTM.getSrcRecord()->getLoc(),
4348 Msg: Twine(Msg) + " on the " +
4349 (Instrs.size() == 1 ? "instruction" : "output instructions"));
4350 // Provide the location of the relevant instruction definitions.
4351 for (const Record *Instr : Instrs) {
4352 if (Instr != PTM.getSrcRecord())
4353 PrintError(ErrorLoc: Instr->getLoc(), Msg: "defined here");
4354 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4355 if (InstInfo.InferredFrom && InstInfo.InferredFrom != InstInfo.TheDef &&
4356 InstInfo.InferredFrom != PTM.getSrcRecord())
4357 PrintError(ErrorLoc: InstInfo.InferredFrom->getLoc(), Msg: "inferred from pattern");
4358 }
4359 }
4360 if (Errors)
4361 PrintFatalError(Msg: "Errors in DAG patterns");
4362}
4363
4364/// Given a pattern result with an unresolved type, see if we can find one
4365/// instruction with an unresolved result type. Force this result type to an
4366/// arbitrary element if it's possible types to converge results.
4367static bool ForceArbitraryInstResultType(TreePatternNode &N, TreePattern &TP) {
4368 if (N.isLeaf())
4369 return false;
4370
4371 // Analyze children.
4372 for (TreePatternNode &Child : N.children())
4373 if (ForceArbitraryInstResultType(N&: Child, TP))
4374 return true;
4375
4376 if (!N.getOperator()->isSubClassOf(Name: "Instruction"))
4377 return false;
4378
4379 // If this type is already concrete or completely unknown we can't do
4380 // anything.
4381 TypeInfer &TI = TP.getInfer();
4382 for (unsigned i = 0, e = N.getNumTypes(); i != e; ++i) {
4383 if (N.getExtType(ResNo: i).empty() ||
4384 N.getExtType(ResNo: i).isValueTypeByHwMode(/*AllowEmpty=*/false))
4385 continue;
4386
4387 // Otherwise, force its type to an arbitrary choice.
4388 if (TI.forceArbitrary(Out&: N.getExtType(ResNo: i)))
4389 return true;
4390 }
4391
4392 return false;
4393}
4394
4395// Promote xform function to be an explicit node wherever set.
4396static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4397 if (const Record *Xform = N->getTransformFn()) {
4398 N->setTransformFn(nullptr);
4399 std::vector<TreePatternNodePtr> Children;
4400 Children.push_back(x: PromoteXForms(N));
4401 return makeIntrusiveRefCnt<TreePatternNode>(A&: Xform, A: std::move(Children),
4402 A: N->getNumTypes());
4403 }
4404
4405 if (!N->isLeaf())
4406 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4407 TreePatternNodePtr Child = N->getChildShared(N: i);
4408 N->setChild(i, N: PromoteXForms(N: Child));
4409 }
4410 return N;
4411}
4412
4413void CodeGenDAGPatterns::ParseOnePattern(
4414 const Record *TheDef, TreePattern &Pattern, TreePattern &Result,
4415 ArrayRef<const Record *> InstImpResults, bool ShouldIgnore) {
4416 // Inline pattern fragments and expand multiple alternatives.
4417 Pattern.InlinePatternFragments();
4418 Result.InlinePatternFragments();
4419
4420 if (Result.getNumTrees() != 1) {
4421 Result.error(Msg: "Cannot use multi-alternative fragments in result pattern!");
4422 return;
4423 }
4424
4425 // Infer types.
4426 bool IterateInference;
4427 bool InferredAllPatternTypes, InferredAllResultTypes;
4428 do {
4429 // Infer as many types as possible. If we cannot infer all of them, we
4430 // can never do anything with this pattern: report it to the user.
4431 InferredAllPatternTypes =
4432 Pattern.InferAllTypes(InNamedTypes: &Pattern.getNamedNodesMap());
4433
4434 // Infer as many types as possible. If we cannot infer all of them, we
4435 // can never do anything with this pattern: report it to the user.
4436 InferredAllResultTypes = Result.InferAllTypes(InNamedTypes: &Pattern.getNamedNodesMap());
4437
4438 IterateInference = false;
4439
4440 // Apply the type of the result to the source pattern. This helps us
4441 // resolve cases where the input type is known to be a pointer type (which
4442 // is considered resolved), but the result knows it needs to be 32- or
4443 // 64-bits. Infer the other way for good measure.
4444 for (const auto &T : Pattern.getTrees())
4445 for (unsigned i = 0, e = std::min(a: Result.getOnlyTree()->getNumTypes(),
4446 b: T->getNumTypes());
4447 i != e; ++i) {
4448 IterateInference |=
4449 T->UpdateNodeType(ResNo: i, InTy: Result.getOnlyTree()->getExtType(ResNo: i), TP&: Result);
4450 IterateInference |=
4451 Result.getOnlyTree()->UpdateNodeType(ResNo: i, InTy: T->getExtType(ResNo: i), TP&: Result);
4452 }
4453
4454 // If our iteration has converged and the input pattern's types are fully
4455 // resolved but the result pattern is not fully resolved, we may have a
4456 // situation where we have two instructions in the result pattern and
4457 // the instructions require a common register class, but don't care about
4458 // what actual MVT is used. This is actually a bug in our modelling:
4459 // output patterns should have register classes, not MVTs.
4460 //
4461 // In any case, to handle this, we just go through and disambiguate some
4462 // arbitrary types to the result pattern's nodes.
4463 if (!IterateInference && InferredAllPatternTypes && !InferredAllResultTypes)
4464 IterateInference =
4465 ForceArbitraryInstResultType(N&: *Result.getTree(i: 0), TP&: Result);
4466 } while (IterateInference);
4467
4468 // Verify that we inferred enough types that we can do something with the
4469 // pattern and result. If these fire the user has to add type casts.
4470 if (!InferredAllPatternTypes)
4471 Pattern.error(Msg: "Could not infer all types in pattern!");
4472 if (!InferredAllResultTypes) {
4473 Pattern.dump();
4474 Result.error(Msg: "Could not infer all types in pattern result!");
4475 }
4476
4477 // Promote xform function to be an explicit node wherever set.
4478 TreePatternNodePtr DstShared = PromoteXForms(N: Result.getOnlyTree());
4479
4480 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4481 Temp.InferAllTypes();
4482
4483 const ListInit *Preds = TheDef->getValueAsListInit(FieldName: "Predicates");
4484 int Complexity = TheDef->getValueAsInt(FieldName: "AddedComplexity");
4485
4486 // A pattern may end up with an "impossible" type, i.e. a situation
4487 // where all types have been eliminated for some node in this pattern.
4488 // This could occur for intrinsics that only make sense for a specific
4489 // value type, and use a specific register class. If, for some mode,
4490 // that register class does not accept that type, the type inference
4491 // will lead to a contradiction, which is not an error however, but
4492 // a sign that this pattern will simply never match.
4493 if (Temp.getOnlyTree()->hasPossibleType()) {
4494 for (const auto &T : Pattern.getTrees()) {
4495 if (T->hasPossibleType())
4496 AddPatternToMatch(Pattern: &Pattern,
4497 PTM: PatternToMatch(TheDef, Preds, T, Temp.getOnlyTree(),
4498 InstImpResults, Complexity,
4499 TheDef->getID(), ShouldIgnore));
4500 }
4501 } else {
4502 // Show a message about a dropped pattern with some info to make it
4503 // easier to identify it in the .td files.
4504 LLVM_DEBUG({
4505 dbgs() << "Dropping: ";
4506 Pattern.dump();
4507 Temp.getOnlyTree()->dump();
4508 dbgs() << "\n";
4509 });
4510 }
4511}
4512
4513void CodeGenDAGPatterns::ParsePatterns() {
4514 for (const Record *CurPattern : Records.getAllDerivedDefinitions(ClassName: "Pattern")) {
4515 const DagInit *Tree = CurPattern->getValueAsDag(FieldName: "PatternToMatch");
4516
4517 // If the pattern references the null_frag, there's nothing to do.
4518 if (hasNullFragReference(DI: Tree))
4519 continue;
4520
4521 TreePattern Pattern(CurPattern, Tree, true, *this);
4522
4523 const ListInit *LI = CurPattern->getValueAsListInit(FieldName: "ResultInstrs");
4524 if (LI->empty())
4525 continue; // no pattern.
4526
4527 // Parse the instruction.
4528 TreePattern Result(CurPattern, LI, false, *this);
4529
4530 if (Result.getNumTrees() != 1)
4531 Result.error(Msg: "Cannot handle instructions producing instructions "
4532 "with temporaries yet!");
4533
4534 // Validate that the input pattern is correct.
4535 InstInputsTy InstInputs;
4536 InstResultsTy InstResults;
4537 std::vector<const Record *> InstImpResults;
4538 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4539 FindPatternInputsAndOutputs(I&: Pattern, Pat: Pattern.getTree(i: j), InstInputs,
4540 InstResults, InstImpResults);
4541
4542 ParseOnePattern(TheDef: CurPattern, Pattern, Result, InstImpResults,
4543 ShouldIgnore: CurPattern->getValueAsBit(FieldName: "GISelShouldIgnore"));
4544 }
4545}
4546
4547static void collectModes(std::set<unsigned> &Modes, const TreePatternNode &N) {
4548 for (const TypeSetByHwMode &VTS : N.getExtTypes())
4549 for (const auto &I : VTS)
4550 Modes.insert(x: I.first);
4551
4552 for (const TreePatternNode &Child : N.children())
4553 collectModes(Modes, N: Child);
4554}
4555
4556void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4557 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4558 if (CGH.getNumModeIds() == 1)
4559 return;
4560
4561 std::vector<PatternToMatch> Copy;
4562 PatternsToMatch.swap(x&: Copy);
4563
4564 auto AppendPattern = [this](PatternToMatch &P, unsigned Mode,
4565 StringRef Check) {
4566 TreePatternNodePtr NewSrc = P.getSrcPattern().clone();
4567 TreePatternNodePtr NewDst = P.getDstPattern().clone();
4568 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4569 return;
4570 }
4571
4572 PatternsToMatch.emplace_back(args: P.getSrcRecord(), args: P.getPredicates(),
4573 args: std::move(NewSrc), args: std::move(NewDst),
4574 args: P.getDstRegs(), args: P.getAddedComplexity(),
4575 args: getNewUID(), args: P.getGISelShouldIgnore(), args&: Check);
4576 };
4577
4578 for (PatternToMatch &P : Copy) {
4579 const TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4580 if (P.getSrcPattern().hasProperTypeByHwMode())
4581 SrcP = &P.getSrcPattern();
4582 if (P.getDstPattern().hasProperTypeByHwMode())
4583 DstP = &P.getDstPattern();
4584 if (!SrcP && !DstP) {
4585 PatternsToMatch.push_back(x: P);
4586 continue;
4587 }
4588
4589 std::set<unsigned> Modes;
4590 if (SrcP)
4591 collectModes(Modes, N: *SrcP);
4592 if (DstP)
4593 collectModes(Modes, N: *DstP);
4594
4595 // The predicate for the default mode needs to be constructed for each
4596 // pattern separately.
4597 // Since not all modes must be present in each pattern, if a mode m is
4598 // absent, then there is no point in constructing a check for m. If such
4599 // a check was created, it would be equivalent to checking the default
4600 // mode, except not all modes' predicates would be a part of the checking
4601 // code. The subsequently generated check for the default mode would then
4602 // have the exact same patterns, but a different predicate code. To avoid
4603 // duplicated patterns with different predicate checks, construct the
4604 // default check as a negation of all predicates that are actually present
4605 // in the source/destination patterns.
4606 SmallString<128> DefaultCheck;
4607
4608 for (unsigned M : Modes) {
4609 if (M == DefaultMode)
4610 continue;
4611
4612 // Fill the map entry for this mode.
4613 const HwMode &HM = CGH.getMode(Id: M);
4614
4615 SmallString<128> PredicateCheck;
4616 raw_svector_ostream PS(PredicateCheck);
4617 SubtargetFeatureInfo::emitPredicateCheck(OS&: PS, Predicates: HM.Predicates);
4618 AppendPattern(P, M, PredicateCheck);
4619
4620 // Add negations of the HM's predicates to the default predicate.
4621 if (!DefaultCheck.empty())
4622 DefaultCheck += " && ";
4623 DefaultCheck += "!(";
4624 DefaultCheck.append(RHS: PredicateCheck);
4625 DefaultCheck += ")";
4626 }
4627
4628 bool HasDefault = Modes.count(x: DefaultMode);
4629 if (HasDefault)
4630 AppendPattern(P, DefaultMode, DefaultCheck);
4631 }
4632}
4633
4634/// Dependent variable map for CodeGenDAGPattern variant generation
4635using DepVarMap = StringMap<int>;
4636
4637static void FindDepVarsOf(TreePatternNode &N, DepVarMap &DepMap) {
4638 if (N.isLeaf()) {
4639 if (N.hasName() && isa<DefInit>(Val: N.getLeafValue()))
4640 DepMap[N.getName()]++;
4641 } else {
4642 for (TreePatternNode &Child : N.children())
4643 FindDepVarsOf(N&: Child, DepMap);
4644 }
4645}
4646
4647/// Find dependent variables within child patterns
4648static void FindDepVars(TreePatternNode &N, MultipleUseVarSet &DepVars) {
4649 DepVarMap depcounts;
4650 FindDepVarsOf(N, DepMap&: depcounts);
4651 for (const auto &Pair : depcounts) {
4652 if (Pair.getValue() > 1)
4653 DepVars.insert(key: Pair.getKey());
4654 }
4655}
4656
4657#ifndef NDEBUG
4658/// Dump the dependent variable set:
4659static void DumpDepVars(MultipleUseVarSet &DepVars) {
4660 if (DepVars.empty()) {
4661 LLVM_DEBUG(errs() << "<empty set>");
4662 } else {
4663 LLVM_DEBUG(errs() << "[ ");
4664 for (const auto &DepVar : DepVars) {
4665 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
4666 }
4667 LLVM_DEBUG(errs() << "]");
4668 }
4669}
4670#endif
4671
4672/// CombineChildVariants - Given a bunch of permutations of each child of the
4673/// 'operator' node, put them together in all possible ways.
4674static void CombineChildVariants(
4675 TreePatternNodePtr Orig,
4676 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4677 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4678 const MultipleUseVarSet &DepVars) {
4679 // Make sure that each operand has at least one variant to choose from.
4680 for (const auto &Variants : ChildVariants)
4681 if (Variants.empty())
4682 return;
4683
4684 // The end result is an all-pairs construction of the resultant pattern.
4685 std::vector<unsigned> Idxs(ChildVariants.size());
4686 bool NotDone;
4687 do {
4688#ifndef NDEBUG
4689 LLVM_DEBUG(if (!Idxs.empty()) {
4690 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4691 for (unsigned Idx : Idxs) {
4692 errs() << Idx << " ";
4693 }
4694 errs() << "]\n";
4695 });
4696#endif
4697 // Create the variant and add it to the output list.
4698 std::vector<TreePatternNodePtr> NewChildren;
4699 NewChildren.reserve(n: ChildVariants.size());
4700 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4701 NewChildren.push_back(x: ChildVariants[i][Idxs[i]]);
4702 TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
4703 A: Orig->getOperator(), A: std::move(NewChildren), A: Orig->getNumTypes());
4704
4705 // Copy over properties.
4706 R->setName(Orig->getName());
4707 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4708 R->setPredicateCalls(Orig->getPredicateCalls());
4709 R->setGISelFlagsRecord(Orig->getGISelFlagsRecord());
4710 R->setTransformFn(Orig->getTransformFn());
4711 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4712 R->setType(ResNo: i, T: Orig->getExtType(ResNo: i));
4713
4714 // If this pattern cannot match, do not include it as a variant.
4715 std::string ErrString;
4716 // Scan to see if this pattern has already been emitted. We can get
4717 // duplication due to things like commuting:
4718 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4719 // which are the same pattern. Ignore the dups.
4720 if (R->canPatternMatch(Reason&: ErrString, CDP) &&
4721 none_of(Range&: OutVariants, P: [&](TreePatternNodePtr Variant) {
4722 return R->isIsomorphicTo(N: *Variant, DepVars);
4723 }))
4724 OutVariants.push_back(x: R);
4725
4726 // Increment indices to the next permutation by incrementing the
4727 // indices from last index backward, e.g., generate the sequence
4728 // [0, 0], [0, 1], [1, 0], [1, 1].
4729 int IdxsIdx;
4730 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4731 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4732 Idxs[IdxsIdx] = 0;
4733 else
4734 break;
4735 }
4736 NotDone = (IdxsIdx >= 0);
4737 } while (NotDone);
4738}
4739
4740/// CombineChildVariants - A helper function for binary operators.
4741///
4742static void CombineChildVariants(TreePatternNodePtr Orig,
4743 const std::vector<TreePatternNodePtr> &LHS,
4744 const std::vector<TreePatternNodePtr> &RHS,
4745 std::vector<TreePatternNodePtr> &OutVariants,
4746 CodeGenDAGPatterns &CDP,
4747 const MultipleUseVarSet &DepVars) {
4748 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4749 ChildVariants.push_back(x: LHS);
4750 ChildVariants.push_back(x: RHS);
4751 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4752}
4753
4754static void
4755GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4756 std::vector<TreePatternNodePtr> &Children) {
4757 assert(N->getNumChildren() == 2 &&
4758 "Associative but doesn't have 2 children!");
4759 const Record *Operator = N->getOperator();
4760
4761 // Only permit raw nodes.
4762 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
4763 N->getTransformFn()) {
4764 Children.push_back(x: N);
4765 return;
4766 }
4767
4768 if (N->getChild(N: 0).isLeaf() || N->getChild(N: 0).getOperator() != Operator)
4769 Children.push_back(x: N->getChildShared(N: 0));
4770 else
4771 GatherChildrenOfAssociativeOpcode(N: N->getChildShared(N: 0), Children);
4772
4773 if (N->getChild(N: 1).isLeaf() || N->getChild(N: 1).getOperator() != Operator)
4774 Children.push_back(x: N->getChildShared(N: 1));
4775 else
4776 GatherChildrenOfAssociativeOpcode(N: N->getChildShared(N: 1), Children);
4777}
4778
4779/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4780/// the (potentially recursive) pattern by using algebraic laws.
4781///
4782static void GenerateVariantsOf(TreePatternNodePtr N,
4783 std::vector<TreePatternNodePtr> &OutVariants,
4784 CodeGenDAGPatterns &CDP,
4785 const MultipleUseVarSet &DepVars) {
4786 // We cannot permute leaves or ComplexPattern uses.
4787 if (N->isLeaf() || N->getOperator()->isSubClassOf(Name: "ComplexPattern")) {
4788 OutVariants.push_back(x: N);
4789 return;
4790 }
4791
4792 // Look up interesting info about the node.
4793 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(R: N->getOperator());
4794
4795 // If this node is associative, re-associate.
4796 if (NodeInfo.hasProperty(Prop: SDNPAssociative)) {
4797 // Re-associate by pulling together all of the linked operators
4798 std::vector<TreePatternNodePtr> MaximalChildren;
4799 GatherChildrenOfAssociativeOpcode(N, Children&: MaximalChildren);
4800
4801 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4802 // permutations.
4803 if (MaximalChildren.size() == 3) {
4804 // Find the variants of all of our maximal children.
4805 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4806 GenerateVariantsOf(N: MaximalChildren[0], OutVariants&: AVariants, CDP, DepVars);
4807 GenerateVariantsOf(N: MaximalChildren[1], OutVariants&: BVariants, CDP, DepVars);
4808 GenerateVariantsOf(N: MaximalChildren[2], OutVariants&: CVariants, CDP, DepVars);
4809
4810 // There are only two ways we can permute the tree:
4811 // (A op B) op C and A op (B op C)
4812 // Within these forms, we can also permute A/B/C.
4813
4814 // Generate legal pair permutations of A/B/C.
4815 std::vector<TreePatternNodePtr> ABVariants;
4816 std::vector<TreePatternNodePtr> BAVariants;
4817 std::vector<TreePatternNodePtr> ACVariants;
4818 std::vector<TreePatternNodePtr> CAVariants;
4819 std::vector<TreePatternNodePtr> BCVariants;
4820 std::vector<TreePatternNodePtr> CBVariants;
4821 CombineChildVariants(Orig: N, LHS: AVariants, RHS: BVariants, OutVariants&: ABVariants, CDP, DepVars);
4822 CombineChildVariants(Orig: N, LHS: BVariants, RHS: AVariants, OutVariants&: BAVariants, CDP, DepVars);
4823 CombineChildVariants(Orig: N, LHS: AVariants, RHS: CVariants, OutVariants&: ACVariants, CDP, DepVars);
4824 CombineChildVariants(Orig: N, LHS: CVariants, RHS: AVariants, OutVariants&: CAVariants, CDP, DepVars);
4825 CombineChildVariants(Orig: N, LHS: BVariants, RHS: CVariants, OutVariants&: BCVariants, CDP, DepVars);
4826 CombineChildVariants(Orig: N, LHS: CVariants, RHS: BVariants, OutVariants&: CBVariants, CDP, DepVars);
4827
4828 // Combine those into the result: (x op x) op x
4829 CombineChildVariants(Orig: N, LHS: ABVariants, RHS: CVariants, OutVariants, CDP, DepVars);
4830 CombineChildVariants(Orig: N, LHS: BAVariants, RHS: CVariants, OutVariants, CDP, DepVars);
4831 CombineChildVariants(Orig: N, LHS: ACVariants, RHS: BVariants, OutVariants, CDP, DepVars);
4832 CombineChildVariants(Orig: N, LHS: CAVariants, RHS: BVariants, OutVariants, CDP, DepVars);
4833 CombineChildVariants(Orig: N, LHS: BCVariants, RHS: AVariants, OutVariants, CDP, DepVars);
4834 CombineChildVariants(Orig: N, LHS: CBVariants, RHS: AVariants, OutVariants, CDP, DepVars);
4835
4836 // Combine those into the result: x op (x op x)
4837 CombineChildVariants(Orig: N, LHS: CVariants, RHS: ABVariants, OutVariants, CDP, DepVars);
4838 CombineChildVariants(Orig: N, LHS: CVariants, RHS: BAVariants, OutVariants, CDP, DepVars);
4839 CombineChildVariants(Orig: N, LHS: BVariants, RHS: ACVariants, OutVariants, CDP, DepVars);
4840 CombineChildVariants(Orig: N, LHS: BVariants, RHS: CAVariants, OutVariants, CDP, DepVars);
4841 CombineChildVariants(Orig: N, LHS: AVariants, RHS: BCVariants, OutVariants, CDP, DepVars);
4842 CombineChildVariants(Orig: N, LHS: AVariants, RHS: CBVariants, OutVariants, CDP, DepVars);
4843 return;
4844 }
4845 }
4846
4847 // Compute permutations of all children.
4848 std::vector<std::vector<TreePatternNodePtr>> ChildVariants(
4849 N->getNumChildren());
4850 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4851 GenerateVariantsOf(N: N->getChildShared(N: i), OutVariants&: ChildVariants[i], CDP, DepVars);
4852
4853 // Build all permutations based on how the children were formed.
4854 CombineChildVariants(Orig: N, ChildVariants, OutVariants, CDP, DepVars);
4855
4856 // If this node is commutative, consider the commuted order.
4857 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4858 if (NodeInfo.hasProperty(Prop: SDNPCommutative) || isCommIntrinsic) {
4859 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
4860 assert(N->getNumChildren() >= (2 + Skip) &&
4861 "Commutative but doesn't have 2 children!");
4862 // Don't allow commuting children which are actually register references.
4863 bool NoRegisters = true;
4864 unsigned i = 0 + Skip;
4865 unsigned e = 2 + Skip;
4866 for (; i != e; ++i) {
4867 TreePatternNode &Child = N->getChild(N: i);
4868 if (Child.isLeaf())
4869 if (const DefInit *DI = dyn_cast<DefInit>(Val: Child.getLeafValue())) {
4870 const Record *RR = DI->getDef();
4871 if (RR->isSubClassOf(Name: "Register"))
4872 NoRegisters = false;
4873 }
4874 }
4875 // Consider the commuted order.
4876 if (NoRegisters) {
4877 // Swap the first two operands after the intrinsic id, if present.
4878 unsigned i = isCommIntrinsic ? 1 : 0;
4879 std::swap(x&: ChildVariants[i], y&: ChildVariants[i + 1]);
4880 CombineChildVariants(Orig: N, ChildVariants, OutVariants, CDP, DepVars);
4881 }
4882 }
4883}
4884
4885// GenerateVariants - Generate variants. For example, commutative patterns can
4886// match multiple ways. Add them to PatternsToMatch as well.
4887void CodeGenDAGPatterns::GenerateVariants() {
4888 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4889
4890 // Loop over all of the patterns we've collected, checking to see if we can
4891 // generate variants of the instruction, through the exploitation of
4892 // identities. This permits the target to provide aggressive matching without
4893 // the .td file having to contain tons of variants of instructions.
4894 //
4895 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4896 // intentionally do not reconsider these. Any variants of added patterns have
4897 // already been added.
4898 //
4899 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4900 MultipleUseVarSet DepVars;
4901 std::vector<TreePatternNodePtr> Variants;
4902 FindDepVars(N&: PatternsToMatch[i].getSrcPattern(), DepVars);
4903 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4904 LLVM_DEBUG(DumpDepVars(DepVars));
4905 LLVM_DEBUG(errs() << "\n");
4906 GenerateVariantsOf(N: PatternsToMatch[i].getSrcPatternShared(), OutVariants&: Variants,
4907 CDP&: *this, DepVars);
4908
4909 assert(PatternsToMatch[i].getHwModeFeatures().empty() &&
4910 "HwModes should not have been expanded yet!");
4911
4912 assert(!Variants.empty() && "Must create at least original variant!");
4913 if (Variants.size() == 1) // No additional variants for this pattern.
4914 continue;
4915
4916 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4917 PatternsToMatch[i].getSrcPattern().dump(); errs() << "\n");
4918
4919 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4920 TreePatternNodePtr Variant = Variants[v];
4921
4922 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4923 errs() << "\n");
4924
4925 // Scan to see if an instruction or explicit pattern already matches this.
4926 bool AlreadyExists = false;
4927 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4928 // Skip if the top level predicates do not match.
4929 if ((i != p) && (PatternsToMatch[i].getPredicates() !=
4930 PatternsToMatch[p].getPredicates()))
4931 continue;
4932 // Check to see if this variant already exists.
4933 if (Variant->isIsomorphicTo(N: PatternsToMatch[p].getSrcPattern(),
4934 DepVars)) {
4935 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
4936 AlreadyExists = true;
4937 break;
4938 }
4939 }
4940 // If we already have it, ignore the variant.
4941 if (AlreadyExists)
4942 continue;
4943
4944 // Otherwise, add it to the list of patterns we have.
4945 PatternsToMatch.emplace_back(
4946 args: PatternsToMatch[i].getSrcRecord(), args: PatternsToMatch[i].getPredicates(),
4947 args&: Variant, args: PatternsToMatch[i].getDstPatternShared(),
4948 args: PatternsToMatch[i].getDstRegs(),
4949 args: PatternsToMatch[i].getAddedComplexity(), args: getNewUID(),
4950 args: PatternsToMatch[i].getGISelShouldIgnore(),
4951 args: PatternsToMatch[i].getHwModeFeatures());
4952 }
4953
4954 LLVM_DEBUG(errs() << "\n");
4955 }
4956}
4957
4958unsigned CodeGenDAGPatterns::getNewUID() {
4959 RecordKeeper &MutableRC = const_cast<RecordKeeper &>(Records);
4960 return Record::getNewUID(RK&: MutableRC);
4961}
4962