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