blob: 433da18cecb6cbba2760a28bf82eb0eab9b650b7 [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 Lattner67ea6a72010-03-01 22:49:06 +000039
40 // If this occurs in multiple register classes, they all have to agree.
41 assert(VT == RC.getValueTypeNum(0));
Chris Lattner8e946be2010-02-21 03:22:59 +000042 }
43 return VT;
44}
45
46
47namespace {
Chris Lattnerda272d12010-02-15 08:04:42 +000048 class MatcherGen {
49 const PatternToMatch &Pattern;
50 const CodeGenDAGPatterns &CGP;
51
52 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
53 /// out with all of the types removed. This allows us to insert type checks
54 /// as we scan the tree.
55 TreePatternNode *PatWithNoTypes;
56
57 /// VariableMap - A map from variable names ('$dst') to the recorded operand
58 /// number that they were captured as. These are biased by 1 to make
59 /// insertion easier.
60 StringMap<unsigned> VariableMap;
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000061
62 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
63 /// the RecordedNodes array, this keeps track of which slot will be next to
64 /// record into.
Chris Lattnerda272d12010-02-15 08:04:42 +000065 unsigned NextRecordedOperandNo;
66
Chris Lattner8e946be2010-02-21 03:22:59 +000067 /// MatchedChainNodes - This maintains the position in the recorded nodes
68 /// array of all of the recorded input nodes that have chains.
69 SmallVector<unsigned, 2> MatchedChainNodes;
Chris Lattner02f73582010-02-24 05:33:42 +000070
71 /// MatchedFlagResultNodes - This maintains the position in the recorded
72 /// nodes array of all of the recorded input nodes that have flag results.
73 SmallVector<unsigned, 2> MatchedFlagResultNodes;
Chris Lattner8e946be2010-02-21 03:22:59 +000074
Chris Lattner57bf8a42010-03-04 01:23:08 +000075 /// MatchedComplexPatterns - This maintains a list of all of the
76 /// ComplexPatterns that we need to check. The patterns are known to have
77 /// names which were recorded. The second element of each pair is the first
78 /// slot number that the OPC_CheckComplexPat opcode drops the matched
79 /// results into.
80 SmallVector<std::pair<const TreePatternNode*,
81 unsigned>, 2> MatchedComplexPatterns;
82
Chris Lattner8e946be2010-02-21 03:22:59 +000083 /// PhysRegInputs - List list has an entry for each explicitly specified
84 /// physreg input to the pattern. The first elt is the Register node, the
85 /// second is the recorded slot number the input pattern match saved it in.
86 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
87
Chris Lattner785d16f2010-02-17 02:16:19 +000088 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattnerb21ba712010-02-25 02:04:40 +000089 Matcher *TheMatcher;
Chris Lattner785d16f2010-02-17 02:16:19 +000090
91 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattnerbd8227f2010-02-18 02:53:41 +000092 /// which should have future checks stuck into its Next position.
Chris Lattnerb21ba712010-02-25 02:04:40 +000093 Matcher *CurPredicate;
Chris Lattnerda272d12010-02-15 08:04:42 +000094 public:
95 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
96
97 ~MatcherGen() {
98 delete PatWithNoTypes;
99 }
100
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000101 bool EmitMatcherCode(unsigned Variant);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000102 void EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000103
Chris Lattnerb21ba712010-02-25 02:04:40 +0000104 Matcher *GetMatcher() const { return TheMatcher; }
105 Matcher *GetCurPredicate() const { return CurPredicate; }
Chris Lattnerda272d12010-02-15 08:04:42 +0000106 private:
Chris Lattnerb21ba712010-02-25 02:04:40 +0000107 void AddMatcher(Matcher *NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000108 void InferPossibleTypes();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000109
110 // Matcher Generation.
Chris Lattnerda272d12010-02-15 08:04:42 +0000111 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
112 void EmitLeafMatchCode(const TreePatternNode *N);
113 void EmitOperatorMatchCode(const TreePatternNode *N,
114 TreePatternNode *NodeNoTypes);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000115
116 // Result Code Generation.
Chris Lattner8e946be2010-02-21 03:22:59 +0000117 unsigned getNamedArgumentSlot(StringRef Name) {
118 unsigned VarMapEntry = VariableMap[Name];
119 assert(VarMapEntry != 0 &&
120 "Variable referenced but not defined and not caught earlier!");
121 return VarMapEntry-1;
122 }
123
124 /// GetInstPatternNode - Get the pattern for an instruction.
125 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
126 const TreePatternNode *N);
127
Chris Lattnerb49985a2010-02-18 06:47:49 +0000128 void EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000129 SmallVectorImpl<unsigned> &ResultOps);
130 void EmitResultOfNamedOperand(const TreePatternNode *N,
131 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000132 void EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000133 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000134 void EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000135 SmallVectorImpl<unsigned> &ResultOps);
136 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
137 SmallVectorImpl<unsigned> &ResultOps);
138 };
Chris Lattnerda272d12010-02-15 08:04:42 +0000139
140} // end anon namespace.
141
142MatcherGen::MatcherGen(const PatternToMatch &pattern,
143 const CodeGenDAGPatterns &cgp)
Chris Lattner853b9192010-02-19 00:33:13 +0000144: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Chris Lattner01bcd942010-03-01 22:46:42 +0000145 TheMatcher(0), CurPredicate(0) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000146 // We need to produce the matcher tree for the patterns source pattern. To do
147 // this we need to match the structure as well as the types. To do the type
148 // matching, we want to figure out the fewest number of type checks we need to
149 // emit. For example, if there is only one integer type supported by a
150 // target, there should be no type comparisons at all for integer patterns!
151 //
152 // To figure out the fewest number of type checks needed, clone the pattern,
153 // remove the types, then perform type inference on the pattern as a whole.
154 // If there are unresolved types, emit an explicit check for those types,
155 // apply the type to the tree, then rerun type inference. Iterate until all
156 // types are resolved.
157 //
158 PatWithNoTypes = Pattern.getSrcPattern()->clone();
159 PatWithNoTypes->RemoveAllTypes();
160
161 // If there are types that are manifestly known, infer them.
162 InferPossibleTypes();
163}
164
165/// InferPossibleTypes - As we emit the pattern, we end up generating type
166/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
167/// want to propagate implied types as far throughout the tree as possible so
168/// that we avoid doing redundant type checks. This does the type propagation.
169void MatcherGen::InferPossibleTypes() {
170 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
171 // diagnostics, which we know are impossible at this point.
172 TreePattern &TP = *CGP.pf_begin()->second;
173
174 try {
175 bool MadeChange = true;
176 while (MadeChange)
177 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
178 true/*Ignore reg constraints*/);
179 } catch (...) {
180 errs() << "Type constraint application shouldn't fail!";
181 abort();
182 }
183}
184
185
Chris Lattnerb21ba712010-02-25 02:04:40 +0000186/// AddMatcher - Add a matcher node to the current graph we're building.
187void MatcherGen::AddMatcher(Matcher *NewNode) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000188 if (CurPredicate != 0)
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000189 CurPredicate->setNext(NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000190 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000191 TheMatcher = NewNode;
Chris Lattnerda272d12010-02-15 08:04:42 +0000192 CurPredicate = NewNode;
193}
194
195
Chris Lattnerb49985a2010-02-18 06:47:49 +0000196//===----------------------------------------------------------------------===//
197// Pattern Match Generation
198//===----------------------------------------------------------------------===//
Chris Lattnerda272d12010-02-15 08:04:42 +0000199
200/// EmitLeafMatchCode - Generate matching code for leaf nodes.
201void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
202 assert(N->isLeaf() && "Not a leaf?");
Chris Lattner8e946be2010-02-21 03:22:59 +0000203
204 // If there are node predicates for this node, generate their checks.
205 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000206 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Chris Lattner8e946be2010-02-21 03:22:59 +0000207
Chris Lattnerda272d12010-02-15 08:04:42 +0000208 // Direct match against an integer constant.
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000209 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
210 // If this is the root of the dag we're matching, we emit a redundant opcode
211 // check to ensure that this gets folded into the normal top-level
212 // OpcodeSwitch.
213 if (N == Pattern.getSrcPattern()) {
214 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
215 AddMatcher(new CheckOpcodeMatcher(NI));
216 }
217
Chris Lattnerb21ba712010-02-25 02:04:40 +0000218 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000219 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000220
221 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
222 if (DI == 0) {
223 errs() << "Unknown leaf kind: " << *DI << "\n";
224 abort();
225 }
226
227 Record *LeafRec = DI->getDef();
228 if (// Handle register references. Nothing to do here, they always match.
229 LeafRec->isSubClassOf("RegisterClass") ||
230 LeafRec->isSubClassOf("PointerLikeRegClass") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000231 // Place holder for SRCVALUE nodes. Nothing to do here.
232 LeafRec->getName() == "srcvalue")
233 return;
Chris Lattner8e946be2010-02-21 03:22:59 +0000234
235 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
236 // record the register
237 if (LeafRec->isSubClassOf("Register")) {
Chris Lattner0cebe612010-03-01 02:24:17 +0000238 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
239 NextRecordedOperandNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000240 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
241 return;
242 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000243
244 if (LeafRec->isSubClassOf("ValueType"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000245 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000246
247 if (LeafRec->isSubClassOf("CondCode"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000248 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000249
250 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000251 // We can't model ComplexPattern uses that don't have their name taken yet.
252 // The OPC_CheckComplexPattern operation implicitly records the results.
253 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000254 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
255 exit(1);
256 }
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000257
Chris Lattner57bf8a42010-03-04 01:23:08 +0000258 // Remember this ComplexPattern so that we can emit it after all the other
259 // structural matches are done.
260 MatchedComplexPatterns.push_back(std::make_pair(N, 0));
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000261 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000262 }
263
264 errs() << "Unknown leaf kind: " << *N << "\n";
265 abort();
266}
267
268void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
269 TreePatternNode *NodeNoTypes) {
270 assert(!N->isLeaf() && "Not an operator?");
271 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
272
273 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
274 // a constant without a predicate fn that has more that one bit set, handle
275 // this as a special case. This is usually for targets that have special
276 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
277 // handling stuff). Using these instructions is often far more efficient
278 // than materializing the constant. Unfortunately, both the instcombiner
279 // and the dag combiner can often infer that bits are dead, and thus drop
280 // them from the mask in the dag. For example, it might turn 'AND X, 255'
281 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
282 // to handle this.
283 if ((N->getOperator()->getName() == "and" ||
284 N->getOperator()->getName() == "or") &&
Chris Lattner8e946be2010-02-21 03:22:59 +0000285 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
286 N->getPredicateFns().empty()) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000287 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
288 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Chris Lattnere9eeda82010-03-01 02:15:34 +0000289 // If this is at the root of the pattern, we emit a redundant
290 // CheckOpcode so that the following checks get factored properly under
291 // a single opcode check.
292 if (N == Pattern.getSrcPattern())
293 AddMatcher(new CheckOpcodeMatcher(CInfo));
294
295 // Emit the CheckAndImm/CheckOrImm node.
Chris Lattnerda272d12010-02-15 08:04:42 +0000296 if (N->getOperator()->getName() == "and")
Chris Lattnerb21ba712010-02-25 02:04:40 +0000297 AddMatcher(new CheckAndImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000298 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000299 AddMatcher(new CheckOrImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000300
301 // Match the LHS of the AND as appropriate.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000302 AddMatcher(new MoveChildMatcher(0));
Chris Lattnerda272d12010-02-15 08:04:42 +0000303 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000304 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000305 return;
306 }
307 }
308 }
309
310 // Check that the current opcode lines up.
Chris Lattnera230f962010-02-27 21:48:43 +0000311 AddMatcher(new CheckOpcodeMatcher(CInfo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000312
Chris Lattner8e946be2010-02-21 03:22:59 +0000313 // If there are node predicates for this node, generate their checks.
314 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000315 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Chris Lattner8e946be2010-02-21 03:22:59 +0000316
317
318 // If this node has memory references (i.e. is a load or store), tell the
319 // interpreter to capture them in the memref array.
320 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000321 AddMatcher(new RecordMemRefMatcher());
Chris Lattner8e946be2010-02-21 03:22:59 +0000322
Chris Lattnerda272d12010-02-15 08:04:42 +0000323 // If this node has a chain, then the chain is operand #0 is the SDNode, and
324 // the child numbers of the node are all offset by one.
325 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000326 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000327 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000328 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner0cebe612010-03-01 02:24:17 +0000329 "' chained node",
330 NextRecordedOperandNo));
Chris Lattner785d16f2010-02-17 02:16:19 +0000331 // Remember all of the input chains our pattern will match.
Chris Lattner8e946be2010-02-21 03:22:59 +0000332 MatchedChainNodes.push_back(NextRecordedOperandNo++);
Chris Lattner785d16f2010-02-17 02:16:19 +0000333
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000334 // Don't look at the input chain when matching the tree pattern to the
335 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000336 OpNo = 1;
337
Chris Lattner6bc1b512010-02-16 19:19:58 +0000338 // If this node is not the root and the subtree underneath it produces a
339 // chain, then the result of matching the node is also produce a chain.
340 // Beyond that, this means that we're also folding (at least) the root node
341 // into the node that produce the chain (for example, matching
342 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
343 // problematic, if the 'reg' node also uses the load (say, its chain).
344 // Graphically:
345 //
346 // [LD]
347 // ^ ^
348 // | \ DAG's like cheese.
349 // / |
350 // / [YY]
351 // | ^
352 // [XX]--/
353 //
354 // It would be invalid to fold XX and LD. In this case, folding the two
355 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
356 // To prevent this, we emit a dynamic check for legality before allowing
357 // this to be folded.
358 //
359 const TreePatternNode *Root = Pattern.getSrcPattern();
360 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000361 // If there is a node between the root and this node, then we definitely
362 // need to emit the check.
363 bool NeedCheck = !Root->hasChild(N);
364
365 // If it *is* an immediate child of the root, we can still need a check if
366 // the root SDNode has multiple inputs. For us, this means that it is an
367 // intrinsic, has multiple operands, or has other inputs like chain or
368 // flag).
369 if (!NeedCheck) {
370 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
371 NeedCheck =
372 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
373 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
374 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
375 PInfo.getNumOperands() > 1 ||
376 PInfo.hasProperty(SDNPHasChain) ||
377 PInfo.hasProperty(SDNPInFlag) ||
378 PInfo.hasProperty(SDNPOptInFlag);
379 }
380
381 if (NeedCheck)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000382 AddMatcher(new CheckFoldableChainNodeMatcher());
Chris Lattnere39650a2010-02-16 06:10:58 +0000383 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000384 }
Chris Lattner02f73582010-02-24 05:33:42 +0000385
386 // If this node has an output flag and isn't the root, remember it.
387 if (N->NodeHasProperty(SDNPOutFlag, CGP) &&
388 N != Pattern.getSrcPattern()) {
389 // TODO: This redundantly records nodes with both flags and chains.
390
391 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000392 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner0cebe612010-03-01 02:24:17 +0000393 "' flag output node",
394 NextRecordedOperandNo));
Chris Lattner02f73582010-02-24 05:33:42 +0000395 // Remember all of the nodes with output flags our pattern will match.
396 MatchedFlagResultNodes.push_back(NextRecordedOperandNo++);
397 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000398
399 // If this node is known to have an input flag or if it *might* have an input
400 // flag, capture it as the flag input of the pattern.
401 if (N->NodeHasProperty(SDNPOptInFlag, CGP) ||
402 N->NodeHasProperty(SDNPInFlag, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000403 AddMatcher(new CaptureFlagInputMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000404
Chris Lattnerda272d12010-02-15 08:04:42 +0000405 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
406 // Get the code suitable for matching this child. Move to the child, check
407 // it then move back to the parent.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000408 AddMatcher(new MoveChildMatcher(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000409 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000410 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000411 }
412}
413
414
415void MatcherGen::EmitMatchCode(const TreePatternNode *N,
416 TreePatternNode *NodeNoTypes) {
417 // If N and NodeNoTypes don't agree on a type, then this is a case where we
418 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
419 // reinfer any correlated types.
Chris Lattner60c0e372010-03-01 07:54:59 +0000420 unsigned NodeType = EEVT::isUnknown;
Chris Lattnerda272d12010-02-15 08:04:42 +0000421 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
Chris Lattner60c0e372010-03-01 07:54:59 +0000422 NodeType = N->getTypeNum(0);
Chris Lattnerda272d12010-02-15 08:04:42 +0000423 NodeNoTypes->setTypes(N->getExtTypes());
424 InferPossibleTypes();
425 }
426
Chris Lattnerda272d12010-02-15 08:04:42 +0000427 // If this node has a name associated with it, capture it in VariableMap. If
428 // we already saw this in the pattern, emit code to verify dagness.
429 if (!N->getName().empty()) {
430 unsigned &VarMapEntry = VariableMap[N->getName()];
431 if (VarMapEntry == 0) {
Chris Lattner20df2422010-02-22 23:33:44 +0000432 // If it is a named node, we must emit a 'Record' opcode.
Chris Lattner0cebe612010-03-01 02:24:17 +0000433 AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
Chris Lattner20df2422010-02-22 23:33:44 +0000434 VarMapEntry = ++NextRecordedOperandNo;
Chris Lattnerda272d12010-02-15 08:04:42 +0000435 } else {
436 // If we get here, this is a second reference to a specific name. Since
437 // we already have checked that the first reference is valid, we don't
438 // have to recursively match it, just check that it's the same as the
439 // previously named thing.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000440 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
Chris Lattnerda272d12010-02-15 08:04:42 +0000441 return;
442 }
443 }
444
Chris Lattnerda272d12010-02-15 08:04:42 +0000445 if (N->isLeaf())
446 EmitLeafMatchCode(N);
447 else
448 EmitOperatorMatchCode(N, NodeNoTypes);
Chris Lattner60c0e372010-03-01 07:54:59 +0000449
450 if (NodeType != EEVT::isUnknown)
451 AddMatcher(new CheckTypeMatcher((MVT::SimpleValueType)NodeType));
452
Chris Lattnerda272d12010-02-15 08:04:42 +0000453}
454
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000455/// EmitMatcherCode - Generate the code that matches the predicate of this
456/// pattern for the specified Variant. If the variant is invalid this returns
457/// true and does not generate code, if it is valid, it returns false.
458bool MatcherGen::EmitMatcherCode(unsigned Variant) {
459 // If the root of the pattern is a ComplexPattern and if it is specified to
460 // match some number of root opcodes, these are considered to be our variants.
461 // Depending on which variant we're generating code for, emit the root opcode
462 // check.
463 if (const ComplexPattern *CP =
464 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000465 const std::vector<Record*> &OpNodes = CP->getRootNodes();
Chris Lattner405f1252010-03-01 22:29:19 +0000466 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
467 if (Variant >= OpNodes.size()) return true;
468
469 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000470 } else {
471 if (Variant != 0) return true;
472 }
473
Chris Lattnerda272d12010-02-15 08:04:42 +0000474 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
475 // feature is around, do the check).
Chris Lattner2a1263b2010-02-25 00:03:03 +0000476 // FIXME: This should get emitted after the match code below to encourage
477 // sharing. This can't happen until we get an X86ISD::AddrMode node made by
478 // dag combine, eliminating the horrible side-effect-full stuff from
479 // X86's MatchAddress.
Chris Lattnerda272d12010-02-15 08:04:42 +0000480 if (!Pattern.getPredicateCheck().empty())
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000481 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
482
Chris Lattnerda272d12010-02-15 08:04:42 +0000483 // Emit the matcher for the pattern structure and types.
484 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
Chris Lattner57bf8a42010-03-04 01:23:08 +0000485
486 // Now that we've completed the structural type match, emit any ComplexPattern
487 // checks (e.g. addrmode matches). We emit this after the structural match
488 // because they are generally more expensive to evaluate and more difficult to
489 // factor.
490 // FIXME2: Can the patternpredicatematcher be moved to right before this??
491 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
492 const TreePatternNode *N = MatchedComplexPatterns[i].first;
493
494 // Remember where the results of this match get stuck.
495 MatchedComplexPatterns[i].second = NextRecordedOperandNo;
496
497 // Get the slot we recorded the value in from the name on the node.
498 unsigned RecNodeEntry = VariableMap[N->getName()];
499 assert(!N->getName().empty() && RecNodeEntry &&
500 "Complex pattern should have a name and slot");
501 --RecNodeEntry; // Entries in VariableMap are biased.
502
503 const ComplexPattern &CP =
504 CGP.getComplexPattern(((DefInit*)N->getLeafValue())->getDef());
505
506 // Emit a CheckComplexPat operation, which does the match (aborting if it
507 // fails) and pushes the matched operands onto the recorded nodes list.
508 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
509 N->getName(), NextRecordedOperandNo));
510
511 // Record the right number of operands.
512 NextRecordedOperandNo += CP.getNumOperands();
513 if (CP.hasProperty(SDNPHasChain)) {
514 // If the complex pattern has a chain, then we need to keep track of the
515 // fact that we just recorded a chain input. The chain input will be
516 // matched as the last operand of the predicate if it was successful.
517 ++NextRecordedOperandNo; // Chained node operand.
518
519 // It is the last operand recorded.
520 assert(NextRecordedOperandNo > 1 &&
521 "Should have recorded input/result chains at least!");
522 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
523 }
524
525 // TODO: Complex patterns can't have output flags, if they did, we'd want
526 // to record them.
527 }
528
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000529 return false;
Chris Lattnerda272d12010-02-15 08:04:42 +0000530}
531
532
Chris Lattnerb49985a2010-02-18 06:47:49 +0000533//===----------------------------------------------------------------------===//
534// Node Result Generation
535//===----------------------------------------------------------------------===//
536
Chris Lattner8e946be2010-02-21 03:22:59 +0000537void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
538 SmallVectorImpl<unsigned> &ResultOps){
539 assert(!N->getName().empty() && "Operand not named!");
540
Chris Lattner8e946be2010-02-21 03:22:59 +0000541 // A reference to a complex pattern gets all of the results of the complex
542 // pattern's match.
543 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattner57bf8a42010-03-04 01:23:08 +0000544 unsigned SlotNo = 0;
545 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i)
546 if (MatchedComplexPatterns[i].first->getName() == N->getName()) {
547 SlotNo = MatchedComplexPatterns[i].second;
548 break;
549 }
550 assert(SlotNo != 0 && "Didn't get a slot number assigned?");
551
Chris Lattner20df2422010-02-22 23:33:44 +0000552 // The first slot entry is the node itself, the subsequent entries are the
553 // matched values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000554 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner57bf8a42010-03-04 01:23:08 +0000555 ResultOps.push_back(SlotNo+i);
Chris Lattner8e946be2010-02-21 03:22:59 +0000556 return;
557 }
558
Chris Lattner57bf8a42010-03-04 01:23:08 +0000559 unsigned SlotNo = getNamedArgumentSlot(N->getName());
560
Chris Lattner8e946be2010-02-21 03:22:59 +0000561 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
562 // version of the immediate so that it doesn't get selected due to some other
563 // node use.
564 if (!N->isLeaf()) {
565 StringRef OperatorName = N->getOperator()->getName();
566 if (OperatorName == "imm" || OperatorName == "fpimm") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000567 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000568 ResultOps.push_back(NextRecordedOperandNo++);
569 return;
570 }
571 }
572
573 ResultOps.push_back(SlotNo);
574}
575
Chris Lattnerb49985a2010-02-18 06:47:49 +0000576void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000577 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattner845c0422010-02-18 22:03:03 +0000578 assert(N->isLeaf() && "Must be a leaf");
579
580 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000581 AddMatcher(new EmitIntegerMatcher(II->getValue(),N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000582 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000583 return;
584 }
585
586 // If this is an explicit register reference, handle it.
587 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
588 if (DI->getDef()->isSubClassOf("Register")) {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000589 AddMatcher(new EmitRegisterMatcher(DI->getDef(),
Chris Lattner845c0422010-02-18 22:03:03 +0000590 N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000591 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000592 return;
593 }
594
595 if (DI->getDef()->getName() == "zero_reg") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000596 AddMatcher(new EmitRegisterMatcher(0, N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000597 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000598 return;
599 }
600
Chris Lattner8e946be2010-02-21 03:22:59 +0000601 // Handle a reference to a register class. This is used
602 // in COPY_TO_SUBREG instructions.
Chris Lattner845c0422010-02-18 22:03:03 +0000603 if (DI->getDef()->isSubClassOf("RegisterClass")) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000604 std::string Value = getQualifiedName(DI->getDef()) + "RegClassID";
Chris Lattnerb21ba712010-02-25 02:04:40 +0000605 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
Chris Lattner8e946be2010-02-21 03:22:59 +0000606 ResultOps.push_back(NextRecordedOperandNo++);
607 return;
Chris Lattner845c0422010-02-18 22:03:03 +0000608 }
Chris Lattner845c0422010-02-18 22:03:03 +0000609 }
610
Chris Lattnerb49985a2010-02-18 06:47:49 +0000611 errs() << "unhandled leaf node: \n";
612 N->dump();
613}
614
Chris Lattner8e946be2010-02-21 03:22:59 +0000615/// GetInstPatternNode - Get the pattern for an instruction.
616///
617const TreePatternNode *MatcherGen::
618GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
619 const TreePattern *InstPat = Inst.getPattern();
620
621 // FIXME2?: Assume actual pattern comes before "implicit".
622 TreePatternNode *InstPatNode;
623 if (InstPat)
624 InstPatNode = InstPat->getTree(0);
625 else if (/*isRoot*/ N == Pattern.getDstPattern())
626 InstPatNode = Pattern.getSrcPattern();
627 else
628 return 0;
629
630 if (InstPatNode && !InstPatNode->isLeaf() &&
631 InstPatNode->getOperator()->getName() == "set")
632 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
633
634 return InstPatNode;
635}
636
637void MatcherGen::
638EmitResultInstructionAsOperand(const TreePatternNode *N,
639 SmallVectorImpl<unsigned> &OutputOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000640 Record *Op = N->getOperator();
641 const CodeGenTarget &CGT = CGP.getTargetInfo();
642 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
643 const DAGInstruction &Inst = CGP.getInstruction(Op);
644
Chris Lattner8e946be2010-02-21 03:22:59 +0000645 // If we can, get the pattern for the instruction we're generating. We derive
646 // a variety of information from this pattern, such as whether it has a chain.
647 //
648 // FIXME2: This is extremely dubious for several reasons, not the least of
649 // which it gives special status to instructions with patterns that Pat<>
650 // nodes can't duplicate.
651 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
652
653 // NodeHasChain - Whether the instruction node we're creating takes chains.
654 bool NodeHasChain = InstPatNode &&
655 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000656
Chris Lattner8e946be2010-02-21 03:22:59 +0000657 bool isRoot = N == Pattern.getDstPattern();
658
Chris Lattner02f73582010-02-24 05:33:42 +0000659 // TreeHasOutFlag - True if this tree has a flag.
660 bool TreeHasInFlag = false, TreeHasOutFlag = false;
Chris Lattner8e946be2010-02-21 03:22:59 +0000661 if (isRoot) {
662 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
Chris Lattner02f73582010-02-24 05:33:42 +0000663 TreeHasInFlag = SrcPat->TreeHasProperty(SDNPOptInFlag, CGP) ||
Chris Lattner8e946be2010-02-21 03:22:59 +0000664 SrcPat->TreeHasProperty(SDNPInFlag, CGP);
665
666 // FIXME2: this is checking the entire pattern, not just the node in
667 // question, doing this just for the root seems like a total hack.
Chris Lattner02f73582010-02-24 05:33:42 +0000668 TreeHasOutFlag = SrcPat->TreeHasProperty(SDNPOutFlag, CGP);
Chris Lattner8e946be2010-02-21 03:22:59 +0000669 }
670
671 // NumResults - This is the number of results produced by the instruction in
672 // the "outs" list.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000673 unsigned NumResults = Inst.getNumResults();
674
Chris Lattnerb49985a2010-02-18 06:47:49 +0000675 // Loop over all of the operands of the instruction pattern, emitting code
676 // to fill them all in. The node 'N' usually has number children equal to
677 // the number of input operands of the instruction. However, in cases
678 // where there are predicate operands for an instruction, we need to fill
679 // in the 'execute always' values. Match up the node operands to the
680 // instruction operands to do this.
Chris Lattner8e946be2010-02-21 03:22:59 +0000681 SmallVector<unsigned, 8> InstOps;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000682 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.OperandList.size();
683 InstOpNo != e; ++InstOpNo) {
684
685 // Determine what to emit for this operand.
686 Record *OperandNode = II.OperandList[InstOpNo].Rec;
687 if ((OperandNode->isSubClassOf("PredicateOperand") ||
688 OperandNode->isSubClassOf("OptionalDefOperand")) &&
689 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
690 // This is a predicate or optional def operand; emit the
691 // 'default ops' operands.
692 const DAGDefaultOperand &DefaultOp =
693 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
694 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
Chris Lattner8e946be2010-02-21 03:22:59 +0000695 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000696 continue;
697 }
698
699 // Otherwise this is a normal operand or a predicate operand without
700 // 'execute always'; emit it.
Chris Lattner8e946be2010-02-21 03:22:59 +0000701 EmitResultOperand(N->getChild(ChildNo), InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000702 ++ChildNo;
703 }
704
Chris Lattner8e946be2010-02-21 03:22:59 +0000705 // If this node has an input flag or explicitly specified input physregs, we
706 // need to add chained and flagged copyfromreg nodes and materialize the flag
707 // input.
708 if (isRoot && !PhysRegInputs.empty()) {
709 // Emit all of the CopyToReg nodes for the input physical registers. These
710 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
711 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000712 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
Chris Lattner8e946be2010-02-21 03:22:59 +0000713 PhysRegInputs[i].first));
714 // Even if the node has no other flag inputs, the resultant node must be
715 // flagged to the CopyFromReg nodes we just generated.
Chris Lattner02f73582010-02-24 05:33:42 +0000716 TreeHasInFlag = true;
Chris Lattner8e946be2010-02-21 03:22:59 +0000717 }
718
719 // Result order: node results, chain, flags
720
721 // Determine the result types.
722 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
Chris Lattner565a6f92010-02-21 23:54:05 +0000723 if (NumResults != 0 && N->getTypeNum(0) != MVT::isVoid) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000724 // FIXME2: If the node has multiple results, we should add them. For now,
725 // preserve existing behavior?!
726 ResultVTs.push_back(N->getTypeNum(0));
727 }
728
729
730 // If this is the root instruction of a pattern that has physical registers in
731 // its result pattern, add output VTs for them. For example, X86 has:
732 // (set AL, (mul ...))
733 // This also handles implicit results like:
734 // (implicit EFLAGS)
735 if (isRoot && Pattern.getDstRegs().size() != 0) {
736 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i)
737 if (Pattern.getDstRegs()[i]->isSubClassOf("Register"))
738 ResultVTs.push_back(getRegisterValueType(Pattern.getDstRegs()[i], CGT));
739 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000740
741 // FIXME2: Instead of using the isVariadic flag on the instruction, we should
742 // have an SDNP that indicates variadicism. The TargetInstrInfo isVariadic
743 // property should be inferred from this when an instruction has a pattern.
744 int NumFixedArityOperands = -1;
745 if (isRoot && II.isVariadic)
746 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
747
748 // If this is the root node and any of the nodes matched nodes in the input
749 // pattern have MemRefs in them, have the interpreter collect them and plop
750 // them onto this node.
751 //
752 // FIXME3: This is actively incorrect for result patterns where the root of
753 // the pattern is not the memory reference and is also incorrect when the
754 // result pattern has multiple memory-referencing instructions. For example,
755 // in the X86 backend, this pattern causes the memrefs to get attached to the
756 // CVTSS2SDrr instead of the MOVSSrm:
757 //
758 // def : Pat<(extloadf32 addr:$src),
759 // (CVTSS2SDrr (MOVSSrm addr:$src))>;
760 //
761 bool NodeHasMemRefs =
762 isRoot && Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
763
Chris Lattnerb21ba712010-02-25 02:04:40 +0000764 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
Chris Lattnere86097a2010-02-28 02:31:26 +0000765 ResultVTs.data(), ResultVTs.size(),
766 InstOps.data(), InstOps.size(),
Chris Lattnerff7fb602010-02-28 21:53:42 +0000767 NodeHasChain, TreeHasInFlag, TreeHasOutFlag,
Chris Lattner6281cda2010-02-28 02:41:25 +0000768 NodeHasMemRefs, NumFixedArityOperands,
769 NextRecordedOperandNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000770
Chris Lattner565a6f92010-02-21 23:54:05 +0000771 // The non-chain and non-flag results of the newly emitted node get recorded.
772 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
773 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Flag) break;
Chris Lattner77f2e272010-02-21 06:03:07 +0000774 OutputOps.push_back(NextRecordedOperandNo++);
Chris Lattner565a6f92010-02-21 23:54:05 +0000775 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000776}
777
778void MatcherGen::
779EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
780 SmallVectorImpl<unsigned> &ResultOps) {
781 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
782
783 // Emit the operand.
784 SmallVector<unsigned, 8> InputOps;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000785
Chris Lattner8e946be2010-02-21 03:22:59 +0000786 // FIXME2: Could easily generalize this to support multiple inputs and outputs
787 // to the SDNodeXForm. For now we just support one input and one output like
788 // the old instruction selector.
789 assert(N->getNumChildren() == 1);
790 EmitResultOperand(N->getChild(0), InputOps);
791
792 // The input currently must have produced exactly one result.
793 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
794
Chris Lattnerb21ba712010-02-25 02:04:40 +0000795 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
Chris Lattner8e946be2010-02-21 03:22:59 +0000796 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000797}
798
799void MatcherGen::EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000800 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000801 // This is something selected from the pattern we matched.
Chris Lattner8e946be2010-02-21 03:22:59 +0000802 if (!N->getName().empty())
803 return EmitResultOfNamedOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000804
805 if (N->isLeaf())
806 return EmitResultLeafAsOperand(N, ResultOps);
807
808 Record *OpRec = N->getOperator();
809 if (OpRec->isSubClassOf("Instruction"))
810 return EmitResultInstructionAsOperand(N, ResultOps);
811 if (OpRec->isSubClassOf("SDNodeXForm"))
Chris Lattner8e946be2010-02-21 03:22:59 +0000812 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000813 errs() << "Unknown result node to emit code for: " << *N << '\n';
814 throw std::string("Unknown node in result pattern!");
815}
816
817void MatcherGen::EmitResultCode() {
Chris Lattner01bcd942010-03-01 22:46:42 +0000818 // Patterns that match nodes with (potentially multiple) chain inputs have to
819 // merge them together into a token factor. This informs the generated code
820 // what all the chained nodes are.
821 if (!MatchedChainNodes.empty())
822 AddMatcher(new EmitMergeInputChainsMatcher
823 (MatchedChainNodes.data(), MatchedChainNodes.size()));
824
Chris Lattner565a6f92010-02-21 23:54:05 +0000825 // Codegen the root of the result pattern, capturing the resulting values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000826 SmallVector<unsigned, 8> Ops;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000827 EmitResultOperand(Pattern.getDstPattern(), Ops);
Chris Lattner8e946be2010-02-21 03:22:59 +0000828
Chris Lattner565a6f92010-02-21 23:54:05 +0000829 // At this point, we have however many values the result pattern produces.
830 // However, the input pattern might not need all of these. If there are
831 // excess values at the end (such as condition codes etc) just lop them off.
832 // This doesn't need to worry about flags or chains, just explicit results.
833 //
834 // FIXME2: This doesn't work because there is currently no way to get an
835 // accurate count of the # results the source pattern sets. This is because
836 // of the "parallel" construct in X86 land, which looks like this:
837 //
838 //def : Pat<(parallel (X86and_flag GR8:$src1, GR8:$src2),
839 // (implicit EFLAGS)),
840 // (AND8rr GR8:$src1, GR8:$src2)>;
841 //
842 // This idiom means to match the two-result node X86and_flag (which is
843 // declared as returning a single result, because we can't match multi-result
844 // nodes yet). In this case, we would have to know that the input has two
845 // results. However, mul8r is modelled exactly the same way, but without
846 // implicit defs included. The fix is to support multiple results directly
847 // and eliminate 'parallel'.
848 //
849 // FIXME2: When this is fixed, we should revert the terrible hack in the
850 // OPC_EmitNode code in the interpreter.
851#if 0
852 const TreePatternNode *Src = Pattern.getSrcPattern();
853 unsigned NumSrcResults = Src->getTypeNum(0) != MVT::isVoid ? 1 : 0;
854 NumSrcResults += Pattern.getDstRegs().size();
855 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
856 Ops.resize(NumSrcResults);
857#endif
Chris Lattner02f73582010-02-24 05:33:42 +0000858
859 // If the matched pattern covers nodes which define a flag result, emit a node
860 // that tells the matcher about them so that it can update their results.
861 if (!MatchedFlagResultNodes.empty())
Chris Lattnerb21ba712010-02-25 02:04:40 +0000862 AddMatcher(new MarkFlagResultsMatcher(MatchedFlagResultNodes.data(),
Chris Lattner4d0c9312010-03-01 01:54:19 +0000863 MatchedFlagResultNodes.size()));
Chris Lattner02f73582010-02-24 05:33:42 +0000864
Chris Lattnerb21ba712010-02-25 02:04:40 +0000865 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
Chris Lattnerb49985a2010-02-18 06:47:49 +0000866}
867
868
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000869/// ConvertPatternToMatcher - Create the matcher for the specified pattern with
870/// the specified variant. If the variant number is invalid, this returns null.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000871Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000872 unsigned Variant,
Chris Lattnerc78f2a32010-02-28 20:49:53 +0000873 const CodeGenDAGPatterns &CGP) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000874 MatcherGen Gen(Pattern, CGP);
875
876 // Generate the code for the matcher.
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000877 if (Gen.EmitMatcherCode(Variant))
878 return 0;
Chris Lattner8e946be2010-02-21 03:22:59 +0000879
880 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
881 // FIXME2: Split result code out to another table, and make the matcher end
882 // with an "Emit <index>" command. This allows result generation stuff to be
883 // shared and factored?
884
Chris Lattnerda272d12010-02-15 08:04:42 +0000885 // If the match succeeds, then we generate Pattern.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000886 Gen.EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000887
888 // Unconditional match.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000889 return Gen.GetMatcher();
Chris Lattnerda272d12010-02-15 08:04:42 +0000890}
891
892
893