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