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