DAGISelMatcherGen.cpp 44 KB

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