1 //===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file declares the CodeGenDAGPatterns class, which is used to read and 10 // represent the patterns present in a .td file for instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H 15 #define LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H 16 17 #include "CodeGenHwModes.h" 18 #include "CodeGenIntrinsics.h" 19 #include "CodeGenTarget.h" 20 #include "SDNodeProperties.h" 21 #include "llvm/ADT/MapVector.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/StringMap.h" 24 #include "llvm/ADT/StringSet.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/Support/MathExtras.h" 27 #include <algorithm> 28 #include <array> 29 #include <functional> 30 #include <map> 31 #include <numeric> 32 #include <set> 33 #include <vector> 34 35 namespace llvm { 36 37 class Record; 38 class Init; 39 class ListInit; 40 class DagInit; 41 class SDNodeInfo; 42 class TreePattern; 43 class TreePatternNode; 44 class CodeGenDAGPatterns; 45 class ComplexPattern; 46 47 /// Shared pointer for TreePatternNode. 48 using TreePatternNodePtr = std::shared_ptr<TreePatternNode>; 49 50 /// This represents a set of MVTs. Since the underlying type for the MVT 51 /// is uint8_t, there are at most 256 values. To reduce the number of memory 52 /// allocations and deallocations, represent the set as a sequence of bits. 53 /// To reduce the allocations even further, make MachineValueTypeSet own 54 /// the storage and use std::array as the bit container. 55 struct MachineValueTypeSet { 56 static_assert(std::is_same<std::underlying_type<MVT::SimpleValueType>::type, 57 uint8_t>::value, 58 "Change uint8_t here to the SimpleValueType's type"); 59 static unsigned constexpr Capacity = std::numeric_limits<uint8_t>::max()+1; 60 using WordType = uint64_t; 61 static unsigned constexpr WordWidth = CHAR_BIT*sizeof(WordType); 62 static unsigned constexpr NumWords = Capacity/WordWidth; 63 static_assert(NumWords*WordWidth == Capacity, 64 "Capacity should be a multiple of WordWidth"); 65 66 LLVM_ATTRIBUTE_ALWAYS_INLINE 67 MachineValueTypeSet() { 68 clear(); 69 } 70 71 LLVM_ATTRIBUTE_ALWAYS_INLINE 72 unsigned size() const { 73 unsigned Count = 0; 74 for (WordType W : Words) 75 Count += countPopulation(W); 76 return Count; 77 } 78 LLVM_ATTRIBUTE_ALWAYS_INLINE 79 void clear() { 80 std::memset(Words.data(), 0, NumWords*sizeof(WordType)); 81 } 82 LLVM_ATTRIBUTE_ALWAYS_INLINE 83 bool empty() const { 84 for (WordType W : Words) 85 if (W != 0) 86 return false; 87 return true; 88 } 89 LLVM_ATTRIBUTE_ALWAYS_INLINE 90 unsigned count(MVT T) const { 91 return (Words[T.SimpleTy / WordWidth] >> (T.SimpleTy % WordWidth)) & 1; 92 } 93 std::pair<MachineValueTypeSet&,bool> insert(MVT T) { 94 bool V = count(T.SimpleTy); 95 Words[T.SimpleTy / WordWidth] |= WordType(1) << (T.SimpleTy % WordWidth); 96 return {*this, V}; 97 } 98 MachineValueTypeSet &insert(const MachineValueTypeSet &S) { 99 for (unsigned i = 0; i != NumWords; ++i) 100 Words[i] |= S.Words[i]; 101 return *this; 102 } 103 LLVM_ATTRIBUTE_ALWAYS_INLINE 104 void erase(MVT T) { 105 Words[T.SimpleTy / WordWidth] &= ~(WordType(1) << (T.SimpleTy % WordWidth)); 106 } 107 108 struct const_iterator { 109 // Some implementations of the C++ library require these traits to be 110 // defined. 111 using iterator_category = std::forward_iterator_tag; 112 using value_type = MVT; 113 using difference_type = ptrdiff_t; 114 using pointer = const MVT*; 115 using reference = const MVT&; 116 117 LLVM_ATTRIBUTE_ALWAYS_INLINE 118 MVT operator*() const { 119 assert(Pos != Capacity); 120 return MVT::SimpleValueType(Pos); 121 } 122 LLVM_ATTRIBUTE_ALWAYS_INLINE 123 const_iterator(const MachineValueTypeSet *S, bool End) : Set(S) { 124 Pos = End ? Capacity : find_from_pos(0); 125 } 126 LLVM_ATTRIBUTE_ALWAYS_INLINE 127 const_iterator &operator++() { 128 assert(Pos != Capacity); 129 Pos = find_from_pos(Pos+1); 130 return *this; 131 } 132 133 LLVM_ATTRIBUTE_ALWAYS_INLINE 134 bool operator==(const const_iterator &It) const { 135 return Set == It.Set && Pos == It.Pos; 136 } 137 LLVM_ATTRIBUTE_ALWAYS_INLINE 138 bool operator!=(const const_iterator &It) const { 139 return !operator==(It); 140 } 141 142 private: 143 unsigned find_from_pos(unsigned P) const { 144 unsigned SkipWords = P / WordWidth; 145 unsigned SkipBits = P % WordWidth; 146 unsigned Count = SkipWords * WordWidth; 147 148 // If P is in the middle of a word, process it manually here, because 149 // the trailing bits need to be masked off to use findFirstSet. 150 if (SkipBits != 0) { 151 WordType W = Set->Words[SkipWords]; 152 W &= maskLeadingOnes<WordType>(WordWidth-SkipBits); 153 if (W != 0) 154 return Count + findFirstSet(W); 155 Count += WordWidth; 156 SkipWords++; 157 } 158 159 for (unsigned i = SkipWords; i != NumWords; ++i) { 160 WordType W = Set->Words[i]; 161 if (W != 0) 162 return Count + findFirstSet(W); 163 Count += WordWidth; 164 } 165 return Capacity; 166 } 167 168 const MachineValueTypeSet *Set; 169 unsigned Pos; 170 }; 171 172 LLVM_ATTRIBUTE_ALWAYS_INLINE 173 const_iterator begin() const { return const_iterator(this, false); } 174 LLVM_ATTRIBUTE_ALWAYS_INLINE 175 const_iterator end() const { return const_iterator(this, true); } 176 177 LLVM_ATTRIBUTE_ALWAYS_INLINE 178 bool operator==(const MachineValueTypeSet &S) const { 179 return Words == S.Words; 180 } 181 LLVM_ATTRIBUTE_ALWAYS_INLINE 182 bool operator!=(const MachineValueTypeSet &S) const { 183 return !operator==(S); 184 } 185 186 private: 187 friend struct const_iterator; 188 std::array<WordType,NumWords> Words; 189 }; 190 191 struct TypeSetByHwMode : public InfoByHwMode<MachineValueTypeSet> { 192 using SetType = MachineValueTypeSet; 193 194 TypeSetByHwMode() = default; 195 TypeSetByHwMode(const TypeSetByHwMode &VTS) = default; 196 TypeSetByHwMode(MVT::SimpleValueType VT) 197 : TypeSetByHwMode(ValueTypeByHwMode(VT)) {} 198 TypeSetByHwMode(ValueTypeByHwMode VT) 199 : TypeSetByHwMode(ArrayRef<ValueTypeByHwMode>(&VT, 1)) {} 200 TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList); 201 202 SetType &getOrCreate(unsigned Mode) { 203 if (hasMode(Mode)) 204 return get(Mode); 205 return Map.insert({Mode,SetType()}).first->second; 206 } 207 208 bool isValueTypeByHwMode(bool AllowEmpty) const; 209 ValueTypeByHwMode getValueTypeByHwMode() const; 210 211 LLVM_ATTRIBUTE_ALWAYS_INLINE 212 bool isMachineValueType() const { 213 return isDefaultOnly() && Map.begin()->second.size() == 1; 214 } 215 216 LLVM_ATTRIBUTE_ALWAYS_INLINE 217 MVT getMachineValueType() const { 218 assert(isMachineValueType()); 219 return *Map.begin()->second.begin(); 220 } 221 222 bool isPossible() const; 223 224 LLVM_ATTRIBUTE_ALWAYS_INLINE 225 bool isDefaultOnly() const { 226 return Map.size() == 1 && Map.begin()->first == DefaultMode; 227 } 228 229 bool insert(const ValueTypeByHwMode &VVT); 230 bool constrain(const TypeSetByHwMode &VTS); 231 template <typename Predicate> bool constrain(Predicate P); 232 template <typename Predicate> 233 bool assign_if(const TypeSetByHwMode &VTS, Predicate P); 234 235 void writeToStream(raw_ostream &OS) const; 236 static void writeToStream(const SetType &S, raw_ostream &OS); 237 238 bool operator==(const TypeSetByHwMode &VTS) const; 239 bool operator!=(const TypeSetByHwMode &VTS) const { return !(*this == VTS); } 240 241 void dump() const; 242 bool validate() const; 243 244 private: 245 /// Intersect two sets. Return true if anything has changed. 246 bool intersect(SetType &Out, const SetType &In); 247 }; 248 249 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T); 250 251 struct TypeInfer { 252 TypeInfer(TreePattern &T) : TP(T), ForceMode(0) {} 253 254 bool isConcrete(const TypeSetByHwMode &VTS, bool AllowEmpty) const { 255 return VTS.isValueTypeByHwMode(AllowEmpty); 256 } 257 ValueTypeByHwMode getConcrete(const TypeSetByHwMode &VTS, 258 bool AllowEmpty) const { 259 assert(VTS.isValueTypeByHwMode(AllowEmpty)); 260 return VTS.getValueTypeByHwMode(); 261 } 262 263 /// The protocol in the following functions (Merge*, force*, Enforce*, 264 /// expand*) is to return "true" if a change has been made, "false" 265 /// otherwise. 266 267 bool MergeInTypeInfo(TypeSetByHwMode &Out, const TypeSetByHwMode &In); 268 bool MergeInTypeInfo(TypeSetByHwMode &Out, MVT::SimpleValueType InVT) { 269 return MergeInTypeInfo(Out, TypeSetByHwMode(InVT)); 270 } 271 bool MergeInTypeInfo(TypeSetByHwMode &Out, ValueTypeByHwMode InVT) { 272 return MergeInTypeInfo(Out, TypeSetByHwMode(InVT)); 273 } 274 275 /// Reduce the set \p Out to have at most one element for each mode. 276 bool forceArbitrary(TypeSetByHwMode &Out); 277 278 /// The following four functions ensure that upon return the set \p Out 279 /// will only contain types of the specified kind: integer, floating-point, 280 /// scalar, or vector. 281 /// If \p Out is empty, all legal types of the specified kind will be added 282 /// to it. Otherwise, all types that are not of the specified kind will be 283 /// removed from \p Out. 284 bool EnforceInteger(TypeSetByHwMode &Out); 285 bool EnforceFloatingPoint(TypeSetByHwMode &Out); 286 bool EnforceScalar(TypeSetByHwMode &Out); 287 bool EnforceVector(TypeSetByHwMode &Out); 288 289 /// If \p Out is empty, fill it with all legal types. Otherwise, leave it 290 /// unchanged. 291 bool EnforceAny(TypeSetByHwMode &Out); 292 /// Make sure that for each type in \p Small, there exists a larger type 293 /// in \p Big. 294 bool EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big); 295 /// 1. Ensure that for each type T in \p Vec, T is a vector type, and that 296 /// for each type U in \p Elem, U is a scalar type. 297 /// 2. Ensure that for each (scalar) type U in \p Elem, there exists a 298 /// (vector) type T in \p Vec, such that U is the element type of T. 299 bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Elem); 300 bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, 301 const ValueTypeByHwMode &VVT); 302 /// Ensure that for each type T in \p Sub, T is a vector type, and there 303 /// exists a type U in \p Vec such that U is a vector type with the same 304 /// element type as T and at least as many elements as T. 305 bool EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec, 306 TypeSetByHwMode &Sub); 307 /// 1. Ensure that \p V has a scalar type iff \p W has a scalar type. 308 /// 2. Ensure that for each vector type T in \p V, there exists a vector 309 /// type U in \p W, such that T and U have the same number of elements. 310 /// 3. Ensure that for each vector type U in \p W, there exists a vector 311 /// type T in \p V, such that T and U have the same number of elements 312 /// (reverse of 2). 313 bool EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W); 314 /// 1. Ensure that for each type T in \p A, there exists a type U in \p B, 315 /// such that T and U have equal size in bits. 316 /// 2. Ensure that for each type U in \p B, there exists a type T in \p A 317 /// such that T and U have equal size in bits (reverse of 1). 318 bool EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B); 319 320 /// For each overloaded type (i.e. of form *Any), replace it with the 321 /// corresponding subset of legal, specific types. 322 void expandOverloads(TypeSetByHwMode &VTS); 323 void expandOverloads(TypeSetByHwMode::SetType &Out, 324 const TypeSetByHwMode::SetType &Legal); 325 326 struct ValidateOnExit { 327 ValidateOnExit(TypeSetByHwMode &T, TypeInfer &TI) : Infer(TI), VTS(T) {} 328 #ifndef NDEBUG 329 ~ValidateOnExit(); 330 #else 331 ~ValidateOnExit() {} // Empty destructor with NDEBUG. 332 #endif 333 TypeInfer &Infer; 334 TypeSetByHwMode &VTS; 335 }; 336 337 struct SuppressValidation { 338 SuppressValidation(TypeInfer &TI) : Infer(TI), SavedValidate(TI.Validate) { 339 Infer.Validate = false; 340 } 341 ~SuppressValidation() { 342 Infer.Validate = SavedValidate; 343 } 344 TypeInfer &Infer; 345 bool SavedValidate; 346 }; 347 348 TreePattern &TP; 349 unsigned ForceMode; // Mode to use when set. 350 bool CodeGen = false; // Set during generation of matcher code. 351 bool Validate = true; // Indicate whether to validate types. 352 353 private: 354 const TypeSetByHwMode &getLegalTypes(); 355 356 /// Cached legal types (in default mode). 357 bool LegalTypesCached = false; 358 TypeSetByHwMode LegalCache; 359 }; 360 361 /// Set type used to track multiply used variables in patterns 362 typedef StringSet<> MultipleUseVarSet; 363 364 /// SDTypeConstraint - This is a discriminated union of constraints, 365 /// corresponding to the SDTypeConstraint tablegen class in Target.td. 366 struct SDTypeConstraint { 367 SDTypeConstraint(Record *R, const CodeGenHwModes &CGH); 368 369 unsigned OperandNo; // The operand # this constraint applies to. 370 enum { 371 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisVec, SDTCisSameAs, 372 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisEltOfVec, 373 SDTCisSubVecOfVec, SDTCVecEltisVT, SDTCisSameNumEltsAs, SDTCisSameSizeAs 374 } ConstraintType; 375 376 union { // The discriminated union. 377 struct { 378 unsigned OtherOperandNum; 379 } SDTCisSameAs_Info; 380 struct { 381 unsigned OtherOperandNum; 382 } SDTCisVTSmallerThanOp_Info; 383 struct { 384 unsigned BigOperandNum; 385 } SDTCisOpSmallerThanOp_Info; 386 struct { 387 unsigned OtherOperandNum; 388 } SDTCisEltOfVec_Info; 389 struct { 390 unsigned OtherOperandNum; 391 } SDTCisSubVecOfVec_Info; 392 struct { 393 unsigned OtherOperandNum; 394 } SDTCisSameNumEltsAs_Info; 395 struct { 396 unsigned OtherOperandNum; 397 } SDTCisSameSizeAs_Info; 398 } x; 399 400 // The VT for SDTCisVT and SDTCVecEltisVT. 401 // Must not be in the union because it has a non-trivial destructor. 402 ValueTypeByHwMode VVT; 403 404 /// ApplyTypeConstraint - Given a node in a pattern, apply this type 405 /// constraint to the nodes operands. This returns true if it makes a 406 /// change, false otherwise. If a type contradiction is found, an error 407 /// is flagged. 408 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo, 409 TreePattern &TP) const; 410 }; 411 412 /// ScopedName - A name of a node associated with a "scope" that indicates 413 /// the context (e.g. instance of Pattern or PatFrag) in which the name was 414 /// used. This enables substitution of pattern fragments while keeping track 415 /// of what name(s) were originally given to various nodes in the tree. 416 class ScopedName { 417 unsigned Scope; 418 std::string Identifier; 419 public: 420 ScopedName(unsigned Scope, StringRef Identifier) 421 : Scope(Scope), Identifier(Identifier) { 422 assert(Scope != 0 && 423 "Scope == 0 is used to indicate predicates without arguments"); 424 } 425 426 unsigned getScope() const { return Scope; } 427 const std::string &getIdentifier() const { return Identifier; } 428 429 std::string getFullName() const; 430 431 bool operator==(const ScopedName &o) const; 432 bool operator!=(const ScopedName &o) const; 433 }; 434 435 /// SDNodeInfo - One of these records is created for each SDNode instance in 436 /// the target .td file. This represents the various dag nodes we will be 437 /// processing. 438 class SDNodeInfo { 439 Record *Def; 440 StringRef EnumName; 441 StringRef SDClassName; 442 unsigned Properties; 443 unsigned NumResults; 444 int NumOperands; 445 std::vector<SDTypeConstraint> TypeConstraints; 446 public: 447 // Parse the specified record. 448 SDNodeInfo(Record *R, const CodeGenHwModes &CGH); 449 450 unsigned getNumResults() const { return NumResults; } 451 452 /// getNumOperands - This is the number of operands required or -1 if 453 /// variadic. 454 int getNumOperands() const { return NumOperands; } 455 Record *getRecord() const { return Def; } 456 StringRef getEnumName() const { return EnumName; } 457 StringRef getSDClassName() const { return SDClassName; } 458 459 const std::vector<SDTypeConstraint> &getTypeConstraints() const { 460 return TypeConstraints; 461 } 462 463 /// getKnownType - If the type constraints on this node imply a fixed type 464 /// (e.g. all stores return void, etc), then return it as an 465 /// MVT::SimpleValueType. Otherwise, return MVT::Other. 466 MVT::SimpleValueType getKnownType(unsigned ResNo) const; 467 468 /// hasProperty - Return true if this node has the specified property. 469 /// 470 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); } 471 472 /// ApplyTypeConstraints - Given a node in a pattern, apply the type 473 /// constraints for this node to the operands of the node. This returns 474 /// true if it makes a change, false otherwise. If a type contradiction is 475 /// found, an error is flagged. 476 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const; 477 }; 478 479 /// TreePredicateFn - This is an abstraction that represents the predicates on 480 /// a PatFrag node. This is a simple one-word wrapper around a pointer to 481 /// provide nice accessors. 482 class TreePredicateFn { 483 /// PatFragRec - This is the TreePattern for the PatFrag that we 484 /// originally came from. 485 TreePattern *PatFragRec; 486 public: 487 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag. 488 TreePredicateFn(TreePattern *N); 489 490 491 TreePattern *getOrigPatFragRecord() const { return PatFragRec; } 492 493 /// isAlwaysTrue - Return true if this is a noop predicate. 494 bool isAlwaysTrue() const; 495 496 bool isImmediatePattern() const { return hasImmCode(); } 497 498 /// getImmediatePredicateCode - Return the code that evaluates this pattern if 499 /// this is an immediate predicate. It is an error to call this on a 500 /// non-immediate pattern. 501 std::string getImmediatePredicateCode() const { 502 std::string Result = getImmCode(); 503 assert(!Result.empty() && "Isn't an immediate pattern!"); 504 return Result; 505 } 506 507 bool operator==(const TreePredicateFn &RHS) const { 508 return PatFragRec == RHS.PatFragRec; 509 } 510 511 bool operator!=(const TreePredicateFn &RHS) const { return !(*this == RHS); } 512 513 /// Return the name to use in the generated code to reference this, this is 514 /// "Predicate_foo" if from a pattern fragment "foo". 515 std::string getFnName() const; 516 517 /// getCodeToRunOnSDNode - Return the code for the function body that 518 /// evaluates this predicate. The argument is expected to be in "Node", 519 /// not N. This handles casting and conversion to a concrete node type as 520 /// appropriate. 521 std::string getCodeToRunOnSDNode() const; 522 523 /// Get the data type of the argument to getImmediatePredicateCode(). 524 StringRef getImmType() const; 525 526 /// Get a string that describes the type returned by getImmType() but is 527 /// usable as part of an identifier. 528 StringRef getImmTypeIdentifier() const; 529 530 // Predicate code uses the PatFrag's captured operands. 531 bool usesOperands() const; 532 533 // Is the desired predefined predicate for a load? 534 bool isLoad() const; 535 // Is the desired predefined predicate for a store? 536 bool isStore() const; 537 // Is the desired predefined predicate for an atomic? 538 bool isAtomic() const; 539 540 /// Is this predicate the predefined unindexed load predicate? 541 /// Is this predicate the predefined unindexed store predicate? 542 bool isUnindexed() const; 543 /// Is this predicate the predefined non-extending load predicate? 544 bool isNonExtLoad() const; 545 /// Is this predicate the predefined any-extend load predicate? 546 bool isAnyExtLoad() const; 547 /// Is this predicate the predefined sign-extend load predicate? 548 bool isSignExtLoad() const; 549 /// Is this predicate the predefined zero-extend load predicate? 550 bool isZeroExtLoad() const; 551 /// Is this predicate the predefined non-truncating store predicate? 552 bool isNonTruncStore() const; 553 /// Is this predicate the predefined truncating store predicate? 554 bool isTruncStore() const; 555 556 /// Is this predicate the predefined monotonic atomic predicate? 557 bool isAtomicOrderingMonotonic() const; 558 /// Is this predicate the predefined acquire atomic predicate? 559 bool isAtomicOrderingAcquire() const; 560 /// Is this predicate the predefined release atomic predicate? 561 bool isAtomicOrderingRelease() const; 562 /// Is this predicate the predefined acquire-release atomic predicate? 563 bool isAtomicOrderingAcquireRelease() const; 564 /// Is this predicate the predefined sequentially consistent atomic predicate? 565 bool isAtomicOrderingSequentiallyConsistent() const; 566 567 /// Is this predicate the predefined acquire-or-stronger atomic predicate? 568 bool isAtomicOrderingAcquireOrStronger() const; 569 /// Is this predicate the predefined weaker-than-acquire atomic predicate? 570 bool isAtomicOrderingWeakerThanAcquire() const; 571 572 /// Is this predicate the predefined release-or-stronger atomic predicate? 573 bool isAtomicOrderingReleaseOrStronger() const; 574 /// Is this predicate the predefined weaker-than-release atomic predicate? 575 bool isAtomicOrderingWeakerThanRelease() const; 576 577 /// If non-null, indicates that this predicate is a predefined memory VT 578 /// predicate for a load/store and returns the ValueType record for the memory VT. 579 Record *getMemoryVT() const; 580 /// If non-null, indicates that this predicate is a predefined memory VT 581 /// predicate (checking only the scalar type) for load/store and returns the 582 /// ValueType record for the memory VT. 583 Record *getScalarMemoryVT() const; 584 585 // If true, indicates that GlobalISel-based C++ code was supplied. 586 bool hasGISelPredicateCode() const; 587 std::string getGISelPredicateCode() const; 588 589 private: 590 bool hasPredCode() const; 591 bool hasImmCode() const; 592 std::string getPredCode() const; 593 std::string getImmCode() const; 594 bool immCodeUsesAPInt() const; 595 bool immCodeUsesAPFloat() const; 596 597 bool isPredefinedPredicateEqualTo(StringRef Field, bool Value) const; 598 }; 599 600 struct TreePredicateCall { 601 TreePredicateFn Fn; 602 603 // Scope -- unique identifier for retrieving named arguments. 0 is used when 604 // the predicate does not use named arguments. 605 unsigned Scope; 606 607 TreePredicateCall(const TreePredicateFn &Fn, unsigned Scope) 608 : Fn(Fn), Scope(Scope) {} 609 610 bool operator==(const TreePredicateCall &o) const { 611 return Fn == o.Fn && Scope == o.Scope; 612 } 613 bool operator!=(const TreePredicateCall &o) const { 614 return !(*this == o); 615 } 616 }; 617 618 class TreePatternNode { 619 /// The type of each node result. Before and during type inference, each 620 /// result may be a set of possible types. After (successful) type inference, 621 /// each is a single concrete type. 622 std::vector<TypeSetByHwMode> Types; 623 624 /// The index of each result in results of the pattern. 625 std::vector<unsigned> ResultPerm; 626 627 /// Operator - The Record for the operator if this is an interior node (not 628 /// a leaf). 629 Record *Operator; 630 631 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf. 632 /// 633 Init *Val; 634 635 /// Name - The name given to this node with the :$foo notation. 636 /// 637 std::string Name; 638 639 std::vector<ScopedName> NamesAsPredicateArg; 640 641 /// PredicateCalls - The predicate functions to execute on this node to check 642 /// for a match. If this list is empty, no predicate is involved. 643 std::vector<TreePredicateCall> PredicateCalls; 644 645 /// TransformFn - The transformation function to execute on this node before 646 /// it can be substituted into the resulting instruction on a pattern match. 647 Record *TransformFn; 648 649 std::vector<TreePatternNodePtr> Children; 650 651 public: 652 TreePatternNode(Record *Op, std::vector<TreePatternNodePtr> Ch, 653 unsigned NumResults) 654 : Operator(Op), Val(nullptr), TransformFn(nullptr), 655 Children(std::move(Ch)) { 656 Types.resize(NumResults); 657 ResultPerm.resize(NumResults); 658 std::iota(ResultPerm.begin(), ResultPerm.end(), 0); 659 } 660 TreePatternNode(Init *val, unsigned NumResults) // leaf ctor 661 : Operator(nullptr), Val(val), TransformFn(nullptr) { 662 Types.resize(NumResults); 663 ResultPerm.resize(NumResults); 664 std::iota(ResultPerm.begin(), ResultPerm.end(), 0); 665 } 666 667 bool hasName() const { return !Name.empty(); } 668 const std::string &getName() const { return Name; } 669 void setName(StringRef N) { Name.assign(N.begin(), N.end()); } 670 671 const std::vector<ScopedName> &getNamesAsPredicateArg() const { 672 return NamesAsPredicateArg; 673 } 674 void setNamesAsPredicateArg(const std::vector<ScopedName>& Names) { 675 NamesAsPredicateArg = Names; 676 } 677 void addNameAsPredicateArg(const ScopedName &N) { 678 NamesAsPredicateArg.push_back(N); 679 } 680 681 bool isLeaf() const { return Val != nullptr; } 682 683 // Type accessors. 684 unsigned getNumTypes() const { return Types.size(); } 685 ValueTypeByHwMode getType(unsigned ResNo) const { 686 return Types[ResNo].getValueTypeByHwMode(); 687 } 688 const std::vector<TypeSetByHwMode> &getExtTypes() const { return Types; } 689 const TypeSetByHwMode &getExtType(unsigned ResNo) const { 690 return Types[ResNo]; 691 } 692 TypeSetByHwMode &getExtType(unsigned ResNo) { return Types[ResNo]; } 693 void setType(unsigned ResNo, const TypeSetByHwMode &T) { Types[ResNo] = T; } 694 MVT::SimpleValueType getSimpleType(unsigned ResNo) const { 695 return Types[ResNo].getMachineValueType().SimpleTy; 696 } 697 698 bool hasConcreteType(unsigned ResNo) const { 699 return Types[ResNo].isValueTypeByHwMode(false); 700 } 701 bool isTypeCompletelyUnknown(unsigned ResNo, TreePattern &TP) const { 702 return Types[ResNo].empty(); 703 } 704 705 unsigned getNumResults() const { return ResultPerm.size(); } 706 unsigned getResultIndex(unsigned ResNo) const { return ResultPerm[ResNo]; } 707 void setResultIndex(unsigned ResNo, unsigned RI) { ResultPerm[ResNo] = RI; } 708 709 Init *getLeafValue() const { assert(isLeaf()); return Val; } 710 Record *getOperator() const { assert(!isLeaf()); return Operator; } 711 712 unsigned getNumChildren() const { return Children.size(); } 713 TreePatternNode *getChild(unsigned N) const { return Children[N].get(); } 714 const TreePatternNodePtr &getChildShared(unsigned N) const { 715 return Children[N]; 716 } 717 void setChild(unsigned i, TreePatternNodePtr N) { Children[i] = N; } 718 719 /// hasChild - Return true if N is any of our children. 720 bool hasChild(const TreePatternNode *N) const { 721 for (unsigned i = 0, e = Children.size(); i != e; ++i) 722 if (Children[i].get() == N) 723 return true; 724 return false; 725 } 726 727 bool hasProperTypeByHwMode() const; 728 bool hasPossibleType() const; 729 bool setDefaultMode(unsigned Mode); 730 731 bool hasAnyPredicate() const { return !PredicateCalls.empty(); } 732 733 const std::vector<TreePredicateCall> &getPredicateCalls() const { 734 return PredicateCalls; 735 } 736 void clearPredicateCalls() { PredicateCalls.clear(); } 737 void setPredicateCalls(const std::vector<TreePredicateCall> &Calls) { 738 assert(PredicateCalls.empty() && "Overwriting non-empty predicate list!"); 739 PredicateCalls = Calls; 740 } 741 void addPredicateCall(const TreePredicateCall &Call) { 742 assert(!Call.Fn.isAlwaysTrue() && "Empty predicate string!"); 743 assert(!is_contained(PredicateCalls, Call) && "predicate applied recursively"); 744 PredicateCalls.push_back(Call); 745 } 746 void addPredicateCall(const TreePredicateFn &Fn, unsigned Scope) { 747 assert((Scope != 0) == Fn.usesOperands()); 748 addPredicateCall(TreePredicateCall(Fn, Scope)); 749 } 750 751 Record *getTransformFn() const { return TransformFn; } 752 void setTransformFn(Record *Fn) { TransformFn = Fn; } 753 754 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the 755 /// CodeGenIntrinsic information for it, otherwise return a null pointer. 756 const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const; 757 758 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern, 759 /// return the ComplexPattern information, otherwise return null. 760 const ComplexPattern * 761 getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const; 762 763 /// Returns the number of MachineInstr operands that would be produced by this 764 /// node if it mapped directly to an output Instruction's 765 /// operand. ComplexPattern specifies this explicitly; MIOperandInfo gives it 766 /// for Operands; otherwise 1. 767 unsigned getNumMIResults(const CodeGenDAGPatterns &CGP) const; 768 769 /// NodeHasProperty - Return true if this node has the specified property. 770 bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const; 771 772 /// TreeHasProperty - Return true if any node in this tree has the specified 773 /// property. 774 bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const; 775 776 /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is 777 /// marked isCommutative. 778 bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const; 779 780 void print(raw_ostream &OS) const; 781 void dump() const; 782 783 public: // Higher level manipulation routines. 784 785 /// clone - Return a new copy of this tree. 786 /// 787 TreePatternNodePtr clone() const; 788 789 /// RemoveAllTypes - Recursively strip all the types of this tree. 790 void RemoveAllTypes(); 791 792 /// isIsomorphicTo - Return true if this node is recursively isomorphic to 793 /// the specified node. For this comparison, all of the state of the node 794 /// is considered, except for the assigned name. Nodes with differing names 795 /// that are otherwise identical are considered isomorphic. 796 bool isIsomorphicTo(const TreePatternNode *N, 797 const MultipleUseVarSet &DepVars) const; 798 799 /// SubstituteFormalArguments - Replace the formal arguments in this tree 800 /// with actual values specified by ArgMap. 801 void 802 SubstituteFormalArguments(std::map<std::string, TreePatternNodePtr> &ArgMap); 803 804 /// InlinePatternFragments - If this pattern refers to any pattern 805 /// fragments, return the set of inlined versions (this can be more than 806 /// one if a PatFrags record has multiple alternatives). 807 void InlinePatternFragments(TreePatternNodePtr T, 808 TreePattern &TP, 809 std::vector<TreePatternNodePtr> &OutAlternatives); 810 811 /// ApplyTypeConstraints - Apply all of the type constraints relevant to 812 /// this node and its children in the tree. This returns true if it makes a 813 /// change, false otherwise. If a type contradiction is found, flag an error. 814 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters); 815 816 /// UpdateNodeType - Set the node type of N to VT if VT contains 817 /// information. If N already contains a conflicting type, then flag an 818 /// error. This returns true if any information was updated. 819 /// 820 bool UpdateNodeType(unsigned ResNo, const TypeSetByHwMode &InTy, 821 TreePattern &TP); 822 bool UpdateNodeType(unsigned ResNo, MVT::SimpleValueType InTy, 823 TreePattern &TP); 824 bool UpdateNodeType(unsigned ResNo, ValueTypeByHwMode InTy, 825 TreePattern &TP); 826 827 // Update node type with types inferred from an instruction operand or result 828 // def from the ins/outs lists. 829 // Return true if the type changed. 830 bool UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand, TreePattern &TP); 831 832 /// ContainsUnresolvedType - Return true if this tree contains any 833 /// unresolved types. 834 bool ContainsUnresolvedType(TreePattern &TP) const; 835 836 /// canPatternMatch - If it is impossible for this pattern to match on this 837 /// target, fill in Reason and return false. Otherwise, return true. 838 bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP); 839 }; 840 841 inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) { 842 TPN.print(OS); 843 return OS; 844 } 845 846 847 /// TreePattern - Represent a pattern, used for instructions, pattern 848 /// fragments, etc. 849 /// 850 class TreePattern { 851 /// Trees - The list of pattern trees which corresponds to this pattern. 852 /// Note that PatFrag's only have a single tree. 853 /// 854 std::vector<TreePatternNodePtr> Trees; 855 856 /// NamedNodes - This is all of the nodes that have names in the trees in this 857 /// pattern. 858 StringMap<SmallVector<TreePatternNode *, 1>> NamedNodes; 859 860 /// TheRecord - The actual TableGen record corresponding to this pattern. 861 /// 862 Record *TheRecord; 863 864 /// Args - This is a list of all of the arguments to this pattern (for 865 /// PatFrag patterns), which are the 'node' markers in this pattern. 866 std::vector<std::string> Args; 867 868 /// CDP - the top-level object coordinating this madness. 869 /// 870 CodeGenDAGPatterns &CDP; 871 872 /// isInputPattern - True if this is an input pattern, something to match. 873 /// False if this is an output pattern, something to emit. 874 bool isInputPattern; 875 876 /// hasError - True if the currently processed nodes have unresolvable types 877 /// or other non-fatal errors 878 bool HasError; 879 880 /// It's important that the usage of operands in ComplexPatterns is 881 /// consistent: each named operand can be defined by at most one 882 /// ComplexPattern. This records the ComplexPattern instance and the operand 883 /// number for each operand encountered in a ComplexPattern to aid in that 884 /// check. 885 StringMap<std::pair<Record *, unsigned>> ComplexPatternOperands; 886 887 TypeInfer Infer; 888 889 public: 890 891 /// TreePattern constructor - Parse the specified DagInits into the 892 /// current record. 893 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput, 894 CodeGenDAGPatterns &ise); 895 TreePattern(Record *TheRec, DagInit *Pat, bool isInput, 896 CodeGenDAGPatterns &ise); 897 TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput, 898 CodeGenDAGPatterns &ise); 899 900 /// getTrees - Return the tree patterns which corresponds to this pattern. 901 /// 902 const std::vector<TreePatternNodePtr> &getTrees() const { return Trees; } 903 unsigned getNumTrees() const { return Trees.size(); } 904 const TreePatternNodePtr &getTree(unsigned i) const { return Trees[i]; } 905 void setTree(unsigned i, TreePatternNodePtr Tree) { Trees[i] = Tree; } 906 const TreePatternNodePtr &getOnlyTree() const { 907 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!"); 908 return Trees[0]; 909 } 910 911 const StringMap<SmallVector<TreePatternNode *, 1>> &getNamedNodesMap() { 912 if (NamedNodes.empty()) 913 ComputeNamedNodes(); 914 return NamedNodes; 915 } 916 917 /// getRecord - Return the actual TableGen record corresponding to this 918 /// pattern. 919 /// 920 Record *getRecord() const { return TheRecord; } 921 922 unsigned getNumArgs() const { return Args.size(); } 923 const std::string &getArgName(unsigned i) const { 924 assert(i < Args.size() && "Argument reference out of range!"); 925 return Args[i]; 926 } 927 std::vector<std::string> &getArgList() { return Args; } 928 929 CodeGenDAGPatterns &getDAGPatterns() const { return CDP; } 930 931 /// InlinePatternFragments - If this pattern refers to any pattern 932 /// fragments, inline them into place, giving us a pattern without any 933 /// PatFrags references. This may increase the number of trees in the 934 /// pattern if a PatFrags has multiple alternatives. 935 void InlinePatternFragments() { 936 std::vector<TreePatternNodePtr> Copy = Trees; 937 Trees.clear(); 938 for (unsigned i = 0, e = Copy.size(); i != e; ++i) 939 Copy[i]->InlinePatternFragments(Copy[i], *this, Trees); 940 } 941 942 /// InferAllTypes - Infer/propagate as many types throughout the expression 943 /// patterns as possible. Return true if all types are inferred, false 944 /// otherwise. Bail out if a type contradiction is found. 945 bool InferAllTypes( 946 const StringMap<SmallVector<TreePatternNode *, 1>> *NamedTypes = nullptr); 947 948 /// error - If this is the first error in the current resolution step, 949 /// print it and set the error flag. Otherwise, continue silently. 950 void error(const Twine &Msg); 951 bool hasError() const { 952 return HasError; 953 } 954 void resetError() { 955 HasError = false; 956 } 957 958 TypeInfer &getInfer() { return Infer; } 959 960 void print(raw_ostream &OS) const; 961 void dump() const; 962 963 private: 964 TreePatternNodePtr ParseTreePattern(Init *DI, StringRef OpName); 965 void ComputeNamedNodes(); 966 void ComputeNamedNodes(TreePatternNode *N); 967 }; 968 969 970 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 971 const TypeSetByHwMode &InTy, 972 TreePattern &TP) { 973 TypeSetByHwMode VTS(InTy); 974 TP.getInfer().expandOverloads(VTS); 975 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 976 } 977 978 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 979 MVT::SimpleValueType InTy, 980 TreePattern &TP) { 981 TypeSetByHwMode VTS(InTy); 982 TP.getInfer().expandOverloads(VTS); 983 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 984 } 985 986 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 987 ValueTypeByHwMode InTy, 988 TreePattern &TP) { 989 TypeSetByHwMode VTS(InTy); 990 TP.getInfer().expandOverloads(VTS); 991 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 992 } 993 994 995 /// DAGDefaultOperand - One of these is created for each OperandWithDefaultOps 996 /// that has a set ExecuteAlways / DefaultOps field. 997 struct DAGDefaultOperand { 998 std::vector<TreePatternNodePtr> DefaultOps; 999 }; 1000 1001 class DAGInstruction { 1002 std::vector<Record*> Results; 1003 std::vector<Record*> Operands; 1004 std::vector<Record*> ImpResults; 1005 TreePatternNodePtr SrcPattern; 1006 TreePatternNodePtr ResultPattern; 1007 1008 public: 1009 DAGInstruction(const std::vector<Record*> &results, 1010 const std::vector<Record*> &operands, 1011 const std::vector<Record*> &impresults, 1012 TreePatternNodePtr srcpattern = nullptr, 1013 TreePatternNodePtr resultpattern = nullptr) 1014 : Results(results), Operands(operands), ImpResults(impresults), 1015 SrcPattern(srcpattern), ResultPattern(resultpattern) {} 1016 1017 unsigned getNumResults() const { return Results.size(); } 1018 unsigned getNumOperands() const { return Operands.size(); } 1019 unsigned getNumImpResults() const { return ImpResults.size(); } 1020 const std::vector<Record*>& getImpResults() const { return ImpResults; } 1021 1022 Record *getResult(unsigned RN) const { 1023 assert(RN < Results.size()); 1024 return Results[RN]; 1025 } 1026 1027 Record *getOperand(unsigned ON) const { 1028 assert(ON < Operands.size()); 1029 return Operands[ON]; 1030 } 1031 1032 Record *getImpResult(unsigned RN) const { 1033 assert(RN < ImpResults.size()); 1034 return ImpResults[RN]; 1035 } 1036 1037 TreePatternNodePtr getSrcPattern() const { return SrcPattern; } 1038 TreePatternNodePtr getResultPattern() const { return ResultPattern; } 1039 }; 1040 1041 /// This class represents a condition that has to be satisfied for a pattern 1042 /// to be tried. It is a generalization of a class "Pattern" from Target.td: 1043 /// in addition to the Target.td's predicates, this class can also represent 1044 /// conditions associated with HW modes. Both types will eventually become 1045 /// strings containing C++ code to be executed, the difference is in how 1046 /// these strings are generated. 1047 class Predicate { 1048 public: 1049 Predicate(Record *R, bool C = true) : Def(R), IfCond(C), IsHwMode(false) { 1050 assert(R->isSubClassOf("Predicate") && 1051 "Predicate objects should only be created for records derived" 1052 "from Predicate class"); 1053 } 1054 Predicate(StringRef FS, bool C = true) : Def(nullptr), Features(FS.str()), 1055 IfCond(C), IsHwMode(true) {} 1056 1057 /// Return a string which contains the C++ condition code that will serve 1058 /// as a predicate during instruction selection. 1059 std::string getCondString() const { 1060 // The string will excute in a subclass of SelectionDAGISel. 1061 // Cast to std::string explicitly to avoid ambiguity with StringRef. 1062 std::string C = IsHwMode 1063 ? std::string("MF->getSubtarget().checkFeatures(\"" + Features + "\")") 1064 : std::string(Def->getValueAsString("CondString")); 1065 return IfCond ? C : "!("+C+')'; 1066 } 1067 bool operator==(const Predicate &P) const { 1068 return IfCond == P.IfCond && IsHwMode == P.IsHwMode && Def == P.Def; 1069 } 1070 bool operator<(const Predicate &P) const { 1071 if (IsHwMode != P.IsHwMode) 1072 return IsHwMode < P.IsHwMode; 1073 assert(!Def == !P.Def && "Inconsistency between Def and IsHwMode"); 1074 if (IfCond != P.IfCond) 1075 return IfCond < P.IfCond; 1076 if (Def) 1077 return LessRecord()(Def, P.Def); 1078 return Features < P.Features; 1079 } 1080 Record *Def; ///< Predicate definition from .td file, null for 1081 ///< HW modes. 1082 std::string Features; ///< Feature string for HW mode. 1083 bool IfCond; ///< The boolean value that the condition has to 1084 ///< evaluate to for this predicate to be true. 1085 bool IsHwMode; ///< Does this predicate correspond to a HW mode? 1086 }; 1087 1088 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns 1089 /// processed to produce isel. 1090 class PatternToMatch { 1091 public: 1092 PatternToMatch(Record *srcrecord, std::vector<Predicate> preds, 1093 TreePatternNodePtr src, TreePatternNodePtr dst, 1094 std::vector<Record *> dstregs, int complexity, 1095 unsigned uid, unsigned setmode = 0) 1096 : SrcRecord(srcrecord), SrcPattern(src), DstPattern(dst), 1097 Predicates(std::move(preds)), Dstregs(std::move(dstregs)), 1098 AddedComplexity(complexity), ID(uid), ForceMode(setmode) {} 1099 1100 Record *SrcRecord; // Originating Record for the pattern. 1101 TreePatternNodePtr SrcPattern; // Source pattern to match. 1102 TreePatternNodePtr DstPattern; // Resulting pattern. 1103 std::vector<Predicate> Predicates; // Top level predicate conditions 1104 // to match. 1105 std::vector<Record*> Dstregs; // Physical register defs being matched. 1106 int AddedComplexity; // Add to matching pattern complexity. 1107 unsigned ID; // Unique ID for the record. 1108 unsigned ForceMode; // Force this mode in type inference when set. 1109 1110 Record *getSrcRecord() const { return SrcRecord; } 1111 TreePatternNode *getSrcPattern() const { return SrcPattern.get(); } 1112 TreePatternNodePtr getSrcPatternShared() const { return SrcPattern; } 1113 TreePatternNode *getDstPattern() const { return DstPattern.get(); } 1114 TreePatternNodePtr getDstPatternShared() const { return DstPattern; } 1115 const std::vector<Record*> &getDstRegs() const { return Dstregs; } 1116 int getAddedComplexity() const { return AddedComplexity; } 1117 const std::vector<Predicate> &getPredicates() const { return Predicates; } 1118 1119 std::string getPredicateCheck() const; 1120 1121 /// Compute the complexity metric for the input pattern. This roughly 1122 /// corresponds to the number of nodes that are covered. 1123 int getPatternComplexity(const CodeGenDAGPatterns &CGP) const; 1124 }; 1125 1126 class CodeGenDAGPatterns { 1127 RecordKeeper &Records; 1128 CodeGenTarget Target; 1129 CodeGenIntrinsicTable Intrinsics; 1130 CodeGenIntrinsicTable TgtIntrinsics; 1131 1132 std::map<Record*, SDNodeInfo, LessRecordByID> SDNodes; 1133 std::map<Record*, std::pair<Record*, std::string>, LessRecordByID> 1134 SDNodeXForms; 1135 std::map<Record*, ComplexPattern, LessRecordByID> ComplexPatterns; 1136 std::map<Record *, std::unique_ptr<TreePattern>, LessRecordByID> 1137 PatternFragments; 1138 std::map<Record*, DAGDefaultOperand, LessRecordByID> DefaultOperands; 1139 std::map<Record*, DAGInstruction, LessRecordByID> Instructions; 1140 1141 // Specific SDNode definitions: 1142 Record *intrinsic_void_sdnode; 1143 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode; 1144 1145 /// PatternsToMatch - All of the things we are matching on the DAG. The first 1146 /// value is the pattern to match, the second pattern is the result to 1147 /// emit. 1148 std::vector<PatternToMatch> PatternsToMatch; 1149 1150 TypeSetByHwMode LegalVTS; 1151 1152 using PatternRewriterFn = std::function<void (TreePattern *)>; 1153 PatternRewriterFn PatternRewriter; 1154 1155 unsigned NumScopes = 0; 1156 1157 public: 1158 CodeGenDAGPatterns(RecordKeeper &R, 1159 PatternRewriterFn PatternRewriter = nullptr); 1160 1161 CodeGenTarget &getTargetInfo() { return Target; } 1162 const CodeGenTarget &getTargetInfo() const { return Target; } 1163 const TypeSetByHwMode &getLegalTypes() const { return LegalVTS; } 1164 1165 Record *getSDNodeNamed(const std::string &Name) const; 1166 1167 const SDNodeInfo &getSDNodeInfo(Record *R) const { 1168 auto F = SDNodes.find(R); 1169 assert(F != SDNodes.end() && "Unknown node!"); 1170 return F->second; 1171 } 1172 1173 // Node transformation lookups. 1174 typedef std::pair<Record*, std::string> NodeXForm; 1175 const NodeXForm &getSDNodeTransform(Record *R) const { 1176 auto F = SDNodeXForms.find(R); 1177 assert(F != SDNodeXForms.end() && "Invalid transform!"); 1178 return F->second; 1179 } 1180 1181 typedef std::map<Record*, NodeXForm, LessRecordByID>::const_iterator 1182 nx_iterator; 1183 nx_iterator nx_begin() const { return SDNodeXForms.begin(); } 1184 nx_iterator nx_end() const { return SDNodeXForms.end(); } 1185 1186 1187 const ComplexPattern &getComplexPattern(Record *R) const { 1188 auto F = ComplexPatterns.find(R); 1189 assert(F != ComplexPatterns.end() && "Unknown addressing mode!"); 1190 return F->second; 1191 } 1192 1193 const CodeGenIntrinsic &getIntrinsic(Record *R) const { 1194 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i) 1195 if (Intrinsics[i].TheDef == R) return Intrinsics[i]; 1196 for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i) 1197 if (TgtIntrinsics[i].TheDef == R) return TgtIntrinsics[i]; 1198 llvm_unreachable("Unknown intrinsic!"); 1199 } 1200 1201 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const { 1202 if (IID-1 < Intrinsics.size()) 1203 return Intrinsics[IID-1]; 1204 if (IID-Intrinsics.size()-1 < TgtIntrinsics.size()) 1205 return TgtIntrinsics[IID-Intrinsics.size()-1]; 1206 llvm_unreachable("Bad intrinsic ID!"); 1207 } 1208 1209 unsigned getIntrinsicID(Record *R) const { 1210 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i) 1211 if (Intrinsics[i].TheDef == R) return i; 1212 for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i) 1213 if (TgtIntrinsics[i].TheDef == R) return i + Intrinsics.size(); 1214 llvm_unreachable("Unknown intrinsic!"); 1215 } 1216 1217 const DAGDefaultOperand &getDefaultOperand(Record *R) const { 1218 auto F = DefaultOperands.find(R); 1219 assert(F != DefaultOperands.end() &&"Isn't an analyzed default operand!"); 1220 return F->second; 1221 } 1222 1223 // Pattern Fragment information. 1224 TreePattern *getPatternFragment(Record *R) const { 1225 auto F = PatternFragments.find(R); 1226 assert(F != PatternFragments.end() && "Invalid pattern fragment request!"); 1227 return F->second.get(); 1228 } 1229 TreePattern *getPatternFragmentIfRead(Record *R) const { 1230 auto F = PatternFragments.find(R); 1231 if (F == PatternFragments.end()) 1232 return nullptr; 1233 return F->second.get(); 1234 } 1235 1236 typedef std::map<Record *, std::unique_ptr<TreePattern>, 1237 LessRecordByID>::const_iterator pf_iterator; 1238 pf_iterator pf_begin() const { return PatternFragments.begin(); } 1239 pf_iterator pf_end() const { return PatternFragments.end(); } 1240 iterator_range<pf_iterator> ptfs() const { return PatternFragments; } 1241 1242 // Patterns to match information. 1243 typedef std::vector<PatternToMatch>::const_iterator ptm_iterator; 1244 ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); } 1245 ptm_iterator ptm_end() const { return PatternsToMatch.end(); } 1246 iterator_range<ptm_iterator> ptms() const { return PatternsToMatch; } 1247 1248 /// Parse the Pattern for an instruction, and insert the result in DAGInsts. 1249 typedef std::map<Record*, DAGInstruction, LessRecordByID> DAGInstMap; 1250 void parseInstructionPattern( 1251 CodeGenInstruction &CGI, ListInit *Pattern, 1252 DAGInstMap &DAGInsts); 1253 1254 const DAGInstruction &getInstruction(Record *R) const { 1255 auto F = Instructions.find(R); 1256 assert(F != Instructions.end() && "Unknown instruction!"); 1257 return F->second; 1258 } 1259 1260 Record *get_intrinsic_void_sdnode() const { 1261 return intrinsic_void_sdnode; 1262 } 1263 Record *get_intrinsic_w_chain_sdnode() const { 1264 return intrinsic_w_chain_sdnode; 1265 } 1266 Record *get_intrinsic_wo_chain_sdnode() const { 1267 return intrinsic_wo_chain_sdnode; 1268 } 1269 1270 bool hasTargetIntrinsics() { return !TgtIntrinsics.empty(); } 1271 1272 unsigned allocateScope() { return ++NumScopes; } 1273 1274 private: 1275 void ParseNodeInfo(); 1276 void ParseNodeTransforms(); 1277 void ParseComplexPatterns(); 1278 void ParsePatternFragments(bool OutFrags = false); 1279 void ParseDefaultOperands(); 1280 void ParseInstructions(); 1281 void ParsePatterns(); 1282 void ExpandHwModeBasedTypes(); 1283 void InferInstructionFlags(); 1284 void GenerateVariants(); 1285 void VerifyInstructionFlags(); 1286 1287 std::vector<Predicate> makePredList(ListInit *L); 1288 1289 void ParseOnePattern(Record *TheDef, 1290 TreePattern &Pattern, TreePattern &Result, 1291 const std::vector<Record *> &InstImpResults); 1292 void AddPatternToMatch(TreePattern *Pattern, PatternToMatch &&PTM); 1293 void FindPatternInputsAndOutputs( 1294 TreePattern &I, TreePatternNodePtr Pat, 1295 std::map<std::string, TreePatternNodePtr> &InstInputs, 1296 MapVector<std::string, TreePatternNodePtr, 1297 std::map<std::string, unsigned>> &InstResults, 1298 std::vector<Record *> &InstImpResults); 1299 }; 1300 1301 1302 inline bool SDNodeInfo::ApplyTypeConstraints(TreePatternNode *N, 1303 TreePattern &TP) const { 1304 bool MadeChange = false; 1305 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) 1306 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP); 1307 return MadeChange; 1308 } 1309 1310 } // end namespace llvm 1311 1312 #endif 1313