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