1 //===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "DAGISelMatcher.h"
11 #include "CodeGenDAGPatterns.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringMap.h"
18 /// ResultVal - When generating new nodes for the result of a pattern match,
19 /// this value is used to represent an input to the node. Result values can
20 /// either be an input that is 'recorded' in the RecordedNodes array by the
21 /// matcher or it can be a temporary value created by the emitter for things
26 static ResultVal get(unsigned N) {
32 unsigned getNumber() const {
39 const PatternToMatch &Pattern;
40 const CodeGenDAGPatterns &CGP;
42 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
43 /// out with all of the types removed. This allows us to insert type checks
44 /// as we scan the tree.
45 TreePatternNode *PatWithNoTypes;
47 /// VariableMap - A map from variable names ('$dst') to the recorded operand
48 /// number that they were captured as. These are biased by 1 to make
50 StringMap<unsigned> VariableMap;
52 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
53 /// the RecordedNodes array, this keeps track of which slot will be next to
55 unsigned NextRecordedOperandNo;
57 /// InputChains - This maintains the position in the recorded nodes array of
58 /// all of the recorded input chains.
59 SmallVector<unsigned, 2> InputChains;
61 /// Matcher - This is the top level of the generated matcher, the result.
64 /// CurPredicate - As we emit matcher nodes, this points to the latest check
65 /// which should have future checks stuck into its Next position.
66 MatcherNode *CurPredicate;
68 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
71 delete PatWithNoTypes;
74 void EmitMatcherCode();
75 void EmitResultCode();
77 MatcherNode *GetMatcher() const { return Matcher; }
78 MatcherNode *GetCurPredicate() const { return CurPredicate; }
80 void AddMatcherNode(MatcherNode *NewNode);
81 void InferPossibleTypes();
83 // Matcher Generation.
84 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
85 void EmitLeafMatchCode(const TreePatternNode *N);
86 void EmitOperatorMatchCode(const TreePatternNode *N,
87 TreePatternNode *NodeNoTypes);
89 // Result Code Generation.
90 void EmitResultOperand(const TreePatternNode *N,
91 SmallVectorImpl<ResultVal> &ResultOps);
92 void EmitResultLeafAsOperand(const TreePatternNode *N,
93 SmallVectorImpl<ResultVal> &ResultOps);
94 void EmitResultInstructionAsOperand(const TreePatternNode *N,
95 SmallVectorImpl<ResultVal> &ResultOps);
98 } // end anon namespace.
100 MatcherGen::MatcherGen(const PatternToMatch &pattern,
101 const CodeGenDAGPatterns &cgp)
102 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
103 Matcher(0), CurPredicate(0) {
104 // We need to produce the matcher tree for the patterns source pattern. To do
105 // this we need to match the structure as well as the types. To do the type
106 // matching, we want to figure out the fewest number of type checks we need to
107 // emit. For example, if there is only one integer type supported by a
108 // target, there should be no type comparisons at all for integer patterns!
110 // To figure out the fewest number of type checks needed, clone the pattern,
111 // remove the types, then perform type inference on the pattern as a whole.
112 // If there are unresolved types, emit an explicit check for those types,
113 // apply the type to the tree, then rerun type inference. Iterate until all
114 // types are resolved.
116 PatWithNoTypes = Pattern.getSrcPattern()->clone();
117 PatWithNoTypes->RemoveAllTypes();
119 // If there are types that are manifestly known, infer them.
120 InferPossibleTypes();
123 /// InferPossibleTypes - As we emit the pattern, we end up generating type
124 /// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
125 /// want to propagate implied types as far throughout the tree as possible so
126 /// that we avoid doing redundant type checks. This does the type propagation.
127 void MatcherGen::InferPossibleTypes() {
128 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
129 // diagnostics, which we know are impossible at this point.
130 TreePattern &TP = *CGP.pf_begin()->second;
133 bool MadeChange = true;
135 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
136 true/*Ignore reg constraints*/);
138 errs() << "Type constraint application shouldn't fail!";
144 /// AddMatcherNode - Add a matcher node to the current graph we're building.
145 void MatcherGen::AddMatcherNode(MatcherNode *NewNode) {
146 if (CurPredicate != 0)
147 CurPredicate->setNext(NewNode);
150 CurPredicate = NewNode;
154 //===----------------------------------------------------------------------===//
155 // Pattern Match Generation
156 //===----------------------------------------------------------------------===//
158 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
159 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
160 assert(N->isLeaf() && "Not a leaf?");
161 // Direct match against an integer constant.
162 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
163 return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
165 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
167 errs() << "Unknown leaf kind: " << *DI << "\n";
171 Record *LeafRec = DI->getDef();
172 if (// Handle register references. Nothing to do here, they always match.
173 LeafRec->isSubClassOf("RegisterClass") ||
174 LeafRec->isSubClassOf("PointerLikeRegClass") ||
175 LeafRec->isSubClassOf("Register") ||
176 // Place holder for SRCVALUE nodes. Nothing to do here.
177 LeafRec->getName() == "srcvalue")
180 if (LeafRec->isSubClassOf("ValueType"))
181 return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
183 if (LeafRec->isSubClassOf("CondCode"))
184 return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
186 if (LeafRec->isSubClassOf("ComplexPattern")) {
187 // We can't model ComplexPattern uses that don't have their name taken yet.
188 // The OPC_CheckComplexPattern operation implicitly records the results.
189 if (N->getName().empty()) {
190 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
194 // Handle complex pattern.
195 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
196 AddMatcherNode(new CheckComplexPatMatcherNode(CP));
198 // If the complex pattern has a chain, then we need to keep track of the
199 // fact that we just recorded a chain input. The chain input will be
200 // matched as the last operand of the predicate if it was successful.
201 if (CP.hasProperty(SDNPHasChain)) {
202 // It is the last operand recorded.
203 assert(NextRecordedOperandNo > 1 &&
204 "Should have recorded input/result chains at least!");
205 InputChains.push_back(NextRecordedOperandNo-1);
207 // IF we need to check chains, do so, see comment for
208 // "NodeHasProperty(SDNPHasChain" below.
209 if (InputChains.size() > 1) {
210 // FIXME: This is broken, we should eliminate this nonsense completely,
211 // but we want to produce the same selections that the old matcher does
213 unsigned PrevOp = InputChains[InputChains.size()-2];
214 AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
220 errs() << "Unknown leaf kind: " << *N << "\n";
224 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
225 TreePatternNode *NodeNoTypes) {
226 assert(!N->isLeaf() && "Not an operator?");
227 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
229 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
230 // a constant without a predicate fn that has more that one bit set, handle
231 // this as a special case. This is usually for targets that have special
232 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
233 // handling stuff). Using these instructions is often far more efficient
234 // than materializing the constant. Unfortunately, both the instcombiner
235 // and the dag combiner can often infer that bits are dead, and thus drop
236 // them from the mask in the dag. For example, it might turn 'AND X, 255'
237 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
239 if ((N->getOperator()->getName() == "and" ||
240 N->getOperator()->getName() == "or") &&
241 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
242 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
243 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
244 if (N->getOperator()->getName() == "and")
245 AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
247 AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
249 // Match the LHS of the AND as appropriate.
250 AddMatcherNode(new MoveChildMatcherNode(0));
251 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
252 AddMatcherNode(new MoveParentMatcherNode());
258 // Check that the current opcode lines up.
259 AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
261 // If this node has a chain, then the chain is operand #0 is the SDNode, and
262 // the child numbers of the node are all offset by one.
264 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
265 // Record the input chain, which is always input #0 of the SDNode.
266 AddMatcherNode(new MoveChildMatcherNode(0));
267 AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
270 // Remember all of the input chains our pattern will match.
271 InputChains.push_back(NextRecordedOperandNo);
272 ++NextRecordedOperandNo;
273 AddMatcherNode(new MoveParentMatcherNode());
275 // If this is the second (e.g. indbr(load) or store(add(load))) or third
276 // input chain (e.g. (store (add (load, load))) from msp430) we need to make
277 // sure that folding the chain won't induce cycles in the DAG. This could
278 // happen if there were an intermediate node between the indbr and load, for
280 if (InputChains.size() > 1) {
281 // FIXME: This is broken, we should eliminate this nonsense completely,
282 // but we want to produce the same selections that the old matcher does
284 unsigned PrevOp = InputChains[InputChains.size()-2];
285 AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
288 // Don't look at the input chain when matching the tree pattern to the
292 // If this node is not the root and the subtree underneath it produces a
293 // chain, then the result of matching the node is also produce a chain.
294 // Beyond that, this means that we're also folding (at least) the root node
295 // into the node that produce the chain (for example, matching
296 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
297 // problematic, if the 'reg' node also uses the load (say, its chain).
302 // | \ DAG's like cheese.
308 // It would be invalid to fold XX and LD. In this case, folding the two
309 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
310 // To prevent this, we emit a dynamic check for legality before allowing
311 // this to be folded.
313 const TreePatternNode *Root = Pattern.getSrcPattern();
314 if (N != Root) { // Not the root of the pattern.
315 // If there is a node between the root and this node, then we definitely
316 // need to emit the check.
317 bool NeedCheck = !Root->hasChild(N);
319 // If it *is* an immediate child of the root, we can still need a check if
320 // the root SDNode has multiple inputs. For us, this means that it is an
321 // intrinsic, has multiple operands, or has other inputs like chain or
324 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
326 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
327 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
328 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
329 PInfo.getNumOperands() > 1 ||
330 PInfo.hasProperty(SDNPHasChain) ||
331 PInfo.hasProperty(SDNPInFlag) ||
332 PInfo.hasProperty(SDNPOptInFlag);
336 AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
340 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
341 // Get the code suitable for matching this child. Move to the child, check
342 // it then move back to the parent.
343 AddMatcherNode(new MoveChildMatcherNode(OpNo));
344 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
345 AddMatcherNode(new MoveParentMatcherNode());
350 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
351 TreePatternNode *NodeNoTypes) {
352 // If N and NodeNoTypes don't agree on a type, then this is a case where we
353 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
354 // reinfer any correlated types.
355 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
356 AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
357 NodeNoTypes->setTypes(N->getExtTypes());
358 InferPossibleTypes();
361 // If this node has a name associated with it, capture it in VariableMap. If
362 // we already saw this in the pattern, emit code to verify dagness.
363 if (!N->getName().empty()) {
364 unsigned &VarMapEntry = VariableMap[N->getName()];
365 if (VarMapEntry == 0) {
366 VarMapEntry = NextRecordedOperandNo+1;
368 unsigned NumRecorded;
370 // If this is a complex pattern, the match operation for it will
371 // implicitly record all of the outputs of it (which may be more than
373 if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
374 // Record the right number of operands.
375 NumRecorded = AM->getNumOperands()-1;
377 if (AM->hasProperty(SDNPHasChain))
378 NumRecorded += 2; // Input and output chains.
380 // If it is a normal named node, we must emit a 'Record' opcode.
381 AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
384 NextRecordedOperandNo += NumRecorded;
387 // If we get here, this is a second reference to a specific name. Since
388 // we already have checked that the first reference is valid, we don't
389 // have to recursively match it, just check that it's the same as the
390 // previously named thing.
391 AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
396 // If there are node predicates for this node, generate their checks.
397 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
398 AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
401 EmitLeafMatchCode(N);
403 EmitOperatorMatchCode(N, NodeNoTypes);
406 void MatcherGen::EmitMatcherCode() {
407 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
408 // feature is around, do the check).
409 if (!Pattern.getPredicateCheck().empty())
411 CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
413 // Emit the matcher for the pattern structure and types.
414 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
418 //===----------------------------------------------------------------------===//
419 // Node Result Generation
420 //===----------------------------------------------------------------------===//
422 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
423 SmallVectorImpl<ResultVal> &ResultOps){
424 assert(N->isLeaf() && "Must be a leaf");
426 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
427 AddMatcherNode(new EmitIntegerMatcherNode(II->getValue(),N->getTypeNum(0)));
428 ResultOps.push_back(ResultVal::get(NextRecordedOperandNo++));
432 // If this is an explicit register reference, handle it.
433 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
434 if (DI->getDef()->isSubClassOf("Register")) {
435 AddMatcherNode(new EmitRegisterMatcherNode(DI->getDef(),
437 ResultOps.push_back(ResultVal::get(NextRecordedOperandNo++));
441 if (DI->getDef()->getName() == "zero_reg") {
442 AddMatcherNode(new EmitRegisterMatcherNode(0, N->getTypeNum(0)));
443 ResultOps.push_back(ResultVal::get(NextRecordedOperandNo++));
448 if (DI->getDef()->isSubClassOf("RegisterClass")) {
449 // Handle a reference to a register class. This is used
450 // in COPY_TO_SUBREG instructions.
456 errs() << "unhandled leaf node: \n";
460 void MatcherGen::EmitResultInstructionAsOperand(const TreePatternNode *N,
461 SmallVectorImpl<ResultVal> &ResultOps){
462 Record *Op = N->getOperator();
463 const CodeGenTarget &CGT = CGP.getTargetInfo();
464 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
465 const DAGInstruction &Inst = CGP.getInstruction(Op);
467 // FIXME: Handle (set x, (foo))
469 if (II.isVariadic) // FIXME: Handle variadic instructions.
470 return AddMatcherNode(new EmitNodeMatcherNode(Pattern));
472 // FIXME: Handle OptInFlag, HasInFlag, HasOutFlag
473 // FIXME: Handle Chains.
474 unsigned NumResults = Inst.getNumResults();
477 // Loop over all of the operands of the instruction pattern, emitting code
478 // to fill them all in. The node 'N' usually has number children equal to
479 // the number of input operands of the instruction. However, in cases
480 // where there are predicate operands for an instruction, we need to fill
481 // in the 'execute always' values. Match up the node operands to the
482 // instruction operands to do this.
483 SmallVector<ResultVal, 8> Ops;
484 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.OperandList.size();
485 InstOpNo != e; ++InstOpNo) {
487 // Determine what to emit for this operand.
488 Record *OperandNode = II.OperandList[InstOpNo].Rec;
489 if ((OperandNode->isSubClassOf("PredicateOperand") ||
490 OperandNode->isSubClassOf("OptionalDefOperand")) &&
491 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
492 // This is a predicate or optional def operand; emit the
493 // 'default ops' operands.
494 const DAGDefaultOperand &DefaultOp =
495 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
496 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
497 EmitResultOperand(DefaultOp.DefaultOps[i], Ops);
501 // Otherwise this is a normal operand or a predicate operand without
502 // 'execute always'; emit it.
503 EmitResultOperand(N->getChild(ChildNo), Ops);
515 void MatcherGen::EmitResultOperand(const TreePatternNode *N,
516 SmallVectorImpl<ResultVal> &ResultOps) {
517 // This is something selected from the pattern we matched.
518 if (!N->getName().empty()) {
519 //errs() << "unhandled named node: \n";
525 return EmitResultLeafAsOperand(N, ResultOps);
527 Record *OpRec = N->getOperator();
528 if (OpRec->isSubClassOf("Instruction"))
529 return EmitResultInstructionAsOperand(N, ResultOps);
530 if (OpRec->isSubClassOf("SDNodeXForm"))
533 errs() << "Unknown result node to emit code for: " << *N << '\n';
534 throw std::string("Unknown node in result pattern!");
537 void MatcherGen::EmitResultCode() {
538 // FIXME: Handle Ops.
539 // FIXME: Ops should be vector of "ResultValue> which is either an index into
540 // the results vector is is a temp result.
541 SmallVector<ResultVal, 8> Ops;
542 EmitResultOperand(Pattern.getDstPattern(), Ops);
543 //AddMatcherNode(new EmitNodeMatcherNode(Pattern));
547 MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
548 const CodeGenDAGPatterns &CGP) {
549 MatcherGen Gen(Pattern, CGP);
551 // Generate the code for the matcher.
552 Gen.EmitMatcherCode();
554 // If the match succeeds, then we generate Pattern.
555 Gen.EmitResultCode();
557 // Unconditional match.
558 return Gen.GetMatcher();