CodeGenDAGPatterns.h 46 KB

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