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