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