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