blob: cae2dfbc5960340577502b9b051f0d649e5c1dbe [file] [log] [blame]
Chris Lattnerda272d12010-02-15 08:04:42 +00001//===- 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
10#include "DAGISelMatcher.h"
11#include "CodeGenDAGPatterns.h"
12#include "Record.h"
Chris Lattner785d16f2010-02-17 02:16:19 +000013#include "llvm/ADT/SmallVector.h"
Chris Lattnerda272d12010-02-15 08:04:42 +000014#include "llvm/ADT/StringMap.h"
Chris Lattner8e946be2010-02-21 03:22:59 +000015#include <utility>
Chris Lattnerda272d12010-02-15 08:04:42 +000016using namespace llvm;
17
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000018
Chris Lattner8e946be2010-02-21 03:22:59 +000019/// 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.
22static MVT::SimpleValueType getRegisterValueType(Record *R,
23 const CodeGenTarget &T) {
24 bool FoundRC = false;
25 MVT::SimpleValueType VT = MVT::Other;
26 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
27 std::vector<Record*>::const_iterator Element;
28
29 for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
30 const CodeGenRegisterClass &RC = RCs[rc];
31 if (!std::count(RC.Elements.begin(), RC.Elements.end(), R))
32 continue;
33
34 if (!FoundRC) {
35 FoundRC = true;
36 VT = RC.getValueTypeNum(0);
37 continue;
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000038 }
Chris Lattner8e946be2010-02-21 03:22:59 +000039
40 // In multiple RC's. If the Types of the RC's do not agree, return
41 // MVT::Other. The target is responsible for handling this.
42 if (VT != RC.getValueTypeNum(0))
43 // FIXME2: when does this happen? Abort?
44 return MVT::Other;
45 }
46 return VT;
47}
48
49
50namespace {
Chris Lattnerda272d12010-02-15 08:04:42 +000051 class MatcherGen {
52 const PatternToMatch &Pattern;
53 const CodeGenDAGPatterns &CGP;
54
55 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
56 /// out with all of the types removed. This allows us to insert type checks
57 /// as we scan the tree.
58 TreePatternNode *PatWithNoTypes;
59
60 /// VariableMap - A map from variable names ('$dst') to the recorded operand
61 /// number that they were captured as. These are biased by 1 to make
62 /// insertion easier.
63 StringMap<unsigned> VariableMap;
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000064
65 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
66 /// the RecordedNodes array, this keeps track of which slot will be next to
67 /// record into.
Chris Lattnerda272d12010-02-15 08:04:42 +000068 unsigned NextRecordedOperandNo;
69
Chris Lattner8e946be2010-02-21 03:22:59 +000070 /// MatchedChainNodes - This maintains the position in the recorded nodes
71 /// array of all of the recorded input nodes that have chains.
72 SmallVector<unsigned, 2> MatchedChainNodes;
Chris Lattner02f73582010-02-24 05:33:42 +000073
74 /// MatchedFlagResultNodes - This maintains the position in the recorded
75 /// nodes array of all of the recorded input nodes that have flag results.
76 SmallVector<unsigned, 2> MatchedFlagResultNodes;
Chris Lattner8e946be2010-02-21 03:22:59 +000077
78 /// PhysRegInputs - List list has an entry for each explicitly specified
79 /// physreg input to the pattern. The first elt is the Register node, the
80 /// second is the recorded slot number the input pattern match saved it in.
81 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
82
83 /// EmittedMergeInputChains - For nodes that match patterns involving
84 /// chains, is set to true if we emitted the "MergeInputChains" operation.
85 bool EmittedMergeInputChains;
Chris Lattner785d16f2010-02-17 02:16:19 +000086
87 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattnerb21ba712010-02-25 02:04:40 +000088 Matcher *TheMatcher;
Chris Lattner785d16f2010-02-17 02:16:19 +000089
90 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattnerbd8227f2010-02-18 02:53:41 +000091 /// which should have future checks stuck into its Next position.
Chris Lattnerb21ba712010-02-25 02:04:40 +000092 Matcher *CurPredicate;
Chris Lattnerda272d12010-02-15 08:04:42 +000093 public:
94 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
95
96 ~MatcherGen() {
97 delete PatWithNoTypes;
98 }
99
100 void EmitMatcherCode();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000101 void EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000102
Chris Lattnerb21ba712010-02-25 02:04:40 +0000103 Matcher *GetMatcher() const { return TheMatcher; }
104 Matcher *GetCurPredicate() const { return CurPredicate; }
Chris Lattnerda272d12010-02-15 08:04:42 +0000105 private:
Chris Lattnerb21ba712010-02-25 02:04:40 +0000106 void AddMatcher(Matcher *NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000107 void InferPossibleTypes();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000108
109 // Matcher Generation.
Chris Lattnerda272d12010-02-15 08:04:42 +0000110 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
111 void EmitLeafMatchCode(const TreePatternNode *N);
112 void EmitOperatorMatchCode(const TreePatternNode *N,
113 TreePatternNode *NodeNoTypes);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000114
115 // Result Code Generation.
Chris Lattner8e946be2010-02-21 03:22:59 +0000116 unsigned getNamedArgumentSlot(StringRef Name) {
117 unsigned VarMapEntry = VariableMap[Name];
118 assert(VarMapEntry != 0 &&
119 "Variable referenced but not defined and not caught earlier!");
120 return VarMapEntry-1;
121 }
122
123 /// GetInstPatternNode - Get the pattern for an instruction.
124 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
125 const TreePatternNode *N);
126
Chris Lattnerb49985a2010-02-18 06:47:49 +0000127 void EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000128 SmallVectorImpl<unsigned> &ResultOps);
129 void EmitResultOfNamedOperand(const TreePatternNode *N,
130 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000131 void EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000132 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000133 void EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000134 SmallVectorImpl<unsigned> &ResultOps);
135 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
136 SmallVectorImpl<unsigned> &ResultOps);
137 };
Chris Lattnerda272d12010-02-15 08:04:42 +0000138
139} // end anon namespace.
140
141MatcherGen::MatcherGen(const PatternToMatch &pattern,
142 const CodeGenDAGPatterns &cgp)
Chris Lattner853b9192010-02-19 00:33:13 +0000143: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Chris Lattnerb21ba712010-02-25 02:04:40 +0000144 EmittedMergeInputChains(false), TheMatcher(0), CurPredicate(0) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000145 // We need to produce the matcher tree for the patterns source pattern. To do
146 // this we need to match the structure as well as the types. To do the type
147 // matching, we want to figure out the fewest number of type checks we need to
148 // emit. For example, if there is only one integer type supported by a
149 // target, there should be no type comparisons at all for integer patterns!
150 //
151 // To figure out the fewest number of type checks needed, clone the pattern,
152 // remove the types, then perform type inference on the pattern as a whole.
153 // If there are unresolved types, emit an explicit check for those types,
154 // apply the type to the tree, then rerun type inference. Iterate until all
155 // types are resolved.
156 //
157 PatWithNoTypes = Pattern.getSrcPattern()->clone();
158 PatWithNoTypes->RemoveAllTypes();
159
160 // If there are types that are manifestly known, infer them.
161 InferPossibleTypes();
162}
163
164/// InferPossibleTypes - As we emit the pattern, we end up generating type
165/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
166/// want to propagate implied types as far throughout the tree as possible so
167/// that we avoid doing redundant type checks. This does the type propagation.
168void MatcherGen::InferPossibleTypes() {
169 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
170 // diagnostics, which we know are impossible at this point.
171 TreePattern &TP = *CGP.pf_begin()->second;
172
173 try {
174 bool MadeChange = true;
175 while (MadeChange)
176 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
177 true/*Ignore reg constraints*/);
178 } catch (...) {
179 errs() << "Type constraint application shouldn't fail!";
180 abort();
181 }
182}
183
184
Chris Lattnerb21ba712010-02-25 02:04:40 +0000185/// AddMatcher - Add a matcher node to the current graph we're building.
186void MatcherGen::AddMatcher(Matcher *NewNode) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000187 if (CurPredicate != 0)
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000188 CurPredicate->setNext(NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000189 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000190 TheMatcher = NewNode;
Chris Lattnerda272d12010-02-15 08:04:42 +0000191 CurPredicate = NewNode;
192}
193
194
Chris Lattnerb49985a2010-02-18 06:47:49 +0000195//===----------------------------------------------------------------------===//
196// Pattern Match Generation
197//===----------------------------------------------------------------------===//
Chris Lattnerda272d12010-02-15 08:04:42 +0000198
199/// EmitLeafMatchCode - Generate matching code for leaf nodes.
200void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
201 assert(N->isLeaf() && "Not a leaf?");
Chris Lattner8e946be2010-02-21 03:22:59 +0000202
203 // If there are node predicates for this node, generate their checks.
204 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000205 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Chris Lattner8e946be2010-02-21 03:22:59 +0000206
Chris Lattnerda272d12010-02-15 08:04:42 +0000207 // Direct match against an integer constant.
208 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000209 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000210
211 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
212 if (DI == 0) {
213 errs() << "Unknown leaf kind: " << *DI << "\n";
214 abort();
215 }
216
217 Record *LeafRec = DI->getDef();
218 if (// Handle register references. Nothing to do here, they always match.
219 LeafRec->isSubClassOf("RegisterClass") ||
220 LeafRec->isSubClassOf("PointerLikeRegClass") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000221 // Place holder for SRCVALUE nodes. Nothing to do here.
222 LeafRec->getName() == "srcvalue")
223 return;
Chris Lattner8e946be2010-02-21 03:22:59 +0000224
225 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
226 // record the register
227 if (LeafRec->isSubClassOf("Register")) {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000228 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName()));
Chris Lattner8e946be2010-02-21 03:22:59 +0000229 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
230 return;
231 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000232
233 if (LeafRec->isSubClassOf("ValueType"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000234 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000235
236 if (LeafRec->isSubClassOf("CondCode"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000237 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000238
239 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000240 // We can't model ComplexPattern uses that don't have their name taken yet.
241 // The OPC_CheckComplexPattern operation implicitly records the results.
242 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000243 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
244 exit(1);
245 }
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000246
Chris Lattnerda272d12010-02-15 08:04:42 +0000247 // Handle complex pattern.
248 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000249
250 // If we're at the root of the pattern, we have to check that the opcode
251 // is a one of the ones requested to be matched.
252 if (N == Pattern.getSrcPattern()) {
253 const std::vector<Record*> &OpNodes = CP.getRootNodes();
254 if (OpNodes.size() == 1) {
Chris Lattnera230f962010-02-27 21:48:43 +0000255 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[0])));
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000256 } else if (!OpNodes.empty()) {
Chris Lattnera230f962010-02-27 21:48:43 +0000257 SmallVector<const SDNodeInfo*, 4> OpNames;
Chris Lattner12a667c2010-02-22 22:30:37 +0000258 for (unsigned i = 0, e = OpNodes.size(); i != e; i++)
Chris Lattnera230f962010-02-27 21:48:43 +0000259 OpNames.push_back(&CGP.getSDNodeInfo(OpNodes[i]));
260 AddMatcher(new CheckMultiOpcodeMatcher(OpNames.data(), OpNames.size()));
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000261 }
262 }
263
Chris Lattner20df2422010-02-22 23:33:44 +0000264 // Emit a CheckComplexPat operation, which does the match (aborting if it
265 // fails) and pushes the matched operands onto the recorded nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000266 AddMatcher(new CheckComplexPatMatcher(CP));
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000267
Chris Lattner20df2422010-02-22 23:33:44 +0000268 // Record the right number of operands.
269 NextRecordedOperandNo += CP.getNumOperands();
270 if (CP.hasProperty(SDNPHasChain))
271 ++NextRecordedOperandNo; // Chained node operand.
272
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000273 // If the complex pattern has a chain, then we need to keep track of the
274 // fact that we just recorded a chain input. The chain input will be
275 // matched as the last operand of the predicate if it was successful.
276 if (CP.hasProperty(SDNPHasChain)) {
277 // It is the last operand recorded.
278 assert(NextRecordedOperandNo > 1 &&
279 "Should have recorded input/result chains at least!");
Chris Lattner8e946be2010-02-21 03:22:59 +0000280 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
Chris Lattner9a747f12010-02-17 06:23:39 +0000281
Chris Lattner8e946be2010-02-21 03:22:59 +0000282 // If we need to check chains, do so, see comment for
Chris Lattner9a747f12010-02-17 06:23:39 +0000283 // "NodeHasProperty(SDNPHasChain" below.
Chris Lattner8e946be2010-02-21 03:22:59 +0000284 if (MatchedChainNodes.size() > 1) {
285 // FIXME2: This is broken, we should eliminate this nonsense completely,
Chris Lattner9a747f12010-02-17 06:23:39 +0000286 // but we want to produce the same selections that the old matcher does
287 // for now.
Chris Lattner8e946be2010-02-21 03:22:59 +0000288 unsigned PrevOp = MatchedChainNodes[MatchedChainNodes.size()-2];
Chris Lattnerb21ba712010-02-25 02:04:40 +0000289 AddMatcher(new CheckChainCompatibleMatcher(PrevOp));
Chris Lattner9a747f12010-02-17 06:23:39 +0000290 }
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000291 }
Chris Lattner02f73582010-02-24 05:33:42 +0000292
293 // TODO: Complex patterns can't have output flags, if they did, we'd want
294 // to record them.
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000295 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000296 }
297
298 errs() << "Unknown leaf kind: " << *N << "\n";
299 abort();
300}
301
302void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
303 TreePatternNode *NodeNoTypes) {
304 assert(!N->isLeaf() && "Not an operator?");
305 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
306
307 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
308 // a constant without a predicate fn that has more that one bit set, handle
309 // this as a special case. This is usually for targets that have special
310 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
311 // handling stuff). Using these instructions is often far more efficient
312 // than materializing the constant. Unfortunately, both the instcombiner
313 // and the dag combiner can often infer that bits are dead, and thus drop
314 // them from the mask in the dag. For example, it might turn 'AND X, 255'
315 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
316 // to handle this.
317 if ((N->getOperator()->getName() == "and" ||
318 N->getOperator()->getName() == "or") &&
Chris Lattner8e946be2010-02-21 03:22:59 +0000319 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
320 N->getPredicateFns().empty()) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000321 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
322 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
323 if (N->getOperator()->getName() == "and")
Chris Lattnerb21ba712010-02-25 02:04:40 +0000324 AddMatcher(new CheckAndImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000325 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000326 AddMatcher(new CheckOrImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000327
328 // Match the LHS of the AND as appropriate.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000329 AddMatcher(new MoveChildMatcher(0));
Chris Lattnerda272d12010-02-15 08:04:42 +0000330 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000331 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000332 return;
333 }
334 }
335 }
336
337 // Check that the current opcode lines up.
Chris Lattnera230f962010-02-27 21:48:43 +0000338 AddMatcher(new CheckOpcodeMatcher(CInfo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000339
Chris Lattner8e946be2010-02-21 03:22:59 +0000340 // If there are node predicates for this node, generate their checks.
341 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000342 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Chris Lattner8e946be2010-02-21 03:22:59 +0000343
344
345 // If this node has memory references (i.e. is a load or store), tell the
346 // interpreter to capture them in the memref array.
347 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000348 AddMatcher(new RecordMemRefMatcher());
Chris Lattner8e946be2010-02-21 03:22:59 +0000349
Chris Lattnerda272d12010-02-15 08:04:42 +0000350 // If this node has a chain, then the chain is operand #0 is the SDNode, and
351 // the child numbers of the node are all offset by one.
352 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000353 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000354 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000355 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner8e946be2010-02-21 03:22:59 +0000356 "' chained node"));
Chris Lattner785d16f2010-02-17 02:16:19 +0000357 // Remember all of the input chains our pattern will match.
Chris Lattner8e946be2010-02-21 03:22:59 +0000358 MatchedChainNodes.push_back(NextRecordedOperandNo++);
Chris Lattner785d16f2010-02-17 02:16:19 +0000359
360 // If this is the second (e.g. indbr(load) or store(add(load))) or third
361 // input chain (e.g. (store (add (load, load))) from msp430) we need to make
362 // sure that folding the chain won't induce cycles in the DAG. This could
363 // happen if there were an intermediate node between the indbr and load, for
364 // example.
Chris Lattner8e946be2010-02-21 03:22:59 +0000365 if (MatchedChainNodes.size() > 1) {
366 // FIXME2: This is broken, we should eliminate this nonsense completely,
Chris Lattner9a747f12010-02-17 06:23:39 +0000367 // but we want to produce the same selections that the old matcher does
368 // for now.
Chris Lattner8e946be2010-02-21 03:22:59 +0000369 unsigned PrevOp = MatchedChainNodes[MatchedChainNodes.size()-2];
Chris Lattnerb21ba712010-02-25 02:04:40 +0000370 AddMatcher(new CheckChainCompatibleMatcher(PrevOp));
Chris Lattner9a747f12010-02-17 06:23:39 +0000371 }
Chris Lattner785d16f2010-02-17 02:16:19 +0000372
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000373 // Don't look at the input chain when matching the tree pattern to the
374 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000375 OpNo = 1;
376
Chris Lattner6bc1b512010-02-16 19:19:58 +0000377 // If this node is not the root and the subtree underneath it produces a
378 // chain, then the result of matching the node is also produce a chain.
379 // Beyond that, this means that we're also folding (at least) the root node
380 // into the node that produce the chain (for example, matching
381 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
382 // problematic, if the 'reg' node also uses the load (say, its chain).
383 // Graphically:
384 //
385 // [LD]
386 // ^ ^
387 // | \ DAG's like cheese.
388 // / |
389 // / [YY]
390 // | ^
391 // [XX]--/
392 //
393 // It would be invalid to fold XX and LD. In this case, folding the two
394 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
395 // To prevent this, we emit a dynamic check for legality before allowing
396 // this to be folded.
397 //
398 const TreePatternNode *Root = Pattern.getSrcPattern();
399 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000400 // If there is a node between the root and this node, then we definitely
401 // need to emit the check.
402 bool NeedCheck = !Root->hasChild(N);
403
404 // If it *is* an immediate child of the root, we can still need a check if
405 // the root SDNode has multiple inputs. For us, this means that it is an
406 // intrinsic, has multiple operands, or has other inputs like chain or
407 // flag).
408 if (!NeedCheck) {
409 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
410 NeedCheck =
411 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
412 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
413 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
414 PInfo.getNumOperands() > 1 ||
415 PInfo.hasProperty(SDNPHasChain) ||
416 PInfo.hasProperty(SDNPInFlag) ||
417 PInfo.hasProperty(SDNPOptInFlag);
418 }
419
420 if (NeedCheck)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000421 AddMatcher(new CheckFoldableChainNodeMatcher());
Chris Lattnere39650a2010-02-16 06:10:58 +0000422 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000423 }
Chris Lattner02f73582010-02-24 05:33:42 +0000424
425 // If this node has an output flag and isn't the root, remember it.
426 if (N->NodeHasProperty(SDNPOutFlag, CGP) &&
427 N != Pattern.getSrcPattern()) {
428 // TODO: This redundantly records nodes with both flags and chains.
429
430 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000431 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner02f73582010-02-24 05:33:42 +0000432 "' flag output node"));
433 // Remember all of the nodes with output flags our pattern will match.
434 MatchedFlagResultNodes.push_back(NextRecordedOperandNo++);
435 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000436
437 // If this node is known to have an input flag or if it *might* have an input
438 // flag, capture it as the flag input of the pattern.
439 if (N->NodeHasProperty(SDNPOptInFlag, CGP) ||
440 N->NodeHasProperty(SDNPInFlag, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000441 AddMatcher(new CaptureFlagInputMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000442
Chris Lattnerda272d12010-02-15 08:04:42 +0000443 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
444 // Get the code suitable for matching this child. Move to the child, check
445 // it then move back to the parent.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000446 AddMatcher(new MoveChildMatcher(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000447 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000448 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000449 }
450}
451
452
453void MatcherGen::EmitMatchCode(const TreePatternNode *N,
454 TreePatternNode *NodeNoTypes) {
455 // If N and NodeNoTypes don't agree on a type, then this is a case where we
456 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
457 // reinfer any correlated types.
458 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000459 AddMatcher(new CheckTypeMatcher(N->getTypeNum(0)));
Chris Lattnerda272d12010-02-15 08:04:42 +0000460 NodeNoTypes->setTypes(N->getExtTypes());
461 InferPossibleTypes();
462 }
463
Chris Lattnerda272d12010-02-15 08:04:42 +0000464 // If this node has a name associated with it, capture it in VariableMap. If
465 // we already saw this in the pattern, emit code to verify dagness.
466 if (!N->getName().empty()) {
467 unsigned &VarMapEntry = VariableMap[N->getName()];
468 if (VarMapEntry == 0) {
Chris Lattner20df2422010-02-22 23:33:44 +0000469 // If it is a named node, we must emit a 'Record' opcode.
470 VarMapEntry = ++NextRecordedOperandNo;
Chris Lattnerb21ba712010-02-25 02:04:40 +0000471 AddMatcher(new RecordMatcher("$" + N->getName()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000472 } else {
473 // If we get here, this is a second reference to a specific name. Since
474 // we already have checked that the first reference is valid, we don't
475 // have to recursively match it, just check that it's the same as the
476 // previously named thing.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000477 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
Chris Lattnerda272d12010-02-15 08:04:42 +0000478 return;
479 }
480 }
481
Chris Lattnerda272d12010-02-15 08:04:42 +0000482 if (N->isLeaf())
483 EmitLeafMatchCode(N);
484 else
485 EmitOperatorMatchCode(N, NodeNoTypes);
486}
487
488void MatcherGen::EmitMatcherCode() {
489 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
490 // feature is around, do the check).
Chris Lattner2a1263b2010-02-25 00:03:03 +0000491 // FIXME: This should get emitted after the match code below to encourage
492 // sharing. This can't happen until we get an X86ISD::AddrMode node made by
493 // dag combine, eliminating the horrible side-effect-full stuff from
494 // X86's MatchAddress.
Chris Lattnerda272d12010-02-15 08:04:42 +0000495 if (!Pattern.getPredicateCheck().empty())
Chris Lattnerb21ba712010-02-25 02:04:40 +0000496 AddMatcher(new
497 CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000498
499 // Emit the matcher for the pattern structure and types.
500 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
501}
502
503
Chris Lattnerb49985a2010-02-18 06:47:49 +0000504//===----------------------------------------------------------------------===//
505// Node Result Generation
506//===----------------------------------------------------------------------===//
507
Chris Lattner8e946be2010-02-21 03:22:59 +0000508void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
509 SmallVectorImpl<unsigned> &ResultOps){
510 assert(!N->getName().empty() && "Operand not named!");
511
512 unsigned SlotNo = getNamedArgumentSlot(N->getName());
513
514 // A reference to a complex pattern gets all of the results of the complex
515 // pattern's match.
516 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattner20df2422010-02-22 23:33:44 +0000517 // The first slot entry is the node itself, the subsequent entries are the
518 // matched values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000519 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner20df2422010-02-22 23:33:44 +0000520 ResultOps.push_back(SlotNo+i+1);
Chris Lattner8e946be2010-02-21 03:22:59 +0000521 return;
522 }
523
524 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
525 // version of the immediate so that it doesn't get selected due to some other
526 // node use.
527 if (!N->isLeaf()) {
528 StringRef OperatorName = N->getOperator()->getName();
529 if (OperatorName == "imm" || OperatorName == "fpimm") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000530 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000531 ResultOps.push_back(NextRecordedOperandNo++);
532 return;
533 }
534 }
535
536 ResultOps.push_back(SlotNo);
537}
538
Chris Lattnerb49985a2010-02-18 06:47:49 +0000539void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000540 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattner845c0422010-02-18 22:03:03 +0000541 assert(N->isLeaf() && "Must be a leaf");
542
543 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000544 AddMatcher(new EmitIntegerMatcher(II->getValue(),N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000545 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000546 return;
547 }
548
549 // If this is an explicit register reference, handle it.
550 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
551 if (DI->getDef()->isSubClassOf("Register")) {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000552 AddMatcher(new EmitRegisterMatcher(DI->getDef(),
Chris Lattner845c0422010-02-18 22:03:03 +0000553 N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000554 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000555 return;
556 }
557
558 if (DI->getDef()->getName() == "zero_reg") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000559 AddMatcher(new EmitRegisterMatcher(0, N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000560 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000561 return;
562 }
563
Chris Lattner8e946be2010-02-21 03:22:59 +0000564 // Handle a reference to a register class. This is used
565 // in COPY_TO_SUBREG instructions.
Chris Lattner845c0422010-02-18 22:03:03 +0000566 if (DI->getDef()->isSubClassOf("RegisterClass")) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000567 std::string Value = getQualifiedName(DI->getDef()) + "RegClassID";
Chris Lattnerb21ba712010-02-25 02:04:40 +0000568 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
Chris Lattner8e946be2010-02-21 03:22:59 +0000569 ResultOps.push_back(NextRecordedOperandNo++);
570 return;
Chris Lattner845c0422010-02-18 22:03:03 +0000571 }
Chris Lattner845c0422010-02-18 22:03:03 +0000572 }
573
Chris Lattnerb49985a2010-02-18 06:47:49 +0000574 errs() << "unhandled leaf node: \n";
575 N->dump();
576}
577
Chris Lattner8e946be2010-02-21 03:22:59 +0000578/// GetInstPatternNode - Get the pattern for an instruction.
579///
580const TreePatternNode *MatcherGen::
581GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
582 const TreePattern *InstPat = Inst.getPattern();
583
584 // FIXME2?: Assume actual pattern comes before "implicit".
585 TreePatternNode *InstPatNode;
586 if (InstPat)
587 InstPatNode = InstPat->getTree(0);
588 else if (/*isRoot*/ N == Pattern.getDstPattern())
589 InstPatNode = Pattern.getSrcPattern();
590 else
591 return 0;
592
593 if (InstPatNode && !InstPatNode->isLeaf() &&
594 InstPatNode->getOperator()->getName() == "set")
595 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
596
597 return InstPatNode;
598}
599
600void MatcherGen::
601EmitResultInstructionAsOperand(const TreePatternNode *N,
602 SmallVectorImpl<unsigned> &OutputOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000603 Record *Op = N->getOperator();
604 const CodeGenTarget &CGT = CGP.getTargetInfo();
605 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
606 const DAGInstruction &Inst = CGP.getInstruction(Op);
607
Chris Lattner8e946be2010-02-21 03:22:59 +0000608 // If we can, get the pattern for the instruction we're generating. We derive
609 // a variety of information from this pattern, such as whether it has a chain.
610 //
611 // FIXME2: This is extremely dubious for several reasons, not the least of
612 // which it gives special status to instructions with patterns that Pat<>
613 // nodes can't duplicate.
614 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
615
616 // NodeHasChain - Whether the instruction node we're creating takes chains.
617 bool NodeHasChain = InstPatNode &&
618 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000619
Chris Lattner8e946be2010-02-21 03:22:59 +0000620 bool isRoot = N == Pattern.getDstPattern();
621
Chris Lattner02f73582010-02-24 05:33:42 +0000622 // TreeHasOutFlag - True if this tree has a flag.
623 bool TreeHasInFlag = false, TreeHasOutFlag = false;
Chris Lattner8e946be2010-02-21 03:22:59 +0000624 if (isRoot) {
625 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
Chris Lattner02f73582010-02-24 05:33:42 +0000626 TreeHasInFlag = SrcPat->TreeHasProperty(SDNPOptInFlag, CGP) ||
Chris Lattner8e946be2010-02-21 03:22:59 +0000627 SrcPat->TreeHasProperty(SDNPInFlag, CGP);
628
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.
Chris Lattner02f73582010-02-24 05:33:42 +0000631 TreeHasOutFlag = SrcPat->TreeHasProperty(SDNPOutFlag, CGP);
Chris Lattner8e946be2010-02-21 03:22:59 +0000632 }
633
634 // NumResults - This is the number of results produced by the instruction in
635 // the "outs" list.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000636 unsigned NumResults = Inst.getNumResults();
637
Chris Lattnerb49985a2010-02-18 06:47:49 +0000638 // Loop over all of the operands of the instruction pattern, emitting code
639 // to fill them all in. The node 'N' usually has number children equal to
640 // the number of input operands of the instruction. However, in cases
641 // where there are predicate operands for an instruction, we need to fill
642 // in the 'execute always' values. Match up the node operands to the
643 // instruction operands to do this.
Chris Lattner8e946be2010-02-21 03:22:59 +0000644 SmallVector<unsigned, 8> InstOps;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000645 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.OperandList.size();
646 InstOpNo != e; ++InstOpNo) {
647
648 // Determine what to emit for this operand.
649 Record *OperandNode = II.OperandList[InstOpNo].Rec;
650 if ((OperandNode->isSubClassOf("PredicateOperand") ||
651 OperandNode->isSubClassOf("OptionalDefOperand")) &&
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(II.OperandList[InstOpNo].Rec);
657 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
Chris Lattner8e946be2010-02-21 03:22:59 +0000658 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000659 continue;
660 }
661
662 // Otherwise this is a normal operand or a predicate operand without
663 // 'execute always'; emit it.
Chris Lattner8e946be2010-02-21 03:22:59 +0000664 EmitResultOperand(N->getChild(ChildNo), InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000665 ++ChildNo;
666 }
667
Chris Lattner8e946be2010-02-21 03:22:59 +0000668 // Nodes that match patterns with (potentially multiple) chain inputs have to
669 // merge them together into a token factor.
670 if (NodeHasChain && !EmittedMergeInputChains) {
671 // FIXME2: Move this out of emitresult to a top level place.
672 assert(!MatchedChainNodes.empty() &&
673 "How can this node have chain if no inputs do?");
674 // Otherwise, we have to emit an operation to merge the input chains and
675 // set this as the current input chain.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000676 AddMatcher(new EmitMergeInputChainsMatcher
Chris Lattner8e946be2010-02-21 03:22:59 +0000677 (MatchedChainNodes.data(), MatchedChainNodes.size()));
678 EmittedMergeInputChains = true;
679 }
680
681 // If this node has an input flag or explicitly specified input physregs, we
682 // need to add chained and flagged copyfromreg nodes and materialize the flag
683 // input.
684 if (isRoot && !PhysRegInputs.empty()) {
685 // Emit all of the CopyToReg nodes for the input physical registers. These
686 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
687 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000688 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
Chris Lattner8e946be2010-02-21 03:22:59 +0000689 PhysRegInputs[i].first));
690 // Even if the node has no other flag inputs, the resultant node must be
691 // flagged to the CopyFromReg nodes we just generated.
Chris Lattner02f73582010-02-24 05:33:42 +0000692 TreeHasInFlag = true;
Chris Lattner8e946be2010-02-21 03:22:59 +0000693 }
694
695 // Result order: node results, chain, flags
696
697 // Determine the result types.
698 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
Chris Lattner565a6f92010-02-21 23:54:05 +0000699 if (NumResults != 0 && N->getTypeNum(0) != MVT::isVoid) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000700 // FIXME2: If the node has multiple results, we should add them. For now,
701 // preserve existing behavior?!
702 ResultVTs.push_back(N->getTypeNum(0));
703 }
704
705
706 // If this is the root instruction of a pattern that has physical registers in
707 // its result pattern, add output VTs for them. For example, X86 has:
708 // (set AL, (mul ...))
709 // This also handles implicit results like:
710 // (implicit EFLAGS)
711 if (isRoot && Pattern.getDstRegs().size() != 0) {
712 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i)
713 if (Pattern.getDstRegs()[i]->isSubClassOf("Register"))
714 ResultVTs.push_back(getRegisterValueType(Pattern.getDstRegs()[i], CGT));
715 }
716 if (NodeHasChain)
717 ResultVTs.push_back(MVT::Other);
Chris Lattner02f73582010-02-24 05:33:42 +0000718 if (TreeHasOutFlag)
Chris Lattner8e946be2010-02-21 03:22:59 +0000719 ResultVTs.push_back(MVT::Flag);
720
721 // FIXME2: Instead of using the isVariadic flag on the instruction, we should
722 // have an SDNP that indicates variadicism. The TargetInstrInfo isVariadic
723 // property should be inferred from this when an instruction has a pattern.
724 int NumFixedArityOperands = -1;
725 if (isRoot && II.isVariadic)
726 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
727
728 // If this is the root node and any of the nodes matched nodes in the input
729 // pattern have MemRefs in them, have the interpreter collect them and plop
730 // them onto this node.
731 //
732 // FIXME3: This is actively incorrect for result patterns where the root of
733 // the pattern is not the memory reference and is also incorrect when the
734 // result pattern has multiple memory-referencing instructions. For example,
735 // in the X86 backend, this pattern causes the memrefs to get attached to the
736 // CVTSS2SDrr instead of the MOVSSrm:
737 //
738 // def : Pat<(extloadf32 addr:$src),
739 // (CVTSS2SDrr (MOVSSrm addr:$src))>;
740 //
741 bool NodeHasMemRefs =
742 isRoot && Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
743
744 // FIXME: Eventually add a SelectNodeTo form. It works if the new node has a
745 // superset of the results of the old node, in the same places. E.g. turning
746 // (add (load)) -> add32rm is ok because result #0 is the result and result #1
747 // is new.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000748 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
Chris Lattner8e946be2010-02-21 03:22:59 +0000749 ResultVTs.data(), ResultVTs.size(),
750 InstOps.data(), InstOps.size(),
Chris Lattner02f73582010-02-24 05:33:42 +0000751 NodeHasChain, TreeHasInFlag,
Chris Lattner8e946be2010-02-21 03:22:59 +0000752 NodeHasMemRefs,NumFixedArityOperands));
753
Chris Lattner565a6f92010-02-21 23:54:05 +0000754 // The non-chain and non-flag results of the newly emitted node get recorded.
755 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
756 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Flag) break;
Chris Lattner77f2e272010-02-21 06:03:07 +0000757 OutputOps.push_back(NextRecordedOperandNo++);
Chris Lattner565a6f92010-02-21 23:54:05 +0000758 }
Chris Lattnerb49985a2010-02-18 06:47:49 +0000759
Chris Lattner8e946be2010-02-21 03:22:59 +0000760 // FIXME2: Kill off all the SelectionDAG::SelectNodeTo and getMachineNode
761 // variants. Call MorphNodeTo instead of SelectNodeTo.
762}
763
764void MatcherGen::
765EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
766 SmallVectorImpl<unsigned> &ResultOps) {
767 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
768
769 // Emit the operand.
770 SmallVector<unsigned, 8> InputOps;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000771
Chris Lattner8e946be2010-02-21 03:22:59 +0000772 // FIXME2: Could easily generalize this to support multiple inputs and outputs
773 // to the SDNodeXForm. For now we just support one input and one output like
774 // the old instruction selector.
775 assert(N->getNumChildren() == 1);
776 EmitResultOperand(N->getChild(0), InputOps);
777
778 // The input currently must have produced exactly one result.
779 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
780
Chris Lattnerb21ba712010-02-25 02:04:40 +0000781 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
Chris Lattner8e946be2010-02-21 03:22:59 +0000782 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000783}
784
785void MatcherGen::EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000786 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000787 // This is something selected from the pattern we matched.
Chris Lattner8e946be2010-02-21 03:22:59 +0000788 if (!N->getName().empty())
789 return EmitResultOfNamedOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000790
791 if (N->isLeaf())
792 return EmitResultLeafAsOperand(N, ResultOps);
793
794 Record *OpRec = N->getOperator();
795 if (OpRec->isSubClassOf("Instruction"))
796 return EmitResultInstructionAsOperand(N, ResultOps);
797 if (OpRec->isSubClassOf("SDNodeXForm"))
Chris Lattner8e946be2010-02-21 03:22:59 +0000798 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000799 errs() << "Unknown result node to emit code for: " << *N << '\n';
800 throw std::string("Unknown node in result pattern!");
801}
802
803void MatcherGen::EmitResultCode() {
Chris Lattner565a6f92010-02-21 23:54:05 +0000804 // Codegen the root of the result pattern, capturing the resulting values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000805 SmallVector<unsigned, 8> Ops;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000806 EmitResultOperand(Pattern.getDstPattern(), Ops);
Chris Lattner8e946be2010-02-21 03:22:59 +0000807
Chris Lattner565a6f92010-02-21 23:54:05 +0000808 // 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 condition codes etc) just lop them off.
811 // This doesn't need to worry about flags or chains, just explicit results.
812 //
813 // FIXME2: This doesn't work because there is currently no way to get an
814 // accurate count of the # results the source pattern sets. This is because
815 // of the "parallel" construct in X86 land, which looks like this:
816 //
817 //def : Pat<(parallel (X86and_flag GR8:$src1, GR8:$src2),
818 // (implicit EFLAGS)),
819 // (AND8rr GR8:$src1, GR8:$src2)>;
820 //
821 // This idiom means to match the two-result node X86and_flag (which is
822 // declared as returning a single result, because we can't match multi-result
823 // nodes yet). In this case, we would have to know that the input has two
824 // results. However, mul8r is modelled exactly the same way, but without
825 // implicit defs included. The fix is to support multiple results directly
826 // and eliminate 'parallel'.
827 //
828 // FIXME2: When this is fixed, we should revert the terrible hack in the
829 // OPC_EmitNode code in the interpreter.
830#if 0
831 const TreePatternNode *Src = Pattern.getSrcPattern();
832 unsigned NumSrcResults = Src->getTypeNum(0) != MVT::isVoid ? 1 : 0;
833 NumSrcResults += Pattern.getDstRegs().size();
834 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
835 Ops.resize(NumSrcResults);
836#endif
Chris Lattner02f73582010-02-24 05:33:42 +0000837
838 // If the matched pattern covers nodes which define a flag result, emit a node
839 // that tells the matcher about them so that it can update their results.
840 if (!MatchedFlagResultNodes.empty())
Chris Lattnerb21ba712010-02-25 02:04:40 +0000841 AddMatcher(new MarkFlagResultsMatcher(MatchedFlagResultNodes.data(),
Chris Lattner02f73582010-02-24 05:33:42 +0000842 MatchedFlagResultNodes.size()));
843
Chris Lattner565a6f92010-02-21 23:54:05 +0000844
Chris Lattner8e946be2010-02-21 03:22:59 +0000845 // We know that the resulting pattern has exactly one result/
846 // FIXME2: why? what about something like (set a,b,c, (complexpat))
847 // FIXME2: Implicit results should be pushed here I guess?
Chris Lattnerb21ba712010-02-25 02:04:40 +0000848 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
Chris Lattnerb49985a2010-02-18 06:47:49 +0000849}
850
851
Chris Lattnerb21ba712010-02-25 02:04:40 +0000852Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
Chris Lattnerda272d12010-02-15 08:04:42 +0000853 const CodeGenDAGPatterns &CGP) {
854 MatcherGen Gen(Pattern, CGP);
855
856 // Generate the code for the matcher.
857 Gen.EmitMatcherCode();
858
Chris Lattner8e946be2010-02-21 03:22:59 +0000859
860 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
861 // FIXME2: Split result code out to another table, and make the matcher end
862 // with an "Emit <index>" command. This allows result generation stuff to be
863 // shared and factored?
864
Chris Lattnerda272d12010-02-15 08:04:42 +0000865 // If the match succeeds, then we generate Pattern.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000866 Gen.EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000867
868 // Unconditional match.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000869 return Gen.GetMatcher();
Chris Lattnerda272d12010-02-15 08:04:42 +0000870}
871
872
873