DAGISelMatcherGen.cpp 41 KB

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