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