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