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