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