DAGISelMatcherGen.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. //===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
  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. #include "DAGISelMatcher.h"
  9. #include "CodeGenDAGPatterns.h"
  10. #include "CodeGenRegisters.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StringMap.h"
  13. #include "llvm/TableGen/Error.h"
  14. #include "llvm/TableGen/Record.h"
  15. #include <utility>
  16. using namespace llvm;
  17. /// getRegisterValueType - Look up and return the ValueType of the specified
  18. /// register. If the register is a member of multiple register classes which
  19. /// have different associated types, return MVT::Other.
  20. static MVT::SimpleValueType getRegisterValueType(Record *R,
  21. const CodeGenTarget &T) {
  22. bool FoundRC = false;
  23. MVT::SimpleValueType VT = MVT::Other;
  24. const CodeGenRegister *Reg = T.getRegBank().getReg(R);
  25. for (const auto &RC : T.getRegBank().getRegClasses()) {
  26. if (!RC.contains(Reg))
  27. continue;
  28. if (!FoundRC) {
  29. FoundRC = true;
  30. const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0);
  31. if (VVT.isSimple())
  32. VT = VVT.getSimple().SimpleTy;
  33. continue;
  34. }
  35. #ifndef NDEBUG
  36. // If this occurs in multiple register classes, they all have to agree.
  37. const ValueTypeByHwMode &T = RC.getValueTypeNum(0);
  38. assert((!T.isSimple() || T.getSimple().SimpleTy == VT) &&
  39. "ValueType mismatch between register classes for this register");
  40. #endif
  41. }
  42. return VT;
  43. }
  44. namespace {
  45. class MatcherGen {
  46. const PatternToMatch &Pattern;
  47. const CodeGenDAGPatterns &CGP;
  48. /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
  49. /// out with all of the types removed. This allows us to insert type checks
  50. /// as we scan the tree.
  51. TreePatternNodePtr PatWithNoTypes;
  52. /// VariableMap - A map from variable names ('$dst') to the recorded operand
  53. /// number that they were captured as. These are biased by 1 to make
  54. /// insertion easier.
  55. StringMap<unsigned> VariableMap;
  56. /// This maintains the recorded operand number that OPC_CheckComplexPattern
  57. /// drops each sub-operand into. We don't want to insert these into
  58. /// VariableMap because that leads to identity checking if they are
  59. /// encountered multiple times. Biased by 1 like VariableMap for
  60. /// consistency.
  61. StringMap<unsigned> NamedComplexPatternOperands;
  62. /// NextRecordedOperandNo - As we emit opcodes to record matched values in
  63. /// the RecordedNodes array, this keeps track of which slot will be next to
  64. /// record into.
  65. unsigned NextRecordedOperandNo;
  66. /// MatchedChainNodes - This maintains the position in the recorded nodes
  67. /// array of all of the recorded input nodes that have chains.
  68. SmallVector<unsigned, 2> MatchedChainNodes;
  69. /// MatchedComplexPatterns - This maintains a list of all of the
  70. /// ComplexPatterns that we need to check. The second element of each pair
  71. /// is the recorded operand number of the input node.
  72. SmallVector<std::pair<const TreePatternNode*,
  73. unsigned>, 2> MatchedComplexPatterns;
  74. /// PhysRegInputs - List list has an entry for each explicitly specified
  75. /// physreg input to the pattern. The first elt is the Register node, the
  76. /// second is the recorded slot number the input pattern match saved it in.
  77. SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
  78. /// Matcher - This is the top level of the generated matcher, the result.
  79. Matcher *TheMatcher;
  80. /// CurPredicate - As we emit matcher nodes, this points to the latest check
  81. /// which should have future checks stuck into its Next position.
  82. Matcher *CurPredicate;
  83. public:
  84. MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
  85. bool EmitMatcherCode(unsigned Variant);
  86. void EmitResultCode();
  87. Matcher *GetMatcher() const { return TheMatcher; }
  88. private:
  89. void AddMatcher(Matcher *NewNode);
  90. void InferPossibleTypes(unsigned ForceMode);
  91. // Matcher Generation.
  92. void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes,
  93. unsigned ForceMode);
  94. void EmitLeafMatchCode(const TreePatternNode *N);
  95. void EmitOperatorMatchCode(const TreePatternNode *N,
  96. TreePatternNode *NodeNoTypes,
  97. unsigned ForceMode);
  98. /// If this is the first time a node with unique identifier Name has been
  99. /// seen, record it. Otherwise, emit a check to make sure this is the same
  100. /// node. Returns true if this is the first encounter.
  101. bool recordUniqueNode(ArrayRef<std::string> Names);
  102. // Result Code Generation.
  103. unsigned getNamedArgumentSlot(StringRef Name) {
  104. unsigned VarMapEntry = VariableMap[Name];
  105. assert(VarMapEntry != 0 &&
  106. "Variable referenced but not defined and not caught earlier!");
  107. return VarMapEntry-1;
  108. }
  109. void EmitResultOperand(const TreePatternNode *N,
  110. SmallVectorImpl<unsigned> &ResultOps);
  111. void EmitResultOfNamedOperand(const TreePatternNode *N,
  112. SmallVectorImpl<unsigned> &ResultOps);
  113. void EmitResultLeafAsOperand(const TreePatternNode *N,
  114. SmallVectorImpl<unsigned> &ResultOps);
  115. void EmitResultInstructionAsOperand(const TreePatternNode *N,
  116. SmallVectorImpl<unsigned> &ResultOps);
  117. void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
  118. SmallVectorImpl<unsigned> &ResultOps);
  119. };
  120. } // end anonymous namespace
  121. MatcherGen::MatcherGen(const PatternToMatch &pattern,
  122. const CodeGenDAGPatterns &cgp)
  123. : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
  124. TheMatcher(nullptr), CurPredicate(nullptr) {
  125. // We need to produce the matcher tree for the patterns source pattern. To do
  126. // this we need to match the structure as well as the types. To do the type
  127. // matching, we want to figure out the fewest number of type checks we need to
  128. // emit. For example, if there is only one integer type supported by a
  129. // target, there should be no type comparisons at all for integer patterns!
  130. //
  131. // To figure out the fewest number of type checks needed, clone the pattern,
  132. // remove the types, then perform type inference on the pattern as a whole.
  133. // If there are unresolved types, emit an explicit check for those types,
  134. // apply the type to the tree, then rerun type inference. Iterate until all
  135. // types are resolved.
  136. //
  137. PatWithNoTypes = Pattern.getSrcPattern()->clone();
  138. PatWithNoTypes->RemoveAllTypes();
  139. // If there are types that are manifestly known, infer them.
  140. InferPossibleTypes(Pattern.getForceMode());
  141. }
  142. /// InferPossibleTypes - As we emit the pattern, we end up generating type
  143. /// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
  144. /// want to propagate implied types as far throughout the tree as possible so
  145. /// that we avoid doing redundant type checks. This does the type propagation.
  146. void MatcherGen::InferPossibleTypes(unsigned ForceMode) {
  147. // TP - Get *SOME* tree pattern, we don't care which. It is only used for
  148. // diagnostics, which we know are impossible at this point.
  149. TreePattern &TP = *CGP.pf_begin()->second;
  150. TP.getInfer().CodeGen = true;
  151. TP.getInfer().ForceMode = ForceMode;
  152. bool MadeChange = true;
  153. while (MadeChange)
  154. MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
  155. true/*Ignore reg constraints*/);
  156. }
  157. /// AddMatcher - Add a matcher node to the current graph we're building.
  158. void MatcherGen::AddMatcher(Matcher *NewNode) {
  159. if (CurPredicate)
  160. CurPredicate->setNext(NewNode);
  161. else
  162. TheMatcher = NewNode;
  163. CurPredicate = NewNode;
  164. }
  165. //===----------------------------------------------------------------------===//
  166. // Pattern Match Generation
  167. //===----------------------------------------------------------------------===//
  168. /// EmitLeafMatchCode - Generate matching code for leaf nodes.
  169. void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
  170. assert(N->isLeaf() && "Not a leaf?");
  171. // Direct match against an integer constant.
  172. if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
  173. // If this is the root of the dag we're matching, we emit a redundant opcode
  174. // check to ensure that this gets folded into the normal top-level
  175. // OpcodeSwitch.
  176. if (N == Pattern.getSrcPattern()) {
  177. const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
  178. AddMatcher(new CheckOpcodeMatcher(NI));
  179. }
  180. return AddMatcher(new CheckIntegerMatcher(II->getValue()));
  181. }
  182. // An UnsetInit represents a named node without any constraints.
  183. if (isa<UnsetInit>(N->getLeafValue())) {
  184. assert(N->hasName() && "Unnamed ? leaf");
  185. return;
  186. }
  187. DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
  188. if (!DI) {
  189. errs() << "Unknown leaf kind: " << *N << "\n";
  190. abort();
  191. }
  192. Record *LeafRec = DI->getDef();
  193. // A ValueType leaf node can represent a register when named, or itself when
  194. // unnamed.
  195. if (LeafRec->isSubClassOf("ValueType")) {
  196. // A named ValueType leaf always matches: (add i32:$a, i32:$b).
  197. if (N->hasName())
  198. return;
  199. // An unnamed ValueType as in (sext_inreg GPR:$foo, i8).
  200. return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
  201. }
  202. if (// Handle register references. Nothing to do here, they always match.
  203. LeafRec->isSubClassOf("RegisterClass") ||
  204. LeafRec->isSubClassOf("RegisterOperand") ||
  205. LeafRec->isSubClassOf("PointerLikeRegClass") ||
  206. LeafRec->isSubClassOf("SubRegIndex") ||
  207. // Place holder for SRCVALUE nodes. Nothing to do here.
  208. LeafRec->getName() == "srcvalue")
  209. return;
  210. // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
  211. // record the register
  212. if (LeafRec->isSubClassOf("Register")) {
  213. AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(),
  214. NextRecordedOperandNo));
  215. PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
  216. return;
  217. }
  218. if (LeafRec->isSubClassOf("CondCode"))
  219. return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
  220. if (LeafRec->isSubClassOf("ComplexPattern")) {
  221. // We can't model ComplexPattern uses that don't have their name taken yet.
  222. // The OPC_CheckComplexPattern operation implicitly records the results.
  223. if (N->getName().empty()) {
  224. std::string S;
  225. raw_string_ostream OS(S);
  226. OS << "We expect complex pattern uses to have names: " << *N;
  227. PrintFatalError(S);
  228. }
  229. // Remember this ComplexPattern so that we can emit it after all the other
  230. // structural matches are done.
  231. unsigned InputOperand = VariableMap[N->getName()] - 1;
  232. MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand));
  233. return;
  234. }
  235. if (LeafRec->getName() == "immAllOnesV") {
  236. // If this is the root of the dag we're matching, we emit a redundant opcode
  237. // check to ensure that this gets folded into the normal top-level
  238. // OpcodeSwitch.
  239. if (N == Pattern.getSrcPattern()) {
  240. MVT VT = N->getSimpleType(0);
  241. StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector";
  242. const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name));
  243. AddMatcher(new CheckOpcodeMatcher(NI));
  244. }
  245. return AddMatcher(new CheckImmAllOnesVMatcher());
  246. }
  247. if (LeafRec->getName() == "immAllZerosV") {
  248. // If this is the root of the dag we're matching, we emit a redundant opcode
  249. // check to ensure that this gets folded into the normal top-level
  250. // OpcodeSwitch.
  251. if (N == Pattern.getSrcPattern()) {
  252. MVT VT = N->getSimpleType(0);
  253. StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector";
  254. const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name));
  255. AddMatcher(new CheckOpcodeMatcher(NI));
  256. }
  257. return AddMatcher(new CheckImmAllZerosVMatcher());
  258. }
  259. errs() << "Unknown leaf kind: " << *N << "\n";
  260. abort();
  261. }
  262. void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
  263. TreePatternNode *NodeNoTypes,
  264. unsigned ForceMode) {
  265. assert(!N->isLeaf() && "Not an operator?");
  266. if (N->getOperator()->isSubClassOf("ComplexPattern")) {
  267. // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
  268. // "MY_PAT:op1:op2". We should already have validated that the uses are
  269. // consistent.
  270. std::string PatternName = std::string(N->getOperator()->getName());
  271. for (unsigned i = 0; i < N->getNumChildren(); ++i) {
  272. PatternName += ":";
  273. PatternName += N->getChild(i)->getName();
  274. }
  275. if (recordUniqueNode(PatternName)) {
  276. auto NodeAndOpNum = std::make_pair(N, NextRecordedOperandNo - 1);
  277. MatchedComplexPatterns.push_back(NodeAndOpNum);
  278. }
  279. return;
  280. }
  281. const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
  282. // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
  283. // a constant without a predicate fn that has more than one bit set, handle
  284. // this as a special case. This is usually for targets that have special
  285. // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
  286. // handling stuff). Using these instructions is often far more efficient
  287. // than materializing the constant. Unfortunately, both the instcombiner
  288. // and the dag combiner can often infer that bits are dead, and thus drop
  289. // them from the mask in the dag. For example, it might turn 'AND X, 255'
  290. // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
  291. // to handle this.
  292. if ((N->getOperator()->getName() == "and" ||
  293. N->getOperator()->getName() == "or") &&
  294. N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateCalls().empty() &&
  295. N->getPredicateCalls().empty()) {
  296. if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) {
  297. if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
  298. // If this is at the root of the pattern, we emit a redundant
  299. // CheckOpcode so that the following checks get factored properly under
  300. // a single opcode check.
  301. if (N == Pattern.getSrcPattern())
  302. AddMatcher(new CheckOpcodeMatcher(CInfo));
  303. // Emit the CheckAndImm/CheckOrImm node.
  304. if (N->getOperator()->getName() == "and")
  305. AddMatcher(new CheckAndImmMatcher(II->getValue()));
  306. else
  307. AddMatcher(new CheckOrImmMatcher(II->getValue()));
  308. // Match the LHS of the AND as appropriate.
  309. AddMatcher(new MoveChildMatcher(0));
  310. EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0), ForceMode);
  311. AddMatcher(new MoveParentMatcher());
  312. return;
  313. }
  314. }
  315. }
  316. // Check that the current opcode lines up.
  317. AddMatcher(new CheckOpcodeMatcher(CInfo));
  318. // If this node has memory references (i.e. is a load or store), tell the
  319. // interpreter to capture them in the memref array.
  320. if (N->NodeHasProperty(SDNPMemOperand, CGP))
  321. AddMatcher(new RecordMemRefMatcher());
  322. // If this node has a chain, then the chain is operand #0 is the SDNode, and
  323. // the child numbers of the node are all offset by one.
  324. unsigned OpNo = 0;
  325. if (N->NodeHasProperty(SDNPHasChain, CGP)) {
  326. // Record the node and remember it in our chained nodes list.
  327. AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
  328. "' chained node",
  329. NextRecordedOperandNo));
  330. // Remember all of the input chains our pattern will match.
  331. MatchedChainNodes.push_back(NextRecordedOperandNo++);
  332. // Don't look at the input chain when matching the tree pattern to the
  333. // SDNode.
  334. OpNo = 1;
  335. // If this node is not the root and the subtree underneath it produces a
  336. // chain, then the result of matching the node is also produce a chain.
  337. // Beyond that, this means that we're also folding (at least) the root node
  338. // into the node that produce the chain (for example, matching
  339. // "(add reg, (load ptr))" as a add_with_memory on X86). This is
  340. // problematic, if the 'reg' node also uses the load (say, its chain).
  341. // Graphically:
  342. //
  343. // [LD]
  344. // ^ ^
  345. // | \ DAG's like cheese.
  346. // / |
  347. // / [YY]
  348. // | ^
  349. // [XX]--/
  350. //
  351. // It would be invalid to fold XX and LD. In this case, folding the two
  352. // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
  353. // To prevent this, we emit a dynamic check for legality before allowing
  354. // this to be folded.
  355. //
  356. const TreePatternNode *Root = Pattern.getSrcPattern();
  357. if (N != Root) { // Not the root of the pattern.
  358. // If there is a node between the root and this node, then we definitely
  359. // need to emit the check.
  360. bool NeedCheck = !Root->hasChild(N);
  361. // If it *is* an immediate child of the root, we can still need a check if
  362. // the root SDNode has multiple inputs. For us, this means that it is an
  363. // intrinsic, has multiple operands, or has other inputs like chain or
  364. // glue).
  365. if (!NeedCheck) {
  366. const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
  367. NeedCheck =
  368. Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
  369. Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
  370. Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
  371. PInfo.getNumOperands() > 1 ||
  372. PInfo.hasProperty(SDNPHasChain) ||
  373. PInfo.hasProperty(SDNPInGlue) ||
  374. PInfo.hasProperty(SDNPOptInGlue);
  375. }
  376. if (NeedCheck)
  377. AddMatcher(new CheckFoldableChainNodeMatcher());
  378. }
  379. }
  380. // If this node has an output glue and isn't the root, remember it.
  381. if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
  382. N != Pattern.getSrcPattern()) {
  383. // TODO: This redundantly records nodes with both glues and chains.
  384. // Record the node and remember it in our chained nodes list.
  385. AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
  386. "' glue output node",
  387. NextRecordedOperandNo));
  388. }
  389. // If this node is known to have an input glue or if it *might* have an input
  390. // glue, capture it as the glue input of the pattern.
  391. if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
  392. N->NodeHasProperty(SDNPInGlue, CGP))
  393. AddMatcher(new CaptureGlueInputMatcher());
  394. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
  395. // Get the code suitable for matching this child. Move to the child, check
  396. // it then move back to the parent.
  397. AddMatcher(new MoveChildMatcher(OpNo));
  398. EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i), ForceMode);
  399. AddMatcher(new MoveParentMatcher());
  400. }
  401. }
  402. bool MatcherGen::recordUniqueNode(ArrayRef<std::string> Names) {
  403. unsigned Entry = 0;
  404. for (const std::string &Name : Names) {
  405. unsigned &VarMapEntry = VariableMap[Name];
  406. if (!Entry)
  407. Entry = VarMapEntry;
  408. assert(Entry == VarMapEntry);
  409. }
  410. bool NewRecord = false;
  411. if (Entry == 0) {
  412. // If it is a named node, we must emit a 'Record' opcode.
  413. std::string WhatFor;
  414. for (const std::string &Name : Names) {
  415. if (!WhatFor.empty())
  416. WhatFor += ',';
  417. WhatFor += "$" + Name;
  418. }
  419. AddMatcher(new RecordMatcher(WhatFor, NextRecordedOperandNo));
  420. Entry = ++NextRecordedOperandNo;
  421. NewRecord = true;
  422. } else {
  423. // If we get here, this is a second reference to a specific name. Since
  424. // we already have checked that the first reference is valid, we don't
  425. // have to recursively match it, just check that it's the same as the
  426. // previously named thing.
  427. AddMatcher(new CheckSameMatcher(Entry-1));
  428. }
  429. for (const std::string &Name : Names)
  430. VariableMap[Name] = Entry;
  431. return NewRecord;
  432. }
  433. void MatcherGen::EmitMatchCode(const TreePatternNode *N,
  434. TreePatternNode *NodeNoTypes,
  435. unsigned ForceMode) {
  436. // If N and NodeNoTypes don't agree on a type, then this is a case where we
  437. // need to do a type check. Emit the check, apply the type to NodeNoTypes and
  438. // reinfer any correlated types.
  439. SmallVector<unsigned, 2> ResultsToTypeCheck;
  440. for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
  441. if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
  442. NodeNoTypes->setType(i, N->getExtType(i));
  443. InferPossibleTypes(ForceMode);
  444. ResultsToTypeCheck.push_back(i);
  445. }
  446. // If this node has a name associated with it, capture it in VariableMap. If
  447. // we already saw this in the pattern, emit code to verify dagness.
  448. SmallVector<std::string, 4> Names;
  449. if (!N->getName().empty())
  450. Names.push_back(N->getName());
  451. for (const ScopedName &Name : N->getNamesAsPredicateArg()) {
  452. Names.push_back(("pred:" + Twine(Name.getScope()) + ":" + Name.getIdentifier()).str());
  453. }
  454. if (!Names.empty()) {
  455. if (!recordUniqueNode(Names))
  456. return;
  457. }
  458. if (N->isLeaf())
  459. EmitLeafMatchCode(N);
  460. else
  461. EmitOperatorMatchCode(N, NodeNoTypes, ForceMode);
  462. // If there are node predicates for this node, generate their checks.
  463. for (unsigned i = 0, e = N->getPredicateCalls().size(); i != e; ++i) {
  464. const TreePredicateCall &Pred = N->getPredicateCalls()[i];
  465. SmallVector<unsigned, 4> Operands;
  466. if (Pred.Fn.usesOperands()) {
  467. TreePattern *TP = Pred.Fn.getOrigPatFragRecord();
  468. for (unsigned i = 0; i < TP->getNumArgs(); ++i) {
  469. std::string Name =
  470. ("pred:" + Twine(Pred.Scope) + ":" + TP->getArgName(i)).str();
  471. Operands.push_back(getNamedArgumentSlot(Name));
  472. }
  473. }
  474. AddMatcher(new CheckPredicateMatcher(Pred.Fn, Operands));
  475. }
  476. for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
  477. AddMatcher(new CheckTypeMatcher(N->getSimpleType(ResultsToTypeCheck[i]),
  478. ResultsToTypeCheck[i]));
  479. }
  480. /// EmitMatcherCode - Generate the code that matches the predicate of this
  481. /// pattern for the specified Variant. If the variant is invalid this returns
  482. /// true and does not generate code, if it is valid, it returns false.
  483. bool MatcherGen::EmitMatcherCode(unsigned Variant) {
  484. // If the root of the pattern is a ComplexPattern and if it is specified to
  485. // match some number of root opcodes, these are considered to be our variants.
  486. // Depending on which variant we're generating code for, emit the root opcode
  487. // check.
  488. if (const ComplexPattern *CP =
  489. Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
  490. const std::vector<Record*> &OpNodes = CP->getRootNodes();
  491. assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
  492. if (Variant >= OpNodes.size()) return true;
  493. AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
  494. } else {
  495. if (Variant != 0) return true;
  496. }
  497. // Emit the matcher for the pattern structure and types.
  498. EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes.get(),
  499. Pattern.getForceMode());
  500. // If the pattern has a predicate on it (e.g. only enabled when a subtarget
  501. // feature is around, do the check).
  502. if (!Pattern.getPredicateCheck().empty())
  503. AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
  504. // Now that we've completed the structural type match, emit any ComplexPattern
  505. // checks (e.g. addrmode matches). We emit this after the structural match
  506. // because they are generally more expensive to evaluate and more difficult to
  507. // factor.
  508. for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
  509. auto N = MatchedComplexPatterns[i].first;
  510. // Remember where the results of this match get stuck.
  511. if (N->isLeaf()) {
  512. NamedComplexPatternOperands[N->getName()] = NextRecordedOperandNo + 1;
  513. } else {
  514. unsigned CurOp = NextRecordedOperandNo;
  515. for (unsigned i = 0; i < N->getNumChildren(); ++i) {
  516. NamedComplexPatternOperands[N->getChild(i)->getName()] = CurOp + 1;
  517. CurOp += N->getChild(i)->getNumMIResults(CGP);
  518. }
  519. }
  520. // Get the slot we recorded the value in from the name on the node.
  521. unsigned RecNodeEntry = MatchedComplexPatterns[i].second;
  522. const ComplexPattern &CP = *N->getComplexPatternInfo(CGP);
  523. // Emit a CheckComplexPat operation, which does the match (aborting if it
  524. // fails) and pushes the matched operands onto the recorded nodes list.
  525. AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
  526. N->getName(), NextRecordedOperandNo));
  527. // Record the right number of operands.
  528. NextRecordedOperandNo += CP.getNumOperands();
  529. if (CP.hasProperty(SDNPHasChain)) {
  530. // If the complex pattern has a chain, then we need to keep track of the
  531. // fact that we just recorded a chain input. The chain input will be
  532. // matched as the last operand of the predicate if it was successful.
  533. ++NextRecordedOperandNo; // Chained node operand.
  534. // It is the last operand recorded.
  535. assert(NextRecordedOperandNo > 1 &&
  536. "Should have recorded input/result chains at least!");
  537. MatchedChainNodes.push_back(NextRecordedOperandNo-1);
  538. }
  539. // TODO: Complex patterns can't have output glues, if they did, we'd want
  540. // to record them.
  541. }
  542. return false;
  543. }
  544. //===----------------------------------------------------------------------===//
  545. // Node Result Generation
  546. //===----------------------------------------------------------------------===//
  547. void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
  548. SmallVectorImpl<unsigned> &ResultOps){
  549. assert(!N->getName().empty() && "Operand not named!");
  550. if (unsigned SlotNo = NamedComplexPatternOperands[N->getName()]) {
  551. // Complex operands have already been completely selected, just find the
  552. // right slot ant add the arguments directly.
  553. for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
  554. ResultOps.push_back(SlotNo - 1 + i);
  555. return;
  556. }
  557. unsigned SlotNo = getNamedArgumentSlot(N->getName());
  558. // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
  559. // version of the immediate so that it doesn't get selected due to some other
  560. // node use.
  561. if (!N->isLeaf()) {
  562. StringRef OperatorName = N->getOperator()->getName();
  563. if (OperatorName == "imm" || OperatorName == "fpimm") {
  564. AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
  565. ResultOps.push_back(NextRecordedOperandNo++);
  566. return;
  567. }
  568. }
  569. for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
  570. ResultOps.push_back(SlotNo + i);
  571. }
  572. void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
  573. SmallVectorImpl<unsigned> &ResultOps) {
  574. assert(N->isLeaf() && "Must be a leaf");
  575. if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
  576. AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getSimpleType(0)));
  577. ResultOps.push_back(NextRecordedOperandNo++);
  578. return;
  579. }
  580. // If this is an explicit register reference, handle it.
  581. if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
  582. Record *Def = DI->getDef();
  583. if (Def->isSubClassOf("Register")) {
  584. const CodeGenRegister *Reg =
  585. CGP.getTargetInfo().getRegBank().getReg(Def);
  586. AddMatcher(new EmitRegisterMatcher(Reg, N->getSimpleType(0)));
  587. ResultOps.push_back(NextRecordedOperandNo++);
  588. return;
  589. }
  590. if (Def->getName() == "zero_reg") {
  591. AddMatcher(new EmitRegisterMatcher(nullptr, N->getSimpleType(0)));
  592. ResultOps.push_back(NextRecordedOperandNo++);
  593. return;
  594. }
  595. if (Def->getName() == "undef_tied_input") {
  596. std::array<MVT::SimpleValueType, 1> ResultVTs = {{ N->getSimpleType(0) }};
  597. std::array<unsigned, 0> InstOps;
  598. auto IDOperandNo = NextRecordedOperandNo++;
  599. AddMatcher(new EmitNodeMatcher("TargetOpcode::IMPLICIT_DEF",
  600. ResultVTs, InstOps, false, false, false,
  601. false, -1, IDOperandNo));
  602. ResultOps.push_back(IDOperandNo);
  603. return;
  604. }
  605. // Handle a reference to a register class. This is used
  606. // in COPY_TO_SUBREG instructions.
  607. if (Def->isSubClassOf("RegisterOperand"))
  608. Def = Def->getValueAsDef("RegClass");
  609. if (Def->isSubClassOf("RegisterClass")) {
  610. // If the register class has an enum integer value greater than 127, the
  611. // encoding overflows the limit of 7 bits, which precludes the use of
  612. // StringIntegerMatcher. In this case, fallback to using IntegerMatcher.
  613. const CodeGenRegisterClass &RC =
  614. CGP.getTargetInfo().getRegisterClass(Def);
  615. if (RC.EnumValue <= 127) {
  616. std::string Value = getQualifiedName(Def) + "RegClassID";
  617. AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
  618. ResultOps.push_back(NextRecordedOperandNo++);
  619. } else {
  620. AddMatcher(new EmitIntegerMatcher(RC.EnumValue, MVT::i32));
  621. ResultOps.push_back(NextRecordedOperandNo++);
  622. }
  623. return;
  624. }
  625. // Handle a subregister index. This is used for INSERT_SUBREG etc.
  626. if (Def->isSubClassOf("SubRegIndex")) {
  627. const CodeGenRegBank &RB = CGP.getTargetInfo().getRegBank();
  628. // If we have more than 127 subreg indices the encoding can overflow
  629. // 7 bit and we cannot use StringInteger.
  630. if (RB.getSubRegIndices().size() > 127) {
  631. const CodeGenSubRegIndex *I = RB.findSubRegIdx(Def);
  632. assert(I && "Cannot find subreg index by name!");
  633. if (I->EnumValue > 127) {
  634. AddMatcher(new EmitIntegerMatcher(I->EnumValue, MVT::i32));
  635. ResultOps.push_back(NextRecordedOperandNo++);
  636. return;
  637. }
  638. }
  639. std::string Value = getQualifiedName(Def);
  640. AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
  641. ResultOps.push_back(NextRecordedOperandNo++);
  642. return;
  643. }
  644. }
  645. errs() << "unhandled leaf node:\n";
  646. N->dump();
  647. }
  648. static bool
  649. mayInstNodeLoadOrStore(const TreePatternNode *N,
  650. const CodeGenDAGPatterns &CGP) {
  651. Record *Op = N->getOperator();
  652. const CodeGenTarget &CGT = CGP.getTargetInfo();
  653. CodeGenInstruction &II = CGT.getInstruction(Op);
  654. return II.mayLoad || II.mayStore;
  655. }
  656. static unsigned
  657. numNodesThatMayLoadOrStore(const TreePatternNode *N,
  658. const CodeGenDAGPatterns &CGP) {
  659. if (N->isLeaf())
  660. return 0;
  661. Record *OpRec = N->getOperator();
  662. if (!OpRec->isSubClassOf("Instruction"))
  663. return 0;
  664. unsigned Count = 0;
  665. if (mayInstNodeLoadOrStore(N, CGP))
  666. ++Count;
  667. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  668. Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
  669. return Count;
  670. }
  671. void MatcherGen::
  672. EmitResultInstructionAsOperand(const TreePatternNode *N,
  673. SmallVectorImpl<unsigned> &OutputOps) {
  674. Record *Op = N->getOperator();
  675. const CodeGenTarget &CGT = CGP.getTargetInfo();
  676. CodeGenInstruction &II = CGT.getInstruction(Op);
  677. const DAGInstruction &Inst = CGP.getInstruction(Op);
  678. bool isRoot = N == Pattern.getDstPattern();
  679. // TreeHasOutGlue - True if this tree has glue.
  680. bool TreeHasInGlue = false, TreeHasOutGlue = false;
  681. if (isRoot) {
  682. const TreePatternNode *SrcPat = Pattern.getSrcPattern();
  683. TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
  684. SrcPat->TreeHasProperty(SDNPInGlue, CGP);
  685. // FIXME2: this is checking the entire pattern, not just the node in
  686. // question, doing this just for the root seems like a total hack.
  687. TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
  688. }
  689. // NumResults - This is the number of results produced by the instruction in
  690. // the "outs" list.
  691. unsigned NumResults = Inst.getNumResults();
  692. // Number of operands we know the output instruction must have. If it is
  693. // variadic, we could have more operands.
  694. unsigned NumFixedOperands = II.Operands.size();
  695. SmallVector<unsigned, 8> InstOps;
  696. // Loop over all of the fixed operands of the instruction pattern, emitting
  697. // code to fill them all in. The node 'N' usually has number children equal to
  698. // the number of input operands of the instruction. However, in cases where
  699. // there are predicate operands for an instruction, we need to fill in the
  700. // 'execute always' values. Match up the node operands to the instruction
  701. // operands to do this.
  702. unsigned ChildNo = 0;
  703. // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
  704. // number of operands at the end of the list which have default values.
  705. // Those can come from the pattern if it provides enough arguments, or be
  706. // filled in with the default if the pattern hasn't provided them. But any
  707. // operand with a default value _before_ the last mandatory one will be
  708. // filled in with their defaults unconditionally.
  709. unsigned NonOverridableOperands = NumFixedOperands;
  710. while (NonOverridableOperands > NumResults &&
  711. CGP.operandHasDefault(II.Operands[NonOverridableOperands-1].Rec))
  712. --NonOverridableOperands;
  713. for (unsigned InstOpNo = NumResults, e = NumFixedOperands;
  714. InstOpNo != e; ++InstOpNo) {
  715. // Determine what to emit for this operand.
  716. Record *OperandNode = II.Operands[InstOpNo].Rec;
  717. if (CGP.operandHasDefault(OperandNode) &&
  718. (InstOpNo < NonOverridableOperands || ChildNo >= N->getNumChildren())) {
  719. // This is a predicate or optional def operand which the pattern has not
  720. // overridden, or which we aren't letting it override; emit the 'default
  721. // ops' operands.
  722. const DAGDefaultOperand &DefaultOp
  723. = CGP.getDefaultOperand(OperandNode);
  724. for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
  725. EmitResultOperand(DefaultOp.DefaultOps[i].get(), InstOps);
  726. continue;
  727. }
  728. // Otherwise this is a normal operand or a predicate operand without
  729. // 'execute always'; emit it.
  730. // For operands with multiple sub-operands we may need to emit
  731. // multiple child patterns to cover them all. However, ComplexPattern
  732. // children may themselves emit multiple MI operands.
  733. unsigned NumSubOps = 1;
  734. if (OperandNode->isSubClassOf("Operand")) {
  735. DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
  736. if (unsigned NumArgs = MIOpInfo->getNumArgs())
  737. NumSubOps = NumArgs;
  738. }
  739. unsigned FinalNumOps = InstOps.size() + NumSubOps;
  740. while (InstOps.size() < FinalNumOps) {
  741. const TreePatternNode *Child = N->getChild(ChildNo);
  742. unsigned BeforeAddingNumOps = InstOps.size();
  743. EmitResultOperand(Child, InstOps);
  744. assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
  745. // If the operand is an instruction and it produced multiple results, just
  746. // take the first one.
  747. if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
  748. InstOps.resize(BeforeAddingNumOps+1);
  749. ++ChildNo;
  750. }
  751. }
  752. // If this is a variadic output instruction (i.e. REG_SEQUENCE), we can't
  753. // expand suboperands, use default operands, or other features determined from
  754. // the CodeGenInstruction after the fixed operands, which were handled
  755. // above. Emit the remaining instructions implicitly added by the use for
  756. // variable_ops.
  757. if (II.Operands.isVariadic) {
  758. for (unsigned I = ChildNo, E = N->getNumChildren(); I < E; ++I)
  759. EmitResultOperand(N->getChild(I), InstOps);
  760. }
  761. // If this node has input glue or explicitly specified input physregs, we
  762. // need to add chained and glued copyfromreg nodes and materialize the glue
  763. // input.
  764. if (isRoot && !PhysRegInputs.empty()) {
  765. // Emit all of the CopyToReg nodes for the input physical registers. These
  766. // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
  767. for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i) {
  768. const CodeGenRegister *Reg =
  769. CGP.getTargetInfo().getRegBank().getReg(PhysRegInputs[i].first);
  770. AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
  771. Reg));
  772. }
  773. // Even if the node has no other glue inputs, the resultant node must be
  774. // glued to the CopyFromReg nodes we just generated.
  775. TreeHasInGlue = true;
  776. }
  777. // Result order: node results, chain, glue
  778. // Determine the result types.
  779. SmallVector<MVT::SimpleValueType, 4> ResultVTs;
  780. for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
  781. ResultVTs.push_back(N->getSimpleType(i));
  782. // If this is the root instruction of a pattern that has physical registers in
  783. // its result pattern, add output VTs for them. For example, X86 has:
  784. // (set AL, (mul ...))
  785. // This also handles implicit results like:
  786. // (implicit EFLAGS)
  787. if (isRoot && !Pattern.getDstRegs().empty()) {
  788. // If the root came from an implicit def in the instruction handling stuff,
  789. // don't re-add it.
  790. Record *HandledReg = nullptr;
  791. if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
  792. HandledReg = II.ImplicitDefs[0];
  793. for (Record *Reg : Pattern.getDstRegs()) {
  794. if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
  795. ResultVTs.push_back(getRegisterValueType(Reg, CGT));
  796. }
  797. }
  798. // If this is the root of the pattern and the pattern we're matching includes
  799. // a node that is variadic, mark the generated node as variadic so that it
  800. // gets the excess operands from the input DAG.
  801. int NumFixedArityOperands = -1;
  802. if (isRoot &&
  803. Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP))
  804. NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
  805. // If this is the root node and multiple matched nodes in the input pattern
  806. // have MemRefs in them, have the interpreter collect them and plop them onto
  807. // this node. If there is just one node with MemRefs, leave them on that node
  808. // even if it is not the root.
  809. //
  810. // FIXME3: This is actively incorrect for result patterns with multiple
  811. // memory-referencing instructions.
  812. bool PatternHasMemOperands =
  813. Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
  814. bool NodeHasMemRefs = false;
  815. if (PatternHasMemOperands) {
  816. unsigned NumNodesThatLoadOrStore =
  817. numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
  818. bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
  819. NumNodesThatLoadOrStore == 1;
  820. NodeHasMemRefs =
  821. NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
  822. NumNodesThatLoadOrStore != 1));
  823. }
  824. // Determine whether we need to attach a chain to this node.
  825. bool NodeHasChain = false;
  826. if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)) {
  827. // For some instructions, we were able to infer from the pattern whether
  828. // they should have a chain. Otherwise, attach the chain to the root.
  829. //
  830. // FIXME2: This is extremely dubious for several reasons, not the least of
  831. // which it gives special status to instructions with patterns that Pat<>
  832. // nodes can't duplicate.
  833. if (II.hasChain_Inferred)
  834. NodeHasChain = II.hasChain;
  835. else
  836. NodeHasChain = isRoot;
  837. // Instructions which load and store from memory should have a chain,
  838. // regardless of whether they happen to have a pattern saying so.
  839. if (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
  840. II.hasSideEffects)
  841. NodeHasChain = true;
  842. }
  843. assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
  844. "Node has no result");
  845. AddMatcher(new EmitNodeMatcher(II.Namespace.str()+"::"+II.TheDef->getName().str(),
  846. ResultVTs, InstOps,
  847. NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
  848. NodeHasMemRefs, NumFixedArityOperands,
  849. NextRecordedOperandNo));
  850. // The non-chain and non-glue results of the newly emitted node get recorded.
  851. for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
  852. if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
  853. OutputOps.push_back(NextRecordedOperandNo++);
  854. }
  855. }
  856. void MatcherGen::
  857. EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
  858. SmallVectorImpl<unsigned> &ResultOps) {
  859. assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
  860. // Emit the operand.
  861. SmallVector<unsigned, 8> InputOps;
  862. // FIXME2: Could easily generalize this to support multiple inputs and outputs
  863. // to the SDNodeXForm. For now we just support one input and one output like
  864. // the old instruction selector.
  865. assert(N->getNumChildren() == 1);
  866. EmitResultOperand(N->getChild(0), InputOps);
  867. // The input currently must have produced exactly one result.
  868. assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
  869. AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
  870. ResultOps.push_back(NextRecordedOperandNo++);
  871. }
  872. void MatcherGen::EmitResultOperand(const TreePatternNode *N,
  873. SmallVectorImpl<unsigned> &ResultOps) {
  874. // This is something selected from the pattern we matched.
  875. if (!N->getName().empty())
  876. return EmitResultOfNamedOperand(N, ResultOps);
  877. if (N->isLeaf())
  878. return EmitResultLeafAsOperand(N, ResultOps);
  879. Record *OpRec = N->getOperator();
  880. if (OpRec->isSubClassOf("Instruction"))
  881. return EmitResultInstructionAsOperand(N, ResultOps);
  882. if (OpRec->isSubClassOf("SDNodeXForm"))
  883. return EmitResultSDNodeXFormAsOperand(N, ResultOps);
  884. errs() << "Unknown result node to emit code for: " << *N << '\n';
  885. PrintFatalError("Unknown node in result pattern!");
  886. }
  887. void MatcherGen::EmitResultCode() {
  888. // Patterns that match nodes with (potentially multiple) chain inputs have to
  889. // merge them together into a token factor. This informs the generated code
  890. // what all the chained nodes are.
  891. if (!MatchedChainNodes.empty())
  892. AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes));
  893. // Codegen the root of the result pattern, capturing the resulting values.
  894. SmallVector<unsigned, 8> Ops;
  895. EmitResultOperand(Pattern.getDstPattern(), Ops);
  896. // At this point, we have however many values the result pattern produces.
  897. // However, the input pattern might not need all of these. If there are
  898. // excess values at the end (such as implicit defs of condition codes etc)
  899. // just lop them off. This doesn't need to worry about glue or chains, just
  900. // explicit results.
  901. //
  902. unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
  903. // If the pattern also has (implicit) results, count them as well.
  904. if (!Pattern.getDstRegs().empty()) {
  905. // If the root came from an implicit def in the instruction handling stuff,
  906. // don't re-add it.
  907. Record *HandledReg = nullptr;
  908. const TreePatternNode *DstPat = Pattern.getDstPattern();
  909. if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
  910. const CodeGenTarget &CGT = CGP.getTargetInfo();
  911. CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
  912. if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
  913. HandledReg = II.ImplicitDefs[0];
  914. }
  915. for (Record *Reg : Pattern.getDstRegs()) {
  916. if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
  917. ++NumSrcResults;
  918. }
  919. }
  920. SmallVector<unsigned, 8> Results(Ops);
  921. // Apply result permutation.
  922. for (unsigned ResNo = 0; ResNo < Pattern.getDstPattern()->getNumResults();
  923. ++ResNo) {
  924. Results[ResNo] = Ops[Pattern.getDstPattern()->getResultIndex(ResNo)];
  925. }
  926. Results.resize(NumSrcResults);
  927. AddMatcher(new CompleteMatchMatcher(Results, Pattern));
  928. }
  929. /// ConvertPatternToMatcher - Create the matcher for the specified pattern with
  930. /// the specified variant. If the variant number is invalid, this returns null.
  931. Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
  932. unsigned Variant,
  933. const CodeGenDAGPatterns &CGP) {
  934. MatcherGen Gen(Pattern, CGP);
  935. // Generate the code for the matcher.
  936. if (Gen.EmitMatcherCode(Variant))
  937. return nullptr;
  938. // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
  939. // FIXME2: Split result code out to another table, and make the matcher end
  940. // with an "Emit <index>" command. This allows result generation stuff to be
  941. // shared and factored?
  942. // If the match succeeds, then we generate Pattern.
  943. Gen.EmitResultCode();
  944. // Unconditional match.
  945. return Gen.GetMatcher();
  946. }