]> git.proxmox.com Git - rustc.git/blob - src/llvm/utils/TableGen/DAGISelMatcherGen.cpp
Imported Upstream version 1.0.0+dfsg1
[rustc.git] / src / llvm / utils / TableGen / DAGISelMatcherGen.cpp
1 //===- 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 "CodeGenRegisters.h"
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/TableGen/Error.h"
17 #include "llvm/TableGen/Record.h"
18 #include <utility>
19 using namespace llvm;
20
21
22 /// getRegisterValueType - Look up and return the ValueType of the specified
23 /// register. If the register is a member of multiple register classes which
24 /// have different associated types, return MVT::Other.
25 static MVT::SimpleValueType getRegisterValueType(Record *R,
26 const CodeGenTarget &T) {
27 bool FoundRC = false;
28 MVT::SimpleValueType VT = MVT::Other;
29 const CodeGenRegister *Reg = T.getRegBank().getReg(R);
30
31 for (const auto &RC : T.getRegBank().getRegClasses()) {
32 if (!RC.contains(Reg))
33 continue;
34
35 if (!FoundRC) {
36 FoundRC = true;
37 VT = RC.getValueTypeNum(0);
38 continue;
39 }
40
41 // If this occurs in multiple register classes, they all have to agree.
42 assert(VT == RC.getValueTypeNum(0));
43 }
44 return VT;
45 }
46
47
48 namespace {
49 class MatcherGen {
50 const PatternToMatch &Pattern;
51 const CodeGenDAGPatterns &CGP;
52
53 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
54 /// out with all of the types removed. This allows us to insert type checks
55 /// as we scan the tree.
56 TreePatternNode *PatWithNoTypes;
57
58 /// VariableMap - A map from variable names ('$dst') to the recorded operand
59 /// number that they were captured as. These are biased by 1 to make
60 /// insertion easier.
61 StringMap<unsigned> VariableMap;
62
63 /// This maintains the recorded operand number that OPC_CheckComplexPattern
64 /// drops each sub-operand into. We don't want to insert these into
65 /// VariableMap because that leads to identity checking if they are
66 /// encountered multiple times. Biased by 1 like VariableMap for
67 /// consistency.
68 StringMap<unsigned> NamedComplexPatternOperands;
69
70 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
71 /// the RecordedNodes array, this keeps track of which slot will be next to
72 /// record into.
73 unsigned NextRecordedOperandNo;
74
75 /// MatchedChainNodes - This maintains the position in the recorded nodes
76 /// array of all of the recorded input nodes that have chains.
77 SmallVector<unsigned, 2> MatchedChainNodes;
78
79 /// MatchedGlueResultNodes - This maintains the position in the recorded
80 /// nodes array of all of the recorded input nodes that have glue results.
81 SmallVector<unsigned, 2> MatchedGlueResultNodes;
82
83 /// MatchedComplexPatterns - This maintains a list of all of the
84 /// ComplexPatterns that we need to check. The second element of each pair
85 /// is the recorded operand number of the input node.
86 SmallVector<std::pair<const TreePatternNode*,
87 unsigned>, 2> MatchedComplexPatterns;
88
89 /// PhysRegInputs - List list has an entry for each explicitly specified
90 /// physreg input to the pattern. The first elt is the Register node, the
91 /// second is the recorded slot number the input pattern match saved it in.
92 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
93
94 /// Matcher - This is the top level of the generated matcher, the result.
95 Matcher *TheMatcher;
96
97 /// CurPredicate - As we emit matcher nodes, this points to the latest check
98 /// which should have future checks stuck into its Next position.
99 Matcher *CurPredicate;
100 public:
101 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
102
103 ~MatcherGen() {
104 delete PatWithNoTypes;
105 }
106
107 bool EmitMatcherCode(unsigned Variant);
108 void EmitResultCode();
109
110 Matcher *GetMatcher() const { return TheMatcher; }
111 private:
112 void AddMatcher(Matcher *NewNode);
113 void InferPossibleTypes();
114
115 // Matcher Generation.
116 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
117 void EmitLeafMatchCode(const TreePatternNode *N);
118 void EmitOperatorMatchCode(const TreePatternNode *N,
119 TreePatternNode *NodeNoTypes);
120
121 /// If this is the first time a node with unique identifier Name has been
122 /// seen, record it. Otherwise, emit a check to make sure this is the same
123 /// node. Returns true if this is the first encounter.
124 bool recordUniqueNode(std::string Name);
125
126 // Result Code Generation.
127 unsigned getNamedArgumentSlot(StringRef Name) {
128 unsigned VarMapEntry = VariableMap[Name];
129 assert(VarMapEntry != 0 &&
130 "Variable referenced but not defined and not caught earlier!");
131 return VarMapEntry-1;
132 }
133
134 /// GetInstPatternNode - Get the pattern for an instruction.
135 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
136 const TreePatternNode *N);
137
138 void EmitResultOperand(const TreePatternNode *N,
139 SmallVectorImpl<unsigned> &ResultOps);
140 void EmitResultOfNamedOperand(const TreePatternNode *N,
141 SmallVectorImpl<unsigned> &ResultOps);
142 void EmitResultLeafAsOperand(const TreePatternNode *N,
143 SmallVectorImpl<unsigned> &ResultOps);
144 void EmitResultInstructionAsOperand(const TreePatternNode *N,
145 SmallVectorImpl<unsigned> &ResultOps);
146 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
147 SmallVectorImpl<unsigned> &ResultOps);
148 };
149
150 } // end anon namespace.
151
152 MatcherGen::MatcherGen(const PatternToMatch &pattern,
153 const CodeGenDAGPatterns &cgp)
154 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
155 TheMatcher(nullptr), CurPredicate(nullptr) {
156 // We need to produce the matcher tree for the patterns source pattern. To do
157 // this we need to match the structure as well as the types. To do the type
158 // matching, we want to figure out the fewest number of type checks we need to
159 // emit. For example, if there is only one integer type supported by a
160 // target, there should be no type comparisons at all for integer patterns!
161 //
162 // To figure out the fewest number of type checks needed, clone the pattern,
163 // remove the types, then perform type inference on the pattern as a whole.
164 // If there are unresolved types, emit an explicit check for those types,
165 // apply the type to the tree, then rerun type inference. Iterate until all
166 // types are resolved.
167 //
168 PatWithNoTypes = Pattern.getSrcPattern()->clone();
169 PatWithNoTypes->RemoveAllTypes();
170
171 // If there are types that are manifestly known, infer them.
172 InferPossibleTypes();
173 }
174
175 /// InferPossibleTypes - As we emit the pattern, we end up generating type
176 /// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
177 /// want to propagate implied types as far throughout the tree as possible so
178 /// that we avoid doing redundant type checks. This does the type propagation.
179 void MatcherGen::InferPossibleTypes() {
180 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
181 // diagnostics, which we know are impossible at this point.
182 TreePattern &TP = *CGP.pf_begin()->second;
183
184 bool MadeChange = true;
185 while (MadeChange)
186 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
187 true/*Ignore reg constraints*/);
188 }
189
190
191 /// AddMatcher - Add a matcher node to the current graph we're building.
192 void MatcherGen::AddMatcher(Matcher *NewNode) {
193 if (CurPredicate)
194 CurPredicate->setNext(NewNode);
195 else
196 TheMatcher = NewNode;
197 CurPredicate = NewNode;
198 }
199
200
201 //===----------------------------------------------------------------------===//
202 // Pattern Match Generation
203 //===----------------------------------------------------------------------===//
204
205 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
206 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
207 assert(N->isLeaf() && "Not a leaf?");
208
209 // Direct match against an integer constant.
210 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
211 // If this is the root of the dag we're matching, we emit a redundant opcode
212 // check to ensure that this gets folded into the normal top-level
213 // OpcodeSwitch.
214 if (N == Pattern.getSrcPattern()) {
215 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
216 AddMatcher(new CheckOpcodeMatcher(NI));
217 }
218
219 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
220 }
221
222 // An UnsetInit represents a named node without any constraints.
223 if (N->getLeafValue() == UnsetInit::get()) {
224 assert(N->hasName() && "Unnamed ? leaf");
225 return;
226 }
227
228 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
229 if (!DI) {
230 errs() << "Unknown leaf kind: " << *N << "\n";
231 abort();
232 }
233
234 Record *LeafRec = DI->getDef();
235
236 // A ValueType leaf node can represent a register when named, or itself when
237 // unnamed.
238 if (LeafRec->isSubClassOf("ValueType")) {
239 // A named ValueType leaf always matches: (add i32:$a, i32:$b).
240 if (N->hasName())
241 return;
242 // An unnamed ValueType as in (sext_inreg GPR:$foo, i8).
243 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
244 }
245
246 if (// Handle register references. Nothing to do here, they always match.
247 LeafRec->isSubClassOf("RegisterClass") ||
248 LeafRec->isSubClassOf("RegisterOperand") ||
249 LeafRec->isSubClassOf("PointerLikeRegClass") ||
250 LeafRec->isSubClassOf("SubRegIndex") ||
251 // Place holder for SRCVALUE nodes. Nothing to do here.
252 LeafRec->getName() == "srcvalue")
253 return;
254
255 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
256 // record the register
257 if (LeafRec->isSubClassOf("Register")) {
258 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
259 NextRecordedOperandNo));
260 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
261 return;
262 }
263
264 if (LeafRec->isSubClassOf("CondCode"))
265 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
266
267 if (LeafRec->isSubClassOf("ComplexPattern")) {
268 // We can't model ComplexPattern uses that don't have their name taken yet.
269 // The OPC_CheckComplexPattern operation implicitly records the results.
270 if (N->getName().empty()) {
271 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
272 exit(1);
273 }
274
275 // Remember this ComplexPattern so that we can emit it after all the other
276 // structural matches are done.
277 unsigned InputOperand = VariableMap[N->getName()] - 1;
278 MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand));
279 return;
280 }
281
282 errs() << "Unknown leaf kind: " << *N << "\n";
283 abort();
284 }
285
286 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
287 TreePatternNode *NodeNoTypes) {
288 assert(!N->isLeaf() && "Not an operator?");
289
290 if (N->getOperator()->isSubClassOf("ComplexPattern")) {
291 // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
292 // "MY_PAT:op1:op2". We should already have validated that the uses are
293 // consistent.
294 std::string PatternName = N->getOperator()->getName();
295 for (unsigned i = 0; i < N->getNumChildren(); ++i) {
296 PatternName += ":";
297 PatternName += N->getChild(i)->getName();
298 }
299
300 if (recordUniqueNode(PatternName)) {
301 auto NodeAndOpNum = std::make_pair(N, NextRecordedOperandNo - 1);
302 MatchedComplexPatterns.push_back(NodeAndOpNum);
303 }
304
305 return;
306 }
307
308 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
309
310 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
311 // a constant without a predicate fn that has more that one bit set, handle
312 // this as a special case. This is usually for targets that have special
313 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
314 // handling stuff). Using these instructions is often far more efficient
315 // than materializing the constant. Unfortunately, both the instcombiner
316 // and the dag combiner can often infer that bits are dead, and thus drop
317 // them from the mask in the dag. For example, it might turn 'AND X, 255'
318 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
319 // to handle this.
320 if ((N->getOperator()->getName() == "and" ||
321 N->getOperator()->getName() == "or") &&
322 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
323 N->getPredicateFns().empty()) {
324 if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) {
325 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
326 // If this is at the root of the pattern, we emit a redundant
327 // CheckOpcode so that the following checks get factored properly under
328 // a single opcode check.
329 if (N == Pattern.getSrcPattern())
330 AddMatcher(new CheckOpcodeMatcher(CInfo));
331
332 // Emit the CheckAndImm/CheckOrImm node.
333 if (N->getOperator()->getName() == "and")
334 AddMatcher(new CheckAndImmMatcher(II->getValue()));
335 else
336 AddMatcher(new CheckOrImmMatcher(II->getValue()));
337
338 // Match the LHS of the AND as appropriate.
339 AddMatcher(new MoveChildMatcher(0));
340 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
341 AddMatcher(new MoveParentMatcher());
342 return;
343 }
344 }
345 }
346
347 // Check that the current opcode lines up.
348 AddMatcher(new CheckOpcodeMatcher(CInfo));
349
350 // If this node has memory references (i.e. is a load or store), tell the
351 // interpreter to capture them in the memref array.
352 if (N->NodeHasProperty(SDNPMemOperand, CGP))
353 AddMatcher(new RecordMemRefMatcher());
354
355 // If this node has a chain, then the chain is operand #0 is the SDNode, and
356 // the child numbers of the node are all offset by one.
357 unsigned OpNo = 0;
358 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
359 // Record the node and remember it in our chained nodes list.
360 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
361 "' chained node",
362 NextRecordedOperandNo));
363 // Remember all of the input chains our pattern will match.
364 MatchedChainNodes.push_back(NextRecordedOperandNo++);
365
366 // Don't look at the input chain when matching the tree pattern to the
367 // SDNode.
368 OpNo = 1;
369
370 // If this node is not the root and the subtree underneath it produces a
371 // chain, then the result of matching the node is also produce a chain.
372 // Beyond that, this means that we're also folding (at least) the root node
373 // into the node that produce the chain (for example, matching
374 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
375 // problematic, if the 'reg' node also uses the load (say, its chain).
376 // Graphically:
377 //
378 // [LD]
379 // ^ ^
380 // | \ DAG's like cheese.
381 // / |
382 // / [YY]
383 // | ^
384 // [XX]--/
385 //
386 // It would be invalid to fold XX and LD. In this case, folding the two
387 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
388 // To prevent this, we emit a dynamic check for legality before allowing
389 // this to be folded.
390 //
391 const TreePatternNode *Root = Pattern.getSrcPattern();
392 if (N != Root) { // Not the root of the pattern.
393 // If there is a node between the root and this node, then we definitely
394 // need to emit the check.
395 bool NeedCheck = !Root->hasChild(N);
396
397 // If it *is* an immediate child of the root, we can still need a check if
398 // the root SDNode has multiple inputs. For us, this means that it is an
399 // intrinsic, has multiple operands, or has other inputs like chain or
400 // glue).
401 if (!NeedCheck) {
402 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
403 NeedCheck =
404 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
405 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
406 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
407 PInfo.getNumOperands() > 1 ||
408 PInfo.hasProperty(SDNPHasChain) ||
409 PInfo.hasProperty(SDNPInGlue) ||
410 PInfo.hasProperty(SDNPOptInGlue);
411 }
412
413 if (NeedCheck)
414 AddMatcher(new CheckFoldableChainNodeMatcher());
415 }
416 }
417
418 // If this node has an output glue and isn't the root, remember it.
419 if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
420 N != Pattern.getSrcPattern()) {
421 // TODO: This redundantly records nodes with both glues and chains.
422
423 // Record the node and remember it in our chained nodes list.
424 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
425 "' glue output node",
426 NextRecordedOperandNo));
427 // Remember all of the nodes with output glue our pattern will match.
428 MatchedGlueResultNodes.push_back(NextRecordedOperandNo++);
429 }
430
431 // If this node is known to have an input glue or if it *might* have an input
432 // glue, capture it as the glue input of the pattern.
433 if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
434 N->NodeHasProperty(SDNPInGlue, CGP))
435 AddMatcher(new CaptureGlueInputMatcher());
436
437 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
438 // Get the code suitable for matching this child. Move to the child, check
439 // it then move back to the parent.
440 AddMatcher(new MoveChildMatcher(OpNo));
441 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
442 AddMatcher(new MoveParentMatcher());
443 }
444 }
445
446 bool MatcherGen::recordUniqueNode(std::string Name) {
447 unsigned &VarMapEntry = VariableMap[Name];
448 if (VarMapEntry == 0) {
449 // If it is a named node, we must emit a 'Record' opcode.
450 AddMatcher(new RecordMatcher("$" + Name, NextRecordedOperandNo));
451 VarMapEntry = ++NextRecordedOperandNo;
452 return true;
453 }
454
455 // If we get here, this is a second reference to a specific name. Since
456 // we already have checked that the first reference is valid, we don't
457 // have to recursively match it, just check that it's the same as the
458 // previously named thing.
459 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
460 return false;
461 }
462
463 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
464 TreePatternNode *NodeNoTypes) {
465 // If N and NodeNoTypes don't agree on a type, then this is a case where we
466 // need to do a type check. Emit the check, apply the type to NodeNoTypes and
467 // reinfer any correlated types.
468 SmallVector<unsigned, 2> ResultsToTypeCheck;
469
470 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
471 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
472 NodeNoTypes->setType(i, N->getExtType(i));
473 InferPossibleTypes();
474 ResultsToTypeCheck.push_back(i);
475 }
476
477 // If this node has a name associated with it, capture it in VariableMap. If
478 // we already saw this in the pattern, emit code to verify dagness.
479 if (!N->getName().empty())
480 if (!recordUniqueNode(N->getName()))
481 return;
482
483 if (N->isLeaf())
484 EmitLeafMatchCode(N);
485 else
486 EmitOperatorMatchCode(N, NodeNoTypes);
487
488 // If there are node predicates for this node, generate their checks.
489 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
490 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
491
492 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
493 AddMatcher(new CheckTypeMatcher(N->getType(ResultsToTypeCheck[i]),
494 ResultsToTypeCheck[i]));
495 }
496
497 /// EmitMatcherCode - Generate the code that matches the predicate of this
498 /// pattern for the specified Variant. If the variant is invalid this returns
499 /// true and does not generate code, if it is valid, it returns false.
500 bool MatcherGen::EmitMatcherCode(unsigned Variant) {
501 // If the root of the pattern is a ComplexPattern and if it is specified to
502 // match some number of root opcodes, these are considered to be our variants.
503 // Depending on which variant we're generating code for, emit the root opcode
504 // check.
505 if (const ComplexPattern *CP =
506 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
507 const std::vector<Record*> &OpNodes = CP->getRootNodes();
508 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
509 if (Variant >= OpNodes.size()) return true;
510
511 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
512 } else {
513 if (Variant != 0) return true;
514 }
515
516 // Emit the matcher for the pattern structure and types.
517 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
518
519 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
520 // feature is around, do the check).
521 if (!Pattern.getPredicateCheck().empty())
522 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
523
524 // Now that we've completed the structural type match, emit any ComplexPattern
525 // checks (e.g. addrmode matches). We emit this after the structural match
526 // because they are generally more expensive to evaluate and more difficult to
527 // factor.
528 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
529 const TreePatternNode *N = MatchedComplexPatterns[i].first;
530
531 // Remember where the results of this match get stuck.
532 if (N->isLeaf()) {
533 NamedComplexPatternOperands[N->getName()] = NextRecordedOperandNo + 1;
534 } else {
535 unsigned CurOp = NextRecordedOperandNo;
536 for (unsigned i = 0; i < N->getNumChildren(); ++i) {
537 NamedComplexPatternOperands[N->getChild(i)->getName()] = CurOp + 1;
538 CurOp += N->getChild(i)->getNumMIResults(CGP);
539 }
540 }
541
542 // Get the slot we recorded the value in from the name on the node.
543 unsigned RecNodeEntry = MatchedComplexPatterns[i].second;
544
545 const ComplexPattern &CP = *N->getComplexPatternInfo(CGP);
546
547 // Emit a CheckComplexPat operation, which does the match (aborting if it
548 // fails) and pushes the matched operands onto the recorded nodes list.
549 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
550 N->getName(), NextRecordedOperandNo));
551
552 // Record the right number of operands.
553 NextRecordedOperandNo += CP.getNumOperands();
554 if (CP.hasProperty(SDNPHasChain)) {
555 // If the complex pattern has a chain, then we need to keep track of the
556 // fact that we just recorded a chain input. The chain input will be
557 // matched as the last operand of the predicate if it was successful.
558 ++NextRecordedOperandNo; // Chained node operand.
559
560 // It is the last operand recorded.
561 assert(NextRecordedOperandNo > 1 &&
562 "Should have recorded input/result chains at least!");
563 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
564 }
565
566 // TODO: Complex patterns can't have output glues, if they did, we'd want
567 // to record them.
568 }
569
570 return false;
571 }
572
573
574 //===----------------------------------------------------------------------===//
575 // Node Result Generation
576 //===----------------------------------------------------------------------===//
577
578 void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
579 SmallVectorImpl<unsigned> &ResultOps){
580 assert(!N->getName().empty() && "Operand not named!");
581
582 if (unsigned SlotNo = NamedComplexPatternOperands[N->getName()]) {
583 // Complex operands have already been completely selected, just find the
584 // right slot ant add the arguments directly.
585 for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
586 ResultOps.push_back(SlotNo - 1 + i);
587
588 return;
589 }
590
591 unsigned SlotNo = getNamedArgumentSlot(N->getName());
592
593 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
594 // version of the immediate so that it doesn't get selected due to some other
595 // node use.
596 if (!N->isLeaf()) {
597 StringRef OperatorName = N->getOperator()->getName();
598 if (OperatorName == "imm" || OperatorName == "fpimm") {
599 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
600 ResultOps.push_back(NextRecordedOperandNo++);
601 return;
602 }
603 }
604
605 for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
606 ResultOps.push_back(SlotNo + i);
607 }
608
609 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
610 SmallVectorImpl<unsigned> &ResultOps) {
611 assert(N->isLeaf() && "Must be a leaf");
612
613 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
614 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0)));
615 ResultOps.push_back(NextRecordedOperandNo++);
616 return;
617 }
618
619 // If this is an explicit register reference, handle it.
620 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
621 Record *Def = DI->getDef();
622 if (Def->isSubClassOf("Register")) {
623 const CodeGenRegister *Reg =
624 CGP.getTargetInfo().getRegBank().getReg(Def);
625 AddMatcher(new EmitRegisterMatcher(Reg, N->getType(0)));
626 ResultOps.push_back(NextRecordedOperandNo++);
627 return;
628 }
629
630 if (Def->getName() == "zero_reg") {
631 AddMatcher(new EmitRegisterMatcher(nullptr, N->getType(0)));
632 ResultOps.push_back(NextRecordedOperandNo++);
633 return;
634 }
635
636 // Handle a reference to a register class. This is used
637 // in COPY_TO_SUBREG instructions.
638 if (Def->isSubClassOf("RegisterOperand"))
639 Def = Def->getValueAsDef("RegClass");
640 if (Def->isSubClassOf("RegisterClass")) {
641 std::string Value = getQualifiedName(Def) + "RegClassID";
642 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
643 ResultOps.push_back(NextRecordedOperandNo++);
644 return;
645 }
646
647 // Handle a subregister index. This is used for INSERT_SUBREG etc.
648 if (Def->isSubClassOf("SubRegIndex")) {
649 std::string Value = getQualifiedName(Def);
650 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
651 ResultOps.push_back(NextRecordedOperandNo++);
652 return;
653 }
654 }
655
656 errs() << "unhandled leaf node: \n";
657 N->dump();
658 }
659
660 /// GetInstPatternNode - Get the pattern for an instruction.
661 ///
662 const TreePatternNode *MatcherGen::
663 GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
664 const TreePattern *InstPat = Inst.getPattern();
665
666 // FIXME2?: Assume actual pattern comes before "implicit".
667 TreePatternNode *InstPatNode;
668 if (InstPat)
669 InstPatNode = InstPat->getTree(0);
670 else if (/*isRoot*/ N == Pattern.getDstPattern())
671 InstPatNode = Pattern.getSrcPattern();
672 else
673 return nullptr;
674
675 if (InstPatNode && !InstPatNode->isLeaf() &&
676 InstPatNode->getOperator()->getName() == "set")
677 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
678
679 return InstPatNode;
680 }
681
682 static bool
683 mayInstNodeLoadOrStore(const TreePatternNode *N,
684 const CodeGenDAGPatterns &CGP) {
685 Record *Op = N->getOperator();
686 const CodeGenTarget &CGT = CGP.getTargetInfo();
687 CodeGenInstruction &II = CGT.getInstruction(Op);
688 return II.mayLoad || II.mayStore;
689 }
690
691 static unsigned
692 numNodesThatMayLoadOrStore(const TreePatternNode *N,
693 const CodeGenDAGPatterns &CGP) {
694 if (N->isLeaf())
695 return 0;
696
697 Record *OpRec = N->getOperator();
698 if (!OpRec->isSubClassOf("Instruction"))
699 return 0;
700
701 unsigned Count = 0;
702 if (mayInstNodeLoadOrStore(N, CGP))
703 ++Count;
704
705 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
706 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
707
708 return Count;
709 }
710
711 void MatcherGen::
712 EmitResultInstructionAsOperand(const TreePatternNode *N,
713 SmallVectorImpl<unsigned> &OutputOps) {
714 Record *Op = N->getOperator();
715 const CodeGenTarget &CGT = CGP.getTargetInfo();
716 CodeGenInstruction &II = CGT.getInstruction(Op);
717 const DAGInstruction &Inst = CGP.getInstruction(Op);
718
719 // If we can, get the pattern for the instruction we're generating. We derive
720 // a variety of information from this pattern, such as whether it has a chain.
721 //
722 // FIXME2: This is extremely dubious for several reasons, not the least of
723 // which it gives special status to instructions with patterns that Pat<>
724 // nodes can't duplicate.
725 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
726
727 // NodeHasChain - Whether the instruction node we're creating takes chains.
728 bool NodeHasChain = InstPatNode &&
729 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
730
731 // Instructions which load and store from memory should have a chain,
732 // regardless of whether they happen to have an internal pattern saying so.
733 if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)
734 && (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
735 II.hasSideEffects))
736 NodeHasChain = true;
737
738 bool isRoot = N == Pattern.getDstPattern();
739
740 // TreeHasOutGlue - True if this tree has glue.
741 bool TreeHasInGlue = false, TreeHasOutGlue = false;
742 if (isRoot) {
743 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
744 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
745 SrcPat->TreeHasProperty(SDNPInGlue, CGP);
746
747 // FIXME2: this is checking the entire pattern, not just the node in
748 // question, doing this just for the root seems like a total hack.
749 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
750 }
751
752 // NumResults - This is the number of results produced by the instruction in
753 // the "outs" list.
754 unsigned NumResults = Inst.getNumResults();
755
756 // Number of operands we know the output instruction must have. If it is
757 // variadic, we could have more operands.
758 unsigned NumFixedOperands = II.Operands.size();
759
760 SmallVector<unsigned, 8> InstOps;
761
762 // Loop over all of the fixed operands of the instruction pattern, emitting
763 // code to fill them all in. The node 'N' usually has number children equal to
764 // the number of input operands of the instruction. However, in cases where
765 // there are predicate operands for an instruction, we need to fill in the
766 // 'execute always' values. Match up the node operands to the instruction
767 // operands to do this.
768 unsigned ChildNo = 0;
769 for (unsigned InstOpNo = NumResults, e = NumFixedOperands;
770 InstOpNo != e; ++InstOpNo) {
771 // Determine what to emit for this operand.
772 Record *OperandNode = II.Operands[InstOpNo].Rec;
773 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
774 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
775 // This is a predicate or optional def operand; emit the
776 // 'default ops' operands.
777 const DAGDefaultOperand &DefaultOp
778 = CGP.getDefaultOperand(OperandNode);
779 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
780 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
781 continue;
782 }
783
784 // Otherwise this is a normal operand or a predicate operand without
785 // 'execute always'; emit it.
786
787 // For operands with multiple sub-operands we may need to emit
788 // multiple child patterns to cover them all. However, ComplexPattern
789 // children may themselves emit multiple MI operands.
790 unsigned NumSubOps = 1;
791 if (OperandNode->isSubClassOf("Operand")) {
792 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
793 if (unsigned NumArgs = MIOpInfo->getNumArgs())
794 NumSubOps = NumArgs;
795 }
796
797 unsigned FinalNumOps = InstOps.size() + NumSubOps;
798 while (InstOps.size() < FinalNumOps) {
799 const TreePatternNode *Child = N->getChild(ChildNo);
800 unsigned BeforeAddingNumOps = InstOps.size();
801 EmitResultOperand(Child, InstOps);
802 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
803
804 // If the operand is an instruction and it produced multiple results, just
805 // take the first one.
806 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
807 InstOps.resize(BeforeAddingNumOps+1);
808
809 ++ChildNo;
810 }
811 }
812
813 // If this is a variadic output instruction (i.e. REG_SEQUENCE), we can't
814 // expand suboperands, use default operands, or other features determined from
815 // the CodeGenInstruction after the fixed operands, which were handled
816 // above. Emit the remaining instructions implicitly added by the use for
817 // variable_ops.
818 if (II.Operands.isVariadic) {
819 for (unsigned I = ChildNo, E = N->getNumChildren(); I < E; ++I)
820 EmitResultOperand(N->getChild(I), InstOps);
821 }
822
823 // If this node has input glue or explicitly specified input physregs, we
824 // need to add chained and glued copyfromreg nodes and materialize the glue
825 // input.
826 if (isRoot && !PhysRegInputs.empty()) {
827 // Emit all of the CopyToReg nodes for the input physical registers. These
828 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
829 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
830 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
831 PhysRegInputs[i].first));
832 // Even if the node has no other glue inputs, the resultant node must be
833 // glued to the CopyFromReg nodes we just generated.
834 TreeHasInGlue = true;
835 }
836
837 // Result order: node results, chain, glue
838
839 // Determine the result types.
840 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
841 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
842 ResultVTs.push_back(N->getType(i));
843
844 // If this is the root instruction of a pattern that has physical registers in
845 // its result pattern, add output VTs for them. For example, X86 has:
846 // (set AL, (mul ...))
847 // This also handles implicit results like:
848 // (implicit EFLAGS)
849 if (isRoot && !Pattern.getDstRegs().empty()) {
850 // If the root came from an implicit def in the instruction handling stuff,
851 // don't re-add it.
852 Record *HandledReg = nullptr;
853 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
854 HandledReg = II.ImplicitDefs[0];
855
856 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
857 Record *Reg = Pattern.getDstRegs()[i];
858 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
859 ResultVTs.push_back(getRegisterValueType(Reg, CGT));
860 }
861 }
862
863 // If this is the root of the pattern and the pattern we're matching includes
864 // a node that is variadic, mark the generated node as variadic so that it
865 // gets the excess operands from the input DAG.
866 int NumFixedArityOperands = -1;
867 if (isRoot &&
868 Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP))
869 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
870
871 // If this is the root node and multiple matched nodes in the input pattern
872 // have MemRefs in them, have the interpreter collect them and plop them onto
873 // this node. If there is just one node with MemRefs, leave them on that node
874 // even if it is not the root.
875 //
876 // FIXME3: This is actively incorrect for result patterns with multiple
877 // memory-referencing instructions.
878 bool PatternHasMemOperands =
879 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
880
881 bool NodeHasMemRefs = false;
882 if (PatternHasMemOperands) {
883 unsigned NumNodesThatLoadOrStore =
884 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
885 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
886 NumNodesThatLoadOrStore == 1;
887 NodeHasMemRefs =
888 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
889 NumNodesThatLoadOrStore != 1));
890 }
891
892 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
893 "Node has no result");
894
895 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
896 ResultVTs, InstOps,
897 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
898 NodeHasMemRefs, NumFixedArityOperands,
899 NextRecordedOperandNo));
900
901 // The non-chain and non-glue results of the newly emitted node get recorded.
902 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
903 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
904 OutputOps.push_back(NextRecordedOperandNo++);
905 }
906 }
907
908 void MatcherGen::
909 EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
910 SmallVectorImpl<unsigned> &ResultOps) {
911 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
912
913 // Emit the operand.
914 SmallVector<unsigned, 8> InputOps;
915
916 // FIXME2: Could easily generalize this to support multiple inputs and outputs
917 // to the SDNodeXForm. For now we just support one input and one output like
918 // the old instruction selector.
919 assert(N->getNumChildren() == 1);
920 EmitResultOperand(N->getChild(0), InputOps);
921
922 // The input currently must have produced exactly one result.
923 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
924
925 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
926 ResultOps.push_back(NextRecordedOperandNo++);
927 }
928
929 void MatcherGen::EmitResultOperand(const TreePatternNode *N,
930 SmallVectorImpl<unsigned> &ResultOps) {
931 // This is something selected from the pattern we matched.
932 if (!N->getName().empty())
933 return EmitResultOfNamedOperand(N, ResultOps);
934
935 if (N->isLeaf())
936 return EmitResultLeafAsOperand(N, ResultOps);
937
938 Record *OpRec = N->getOperator();
939 if (OpRec->isSubClassOf("Instruction"))
940 return EmitResultInstructionAsOperand(N, ResultOps);
941 if (OpRec->isSubClassOf("SDNodeXForm"))
942 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
943 errs() << "Unknown result node to emit code for: " << *N << '\n';
944 PrintFatalError("Unknown node in result pattern!");
945 }
946
947 void MatcherGen::EmitResultCode() {
948 // Patterns that match nodes with (potentially multiple) chain inputs have to
949 // merge them together into a token factor. This informs the generated code
950 // what all the chained nodes are.
951 if (!MatchedChainNodes.empty())
952 AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes));
953
954 // Codegen the root of the result pattern, capturing the resulting values.
955 SmallVector<unsigned, 8> Ops;
956 EmitResultOperand(Pattern.getDstPattern(), Ops);
957
958 // At this point, we have however many values the result pattern produces.
959 // However, the input pattern might not need all of these. If there are
960 // excess values at the end (such as implicit defs of condition codes etc)
961 // just lop them off. This doesn't need to worry about glue or chains, just
962 // explicit results.
963 //
964 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
965
966 // If the pattern also has (implicit) results, count them as well.
967 if (!Pattern.getDstRegs().empty()) {
968 // If the root came from an implicit def in the instruction handling stuff,
969 // don't re-add it.
970 Record *HandledReg = nullptr;
971 const TreePatternNode *DstPat = Pattern.getDstPattern();
972 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
973 const CodeGenTarget &CGT = CGP.getTargetInfo();
974 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
975
976 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
977 HandledReg = II.ImplicitDefs[0];
978 }
979
980 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
981 Record *Reg = Pattern.getDstRegs()[i];
982 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
983 ++NumSrcResults;
984 }
985 }
986
987 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
988 Ops.resize(NumSrcResults);
989
990 // If the matched pattern covers nodes which define a glue result, emit a node
991 // that tells the matcher about them so that it can update their results.
992 if (!MatchedGlueResultNodes.empty())
993 AddMatcher(new MarkGlueResultsMatcher(MatchedGlueResultNodes));
994
995 AddMatcher(new CompleteMatchMatcher(Ops, Pattern));
996 }
997
998
999 /// ConvertPatternToMatcher - Create the matcher for the specified pattern with
1000 /// the specified variant. If the variant number is invalid, this returns null.
1001 Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
1002 unsigned Variant,
1003 const CodeGenDAGPatterns &CGP) {
1004 MatcherGen Gen(Pattern, CGP);
1005
1006 // Generate the code for the matcher.
1007 if (Gen.EmitMatcherCode(Variant))
1008 return nullptr;
1009
1010 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
1011 // FIXME2: Split result code out to another table, and make the matcher end
1012 // with an "Emit <index>" command. This allows result generation stuff to be
1013 // shared and factored?
1014
1015 // If the match succeeds, then we generate Pattern.
1016 Gen.EmitResultCode();
1017
1018 // Unconditional match.
1019 return Gen.GetMatcher();
1020 }