blob: e622eecd3c20b129a49205cab1698d795b91ce7e [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"
13#include "llvm/ADT/StringMap.h"
14using namespace llvm;
15
16namespace {
17 class MatcherGen {
18 const PatternToMatch &Pattern;
19 const CodeGenDAGPatterns &CGP;
20
21 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
22 /// out with all of the types removed. This allows us to insert type checks
23 /// as we scan the tree.
24 TreePatternNode *PatWithNoTypes;
25
26 /// VariableMap - A map from variable names ('$dst') to the recorded operand
27 /// number that they were captured as. These are biased by 1 to make
28 /// insertion easier.
29 StringMap<unsigned> VariableMap;
30 unsigned NextRecordedOperandNo;
31
32 MatcherNodeWithChild *Matcher;
33 MatcherNodeWithChild *CurPredicate;
34 public:
35 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
36
37 ~MatcherGen() {
38 delete PatWithNoTypes;
39 }
40
41 void EmitMatcherCode();
42
43 MatcherNodeWithChild *GetMatcher() const { return Matcher; }
44 MatcherNodeWithChild *GetCurPredicate() const { return CurPredicate; }
45 private:
46 void AddMatcherNode(MatcherNodeWithChild *NewNode);
47 void InferPossibleTypes();
48 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
49 void EmitLeafMatchCode(const TreePatternNode *N);
50 void EmitOperatorMatchCode(const TreePatternNode *N,
51 TreePatternNode *NodeNoTypes);
52 };
53
54} // end anon namespace.
55
56MatcherGen::MatcherGen(const PatternToMatch &pattern,
57 const CodeGenDAGPatterns &cgp)
58: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
59 Matcher(0), CurPredicate(0) {
60 // We need to produce the matcher tree for the patterns source pattern. To do
61 // this we need to match the structure as well as the types. To do the type
62 // matching, we want to figure out the fewest number of type checks we need to
63 // emit. For example, if there is only one integer type supported by a
64 // target, there should be no type comparisons at all for integer patterns!
65 //
66 // To figure out the fewest number of type checks needed, clone the pattern,
67 // remove the types, then perform type inference on the pattern as a whole.
68 // If there are unresolved types, emit an explicit check for those types,
69 // apply the type to the tree, then rerun type inference. Iterate until all
70 // types are resolved.
71 //
72 PatWithNoTypes = Pattern.getSrcPattern()->clone();
73 PatWithNoTypes->RemoveAllTypes();
74
75 // If there are types that are manifestly known, infer them.
76 InferPossibleTypes();
77}
78
79/// InferPossibleTypes - As we emit the pattern, we end up generating type
80/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
81/// want to propagate implied types as far throughout the tree as possible so
82/// that we avoid doing redundant type checks. This does the type propagation.
83void MatcherGen::InferPossibleTypes() {
84 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
85 // diagnostics, which we know are impossible at this point.
86 TreePattern &TP = *CGP.pf_begin()->second;
87
88 try {
89 bool MadeChange = true;
90 while (MadeChange)
91 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
92 true/*Ignore reg constraints*/);
93 } catch (...) {
94 errs() << "Type constraint application shouldn't fail!";
95 abort();
96 }
97}
98
99
100/// AddMatcherNode - Add a matcher node to the current graph we're building.
101void MatcherGen::AddMatcherNode(MatcherNodeWithChild *NewNode) {
102 if (CurPredicate != 0)
103 CurPredicate->setChild(NewNode);
104 else
105 Matcher = NewNode;
106 CurPredicate = NewNode;
107}
108
109
110
111/// EmitLeafMatchCode - Generate matching code for leaf nodes.
112void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
113 assert(N->isLeaf() && "Not a leaf?");
114 // Direct match against an integer constant.
115 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
116 return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
117
118 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
119 if (DI == 0) {
120 errs() << "Unknown leaf kind: " << *DI << "\n";
121 abort();
122 }
123
124 Record *LeafRec = DI->getDef();
125 if (// Handle register references. Nothing to do here, they always match.
126 LeafRec->isSubClassOf("RegisterClass") ||
127 LeafRec->isSubClassOf("PointerLikeRegClass") ||
128 LeafRec->isSubClassOf("Register") ||
129 // Place holder for SRCVALUE nodes. Nothing to do here.
130 LeafRec->getName() == "srcvalue")
131 return;
132
133 if (LeafRec->isSubClassOf("ValueType"))
134 return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
135
136 if (LeafRec->isSubClassOf("CondCode"))
137 return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
138
139 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000140 if (!N->getName().empty()) {
141 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
142 exit(1);
143 }
144
Chris Lattnerda272d12010-02-15 08:04:42 +0000145 // Handle complex pattern.
146 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
147 return AddMatcherNode(new CheckComplexPatMatcherNode(CP));
148 }
149
150 errs() << "Unknown leaf kind: " << *N << "\n";
151 abort();
152}
153
154void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
155 TreePatternNode *NodeNoTypes) {
156 assert(!N->isLeaf() && "Not an operator?");
157 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
158
159 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
160 // a constant without a predicate fn that has more that one bit set, handle
161 // this as a special case. This is usually for targets that have special
162 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
163 // handling stuff). Using these instructions is often far more efficient
164 // than materializing the constant. Unfortunately, both the instcombiner
165 // and the dag combiner can often infer that bits are dead, and thus drop
166 // them from the mask in the dag. For example, it might turn 'AND X, 255'
167 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
168 // to handle this.
169 if ((N->getOperator()->getName() == "and" ||
170 N->getOperator()->getName() == "or") &&
171 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
172 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
173 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
174 if (N->getOperator()->getName() == "and")
175 AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
176 else
177 AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
178
179 // Match the LHS of the AND as appropriate.
180 AddMatcherNode(new MoveChildMatcherNode(0));
181 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
182 AddMatcherNode(new MoveParentMatcherNode());
183 return;
184 }
185 }
186 }
187
188 // Check that the current opcode lines up.
189 AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
190
191 // If this node has a chain, then the chain is operand #0 is the SDNode, and
192 // the child numbers of the node are all offset by one.
193 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000194 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000195 OpNo = 1;
196
Chris Lattner6bc1b512010-02-16 19:19:58 +0000197 // If this node is not the root and the subtree underneath it produces a
198 // chain, then the result of matching the node is also produce a chain.
199 // Beyond that, this means that we're also folding (at least) the root node
200 // into the node that produce the chain (for example, matching
201 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
202 // problematic, if the 'reg' node also uses the load (say, its chain).
203 // Graphically:
204 //
205 // [LD]
206 // ^ ^
207 // | \ DAG's like cheese.
208 // / |
209 // / [YY]
210 // | ^
211 // [XX]--/
212 //
213 // It would be invalid to fold XX and LD. In this case, folding the two
214 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
215 // To prevent this, we emit a dynamic check for legality before allowing
216 // this to be folded.
217 //
218 const TreePatternNode *Root = Pattern.getSrcPattern();
219 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000220 // If there is a node between the root and this node, then we definitely
221 // need to emit the check.
222 bool NeedCheck = !Root->hasChild(N);
223
224 // If it *is* an immediate child of the root, we can still need a check if
225 // the root SDNode has multiple inputs. For us, this means that it is an
226 // intrinsic, has multiple operands, or has other inputs like chain or
227 // flag).
228 if (!NeedCheck) {
229 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
230 NeedCheck =
231 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
232 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
233 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
234 PInfo.getNumOperands() > 1 ||
235 PInfo.hasProperty(SDNPHasChain) ||
236 PInfo.hasProperty(SDNPInFlag) ||
237 PInfo.hasProperty(SDNPOptInFlag);
238 }
239
240 if (NeedCheck)
Chris Lattner21390d72010-02-16 19:15:55 +0000241 AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
Chris Lattnere39650a2010-02-16 06:10:58 +0000242 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000243 }
Chris Lattner53a2f602010-02-16 23:16:25 +0000244
245 // FIXME: Need to generate IsChainCompatible checks.
Chris Lattnerda272d12010-02-15 08:04:42 +0000246
Chris Lattnerda272d12010-02-15 08:04:42 +0000247 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
248 // Get the code suitable for matching this child. Move to the child, check
249 // it then move back to the parent.
250 AddMatcherNode(new MoveChildMatcherNode(i));
251 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
252 AddMatcherNode(new MoveParentMatcherNode());
253 }
254}
255
256
257void MatcherGen::EmitMatchCode(const TreePatternNode *N,
258 TreePatternNode *NodeNoTypes) {
259 // If N and NodeNoTypes don't agree on a type, then this is a case where we
260 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
261 // reinfer any correlated types.
262 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
263 AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
264 NodeNoTypes->setTypes(N->getExtTypes());
265 InferPossibleTypes();
266 }
267
268
269 // If this node has a name associated with it, capture it in VariableMap. If
270 // we already saw this in the pattern, emit code to verify dagness.
271 if (!N->getName().empty()) {
272 unsigned &VarMapEntry = VariableMap[N->getName()];
273 if (VarMapEntry == 0) {
274 VarMapEntry = ++NextRecordedOperandNo;
Chris Lattner53a2f602010-02-16 23:16:25 +0000275
276 // If this is a complex pattern, the match operation for it will
277 // implicitly record all of the outputs of it (which may be more than
278 // one).
279 if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
280 // Record the right number of operands.
281 // FIXME: Does this include chain?
282 VarMapEntry += AM->getNumOperands()-1;
283 } else {
284 // If it is a normal named node, we must emit a 'Record' opcode.
285 AddMatcherNode(new RecordMatcherNode());
286 }
287
Chris Lattnerda272d12010-02-15 08:04:42 +0000288 } else {
289 // If we get here, this is a second reference to a specific name. Since
290 // we already have checked that the first reference is valid, we don't
291 // have to recursively match it, just check that it's the same as the
292 // previously named thing.
293 AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
294 return;
295 }
296 }
297
298 // If there are node predicates for this node, generate their checks.
299 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
300 AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
301
302 if (N->isLeaf())
303 EmitLeafMatchCode(N);
304 else
305 EmitOperatorMatchCode(N, NodeNoTypes);
306}
307
308void MatcherGen::EmitMatcherCode() {
309 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
310 // feature is around, do the check).
311 if (!Pattern.getPredicateCheck().empty())
312 AddMatcherNode(new
313 CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
314
315 // Emit the matcher for the pattern structure and types.
316 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
317}
318
319
320MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
321 const CodeGenDAGPatterns &CGP) {
322 MatcherGen Gen(Pattern, CGP);
323
324 // Generate the code for the matcher.
325 Gen.EmitMatcherCode();
326
327 // If the match succeeds, then we generate Pattern.
328 EmitNodeMatcherNode *Result = new EmitNodeMatcherNode(Pattern);
329
330 // Link it into the pattern.
331 if (MatcherNodeWithChild *Pred = Gen.GetCurPredicate()) {
332 Pred->setChild(Result);
333 return Gen.GetMatcher();
334 }
335
336 // Unconditional match.
337 return Result;
338}
339
340
341