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