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