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