blob: f4e2b8d884e43b5e198197939da77365622c15ea [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
75 /// PhysRegInputs - List list has an entry for each explicitly specified
76 /// physreg input to the pattern. The first elt is the Register node, the
77 /// second is the recorded slot number the input pattern match saved it in.
78 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
79
Chris Lattner785d16f2010-02-17 02:16:19 +000080 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattnerb21ba712010-02-25 02:04:40 +000081 Matcher *TheMatcher;
Chris Lattner785d16f2010-02-17 02:16:19 +000082
83 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattnerbd8227f2010-02-18 02:53:41 +000084 /// which should have future checks stuck into its Next position.
Chris Lattnerb21ba712010-02-25 02:04:40 +000085 Matcher *CurPredicate;
Chris Lattnerda272d12010-02-15 08:04:42 +000086 public:
87 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
88
89 ~MatcherGen() {
90 delete PatWithNoTypes;
91 }
92
Chris Lattnerfa342fa2010-03-01 07:17:40 +000093 bool EmitMatcherCode(unsigned Variant);
Chris Lattnerb49985a2010-02-18 06:47:49 +000094 void EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +000095
Chris Lattnerb21ba712010-02-25 02:04:40 +000096 Matcher *GetMatcher() const { return TheMatcher; }
97 Matcher *GetCurPredicate() const { return CurPredicate; }
Chris Lattnerda272d12010-02-15 08:04:42 +000098 private:
Chris Lattnerb21ba712010-02-25 02:04:40 +000099 void AddMatcher(Matcher *NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000100 void InferPossibleTypes();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000101
102 // Matcher Generation.
Chris Lattnerda272d12010-02-15 08:04:42 +0000103 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
104 void EmitLeafMatchCode(const TreePatternNode *N);
105 void EmitOperatorMatchCode(const TreePatternNode *N,
106 TreePatternNode *NodeNoTypes);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000107
108 // Result Code Generation.
Chris Lattner8e946be2010-02-21 03:22:59 +0000109 unsigned getNamedArgumentSlot(StringRef Name) {
110 unsigned VarMapEntry = VariableMap[Name];
111 assert(VarMapEntry != 0 &&
112 "Variable referenced but not defined and not caught earlier!");
113 return VarMapEntry-1;
114 }
115
116 /// GetInstPatternNode - Get the pattern for an instruction.
117 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
118 const TreePatternNode *N);
119
Chris Lattnerb49985a2010-02-18 06:47:49 +0000120 void EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000121 SmallVectorImpl<unsigned> &ResultOps);
122 void EmitResultOfNamedOperand(const TreePatternNode *N,
123 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000124 void EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000125 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000126 void EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000127 SmallVectorImpl<unsigned> &ResultOps);
128 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
129 SmallVectorImpl<unsigned> &ResultOps);
130 };
Chris Lattnerda272d12010-02-15 08:04:42 +0000131
132} // end anon namespace.
133
134MatcherGen::MatcherGen(const PatternToMatch &pattern,
135 const CodeGenDAGPatterns &cgp)
Chris Lattner853b9192010-02-19 00:33:13 +0000136: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Chris Lattner01bcd942010-03-01 22:46:42 +0000137 TheMatcher(0), CurPredicate(0) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000138 // We need to produce the matcher tree for the patterns source pattern. To do
139 // this we need to match the structure as well as the types. To do the type
140 // matching, we want to figure out the fewest number of type checks we need to
141 // emit. For example, if there is only one integer type supported by a
142 // target, there should be no type comparisons at all for integer patterns!
143 //
144 // To figure out the fewest number of type checks needed, clone the pattern,
145 // remove the types, then perform type inference on the pattern as a whole.
146 // If there are unresolved types, emit an explicit check for those types,
147 // apply the type to the tree, then rerun type inference. Iterate until all
148 // types are resolved.
149 //
150 PatWithNoTypes = Pattern.getSrcPattern()->clone();
151 PatWithNoTypes->RemoveAllTypes();
152
153 // If there are types that are manifestly known, infer them.
154 InferPossibleTypes();
155}
156
157/// InferPossibleTypes - As we emit the pattern, we end up generating type
158/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
159/// want to propagate implied types as far throughout the tree as possible so
160/// that we avoid doing redundant type checks. This does the type propagation.
161void MatcherGen::InferPossibleTypes() {
162 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
163 // diagnostics, which we know are impossible at this point.
164 TreePattern &TP = *CGP.pf_begin()->second;
165
166 try {
167 bool MadeChange = true;
168 while (MadeChange)
169 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
170 true/*Ignore reg constraints*/);
171 } catch (...) {
172 errs() << "Type constraint application shouldn't fail!";
173 abort();
174 }
175}
176
177
Chris Lattnerb21ba712010-02-25 02:04:40 +0000178/// AddMatcher - Add a matcher node to the current graph we're building.
179void MatcherGen::AddMatcher(Matcher *NewNode) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000180 if (CurPredicate != 0)
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000181 CurPredicate->setNext(NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000182 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000183 TheMatcher = NewNode;
Chris Lattnerda272d12010-02-15 08:04:42 +0000184 CurPredicate = NewNode;
185}
186
187
Chris Lattnerb49985a2010-02-18 06:47:49 +0000188//===----------------------------------------------------------------------===//
189// Pattern Match Generation
190//===----------------------------------------------------------------------===//
Chris Lattnerda272d12010-02-15 08:04:42 +0000191
192/// EmitLeafMatchCode - Generate matching code for leaf nodes.
193void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
194 assert(N->isLeaf() && "Not a leaf?");
Chris Lattner8e946be2010-02-21 03:22:59 +0000195
196 // If there are node predicates for this node, generate their checks.
197 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000198 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Chris Lattner8e946be2010-02-21 03:22:59 +0000199
Chris Lattnerda272d12010-02-15 08:04:42 +0000200 // Direct match against an integer constant.
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000201 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
202 // If this is the root of the dag we're matching, we emit a redundant opcode
203 // check to ensure that this gets folded into the normal top-level
204 // OpcodeSwitch.
205 if (N == Pattern.getSrcPattern()) {
206 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
207 AddMatcher(new CheckOpcodeMatcher(NI));
208 }
209
Chris Lattnerb21ba712010-02-25 02:04:40 +0000210 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000211 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000212
213 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
214 if (DI == 0) {
215 errs() << "Unknown leaf kind: " << *DI << "\n";
216 abort();
217 }
218
219 Record *LeafRec = DI->getDef();
220 if (// Handle register references. Nothing to do here, they always match.
221 LeafRec->isSubClassOf("RegisterClass") ||
222 LeafRec->isSubClassOf("PointerLikeRegClass") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000223 // Place holder for SRCVALUE nodes. Nothing to do here.
224 LeafRec->getName() == "srcvalue")
225 return;
Chris Lattner8e946be2010-02-21 03:22:59 +0000226
227 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
228 // record the register
229 if (LeafRec->isSubClassOf("Register")) {
Chris Lattner0cebe612010-03-01 02:24:17 +0000230 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
231 NextRecordedOperandNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000232 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
233 return;
234 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000235
236 if (LeafRec->isSubClassOf("ValueType"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000237 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000238
239 if (LeafRec->isSubClassOf("CondCode"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000240 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000241
242 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000243 // We can't model ComplexPattern uses that don't have their name taken yet.
244 // The OPC_CheckComplexPattern operation implicitly records the results.
245 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000246 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
247 exit(1);
248 }
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000249
Chris Lattnerda272d12010-02-15 08:04:42 +0000250 // Handle complex pattern.
251 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000252
Chris Lattner20df2422010-02-22 23:33:44 +0000253 // Emit a CheckComplexPat operation, which does the match (aborting if it
254 // fails) and pushes the matched operands onto the recorded nodes list.
Chris Lattnerd1aca7c2010-03-04 00:28:05 +0000255 AddMatcher(new CheckComplexPatMatcher(CP, NextRecordedOperandNo));
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000256
Chris Lattner20df2422010-02-22 23:33:44 +0000257 // Record the right number of operands.
258 NextRecordedOperandNo += CP.getNumOperands();
259 if (CP.hasProperty(SDNPHasChain))
260 ++NextRecordedOperandNo; // Chained node operand.
261
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000262 // If the complex pattern has a chain, then we need to keep track of the
263 // fact that we just recorded a chain input. The chain input will be
264 // matched as the last operand of the predicate if it was successful.
265 if (CP.hasProperty(SDNPHasChain)) {
266 // It is the last operand recorded.
267 assert(NextRecordedOperandNo > 1 &&
268 "Should have recorded input/result chains at least!");
Chris Lattner8e946be2010-02-21 03:22:59 +0000269 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000270 }
Chris Lattner02f73582010-02-24 05:33:42 +0000271
272 // TODO: Complex patterns can't have output flags, if they did, we'd want
273 // to record them.
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000274 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000275 }
276
277 errs() << "Unknown leaf kind: " << *N << "\n";
278 abort();
279}
280
281void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
282 TreePatternNode *NodeNoTypes) {
283 assert(!N->isLeaf() && "Not an operator?");
284 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
285
286 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
287 // a constant without a predicate fn that has more that one bit set, handle
288 // this as a special case. This is usually for targets that have special
289 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
290 // handling stuff). Using these instructions is often far more efficient
291 // than materializing the constant. Unfortunately, both the instcombiner
292 // and the dag combiner can often infer that bits are dead, and thus drop
293 // them from the mask in the dag. For example, it might turn 'AND X, 255'
294 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
295 // to handle this.
296 if ((N->getOperator()->getName() == "and" ||
297 N->getOperator()->getName() == "or") &&
Chris Lattner8e946be2010-02-21 03:22:59 +0000298 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
299 N->getPredicateFns().empty()) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000300 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
301 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Chris Lattnere9eeda82010-03-01 02:15:34 +0000302 // If this is at the root of the pattern, we emit a redundant
303 // CheckOpcode so that the following checks get factored properly under
304 // a single opcode check.
305 if (N == Pattern.getSrcPattern())
306 AddMatcher(new CheckOpcodeMatcher(CInfo));
307
308 // Emit the CheckAndImm/CheckOrImm node.
Chris Lattnerda272d12010-02-15 08:04:42 +0000309 if (N->getOperator()->getName() == "and")
Chris Lattnerb21ba712010-02-25 02:04:40 +0000310 AddMatcher(new CheckAndImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000311 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000312 AddMatcher(new CheckOrImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000313
314 // Match the LHS of the AND as appropriate.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000315 AddMatcher(new MoveChildMatcher(0));
Chris Lattnerda272d12010-02-15 08:04:42 +0000316 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000317 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000318 return;
319 }
320 }
321 }
322
323 // Check that the current opcode lines up.
Chris Lattnera230f962010-02-27 21:48:43 +0000324 AddMatcher(new CheckOpcodeMatcher(CInfo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000325
Chris Lattner8e946be2010-02-21 03:22:59 +0000326 // If there are node predicates for this node, generate their checks.
327 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000328 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Chris Lattner8e946be2010-02-21 03:22:59 +0000329
330
331 // If this node has memory references (i.e. is a load or store), tell the
332 // interpreter to capture them in the memref array.
333 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000334 AddMatcher(new RecordMemRefMatcher());
Chris Lattner8e946be2010-02-21 03:22:59 +0000335
Chris Lattnerda272d12010-02-15 08:04:42 +0000336 // If this node has a chain, then the chain is operand #0 is the SDNode, and
337 // the child numbers of the node are all offset by one.
338 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000339 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000340 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000341 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner0cebe612010-03-01 02:24:17 +0000342 "' chained node",
343 NextRecordedOperandNo));
Chris Lattner785d16f2010-02-17 02:16:19 +0000344 // Remember all of the input chains our pattern will match.
Chris Lattner8e946be2010-02-21 03:22:59 +0000345 MatchedChainNodes.push_back(NextRecordedOperandNo++);
Chris Lattner785d16f2010-02-17 02:16:19 +0000346
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000347 // Don't look at the input chain when matching the tree pattern to the
348 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000349 OpNo = 1;
350
Chris Lattner6bc1b512010-02-16 19:19:58 +0000351 // If this node is not the root and the subtree underneath it produces a
352 // chain, then the result of matching the node is also produce a chain.
353 // Beyond that, this means that we're also folding (at least) the root node
354 // into the node that produce the chain (for example, matching
355 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
356 // problematic, if the 'reg' node also uses the load (say, its chain).
357 // Graphically:
358 //
359 // [LD]
360 // ^ ^
361 // | \ DAG's like cheese.
362 // / |
363 // / [YY]
364 // | ^
365 // [XX]--/
366 //
367 // It would be invalid to fold XX and LD. In this case, folding the two
368 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
369 // To prevent this, we emit a dynamic check for legality before allowing
370 // this to be folded.
371 //
372 const TreePatternNode *Root = Pattern.getSrcPattern();
373 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000374 // If there is a node between the root and this node, then we definitely
375 // need to emit the check.
376 bool NeedCheck = !Root->hasChild(N);
377
378 // If it *is* an immediate child of the root, we can still need a check if
379 // the root SDNode has multiple inputs. For us, this means that it is an
380 // intrinsic, has multiple operands, or has other inputs like chain or
381 // flag).
382 if (!NeedCheck) {
383 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
384 NeedCheck =
385 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
386 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
387 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
388 PInfo.getNumOperands() > 1 ||
389 PInfo.hasProperty(SDNPHasChain) ||
390 PInfo.hasProperty(SDNPInFlag) ||
391 PInfo.hasProperty(SDNPOptInFlag);
392 }
393
394 if (NeedCheck)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000395 AddMatcher(new CheckFoldableChainNodeMatcher());
Chris Lattnere39650a2010-02-16 06:10:58 +0000396 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000397 }
Chris Lattner02f73582010-02-24 05:33:42 +0000398
399 // If this node has an output flag and isn't the root, remember it.
400 if (N->NodeHasProperty(SDNPOutFlag, CGP) &&
401 N != Pattern.getSrcPattern()) {
402 // TODO: This redundantly records nodes with both flags and chains.
403
404 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000405 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner0cebe612010-03-01 02:24:17 +0000406 "' flag output node",
407 NextRecordedOperandNo));
Chris Lattner02f73582010-02-24 05:33:42 +0000408 // Remember all of the nodes with output flags our pattern will match.
409 MatchedFlagResultNodes.push_back(NextRecordedOperandNo++);
410 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000411
412 // If this node is known to have an input flag or if it *might* have an input
413 // flag, capture it as the flag input of the pattern.
414 if (N->NodeHasProperty(SDNPOptInFlag, CGP) ||
415 N->NodeHasProperty(SDNPInFlag, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000416 AddMatcher(new CaptureFlagInputMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000417
Chris Lattnerda272d12010-02-15 08:04:42 +0000418 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
419 // Get the code suitable for matching this child. Move to the child, check
420 // it then move back to the parent.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000421 AddMatcher(new MoveChildMatcher(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000422 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000423 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000424 }
425}
426
427
428void MatcherGen::EmitMatchCode(const TreePatternNode *N,
429 TreePatternNode *NodeNoTypes) {
430 // If N and NodeNoTypes don't agree on a type, then this is a case where we
431 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
432 // reinfer any correlated types.
Chris Lattner60c0e372010-03-01 07:54:59 +0000433 unsigned NodeType = EEVT::isUnknown;
Chris Lattnerda272d12010-02-15 08:04:42 +0000434 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
Chris Lattner60c0e372010-03-01 07:54:59 +0000435 NodeType = N->getTypeNum(0);
Chris Lattnerda272d12010-02-15 08:04:42 +0000436 NodeNoTypes->setTypes(N->getExtTypes());
437 InferPossibleTypes();
438 }
439
Chris Lattnerda272d12010-02-15 08:04:42 +0000440 // If this node has a name associated with it, capture it in VariableMap. If
441 // we already saw this in the pattern, emit code to verify dagness.
442 if (!N->getName().empty()) {
443 unsigned &VarMapEntry = VariableMap[N->getName()];
444 if (VarMapEntry == 0) {
Chris Lattner20df2422010-02-22 23:33:44 +0000445 // If it is a named node, we must emit a 'Record' opcode.
Chris Lattner0cebe612010-03-01 02:24:17 +0000446 AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
Chris Lattner20df2422010-02-22 23:33:44 +0000447 VarMapEntry = ++NextRecordedOperandNo;
Chris Lattnerda272d12010-02-15 08:04:42 +0000448 } else {
449 // If we get here, this is a second reference to a specific name. Since
450 // we already have checked that the first reference is valid, we don't
451 // have to recursively match it, just check that it's the same as the
452 // previously named thing.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000453 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
Chris Lattnerda272d12010-02-15 08:04:42 +0000454 return;
455 }
456 }
457
Chris Lattnerda272d12010-02-15 08:04:42 +0000458 if (N->isLeaf())
459 EmitLeafMatchCode(N);
460 else
461 EmitOperatorMatchCode(N, NodeNoTypes);
Chris Lattner60c0e372010-03-01 07:54:59 +0000462
463 if (NodeType != EEVT::isUnknown)
464 AddMatcher(new CheckTypeMatcher((MVT::SimpleValueType)NodeType));
465
Chris Lattnerda272d12010-02-15 08:04:42 +0000466}
467
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000468/// EmitMatcherCode - Generate the code that matches the predicate of this
469/// pattern for the specified Variant. If the variant is invalid this returns
470/// true and does not generate code, if it is valid, it returns false.
471bool MatcherGen::EmitMatcherCode(unsigned Variant) {
472 // If the root of the pattern is a ComplexPattern and if it is specified to
473 // match some number of root opcodes, these are considered to be our variants.
474 // Depending on which variant we're generating code for, emit the root opcode
475 // check.
476 if (const ComplexPattern *CP =
477 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000478 const std::vector<Record*> &OpNodes = CP->getRootNodes();
Chris Lattner405f1252010-03-01 22:29:19 +0000479 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
480 if (Variant >= OpNodes.size()) return true;
481
482 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000483 } else {
484 if (Variant != 0) return true;
485 }
486
Chris Lattnerda272d12010-02-15 08:04:42 +0000487 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
488 // feature is around, do the check).
Chris Lattner2a1263b2010-02-25 00:03:03 +0000489 // FIXME: This should get emitted after the match code below to encourage
490 // sharing. This can't happen until we get an X86ISD::AddrMode node made by
491 // dag combine, eliminating the horrible side-effect-full stuff from
492 // X86's MatchAddress.
Chris Lattnerda272d12010-02-15 08:04:42 +0000493 if (!Pattern.getPredicateCheck().empty())
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000494 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
495
Chris Lattnerda272d12010-02-15 08:04:42 +0000496 // Emit the matcher for the pattern structure and types.
497 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000498 return false;
Chris Lattnerda272d12010-02-15 08:04:42 +0000499}
500
501
Chris Lattnerb49985a2010-02-18 06:47:49 +0000502//===----------------------------------------------------------------------===//
503// Node Result Generation
504//===----------------------------------------------------------------------===//
505
Chris Lattner8e946be2010-02-21 03:22:59 +0000506void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
507 SmallVectorImpl<unsigned> &ResultOps){
508 assert(!N->getName().empty() && "Operand not named!");
509
510 unsigned SlotNo = getNamedArgumentSlot(N->getName());
511
512 // A reference to a complex pattern gets all of the results of the complex
513 // pattern's match.
514 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattner20df2422010-02-22 23:33:44 +0000515 // The first slot entry is the node itself, the subsequent entries are the
516 // matched values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000517 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner20df2422010-02-22 23:33:44 +0000518 ResultOps.push_back(SlotNo+i+1);
Chris Lattner8e946be2010-02-21 03:22:59 +0000519 return;
520 }
521
522 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
523 // version of the immediate so that it doesn't get selected due to some other
524 // node use.
525 if (!N->isLeaf()) {
526 StringRef OperatorName = N->getOperator()->getName();
527 if (OperatorName == "imm" || OperatorName == "fpimm") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000528 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000529 ResultOps.push_back(NextRecordedOperandNo++);
530 return;
531 }
532 }
533
534 ResultOps.push_back(SlotNo);
535}
536
Chris Lattnerb49985a2010-02-18 06:47:49 +0000537void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000538 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattner845c0422010-02-18 22:03:03 +0000539 assert(N->isLeaf() && "Must be a leaf");
540
541 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000542 AddMatcher(new EmitIntegerMatcher(II->getValue(),N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000543 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000544 return;
545 }
546
547 // If this is an explicit register reference, handle it.
548 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
549 if (DI->getDef()->isSubClassOf("Register")) {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000550 AddMatcher(new EmitRegisterMatcher(DI->getDef(),
Chris Lattner845c0422010-02-18 22:03:03 +0000551 N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000552 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000553 return;
554 }
555
556 if (DI->getDef()->getName() == "zero_reg") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000557 AddMatcher(new EmitRegisterMatcher(0, N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000558 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000559 return;
560 }
561
Chris Lattner8e946be2010-02-21 03:22:59 +0000562 // Handle a reference to a register class. This is used
563 // in COPY_TO_SUBREG instructions.
Chris Lattner845c0422010-02-18 22:03:03 +0000564 if (DI->getDef()->isSubClassOf("RegisterClass")) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000565 std::string Value = getQualifiedName(DI->getDef()) + "RegClassID";
Chris Lattnerb21ba712010-02-25 02:04:40 +0000566 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
Chris Lattner8e946be2010-02-21 03:22:59 +0000567 ResultOps.push_back(NextRecordedOperandNo++);
568 return;
Chris Lattner845c0422010-02-18 22:03:03 +0000569 }
Chris Lattner845c0422010-02-18 22:03:03 +0000570 }
571
Chris Lattnerb49985a2010-02-18 06:47:49 +0000572 errs() << "unhandled leaf node: \n";
573 N->dump();
574}
575
Chris Lattner8e946be2010-02-21 03:22:59 +0000576/// GetInstPatternNode - Get the pattern for an instruction.
577///
578const TreePatternNode *MatcherGen::
579GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
580 const TreePattern *InstPat = Inst.getPattern();
581
582 // FIXME2?: Assume actual pattern comes before "implicit".
583 TreePatternNode *InstPatNode;
584 if (InstPat)
585 InstPatNode = InstPat->getTree(0);
586 else if (/*isRoot*/ N == Pattern.getDstPattern())
587 InstPatNode = Pattern.getSrcPattern();
588 else
589 return 0;
590
591 if (InstPatNode && !InstPatNode->isLeaf() &&
592 InstPatNode->getOperator()->getName() == "set")
593 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
594
595 return InstPatNode;
596}
597
598void MatcherGen::
599EmitResultInstructionAsOperand(const TreePatternNode *N,
600 SmallVectorImpl<unsigned> &OutputOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000601 Record *Op = N->getOperator();
602 const CodeGenTarget &CGT = CGP.getTargetInfo();
603 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
604 const DAGInstruction &Inst = CGP.getInstruction(Op);
605
Chris Lattner8e946be2010-02-21 03:22:59 +0000606 // If we can, get the pattern for the instruction we're generating. We derive
607 // a variety of information from this pattern, such as whether it has a chain.
608 //
609 // FIXME2: This is extremely dubious for several reasons, not the least of
610 // which it gives special status to instructions with patterns that Pat<>
611 // nodes can't duplicate.
612 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
613
614 // NodeHasChain - Whether the instruction node we're creating takes chains.
615 bool NodeHasChain = InstPatNode &&
616 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000617
Chris Lattner8e946be2010-02-21 03:22:59 +0000618 bool isRoot = N == Pattern.getDstPattern();
619
Chris Lattner02f73582010-02-24 05:33:42 +0000620 // TreeHasOutFlag - True if this tree has a flag.
621 bool TreeHasInFlag = false, TreeHasOutFlag = false;
Chris Lattner8e946be2010-02-21 03:22:59 +0000622 if (isRoot) {
623 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
Chris Lattner02f73582010-02-24 05:33:42 +0000624 TreeHasInFlag = SrcPat->TreeHasProperty(SDNPOptInFlag, CGP) ||
Chris Lattner8e946be2010-02-21 03:22:59 +0000625 SrcPat->TreeHasProperty(SDNPInFlag, CGP);
626
627 // FIXME2: this is checking the entire pattern, not just the node in
628 // question, doing this just for the root seems like a total hack.
Chris Lattner02f73582010-02-24 05:33:42 +0000629 TreeHasOutFlag = SrcPat->TreeHasProperty(SDNPOutFlag, CGP);
Chris Lattner8e946be2010-02-21 03:22:59 +0000630 }
631
632 // NumResults - This is the number of results produced by the instruction in
633 // the "outs" list.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000634 unsigned NumResults = Inst.getNumResults();
635
Chris Lattnerb49985a2010-02-18 06:47:49 +0000636 // Loop over all of the operands of the instruction pattern, emitting code
637 // to fill them all in. The node 'N' usually has number children equal to
638 // the number of input operands of the instruction. However, in cases
639 // where there are predicate operands for an instruction, we need to fill
640 // in the 'execute always' values. Match up the node operands to the
641 // instruction operands to do this.
Chris Lattner8e946be2010-02-21 03:22:59 +0000642 SmallVector<unsigned, 8> InstOps;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000643 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.OperandList.size();
644 InstOpNo != e; ++InstOpNo) {
645
646 // Determine what to emit for this operand.
647 Record *OperandNode = II.OperandList[InstOpNo].Rec;
648 if ((OperandNode->isSubClassOf("PredicateOperand") ||
649 OperandNode->isSubClassOf("OptionalDefOperand")) &&
650 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
651 // This is a predicate or optional def operand; emit the
652 // 'default ops' operands.
653 const DAGDefaultOperand &DefaultOp =
654 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
655 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
Chris Lattner8e946be2010-02-21 03:22:59 +0000656 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000657 continue;
658 }
659
660 // Otherwise this is a normal operand or a predicate operand without
661 // 'execute always'; emit it.
Chris Lattner8e946be2010-02-21 03:22:59 +0000662 EmitResultOperand(N->getChild(ChildNo), InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000663 ++ChildNo;
664 }
665
Chris Lattner8e946be2010-02-21 03:22:59 +0000666 // If this node has an input flag or explicitly specified input physregs, we
667 // need to add chained and flagged copyfromreg nodes and materialize the flag
668 // input.
669 if (isRoot && !PhysRegInputs.empty()) {
670 // Emit all of the CopyToReg nodes for the input physical registers. These
671 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
672 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000673 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
Chris Lattner8e946be2010-02-21 03:22:59 +0000674 PhysRegInputs[i].first));
675 // Even if the node has no other flag inputs, the resultant node must be
676 // flagged to the CopyFromReg nodes we just generated.
Chris Lattner02f73582010-02-24 05:33:42 +0000677 TreeHasInFlag = true;
Chris Lattner8e946be2010-02-21 03:22:59 +0000678 }
679
680 // Result order: node results, chain, flags
681
682 // Determine the result types.
683 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
Chris Lattner565a6f92010-02-21 23:54:05 +0000684 if (NumResults != 0 && N->getTypeNum(0) != MVT::isVoid) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000685 // FIXME2: If the node has multiple results, we should add them. For now,
686 // preserve existing behavior?!
687 ResultVTs.push_back(N->getTypeNum(0));
688 }
689
690
691 // If this is the root instruction of a pattern that has physical registers in
692 // its result pattern, add output VTs for them. For example, X86 has:
693 // (set AL, (mul ...))
694 // This also handles implicit results like:
695 // (implicit EFLAGS)
696 if (isRoot && Pattern.getDstRegs().size() != 0) {
697 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i)
698 if (Pattern.getDstRegs()[i]->isSubClassOf("Register"))
699 ResultVTs.push_back(getRegisterValueType(Pattern.getDstRegs()[i], CGT));
700 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000701
702 // FIXME2: Instead of using the isVariadic flag on the instruction, we should
703 // have an SDNP that indicates variadicism. The TargetInstrInfo isVariadic
704 // property should be inferred from this when an instruction has a pattern.
705 int NumFixedArityOperands = -1;
706 if (isRoot && II.isVariadic)
707 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
708
709 // If this is the root node and any of the nodes matched nodes in the input
710 // pattern have MemRefs in them, have the interpreter collect them and plop
711 // them onto this node.
712 //
713 // FIXME3: This is actively incorrect for result patterns where the root of
714 // the pattern is not the memory reference and is also incorrect when the
715 // result pattern has multiple memory-referencing instructions. For example,
716 // in the X86 backend, this pattern causes the memrefs to get attached to the
717 // CVTSS2SDrr instead of the MOVSSrm:
718 //
719 // def : Pat<(extloadf32 addr:$src),
720 // (CVTSS2SDrr (MOVSSrm addr:$src))>;
721 //
722 bool NodeHasMemRefs =
723 isRoot && Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
724
Chris Lattnerb21ba712010-02-25 02:04:40 +0000725 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
Chris Lattnere86097a2010-02-28 02:31:26 +0000726 ResultVTs.data(), ResultVTs.size(),
727 InstOps.data(), InstOps.size(),
Chris Lattnerff7fb602010-02-28 21:53:42 +0000728 NodeHasChain, TreeHasInFlag, TreeHasOutFlag,
Chris Lattner6281cda2010-02-28 02:41:25 +0000729 NodeHasMemRefs, NumFixedArityOperands,
730 NextRecordedOperandNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000731
Chris Lattner565a6f92010-02-21 23:54:05 +0000732 // The non-chain and non-flag results of the newly emitted node get recorded.
733 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
734 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Flag) break;
Chris Lattner77f2e272010-02-21 06:03:07 +0000735 OutputOps.push_back(NextRecordedOperandNo++);
Chris Lattner565a6f92010-02-21 23:54:05 +0000736 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000737}
738
739void MatcherGen::
740EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
741 SmallVectorImpl<unsigned> &ResultOps) {
742 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
743
744 // Emit the operand.
745 SmallVector<unsigned, 8> InputOps;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000746
Chris Lattner8e946be2010-02-21 03:22:59 +0000747 // FIXME2: Could easily generalize this to support multiple inputs and outputs
748 // to the SDNodeXForm. For now we just support one input and one output like
749 // the old instruction selector.
750 assert(N->getNumChildren() == 1);
751 EmitResultOperand(N->getChild(0), InputOps);
752
753 // The input currently must have produced exactly one result.
754 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
755
Chris Lattnerb21ba712010-02-25 02:04:40 +0000756 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
Chris Lattner8e946be2010-02-21 03:22:59 +0000757 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000758}
759
760void MatcherGen::EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000761 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000762 // This is something selected from the pattern we matched.
Chris Lattner8e946be2010-02-21 03:22:59 +0000763 if (!N->getName().empty())
764 return EmitResultOfNamedOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000765
766 if (N->isLeaf())
767 return EmitResultLeafAsOperand(N, ResultOps);
768
769 Record *OpRec = N->getOperator();
770 if (OpRec->isSubClassOf("Instruction"))
771 return EmitResultInstructionAsOperand(N, ResultOps);
772 if (OpRec->isSubClassOf("SDNodeXForm"))
Chris Lattner8e946be2010-02-21 03:22:59 +0000773 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000774 errs() << "Unknown result node to emit code for: " << *N << '\n';
775 throw std::string("Unknown node in result pattern!");
776}
777
778void MatcherGen::EmitResultCode() {
Chris Lattner01bcd942010-03-01 22:46:42 +0000779 // Patterns that match nodes with (potentially multiple) chain inputs have to
780 // merge them together into a token factor. This informs the generated code
781 // what all the chained nodes are.
782 if (!MatchedChainNodes.empty())
783 AddMatcher(new EmitMergeInputChainsMatcher
784 (MatchedChainNodes.data(), MatchedChainNodes.size()));
785
Chris Lattner565a6f92010-02-21 23:54:05 +0000786 // Codegen the root of the result pattern, capturing the resulting values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000787 SmallVector<unsigned, 8> Ops;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000788 EmitResultOperand(Pattern.getDstPattern(), Ops);
Chris Lattner8e946be2010-02-21 03:22:59 +0000789
Chris Lattner565a6f92010-02-21 23:54:05 +0000790 // At this point, we have however many values the result pattern produces.
791 // However, the input pattern might not need all of these. If there are
792 // excess values at the end (such as condition codes etc) just lop them off.
793 // This doesn't need to worry about flags or chains, just explicit results.
794 //
795 // FIXME2: This doesn't work because there is currently no way to get an
796 // accurate count of the # results the source pattern sets. This is because
797 // of the "parallel" construct in X86 land, which looks like this:
798 //
799 //def : Pat<(parallel (X86and_flag GR8:$src1, GR8:$src2),
800 // (implicit EFLAGS)),
801 // (AND8rr GR8:$src1, GR8:$src2)>;
802 //
803 // This idiom means to match the two-result node X86and_flag (which is
804 // declared as returning a single result, because we can't match multi-result
805 // nodes yet). In this case, we would have to know that the input has two
806 // results. However, mul8r is modelled exactly the same way, but without
807 // implicit defs included. The fix is to support multiple results directly
808 // and eliminate 'parallel'.
809 //
810 // FIXME2: When this is fixed, we should revert the terrible hack in the
811 // OPC_EmitNode code in the interpreter.
812#if 0
813 const TreePatternNode *Src = Pattern.getSrcPattern();
814 unsigned NumSrcResults = Src->getTypeNum(0) != MVT::isVoid ? 1 : 0;
815 NumSrcResults += Pattern.getDstRegs().size();
816 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
817 Ops.resize(NumSrcResults);
818#endif
Chris Lattner02f73582010-02-24 05:33:42 +0000819
820 // If the matched pattern covers nodes which define a flag result, emit a node
821 // that tells the matcher about them so that it can update their results.
822 if (!MatchedFlagResultNodes.empty())
Chris Lattnerb21ba712010-02-25 02:04:40 +0000823 AddMatcher(new MarkFlagResultsMatcher(MatchedFlagResultNodes.data(),
Chris Lattner4d0c9312010-03-01 01:54:19 +0000824 MatchedFlagResultNodes.size()));
Chris Lattner02f73582010-02-24 05:33:42 +0000825
Chris Lattnerb21ba712010-02-25 02:04:40 +0000826 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
Chris Lattnerb49985a2010-02-18 06:47:49 +0000827}
828
829
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000830/// ConvertPatternToMatcher - Create the matcher for the specified pattern with
831/// the specified variant. If the variant number is invalid, this returns null.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000832Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000833 unsigned Variant,
Chris Lattnerc78f2a32010-02-28 20:49:53 +0000834 const CodeGenDAGPatterns &CGP) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000835 MatcherGen Gen(Pattern, CGP);
836
837 // Generate the code for the matcher.
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000838 if (Gen.EmitMatcherCode(Variant))
839 return 0;
Chris Lattner8e946be2010-02-21 03:22:59 +0000840
841 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
842 // FIXME2: Split result code out to another table, and make the matcher end
843 // with an "Emit <index>" command. This allows result generation stuff to be
844 // shared and factored?
845
Chris Lattnerda272d12010-02-15 08:04:42 +0000846 // If the match succeeds, then we generate Pattern.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000847 Gen.EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000848
849 // Unconditional match.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000850 return Gen.GetMatcher();
Chris Lattnerda272d12010-02-15 08:04:42 +0000851}
852
853
854