blob: c5897c72d3659c2c07bacd4db0cd5f00be718e6a [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"
Jim Grosbach4a6d7352011-03-11 02:19:02 +000012#include "CodeGenRegisters.h"
Chris Lattnerda272d12010-02-15 08:04:42 +000013#include "Record.h"
Jim Grosbach4a6d7352011-03-11 02:19:02 +000014#include "llvm/ADT/DenseMap.h"
Chris Lattner785d16f2010-02-17 02:16:19 +000015#include "llvm/ADT/SmallVector.h"
Chris Lattnerda272d12010-02-15 08:04:42 +000016#include "llvm/ADT/StringMap.h"
Chris Lattner8e946be2010-02-21 03:22:59 +000017#include <utility>
Chris Lattnerda272d12010-02-15 08:04:42 +000018using namespace llvm;
19
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000020
Chris Lattner8e946be2010-02-21 03:22:59 +000021/// getRegisterValueType - Look up and return the ValueType of the specified
22/// register. If the register is a member of multiple register classes which
23/// have different associated types, return MVT::Other.
24static MVT::SimpleValueType getRegisterValueType(Record *R,
25 const CodeGenTarget &T) {
26 bool FoundRC = false;
27 MVT::SimpleValueType VT = MVT::Other;
Jakob Stoklund Olesenae1920b2011-06-15 04:50:36 +000028 const CodeGenRegister *Reg = T.getRegBank().getReg(R);
Chris Lattner8e946be2010-02-21 03:22:59 +000029 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000030
Chris Lattner8e946be2010-02-21 03:22:59 +000031 for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
32 const CodeGenRegisterClass &RC = RCs[rc];
Jakob Stoklund Olesenae1920b2011-06-15 04:50:36 +000033 if (!RC.contains(Reg))
Chris Lattner8e946be2010-02-21 03:22:59 +000034 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000035
Chris Lattner8e946be2010-02-21 03:22:59 +000036 if (!FoundRC) {
37 FoundRC = true;
38 VT = RC.getValueTypeNum(0);
39 continue;
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000040 }
Chris Lattner67ea6a72010-03-01 22:49:06 +000041
42 // If this occurs in multiple register classes, they all have to agree.
43 assert(VT == RC.getValueTypeNum(0));
Chris Lattner8e946be2010-02-21 03:22:59 +000044 }
45 return VT;
46}
47
48
49namespace {
Chris Lattnerda272d12010-02-15 08:04:42 +000050 class MatcherGen {
51 const PatternToMatch &Pattern;
52 const CodeGenDAGPatterns &CGP;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000053
Chris Lattnerda272d12010-02-15 08:04:42 +000054 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
55 /// out with all of the types removed. This allows us to insert type checks
56 /// as we scan the tree.
57 TreePatternNode *PatWithNoTypes;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000058
Chris Lattnerda272d12010-02-15 08:04:42 +000059 /// VariableMap - A map from variable names ('$dst') to the recorded operand
60 /// number that they were captured as. These are biased by 1 to make
61 /// insertion easier.
62 StringMap<unsigned> VariableMap;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000063
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000064 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
65 /// the RecordedNodes array, this keeps track of which slot will be next to
66 /// record into.
Chris Lattnerda272d12010-02-15 08:04:42 +000067 unsigned NextRecordedOperandNo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000068
Chris Lattner8e946be2010-02-21 03:22:59 +000069 /// MatchedChainNodes - This maintains the position in the recorded nodes
70 /// array of all of the recorded input nodes that have chains.
71 SmallVector<unsigned, 2> MatchedChainNodes;
Chris Lattner02f73582010-02-24 05:33:42 +000072
Chris Lattner8950bca2010-12-23 17:03:20 +000073 /// MatchedGlueResultNodes - This maintains the position in the recorded
74 /// nodes array of all of the recorded input nodes that have glue results.
75 SmallVector<unsigned, 2> MatchedGlueResultNodes;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000076
Chris Lattner57bf8a42010-03-04 01:23:08 +000077 /// MatchedComplexPatterns - This maintains a list of all of the
78 /// ComplexPatterns that we need to check. The patterns are known to have
79 /// names which were recorded. The second element of each pair is the first
80 /// slot number that the OPC_CheckComplexPat opcode drops the matched
81 /// results into.
82 SmallVector<std::pair<const TreePatternNode*,
83 unsigned>, 2> MatchedComplexPatterns;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000084
Chris Lattner8e946be2010-02-21 03:22:59 +000085 /// PhysRegInputs - List list has an entry for each explicitly specified
86 /// physreg input to the pattern. The first elt is the Register node, the
87 /// second is the recorded slot number the input pattern match saved it in.
88 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000089
Chris Lattner785d16f2010-02-17 02:16:19 +000090 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattnerb21ba712010-02-25 02:04:40 +000091 Matcher *TheMatcher;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000092
Chris Lattner785d16f2010-02-17 02:16:19 +000093 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattnerbd8227f2010-02-18 02:53:41 +000094 /// which should have future checks stuck into its Next position.
Chris Lattnerb21ba712010-02-25 02:04:40 +000095 Matcher *CurPredicate;
Chris Lattnerda272d12010-02-15 08:04:42 +000096 public:
97 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
Jim Grosbachfbadcd02010-12-21 16:16:00 +000098
Chris Lattnerda272d12010-02-15 08:04:42 +000099 ~MatcherGen() {
100 delete PatWithNoTypes;
101 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000102
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000103 bool EmitMatcherCode(unsigned Variant);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000104 void EmitResultCode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000105
Chris Lattnerb21ba712010-02-25 02:04:40 +0000106 Matcher *GetMatcher() const { return TheMatcher; }
Chris Lattnerda272d12010-02-15 08:04:42 +0000107 private:
Chris Lattnerb21ba712010-02-25 02:04:40 +0000108 void AddMatcher(Matcher *NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000109 void InferPossibleTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000110
Chris Lattnerb49985a2010-02-18 06:47:49 +0000111 // Matcher Generation.
Chris Lattnerda272d12010-02-15 08:04:42 +0000112 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
113 void EmitLeafMatchCode(const TreePatternNode *N);
114 void EmitOperatorMatchCode(const TreePatternNode *N,
115 TreePatternNode *NodeNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000116
Chris Lattnerb49985a2010-02-18 06:47:49 +0000117 // Result Code Generation.
Chris Lattner8e946be2010-02-21 03:22:59 +0000118 unsigned getNamedArgumentSlot(StringRef Name) {
119 unsigned VarMapEntry = VariableMap[Name];
120 assert(VarMapEntry != 0 &&
121 "Variable referenced but not defined and not caught earlier!");
122 return VarMapEntry-1;
123 }
124
125 /// GetInstPatternNode - Get the pattern for an instruction.
126 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
127 const TreePatternNode *N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000128
Chris Lattnerb49985a2010-02-18 06:47:49 +0000129 void EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000130 SmallVectorImpl<unsigned> &ResultOps);
131 void EmitResultOfNamedOperand(const TreePatternNode *N,
132 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000133 void EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000134 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000135 void EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000136 SmallVectorImpl<unsigned> &ResultOps);
137 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
138 SmallVectorImpl<unsigned> &ResultOps);
139 };
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000140
Chris Lattnerda272d12010-02-15 08:04:42 +0000141} // end anon namespace.
142
143MatcherGen::MatcherGen(const PatternToMatch &pattern,
144 const CodeGenDAGPatterns &cgp)
Chris Lattner853b9192010-02-19 00:33:13 +0000145: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Chris Lattner01bcd942010-03-01 22:46:42 +0000146 TheMatcher(0), CurPredicate(0) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000147 // We need to produce the matcher tree for the patterns source pattern. To do
148 // this we need to match the structure as well as the types. To do the type
149 // matching, we want to figure out the fewest number of type checks we need to
150 // emit. For example, if there is only one integer type supported by a
151 // target, there should be no type comparisons at all for integer patterns!
152 //
153 // To figure out the fewest number of type checks needed, clone the pattern,
154 // remove the types, then perform type inference on the pattern as a whole.
155 // If there are unresolved types, emit an explicit check for those types,
156 // apply the type to the tree, then rerun type inference. Iterate until all
157 // types are resolved.
158 //
159 PatWithNoTypes = Pattern.getSrcPattern()->clone();
160 PatWithNoTypes->RemoveAllTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000161
Chris Lattnerda272d12010-02-15 08:04:42 +0000162 // If there are types that are manifestly known, infer them.
163 InferPossibleTypes();
164}
165
166/// InferPossibleTypes - As we emit the pattern, we end up generating type
167/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
168/// want to propagate implied types as far throughout the tree as possible so
169/// that we avoid doing redundant type checks. This does the type propagation.
170void MatcherGen::InferPossibleTypes() {
171 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
172 // diagnostics, which we know are impossible at this point.
173 TreePattern &TP = *CGP.pf_begin()->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000174
Chris Lattnerda272d12010-02-15 08:04:42 +0000175 try {
176 bool MadeChange = true;
177 while (MadeChange)
178 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
179 true/*Ignore reg constraints*/);
180 } catch (...) {
181 errs() << "Type constraint application shouldn't fail!";
182 abort();
183 }
184}
185
186
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000187/// AddMatcher - Add a matcher node to the current graph we're building.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000188void MatcherGen::AddMatcher(Matcher *NewNode) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000189 if (CurPredicate != 0)
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000190 CurPredicate->setNext(NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000191 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000192 TheMatcher = NewNode;
Chris Lattnerda272d12010-02-15 08:04:42 +0000193 CurPredicate = NewNode;
194}
195
196
Chris Lattnerb49985a2010-02-18 06:47:49 +0000197//===----------------------------------------------------------------------===//
198// Pattern Match Generation
199//===----------------------------------------------------------------------===//
Chris Lattnerda272d12010-02-15 08:04:42 +0000200
201/// EmitLeafMatchCode - Generate matching code for leaf nodes.
202void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
203 assert(N->isLeaf() && "Not a leaf?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000204
Chris Lattnerda272d12010-02-15 08:04:42 +0000205 // Direct match against an integer constant.
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000206 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
207 // If this is the root of the dag we're matching, we emit a redundant opcode
208 // check to ensure that this gets folded into the normal top-level
209 // OpcodeSwitch.
210 if (N == Pattern.getSrcPattern()) {
211 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
212 AddMatcher(new CheckOpcodeMatcher(NI));
213 }
214
Chris Lattnerb21ba712010-02-25 02:04:40 +0000215 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000216 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000217
Chris Lattnerda272d12010-02-15 08:04:42 +0000218 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
219 if (DI == 0) {
220 errs() << "Unknown leaf kind: " << *DI << "\n";
221 abort();
222 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000223
Chris Lattnerda272d12010-02-15 08:04:42 +0000224 Record *LeafRec = DI->getDef();
225 if (// Handle register references. Nothing to do here, they always match.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000226 LeafRec->isSubClassOf("RegisterClass") ||
Owen Andersonbea6f612011-06-27 21:06:21 +0000227 LeafRec->isSubClassOf("RegisterOperand") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000228 LeafRec->isSubClassOf("PointerLikeRegClass") ||
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +0000229 LeafRec->isSubClassOf("SubRegIndex") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000230 // Place holder for SRCVALUE nodes. Nothing to do here.
231 LeafRec->getName() == "srcvalue")
232 return;
Chris Lattner8e946be2010-02-21 03:22:59 +0000233
234 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000235 // record the register
Chris Lattner8e946be2010-02-21 03:22:59 +0000236 if (LeafRec->isSubClassOf("Register")) {
Chris Lattner0cebe612010-03-01 02:24:17 +0000237 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
238 NextRecordedOperandNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000239 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
240 return;
241 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000242
Chris Lattnerda272d12010-02-15 08:04:42 +0000243 if (LeafRec->isSubClassOf("ValueType"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000244 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000245
Chris Lattnerda272d12010-02-15 08:04:42 +0000246 if (LeafRec->isSubClassOf("CondCode"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000247 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000248
Chris Lattnerda272d12010-02-15 08:04:42 +0000249 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000250 // We can't model ComplexPattern uses that don't have their name taken yet.
251 // The OPC_CheckComplexPattern operation implicitly records the results.
252 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000253 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
254 exit(1);
255 }
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000256
Chris Lattner57bf8a42010-03-04 01:23:08 +0000257 // Remember this ComplexPattern so that we can emit it after all the other
258 // structural matches are done.
259 MatchedComplexPatterns.push_back(std::make_pair(N, 0));
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000260 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000261 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000262
Chris Lattnerda272d12010-02-15 08:04:42 +0000263 errs() << "Unknown leaf kind: " << *N << "\n";
264 abort();
265}
266
267void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
268 TreePatternNode *NodeNoTypes) {
269 assert(!N->isLeaf() && "Not an operator?");
270 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000271
Chris Lattnerda272d12010-02-15 08:04:42 +0000272 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
273 // a constant without a predicate fn that has more that one bit set, handle
274 // this as a special case. This is usually for targets that have special
275 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
276 // handling stuff). Using these instructions is often far more efficient
277 // than materializing the constant. Unfortunately, both the instcombiner
278 // and the dag combiner can often infer that bits are dead, and thus drop
279 // them from the mask in the dag. For example, it might turn 'AND X, 255'
280 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
281 // to handle this.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000282 if ((N->getOperator()->getName() == "and" ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000283 N->getOperator()->getName() == "or") &&
Chris Lattner8e946be2010-02-21 03:22:59 +0000284 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
285 N->getPredicateFns().empty()) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000286 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
287 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Chris Lattnere9eeda82010-03-01 02:15:34 +0000288 // If this is at the root of the pattern, we emit a redundant
289 // CheckOpcode so that the following checks get factored properly under
290 // a single opcode check.
291 if (N == Pattern.getSrcPattern())
292 AddMatcher(new CheckOpcodeMatcher(CInfo));
293
294 // Emit the CheckAndImm/CheckOrImm node.
Chris Lattnerda272d12010-02-15 08:04:42 +0000295 if (N->getOperator()->getName() == "and")
Chris Lattnerb21ba712010-02-25 02:04:40 +0000296 AddMatcher(new CheckAndImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000297 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000298 AddMatcher(new CheckOrImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000299
300 // Match the LHS of the AND as appropriate.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000301 AddMatcher(new MoveChildMatcher(0));
Chris Lattnerda272d12010-02-15 08:04:42 +0000302 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000303 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000304 return;
305 }
306 }
307 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000308
Chris Lattnerda272d12010-02-15 08:04:42 +0000309 // Check that the current opcode lines up.
Chris Lattnera230f962010-02-27 21:48:43 +0000310 AddMatcher(new CheckOpcodeMatcher(CInfo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000311
Chris Lattner8e946be2010-02-21 03:22:59 +0000312 // If this node has memory references (i.e. is a load or store), tell the
313 // interpreter to capture them in the memref array.
314 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000315 AddMatcher(new RecordMemRefMatcher());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000316
Chris Lattnerda272d12010-02-15 08:04:42 +0000317 // If this node has a chain, then the chain is operand #0 is the SDNode, and
318 // the child numbers of the node are all offset by one.
319 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000320 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000321 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000322 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner0cebe612010-03-01 02:24:17 +0000323 "' chained node",
324 NextRecordedOperandNo));
Chris Lattner785d16f2010-02-17 02:16:19 +0000325 // Remember all of the input chains our pattern will match.
Chris Lattner8e946be2010-02-21 03:22:59 +0000326 MatchedChainNodes.push_back(NextRecordedOperandNo++);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000327
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000328 // Don't look at the input chain when matching the tree pattern to the
329 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000330 OpNo = 1;
331
Chris Lattner6bc1b512010-02-16 19:19:58 +0000332 // If this node is not the root and the subtree underneath it produces a
333 // chain, then the result of matching the node is also produce a chain.
334 // Beyond that, this means that we're also folding (at least) the root node
335 // into the node that produce the chain (for example, matching
336 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
337 // problematic, if the 'reg' node also uses the load (say, its chain).
338 // Graphically:
339 //
340 // [LD]
341 // ^ ^
342 // | \ DAG's like cheese.
343 // / |
344 // / [YY]
345 // | ^
346 // [XX]--/
347 //
348 // It would be invalid to fold XX and LD. In this case, folding the two
349 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
350 // To prevent this, we emit a dynamic check for legality before allowing
351 // this to be folded.
352 //
353 const TreePatternNode *Root = Pattern.getSrcPattern();
354 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000355 // If there is a node between the root and this node, then we definitely
356 // need to emit the check.
357 bool NeedCheck = !Root->hasChild(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000358
Chris Lattnere39650a2010-02-16 06:10:58 +0000359 // If it *is* an immediate child of the root, we can still need a check if
360 // the root SDNode has multiple inputs. For us, this means that it is an
361 // intrinsic, has multiple operands, or has other inputs like chain or
Chris Lattner8950bca2010-12-23 17:03:20 +0000362 // glue).
Chris Lattnere39650a2010-02-16 06:10:58 +0000363 if (!NeedCheck) {
364 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
365 NeedCheck =
366 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
367 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
368 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
369 PInfo.getNumOperands() > 1 ||
370 PInfo.hasProperty(SDNPHasChain) ||
Chris Lattner036609b2010-12-23 18:28:41 +0000371 PInfo.hasProperty(SDNPInGlue) ||
372 PInfo.hasProperty(SDNPOptInGlue);
Chris Lattnere39650a2010-02-16 06:10:58 +0000373 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000374
Chris Lattnere39650a2010-02-16 06:10:58 +0000375 if (NeedCheck)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000376 AddMatcher(new CheckFoldableChainNodeMatcher());
Chris Lattnere39650a2010-02-16 06:10:58 +0000377 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000378 }
Chris Lattner02f73582010-02-24 05:33:42 +0000379
Chris Lattner8950bca2010-12-23 17:03:20 +0000380 // If this node has an output glue and isn't the root, remember it.
Chris Lattner036609b2010-12-23 18:28:41 +0000381 if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
Chris Lattner02f73582010-02-24 05:33:42 +0000382 N != Pattern.getSrcPattern()) {
Chris Lattner8950bca2010-12-23 17:03:20 +0000383 // TODO: This redundantly records nodes with both glues and chains.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000384
Chris Lattner02f73582010-02-24 05:33:42 +0000385 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000386 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner8950bca2010-12-23 17:03:20 +0000387 "' glue output node",
Chris Lattner0cebe612010-03-01 02:24:17 +0000388 NextRecordedOperandNo));
Chris Lattner8950bca2010-12-23 17:03:20 +0000389 // Remember all of the nodes with output glue our pattern will match.
390 MatchedGlueResultNodes.push_back(NextRecordedOperandNo++);
Chris Lattner02f73582010-02-24 05:33:42 +0000391 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000392
Chris Lattner8950bca2010-12-23 17:03:20 +0000393 // If this node is known to have an input glue or if it *might* have an input
394 // glue, capture it as the glue input of the pattern.
Chris Lattner036609b2010-12-23 18:28:41 +0000395 if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
396 N->NodeHasProperty(SDNPInGlue, CGP))
Chris Lattner8950bca2010-12-23 17:03:20 +0000397 AddMatcher(new CaptureGlueInputMatcher());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000398
Chris Lattnerda272d12010-02-15 08:04:42 +0000399 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
400 // Get the code suitable for matching this child. Move to the child, check
401 // it then move back to the parent.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000402 AddMatcher(new MoveChildMatcher(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000403 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000404 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000405 }
406}
407
408
409void MatcherGen::EmitMatchCode(const TreePatternNode *N,
410 TreePatternNode *NodeNoTypes) {
411 // If N and NodeNoTypes don't agree on a type, then this is a case where we
412 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
413 // reinfer any correlated types.
Chris Lattner084df622010-03-24 00:41:19 +0000414 SmallVector<unsigned, 2> ResultsToTypeCheck;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000415
Chris Lattner084df622010-03-24 00:41:19 +0000416 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
417 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
418 NodeNoTypes->setType(i, N->getExtType(i));
Chris Lattnerda272d12010-02-15 08:04:42 +0000419 InferPossibleTypes();
Chris Lattner084df622010-03-24 00:41:19 +0000420 ResultsToTypeCheck.push_back(i);
Chris Lattnerda272d12010-02-15 08:04:42 +0000421 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000422
Chris Lattnerda272d12010-02-15 08:04:42 +0000423 // If this node has a name associated with it, capture it in VariableMap. If
424 // we already saw this in the pattern, emit code to verify dagness.
425 if (!N->getName().empty()) {
426 unsigned &VarMapEntry = VariableMap[N->getName()];
427 if (VarMapEntry == 0) {
Chris Lattner20df2422010-02-22 23:33:44 +0000428 // If it is a named node, we must emit a 'Record' opcode.
Chris Lattner0cebe612010-03-01 02:24:17 +0000429 AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
Chris Lattner20df2422010-02-22 23:33:44 +0000430 VarMapEntry = ++NextRecordedOperandNo;
Chris Lattnerda272d12010-02-15 08:04:42 +0000431 } else {
432 // If we get here, this is a second reference to a specific name. Since
433 // we already have checked that the first reference is valid, we don't
434 // have to recursively match it, just check that it's the same as the
435 // previously named thing.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000436 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
Chris Lattnerda272d12010-02-15 08:04:42 +0000437 return;
438 }
439 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000440
Chris Lattnerda272d12010-02-15 08:04:42 +0000441 if (N->isLeaf())
442 EmitLeafMatchCode(N);
443 else
444 EmitOperatorMatchCode(N, NodeNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000445
Chris Lattner6fd326b2010-03-07 07:20:49 +0000446 // If there are node predicates for this node, generate their checks.
447 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
448 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000449
Chris Lattner084df622010-03-24 00:41:19 +0000450 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
451 AddMatcher(new CheckTypeMatcher(N->getType(ResultsToTypeCheck[i]),
452 ResultsToTypeCheck[i]));
Chris Lattnerda272d12010-02-15 08:04:42 +0000453}
454
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000455/// EmitMatcherCode - Generate the code that matches the predicate of this
456/// pattern for the specified Variant. If the variant is invalid this returns
457/// true and does not generate code, if it is valid, it returns false.
458bool MatcherGen::EmitMatcherCode(unsigned Variant) {
459 // If the root of the pattern is a ComplexPattern and if it is specified to
460 // match some number of root opcodes, these are considered to be our variants.
461 // Depending on which variant we're generating code for, emit the root opcode
462 // check.
463 if (const ComplexPattern *CP =
464 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000465 const std::vector<Record*> &OpNodes = CP->getRootNodes();
Chris Lattner405f1252010-03-01 22:29:19 +0000466 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
467 if (Variant >= OpNodes.size()) return true;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000468
Chris Lattner405f1252010-03-01 22:29:19 +0000469 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000470 } else {
471 if (Variant != 0) return true;
472 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000473
Chris Lattner9752fb12010-03-04 01:25:36 +0000474 // Emit the matcher for the pattern structure and types.
475 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000476
Chris Lattnerda272d12010-02-15 08:04:42 +0000477 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
478 // feature is around, do the check).
479 if (!Pattern.getPredicateCheck().empty())
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000480 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000481
Chris Lattner57bf8a42010-03-04 01:23:08 +0000482 // Now that we've completed the structural type match, emit any ComplexPattern
483 // checks (e.g. addrmode matches). We emit this after the structural match
484 // because they are generally more expensive to evaluate and more difficult to
485 // factor.
Chris Lattner57bf8a42010-03-04 01:23:08 +0000486 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
487 const TreePatternNode *N = MatchedComplexPatterns[i].first;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000488
Chris Lattner57bf8a42010-03-04 01:23:08 +0000489 // Remember where the results of this match get stuck.
490 MatchedComplexPatterns[i].second = NextRecordedOperandNo;
491
492 // Get the slot we recorded the value in from the name on the node.
493 unsigned RecNodeEntry = VariableMap[N->getName()];
494 assert(!N->getName().empty() && RecNodeEntry &&
495 "Complex pattern should have a name and slot");
496 --RecNodeEntry; // Entries in VariableMap are biased.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000497
Chris Lattner57bf8a42010-03-04 01:23:08 +0000498 const ComplexPattern &CP =
499 CGP.getComplexPattern(((DefInit*)N->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000500
Chris Lattner57bf8a42010-03-04 01:23:08 +0000501 // Emit a CheckComplexPat operation, which does the match (aborting if it
502 // fails) and pushes the matched operands onto the recorded nodes list.
503 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
504 N->getName(), NextRecordedOperandNo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000505
Chris Lattner57bf8a42010-03-04 01:23:08 +0000506 // Record the right number of operands.
507 NextRecordedOperandNo += CP.getNumOperands();
508 if (CP.hasProperty(SDNPHasChain)) {
509 // If the complex pattern has a chain, then we need to keep track of the
510 // fact that we just recorded a chain input. The chain input will be
511 // matched as the last operand of the predicate if it was successful.
512 ++NextRecordedOperandNo; // Chained node operand.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000513
Chris Lattner57bf8a42010-03-04 01:23:08 +0000514 // It is the last operand recorded.
515 assert(NextRecordedOperandNo > 1 &&
516 "Should have recorded input/result chains at least!");
517 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
518 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000519
Chris Lattner8950bca2010-12-23 17:03:20 +0000520 // TODO: Complex patterns can't have output glues, if they did, we'd want
Chris Lattner57bf8a42010-03-04 01:23:08 +0000521 // to record them.
522 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000523
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000524 return false;
Chris Lattnerda272d12010-02-15 08:04:42 +0000525}
526
527
Chris Lattnerb49985a2010-02-18 06:47:49 +0000528//===----------------------------------------------------------------------===//
529// Node Result Generation
530//===----------------------------------------------------------------------===//
531
Chris Lattner8e946be2010-02-21 03:22:59 +0000532void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
533 SmallVectorImpl<unsigned> &ResultOps){
534 assert(!N->getName().empty() && "Operand not named!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000535
Chris Lattner8e946be2010-02-21 03:22:59 +0000536 // A reference to a complex pattern gets all of the results of the complex
537 // pattern's match.
538 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattner57bf8a42010-03-04 01:23:08 +0000539 unsigned SlotNo = 0;
540 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i)
541 if (MatchedComplexPatterns[i].first->getName() == N->getName()) {
542 SlotNo = MatchedComplexPatterns[i].second;
543 break;
544 }
545 assert(SlotNo != 0 && "Didn't get a slot number assigned?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000546
Chris Lattner20df2422010-02-22 23:33:44 +0000547 // The first slot entry is the node itself, the subsequent entries are the
548 // matched values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000549 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner57bf8a42010-03-04 01:23:08 +0000550 ResultOps.push_back(SlotNo+i);
Chris Lattner8e946be2010-02-21 03:22:59 +0000551 return;
552 }
553
Chris Lattner57bf8a42010-03-04 01:23:08 +0000554 unsigned SlotNo = getNamedArgumentSlot(N->getName());
555
Chris Lattner8e946be2010-02-21 03:22:59 +0000556 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
557 // version of the immediate so that it doesn't get selected due to some other
558 // node use.
559 if (!N->isLeaf()) {
560 StringRef OperatorName = N->getOperator()->getName();
561 if (OperatorName == "imm" || OperatorName == "fpimm") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000562 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000563 ResultOps.push_back(NextRecordedOperandNo++);
564 return;
565 }
566 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000567
Chris Lattner8e946be2010-02-21 03:22:59 +0000568 ResultOps.push_back(SlotNo);
569}
570
Chris Lattnerb49985a2010-02-18 06:47:49 +0000571void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000572 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattner845c0422010-02-18 22:03:03 +0000573 assert(N->isLeaf() && "Must be a leaf");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000574
Chris Lattner845c0422010-02-18 22:03:03 +0000575 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000576 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000577 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000578 return;
579 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000580
Chris Lattner845c0422010-02-18 22:03:03 +0000581 // If this is an explicit register reference, handle it.
582 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Owen Andersonbea6f612011-06-27 21:06:21 +0000583 Record *Def = DI->getDef();
584 if (Def->isSubClassOf("Register")) {
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +0000585 const CodeGenRegister *Reg =
Owen Andersonbea6f612011-06-27 21:06:21 +0000586 CGP.getTargetInfo().getRegBank().getReg(Def);
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +0000587 AddMatcher(new EmitRegisterMatcher(Reg, N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000588 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000589 return;
590 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000591
Owen Andersonbea6f612011-06-27 21:06:21 +0000592 if (Def->getName() == "zero_reg") {
Chris Lattnerd7349192010-03-19 21:37:09 +0000593 AddMatcher(new EmitRegisterMatcher(0, N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000594 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000595 return;
596 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000597
Chris Lattner8e946be2010-02-21 03:22:59 +0000598 // Handle a reference to a register class. This is used
599 // in COPY_TO_SUBREG instructions.
Owen Andersonbea6f612011-06-27 21:06:21 +0000600 if (Def->isSubClassOf("RegisterOperand"))
601 Def = Def->getValueAsDef("RegClass");
602 if (Def->isSubClassOf("RegisterClass")) {
603 std::string Value = getQualifiedName(Def) + "RegClassID";
Chris Lattnerb21ba712010-02-25 02:04:40 +0000604 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
Chris Lattner8e946be2010-02-21 03:22:59 +0000605 ResultOps.push_back(NextRecordedOperandNo++);
606 return;
Chris Lattner845c0422010-02-18 22:03:03 +0000607 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +0000608
609 // Handle a subregister index. This is used for INSERT_SUBREG etc.
Owen Andersonbea6f612011-06-27 21:06:21 +0000610 if (Def->isSubClassOf("SubRegIndex")) {
611 std::string Value = getQualifiedName(Def);
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +0000612 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
613 ResultOps.push_back(NextRecordedOperandNo++);
614 return;
615 }
Chris Lattner845c0422010-02-18 22:03:03 +0000616 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000617
Chris Lattnerb49985a2010-02-18 06:47:49 +0000618 errs() << "unhandled leaf node: \n";
619 N->dump();
620}
621
Chris Lattner8e946be2010-02-21 03:22:59 +0000622/// GetInstPatternNode - Get the pattern for an instruction.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000623///
Chris Lattner8e946be2010-02-21 03:22:59 +0000624const TreePatternNode *MatcherGen::
625GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
626 const TreePattern *InstPat = Inst.getPattern();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000627
Chris Lattner8e946be2010-02-21 03:22:59 +0000628 // FIXME2?: Assume actual pattern comes before "implicit".
629 TreePatternNode *InstPatNode;
630 if (InstPat)
631 InstPatNode = InstPat->getTree(0);
632 else if (/*isRoot*/ N == Pattern.getDstPattern())
633 InstPatNode = Pattern.getSrcPattern();
634 else
635 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000636
Chris Lattner8e946be2010-02-21 03:22:59 +0000637 if (InstPatNode && !InstPatNode->isLeaf() &&
638 InstPatNode->getOperator()->getName() == "set")
639 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000640
Chris Lattner8e946be2010-02-21 03:22:59 +0000641 return InstPatNode;
642}
643
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000644static bool
645mayInstNodeLoadOrStore(const TreePatternNode *N,
646 const CodeGenDAGPatterns &CGP) {
647 Record *Op = N->getOperator();
648 const CodeGenTarget &CGT = CGP.getTargetInfo();
649 CodeGenInstruction &II = CGT.getInstruction(Op);
650 return II.mayLoad || II.mayStore;
651}
652
653static unsigned
654numNodesThatMayLoadOrStore(const TreePatternNode *N,
655 const CodeGenDAGPatterns &CGP) {
656 if (N->isLeaf())
657 return 0;
658
659 Record *OpRec = N->getOperator();
660 if (!OpRec->isSubClassOf("Instruction"))
661 return 0;
662
663 unsigned Count = 0;
664 if (mayInstNodeLoadOrStore(N, CGP))
665 ++Count;
666
667 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
668 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
669
670 return Count;
671}
672
Chris Lattner8e946be2010-02-21 03:22:59 +0000673void MatcherGen::
674EmitResultInstructionAsOperand(const TreePatternNode *N,
675 SmallVectorImpl<unsigned> &OutputOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000676 Record *Op = N->getOperator();
677 const CodeGenTarget &CGT = CGP.getTargetInfo();
Chris Lattnerf30187a2010-03-19 00:07:20 +0000678 CodeGenInstruction &II = CGT.getInstruction(Op);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000679 const DAGInstruction &Inst = CGP.getInstruction(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000680
Chris Lattner8e946be2010-02-21 03:22:59 +0000681 // If we can, get the pattern for the instruction we're generating. We derive
682 // a variety of information from this pattern, such as whether it has a chain.
683 //
684 // FIXME2: This is extremely dubious for several reasons, not the least of
685 // which it gives special status to instructions with patterns that Pat<>
686 // nodes can't duplicate.
687 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
688
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000689 // NodeHasChain - Whether the instruction node we're creating takes chains.
Chris Lattner8e946be2010-02-21 03:22:59 +0000690 bool NodeHasChain = InstPatNode &&
691 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000692
Chris Lattner8e946be2010-02-21 03:22:59 +0000693 bool isRoot = N == Pattern.getDstPattern();
694
Chris Lattner8950bca2010-12-23 17:03:20 +0000695 // TreeHasOutGlue - True if this tree has glue.
696 bool TreeHasInGlue = false, TreeHasOutGlue = false;
Chris Lattner8e946be2010-02-21 03:22:59 +0000697 if (isRoot) {
698 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
Chris Lattner036609b2010-12-23 18:28:41 +0000699 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
700 SrcPat->TreeHasProperty(SDNPInGlue, CGP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000701
Chris Lattner8e946be2010-02-21 03:22:59 +0000702 // FIXME2: this is checking the entire pattern, not just the node in
703 // question, doing this just for the root seems like a total hack.
Chris Lattner036609b2010-12-23 18:28:41 +0000704 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
Chris Lattner8e946be2010-02-21 03:22:59 +0000705 }
706
707 // NumResults - This is the number of results produced by the instruction in
708 // the "outs" list.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000709 unsigned NumResults = Inst.getNumResults();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000710
Chris Lattnerb49985a2010-02-18 06:47:49 +0000711 // Loop over all of the operands of the instruction pattern, emitting code
712 // to fill them all in. The node 'N' usually has number children equal to
713 // the number of input operands of the instruction. However, in cases
714 // where there are predicate operands for an instruction, we need to fill
715 // in the 'execute always' values. Match up the node operands to the
716 // instruction operands to do this.
Chris Lattner8e946be2010-02-21 03:22:59 +0000717 SmallVector<unsigned, 8> InstOps;
Chris Lattnerc240bb02010-11-01 04:03:32 +0000718 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.Operands.size();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000719 InstOpNo != e; ++InstOpNo) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000720
Chris Lattnerb49985a2010-02-18 06:47:49 +0000721 // Determine what to emit for this operand.
Chris Lattnerc240bb02010-11-01 04:03:32 +0000722 Record *OperandNode = II.Operands[InstOpNo].Rec;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000723 if ((OperandNode->isSubClassOf("PredicateOperand") ||
724 OperandNode->isSubClassOf("OptionalDefOperand")) &&
725 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
726 // This is a predicate or optional def operand; emit the
727 // 'default ops' operands.
Eric Christopherae321ed2010-08-10 23:46:20 +0000728 const DAGDefaultOperand &DefaultOp
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000729 = CGP.getDefaultOperand(OperandNode);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000730 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
Chris Lattner8e946be2010-02-21 03:22:59 +0000731 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000732 continue;
733 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000734
Chris Lattner0be6fe72010-03-27 19:15:02 +0000735 const TreePatternNode *Child = N->getChild(ChildNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000736
Chris Lattnerb49985a2010-02-18 06:47:49 +0000737 // Otherwise this is a normal operand or a predicate operand without
738 // 'execute always'; emit it.
Chris Lattner0be6fe72010-03-27 19:15:02 +0000739 unsigned BeforeAddingNumOps = InstOps.size();
740 EmitResultOperand(Child, InstOps);
741 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000742
Chris Lattner0be6fe72010-03-27 19:15:02 +0000743 // If the operand is an instruction and it produced multiple results, just
744 // take the first one.
745 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
746 InstOps.resize(BeforeAddingNumOps+1);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000747
Chris Lattnerb49985a2010-02-18 06:47:49 +0000748 ++ChildNo;
749 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000750
Chris Lattner8950bca2010-12-23 17:03:20 +0000751 // If this node has input glue or explicitly specified input physregs, we
752 // need to add chained and glued copyfromreg nodes and materialize the glue
Chris Lattner8e946be2010-02-21 03:22:59 +0000753 // input.
754 if (isRoot && !PhysRegInputs.empty()) {
755 // Emit all of the CopyToReg nodes for the input physical registers. These
756 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
757 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000758 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
Chris Lattner92879532010-03-18 23:57:40 +0000759 PhysRegInputs[i].first));
Chris Lattner8950bca2010-12-23 17:03:20 +0000760 // Even if the node has no other glue inputs, the resultant node must be
761 // glued to the CopyFromReg nodes we just generated.
762 TreeHasInGlue = true;
Chris Lattner8e946be2010-02-21 03:22:59 +0000763 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000764
Chris Lattner8950bca2010-12-23 17:03:20 +0000765 // Result order: node results, chain, glue
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000766
Chris Lattner8e946be2010-02-21 03:22:59 +0000767 // Determine the result types.
768 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
Chris Lattner0be6fe72010-03-27 19:15:02 +0000769 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
770 ResultVTs.push_back(N->getType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000771
Chris Lattner8e946be2010-02-21 03:22:59 +0000772 // If this is the root instruction of a pattern that has physical registers in
773 // its result pattern, add output VTs for them. For example, X86 has:
774 // (set AL, (mul ...))
775 // This also handles implicit results like:
776 // (implicit EFLAGS)
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000777 if (isRoot && !Pattern.getDstRegs().empty()) {
Chris Lattner92879532010-03-18 23:57:40 +0000778 // If the root came from an implicit def in the instruction handling stuff,
779 // don't re-add it.
780 Record *HandledReg = 0;
Chris Lattner9414ae52010-03-27 20:09:24 +0000781 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
Chris Lattner92879532010-03-18 23:57:40 +0000782 HandledReg = II.ImplicitDefs[0];
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000783
Chris Lattner92879532010-03-18 23:57:40 +0000784 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
785 Record *Reg = Pattern.getDstRegs()[i];
786 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
787 ResultVTs.push_back(getRegisterValueType(Reg, CGT));
788 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000789 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000790
Chris Lattner1e506312010-03-19 05:34:15 +0000791 // If this is the root of the pattern and the pattern we're matching includes
792 // a node that is variadic, mark the generated node as variadic so that it
793 // gets the excess operands from the input DAG.
Chris Lattner8e946be2010-02-21 03:22:59 +0000794 int NumFixedArityOperands = -1;
Chris Lattner1e506312010-03-19 05:34:15 +0000795 if (isRoot &&
796 (Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP)))
Chris Lattner8e946be2010-02-21 03:22:59 +0000797 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000798
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000799 // If this is the root node and multiple matched nodes in the input pattern
800 // have MemRefs in them, have the interpreter collect them and plop them onto
801 // this node. If there is just one node with MemRefs, leave them on that node
802 // even if it is not the root.
Chris Lattner8e946be2010-02-21 03:22:59 +0000803 //
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000804 // FIXME3: This is actively incorrect for result patterns with multiple
805 // memory-referencing instructions.
806 bool PatternHasMemOperands =
807 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
808
809 bool NodeHasMemRefs = false;
810 if (PatternHasMemOperands) {
811 unsigned NumNodesThatLoadOrStore =
812 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
813 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
814 NumNodesThatLoadOrStore == 1;
815 NodeHasMemRefs =
816 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
817 NumNodesThatLoadOrStore != 1));
818 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000819
Chris Lattner8950bca2010-12-23 17:03:20 +0000820 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
Chris Lattner0be6fe72010-03-27 19:15:02 +0000821 "Node has no result");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000822
Chris Lattnerb21ba712010-02-25 02:04:40 +0000823 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
Chris Lattnere86097a2010-02-28 02:31:26 +0000824 ResultVTs.data(), ResultVTs.size(),
825 InstOps.data(), InstOps.size(),
Chris Lattner8950bca2010-12-23 17:03:20 +0000826 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
Chris Lattner6281cda2010-02-28 02:41:25 +0000827 NodeHasMemRefs, NumFixedArityOperands,
828 NextRecordedOperandNo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000829
Chris Lattner8950bca2010-12-23 17:03:20 +0000830 // The non-chain and non-glue results of the newly emitted node get recorded.
Chris Lattner565a6f92010-02-21 23:54:05 +0000831 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000832 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
Chris Lattner77f2e272010-02-21 06:03:07 +0000833 OutputOps.push_back(NextRecordedOperandNo++);
Chris Lattner565a6f92010-02-21 23:54:05 +0000834 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000835}
836
837void MatcherGen::
838EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
839 SmallVectorImpl<unsigned> &ResultOps) {
840 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
841
842 // Emit the operand.
843 SmallVector<unsigned, 8> InputOps;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000844
Chris Lattner8e946be2010-02-21 03:22:59 +0000845 // FIXME2: Could easily generalize this to support multiple inputs and outputs
846 // to the SDNodeXForm. For now we just support one input and one output like
847 // the old instruction selector.
848 assert(N->getNumChildren() == 1);
849 EmitResultOperand(N->getChild(0), InputOps);
850
851 // The input currently must have produced exactly one result.
852 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
853
Chris Lattnerb21ba712010-02-25 02:04:40 +0000854 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
Chris Lattner8e946be2010-02-21 03:22:59 +0000855 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000856}
857
858void MatcherGen::EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000859 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000860 // This is something selected from the pattern we matched.
Chris Lattner8e946be2010-02-21 03:22:59 +0000861 if (!N->getName().empty())
862 return EmitResultOfNamedOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000863
864 if (N->isLeaf())
865 return EmitResultLeafAsOperand(N, ResultOps);
866
867 Record *OpRec = N->getOperator();
868 if (OpRec->isSubClassOf("Instruction"))
869 return EmitResultInstructionAsOperand(N, ResultOps);
870 if (OpRec->isSubClassOf("SDNodeXForm"))
Chris Lattner8e946be2010-02-21 03:22:59 +0000871 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000872 errs() << "Unknown result node to emit code for: " << *N << '\n';
873 throw std::string("Unknown node in result pattern!");
874}
875
876void MatcherGen::EmitResultCode() {
Chris Lattner01bcd942010-03-01 22:46:42 +0000877 // Patterns that match nodes with (potentially multiple) chain inputs have to
878 // merge them together into a token factor. This informs the generated code
879 // what all the chained nodes are.
880 if (!MatchedChainNodes.empty())
881 AddMatcher(new EmitMergeInputChainsMatcher
882 (MatchedChainNodes.data(), MatchedChainNodes.size()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000883
Chris Lattner565a6f92010-02-21 23:54:05 +0000884 // Codegen the root of the result pattern, capturing the resulting values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000885 SmallVector<unsigned, 8> Ops;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000886 EmitResultOperand(Pattern.getDstPattern(), Ops);
Chris Lattner8e946be2010-02-21 03:22:59 +0000887
Chris Lattner565a6f92010-02-21 23:54:05 +0000888 // At this point, we have however many values the result pattern produces.
889 // However, the input pattern might not need all of these. If there are
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000890 // excess values at the end (such as implicit defs of condition codes etc)
Chris Lattner8950bca2010-12-23 17:03:20 +0000891 // just lop them off. This doesn't need to worry about glue or chains, just
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000892 // explicit results.
Chris Lattner565a6f92010-02-21 23:54:05 +0000893 //
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000894 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000895
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000896 // If the pattern also has (implicit) results, count them as well.
897 if (!Pattern.getDstRegs().empty()) {
898 // If the root came from an implicit def in the instruction handling stuff,
899 // don't re-add it.
900 Record *HandledReg = 0;
901 const TreePatternNode *DstPat = Pattern.getDstPattern();
902 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
903 const CodeGenTarget &CGT = CGP.getTargetInfo();
904 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
905
906 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
907 HandledReg = II.ImplicitDefs[0];
908 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000909
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000910 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
911 Record *Reg = Pattern.getDstRegs()[i];
912 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
913 ++NumSrcResults;
914 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000915 }
916
Chris Lattner565a6f92010-02-21 23:54:05 +0000917 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
918 Ops.resize(NumSrcResults);
Chris Lattner02f73582010-02-24 05:33:42 +0000919
Chris Lattner8950bca2010-12-23 17:03:20 +0000920 // If the matched pattern covers nodes which define a glue result, emit a node
Chris Lattner02f73582010-02-24 05:33:42 +0000921 // that tells the matcher about them so that it can update their results.
Chris Lattner8950bca2010-12-23 17:03:20 +0000922 if (!MatchedGlueResultNodes.empty())
923 AddMatcher(new MarkGlueResultsMatcher(MatchedGlueResultNodes.data(),
924 MatchedGlueResultNodes.size()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000925
Chris Lattnerb21ba712010-02-25 02:04:40 +0000926 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
Chris Lattnerb49985a2010-02-18 06:47:49 +0000927}
928
929
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000930/// ConvertPatternToMatcher - Create the matcher for the specified pattern with
931/// the specified variant. If the variant number is invalid, this returns null.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000932Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000933 unsigned Variant,
Chris Lattnerc78f2a32010-02-28 20:49:53 +0000934 const CodeGenDAGPatterns &CGP) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000935 MatcherGen Gen(Pattern, CGP);
936
937 // Generate the code for the matcher.
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000938 if (Gen.EmitMatcherCode(Variant))
939 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000940
Chris Lattner8e946be2010-02-21 03:22:59 +0000941 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
942 // FIXME2: Split result code out to another table, and make the matcher end
943 // with an "Emit <index>" command. This allows result generation stuff to be
944 // shared and factored?
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000945
Chris Lattnerda272d12010-02-15 08:04:42 +0000946 // If the match succeeds, then we generate Pattern.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000947 Gen.EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000948
949 // Unconditional match.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000950 return Gen.GetMatcher();
Chris Lattnerda272d12010-02-15 08:04:42 +0000951}