blob: 590a5badd46fb3c3ea248c73d0ea33103431a674 [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000018#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include <set>
20using namespace llvm;
21
Chris Lattnerca559d02005-09-08 21:03:01 +000022//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000023// Helpers for working with extended types.
24
25/// FilterVTs - Filter a list of VT's according to a predicate.
26///
27template<typename T>
28static std::vector<MVT::ValueType>
29FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32 if (Filter(InVTs[i]))
33 Result.push_back(InVTs[i]);
34 return Result;
35}
36
37/// isExtIntegerVT - Return true if the specified extended value type is
38/// integer, or isInt.
39static bool isExtIntegerVT(unsigned char VT) {
40 return VT == MVT::isInt ||
41 (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
42}
43
44/// isExtFloatingPointVT - Return true if the specified extended value type is
45/// floating point, or isFP.
46static bool isExtFloatingPointVT(unsigned char VT) {
47 return VT == MVT::isFP ||
48 (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
49}
50
51//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000052// SDTypeConstraint implementation
53//
54
55SDTypeConstraint::SDTypeConstraint(Record *R) {
56 OperandNo = R->getValueAsInt("OperandNum");
57
58 if (R->isSubClassOf("SDTCisVT")) {
59 ConstraintType = SDTCisVT;
60 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61 } else if (R->isSubClassOf("SDTCisInt")) {
62 ConstraintType = SDTCisInt;
63 } else if (R->isSubClassOf("SDTCisFP")) {
64 ConstraintType = SDTCisFP;
65 } else if (R->isSubClassOf("SDTCisSameAs")) {
66 ConstraintType = SDTCisSameAs;
67 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
68 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
69 ConstraintType = SDTCisVTSmallerThanOp;
70 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
71 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +000072 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
73 ConstraintType = SDTCisOpSmallerThanOp;
74 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
75 R->getValueAsInt("BigOperandNum");
Chris Lattner33c92e92005-09-08 21:27:15 +000076 } else {
77 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
78 exit(1);
79 }
80}
81
Chris Lattner32707602005-09-08 23:22:48 +000082/// getOperandNum - Return the node corresponding to operand #OpNo in tree
83/// N, which has NumResults results.
84TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
85 TreePatternNode *N,
86 unsigned NumResults) const {
87 assert(NumResults == 1 && "We only work with single result nodes so far!");
88
89 if (OpNo < NumResults)
90 return N; // FIXME: need value #
91 else
92 return N->getChild(OpNo-NumResults);
93}
94
95/// ApplyTypeConstraint - Given a node in a pattern, apply this type
96/// constraint to the nodes operands. This returns true if it makes a
97/// change, false otherwise. If a type contradiction is found, throw an
98/// exception.
99bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
100 const SDNodeInfo &NodeInfo,
101 TreePattern &TP) const {
102 unsigned NumResults = NodeInfo.getNumResults();
103 assert(NumResults == 1 && "We only work with single result nodes so far!");
104
105 // Check that the number of operands is sane.
106 if (NodeInfo.getNumOperands() >= 0) {
107 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
108 TP.error(N->getOperator()->getName() + " node requires exactly " +
109 itostr(NodeInfo.getNumOperands()) + " operands!");
110 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000111
112 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000113
114 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
115
116 switch (ConstraintType) {
117 default: assert(0 && "Unknown constraint type!");
118 case SDTCisVT:
119 // Operand must be a particular type.
120 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000121 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000122 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000123 std::vector<MVT::ValueType> IntVTs =
124 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000125
126 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000127 if (IntVTs.size() == 1)
128 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000129 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000130 }
131 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000132 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000133 std::vector<MVT::ValueType> FPVTs =
134 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000135
136 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000137 if (FPVTs.size() == 1)
138 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000139 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000140 }
Chris Lattner32707602005-09-08 23:22:48 +0000141 case SDTCisSameAs: {
142 TreePatternNode *OtherNode =
143 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000144 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
145 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000146 }
147 case SDTCisVTSmallerThanOp: {
148 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
149 // have an integer type that is smaller than the VT.
150 if (!NodeToApply->isLeaf() ||
151 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
152 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
153 ->isSubClassOf("ValueType"))
154 TP.error(N->getOperator()->getName() + " expects a VT operand!");
155 MVT::ValueType VT =
156 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
157 if (!MVT::isInteger(VT))
158 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
159
160 TreePatternNode *OtherNode =
161 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000162
163 // It must be integer.
164 bool MadeChange = false;
165 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
166
167 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000168 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
169 return false;
170 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000171 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000172 TreePatternNode *BigOperand =
173 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
174
175 // Both operands must be integer or FP, but we don't care which.
176 bool MadeChange = false;
177
178 if (isExtIntegerVT(NodeToApply->getExtType()))
179 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
180 else if (isExtFloatingPointVT(NodeToApply->getExtType()))
181 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
182 if (isExtIntegerVT(BigOperand->getExtType()))
183 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
184 else if (isExtFloatingPointVT(BigOperand->getExtType()))
185 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
186
187 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
188
189 if (isExtIntegerVT(NodeToApply->getExtType())) {
190 VTs = FilterVTs(VTs, MVT::isInteger);
191 } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
192 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
193 } else {
194 VTs.clear();
195 }
196
197 switch (VTs.size()) {
198 default: // Too many VT's to pick from.
199 case 0: break; // No info yet.
200 case 1:
201 // Only one VT of this flavor. Cannot ever satisify the constraints.
202 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
203 case 2:
204 // If we have exactly two possible types, the little operand must be the
205 // small one, the big operand should be the big one. Common with
206 // float/double for example.
207 assert(VTs[0] < VTs[1] && "Should be sorted!");
208 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
209 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
210 break;
211 }
212 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000213 }
Chris Lattner32707602005-09-08 23:22:48 +0000214 }
215 return false;
216}
217
218
Chris Lattner33c92e92005-09-08 21:27:15 +0000219//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000220// SDNodeInfo implementation
221//
222SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
223 EnumName = R->getValueAsString("Opcode");
224 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000225 Record *TypeProfile = R->getValueAsDef("TypeProfile");
226 NumResults = TypeProfile->getValueAsInt("NumResults");
227 NumOperands = TypeProfile->getValueAsInt("NumOperands");
228
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000229 // Parse the properties.
230 Properties = 0;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000231 std::vector<Record*> PropList = R->getValueAsListDef("Properties");
232 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
233 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000234 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000235 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000236 Properties |= 1 << SDNPAssociative;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000237 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000238 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000239 << "' on node '" << R->getName() << "'!\n";
240 exit(1);
241 }
242 }
243
244
Chris Lattner33c92e92005-09-08 21:27:15 +0000245 // Parse the type constraints.
Chris Lattner6bc0d742005-10-28 22:43:25 +0000246 std::vector<Record*> ConstList =TypeProfile->getValueAsListDef("Constraints");
247 TypeConstraints.assign(ConstList.begin(), ConstList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000248}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000249
250//===----------------------------------------------------------------------===//
251// TreePatternNode implementation
252//
253
254TreePatternNode::~TreePatternNode() {
255#if 0 // FIXME: implement refcounted tree nodes!
256 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
257 delete getChild(i);
258#endif
259}
260
Chris Lattner32707602005-09-08 23:22:48 +0000261/// UpdateNodeType - Set the node type of N to VT if VT contains
262/// information. If N already contains a conflicting type, then throw an
263/// exception. This returns true if any information was updated.
264///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000265bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
266 if (VT == MVT::isUnknown || getExtType() == VT) return false;
267 if (getExtType() == MVT::isUnknown) {
Chris Lattner32707602005-09-08 23:22:48 +0000268 setType(VT);
269 return true;
270 }
271
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000272 // If we are told this is to be an int or FP type, and it already is, ignore
273 // the advice.
274 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
275 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
276 return false;
277
278 // If we know this is an int or fp type, and we are told it is a specific one,
279 // take the advice.
280 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
281 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
282 setType(VT);
283 return true;
284 }
285
Chris Lattner1531f202005-10-26 16:59:37 +0000286 if (isLeaf()) {
287 dump();
288 TP.error("Type inference contradiction found in node!");
289 } else {
290 TP.error("Type inference contradiction found in node " +
291 getOperator()->getName() + "!");
292 }
Chris Lattner32707602005-09-08 23:22:48 +0000293 return true; // unreachable
294}
295
296
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000297void TreePatternNode::print(std::ostream &OS) const {
298 if (isLeaf()) {
299 OS << *getLeafValue();
300 } else {
301 OS << "(" << getOperator()->getName();
302 }
303
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000304 switch (getExtType()) {
305 case MVT::Other: OS << ":Other"; break;
306 case MVT::isInt: OS << ":isInt"; break;
307 case MVT::isFP : OS << ":isFP"; break;
308 case MVT::isUnknown: ; /*OS << ":?";*/ break;
309 default: OS << ":" << getType(); break;
310 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000311
312 if (!isLeaf()) {
313 if (getNumChildren() != 0) {
314 OS << " ";
315 getChild(0)->print(OS);
316 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
317 OS << ", ";
318 getChild(i)->print(OS);
319 }
320 }
321 OS << ")";
322 }
323
324 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000325 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000326 if (TransformFn)
327 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000328 if (!getName().empty())
329 OS << ":$" << getName();
330
331}
332void TreePatternNode::dump() const {
333 print(std::cerr);
334}
335
Chris Lattnere46e17b2005-09-29 19:28:10 +0000336/// isIsomorphicTo - Return true if this node is recursively isomorphic to
337/// the specified node. For this comparison, all of the state of the node
338/// is considered, except for the assigned name. Nodes with differing names
339/// that are otherwise identical are considered isomorphic.
340bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
341 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000342 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000343 getPredicateFn() != N->getPredicateFn() ||
344 getTransformFn() != N->getTransformFn())
345 return false;
346
347 if (isLeaf()) {
348 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
349 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
350 return DI->getDef() == NDI->getDef();
351 return getLeafValue() == N->getLeafValue();
352 }
353
354 if (N->getOperator() != getOperator() ||
355 N->getNumChildren() != getNumChildren()) return false;
356 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
357 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
358 return false;
359 return true;
360}
361
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000362/// clone - Make a copy of this tree and all of its children.
363///
364TreePatternNode *TreePatternNode::clone() const {
365 TreePatternNode *New;
366 if (isLeaf()) {
367 New = new TreePatternNode(getLeafValue());
368 } else {
369 std::vector<TreePatternNode*> CChildren;
370 CChildren.reserve(Children.size());
371 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
372 CChildren.push_back(getChild(i)->clone());
373 New = new TreePatternNode(getOperator(), CChildren);
374 }
375 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000376 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000377 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000378 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000379 return New;
380}
381
Chris Lattner32707602005-09-08 23:22:48 +0000382/// SubstituteFormalArguments - Replace the formal arguments in this tree
383/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000384void TreePatternNode::
385SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
386 if (isLeaf()) return;
387
388 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
389 TreePatternNode *Child = getChild(i);
390 if (Child->isLeaf()) {
391 Init *Val = Child->getLeafValue();
392 if (dynamic_cast<DefInit*>(Val) &&
393 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
394 // We found a use of a formal argument, replace it with its value.
395 Child = ArgMap[Child->getName()];
396 assert(Child && "Couldn't find formal argument!");
397 setChild(i, Child);
398 }
399 } else {
400 getChild(i)->SubstituteFormalArguments(ArgMap);
401 }
402 }
403}
404
405
406/// InlinePatternFragments - If this pattern refers to any pattern
407/// fragments, inline them into place, giving us a pattern without any
408/// PatFrag references.
409TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
410 if (isLeaf()) return this; // nothing to do.
411 Record *Op = getOperator();
412
413 if (!Op->isSubClassOf("PatFrag")) {
414 // Just recursively inline children nodes.
415 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
416 setChild(i, getChild(i)->InlinePatternFragments(TP));
417 return this;
418 }
419
420 // Otherwise, we found a reference to a fragment. First, look up its
421 // TreePattern record.
422 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
423
424 // Verify that we are passing the right number of operands.
425 if (Frag->getNumArgs() != Children.size())
426 TP.error("'" + Op->getName() + "' fragment requires " +
427 utostr(Frag->getNumArgs()) + " operands!");
428
Chris Lattner37937092005-09-09 01:15:01 +0000429 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000430
431 // Resolve formal arguments to their actual value.
432 if (Frag->getNumArgs()) {
433 // Compute the map of formal to actual arguments.
434 std::map<std::string, TreePatternNode*> ArgMap;
435 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
436 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
437
438 FragTree->SubstituteFormalArguments(ArgMap);
439 }
440
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000441 FragTree->setName(getName());
442
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000443 // Get a new copy of this fragment to stitch into here.
444 //delete this; // FIXME: implement refcounting!
445 return FragTree;
446}
447
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000448/// getIntrinsicType - Check to see if the specified record has an intrinsic
449/// type which should be applied to it. This infer the type of register
450/// references from the register file information, for example.
451///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000452static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
453 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000454 // Check to see if this is a register or a register class...
455 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000456 if (NotRegisters) return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000457 return getValueType(R->getValueAsDef("RegType"));
458 } else if (R->isSubClassOf("PatFrag")) {
459 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000460 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000461 } else if (R->isSubClassOf("Register")) {
Chris Lattnerab1bf272005-10-19 01:55:23 +0000462 //const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
463 // TODO: if a register appears in exactly one regclass, we could use that
464 // type info.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000465 return MVT::isUnknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000466 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
467 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000468 return MVT::Other;
469 } else if (R->getName() == "node") {
470 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000471 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000472 }
473
474 TP.error("Unknown node flavor used in pattern: " + R->getName());
475 return MVT::Other;
476}
477
Chris Lattner32707602005-09-08 23:22:48 +0000478/// ApplyTypeConstraints - Apply all of the type constraints relevent to
479/// this node and its children in the tree. This returns true if it makes a
480/// change, false otherwise. If a type contradiction is found, throw an
481/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000482bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
483 if (isLeaf()) {
484 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
485 // If it's a regclass or something else known, include the type.
486 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
487 TP);
488 return false;
489 }
Chris Lattner32707602005-09-08 23:22:48 +0000490
491 // special handling for set, which isn't really an SDNode.
492 if (getOperator()->getName() == "set") {
493 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000494 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
495 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000496
497 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000498 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
499 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000500 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
501 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000502 } else if (getOperator()->isSubClassOf("SDNode")) {
503 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
504
505 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
506 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000507 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000508 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000509 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000510 const DAGInstruction &Inst =
511 TP.getDAGISelEmitter().getInstruction(getOperator());
512
Chris Lattnera28aec12005-09-15 22:23:50 +0000513 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
514 // Apply the result type to the node
515 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
516
517 if (getNumChildren() != Inst.getNumOperands())
518 TP.error("Instruction '" + getOperator()->getName() + " expects " +
519 utostr(Inst.getNumOperands()) + " operands, not " +
520 utostr(getNumChildren()) + " operands!");
521 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
522 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000523 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000524 }
525 return MadeChange;
526 } else {
527 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
528
529 // Node transforms always take one operand, and take and return the same
530 // type.
531 if (getNumChildren() != 1)
532 TP.error("Node transform '" + getOperator()->getName() +
533 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000534 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
535 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000536 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000537 }
Chris Lattner32707602005-09-08 23:22:48 +0000538}
539
Chris Lattnere97603f2005-09-28 19:27:25 +0000540/// canPatternMatch - If it is impossible for this pattern to match on this
541/// target, fill in Reason and return false. Otherwise, return true. This is
542/// used as a santity check for .td files (to prevent people from writing stuff
543/// that can never possibly work), and to prevent the pattern permuter from
544/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000545bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000546 if (isLeaf()) return true;
547
548 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
549 if (!getChild(i)->canPatternMatch(Reason, ISE))
550 return false;
551
552 // If this node is a commutative operator, check that the LHS isn't an
553 // immediate.
554 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
555 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
556 // Scan all of the operands of the node and make sure that only the last one
557 // is a constant node.
558 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
559 if (!getChild(i)->isLeaf() &&
560 getChild(i)->getOperator()->getName() == "imm") {
561 Reason = "Immediate value must be on the RHS of commutative operators!";
562 return false;
563 }
564 }
565
566 return true;
567}
Chris Lattner32707602005-09-08 23:22:48 +0000568
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000569//===----------------------------------------------------------------------===//
570// TreePattern implementation
571//
572
Chris Lattneredbd8712005-10-21 01:19:59 +0000573TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000574 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000575 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000576 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
577 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000578}
579
Chris Lattneredbd8712005-10-21 01:19:59 +0000580TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000581 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000582 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000583 Trees.push_back(ParseTreePattern(Pat));
584}
585
Chris Lattneredbd8712005-10-21 01:19:59 +0000586TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000587 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000588 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000589 Trees.push_back(Pat);
590}
591
592
593
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000594void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000595 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000596 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000597}
598
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000599TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
600 Record *Operator = Dag->getNodeType();
601
602 if (Operator->isSubClassOf("ValueType")) {
603 // If the operator is a ValueType, then this must be "type cast" of a leaf
604 // node.
605 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000606 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000607
608 Init *Arg = Dag->getArg(0);
609 TreePatternNode *New;
610 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000611 Record *R = DI->getDef();
612 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
613 Dag->setArg(0, new DagInit(R,
614 std::vector<std::pair<Init*, std::string> >()));
615 TreePatternNode *TPN = ParseTreePattern(Dag);
616 TPN->setName(Dag->getArgName(0));
617 return TPN;
618 }
619
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000620 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000621 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
622 New = ParseTreePattern(DI);
623 } else {
624 Arg->dump();
625 error("Unknown leaf value for tree pattern!");
626 return 0;
627 }
628
Chris Lattner32707602005-09-08 23:22:48 +0000629 // Apply the type cast.
630 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000631 return New;
632 }
633
634 // Verify that this is something that makes sense for an operator.
635 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000636 !Operator->isSubClassOf("Instruction") &&
637 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000638 Operator->getName() != "set")
639 error("Unrecognized node '" + Operator->getName() + "'!");
640
Chris Lattneredbd8712005-10-21 01:19:59 +0000641 // Check to see if this is something that is illegal in an input pattern.
642 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
643 Operator->isSubClassOf("SDNodeXForm")))
644 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
645
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000646 std::vector<TreePatternNode*> Children;
647
648 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
649 Init *Arg = Dag->getArg(i);
650 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
651 Children.push_back(ParseTreePattern(DI));
652 Children.back()->setName(Dag->getArgName(i));
653 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
654 Record *R = DefI->getDef();
655 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
656 // TreePatternNode if its own.
657 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
658 Dag->setArg(i, new DagInit(R,
659 std::vector<std::pair<Init*, std::string> >()));
660 --i; // Revisit this node...
661 } else {
662 TreePatternNode *Node = new TreePatternNode(DefI);
663 Node->setName(Dag->getArgName(i));
664 Children.push_back(Node);
665
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000666 // Input argument?
667 if (R->getName() == "node") {
668 if (Dag->getArgName(i).empty())
669 error("'node' argument requires a name to match with operand list");
670 Args.push_back(Dag->getArgName(i));
671 }
672 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000673 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
674 TreePatternNode *Node = new TreePatternNode(II);
675 if (!Dag->getArgName(i).empty())
676 error("Constant int argument should not have a name!");
677 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000678 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000679 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000680 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000681 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000682 error("Unknown leaf value for tree pattern!");
683 }
684 }
685
686 return new TreePatternNode(Operator, Children);
687}
688
Chris Lattner32707602005-09-08 23:22:48 +0000689/// InferAllTypes - Infer/propagate as many types throughout the expression
690/// patterns as possible. Return true if all types are infered, false
691/// otherwise. Throw an exception if a type contradiction is found.
692bool TreePattern::InferAllTypes() {
693 bool MadeChange = true;
694 while (MadeChange) {
695 MadeChange = false;
696 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000697 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000698 }
699
700 bool HasUnresolvedTypes = false;
701 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
702 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
703 return !HasUnresolvedTypes;
704}
705
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000706void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000707 OS << getRecord()->getName();
708 if (!Args.empty()) {
709 OS << "(" << Args[0];
710 for (unsigned i = 1, e = Args.size(); i != e; ++i)
711 OS << ", " << Args[i];
712 OS << ")";
713 }
714 OS << ": ";
715
716 if (Trees.size() > 1)
717 OS << "[\n";
718 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
719 OS << "\t";
720 Trees[i]->print(OS);
721 OS << "\n";
722 }
723
724 if (Trees.size() > 1)
725 OS << "]\n";
726}
727
728void TreePattern::dump() const { print(std::cerr); }
729
730
731
732//===----------------------------------------------------------------------===//
733// DAGISelEmitter implementation
734//
735
Chris Lattnerca559d02005-09-08 21:03:01 +0000736// Parse all of the SDNode definitions for the target, populating SDNodes.
737void DAGISelEmitter::ParseNodeInfo() {
738 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
739 while (!Nodes.empty()) {
740 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
741 Nodes.pop_back();
742 }
743}
744
Chris Lattner24eeeb82005-09-13 21:51:00 +0000745/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
746/// map, and emit them to the file as functions.
747void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
748 OS << "\n// Node transformations.\n";
749 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
750 while (!Xforms.empty()) {
751 Record *XFormNode = Xforms.back();
752 Record *SDNode = XFormNode->getValueAsDef("Opcode");
753 std::string Code = XFormNode->getValueAsCode("XFormFunction");
754 SDNodeXForms.insert(std::make_pair(XFormNode,
755 std::make_pair(SDNode, Code)));
756
Chris Lattner1048b7a2005-09-13 22:03:37 +0000757 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000758 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
759 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
760
Chris Lattner1048b7a2005-09-13 22:03:37 +0000761 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000762 << "(SDNode *" << C2 << ") {\n";
763 if (ClassName != "SDNode")
764 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
765 OS << Code << "\n}\n";
766 }
767
768 Xforms.pop_back();
769 }
770}
771
772
773
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000774/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
775/// file, building up the PatternFragments map. After we've collected them all,
776/// inline fragments together as necessary, so that there are no references left
777/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000778///
779/// This also emits all of the predicate functions to the output file.
780///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000781void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000782 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
783
784 // First step, parse all of the fragments and emit predicate functions.
785 OS << "\n// Predicate functions.\n";
786 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000787 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000788 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000789 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000790
791 // Validate the argument list, converting it to map, to discard duplicates.
792 std::vector<std::string> &Args = P->getArgList();
793 std::set<std::string> OperandsMap(Args.begin(), Args.end());
794
795 if (OperandsMap.count(""))
796 P->error("Cannot have unnamed 'node' values in pattern fragment!");
797
798 // Parse the operands list.
799 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
800 if (OpsList->getNodeType()->getName() != "ops")
801 P->error("Operands list should start with '(ops ... '!");
802
803 // Copy over the arguments.
804 Args.clear();
805 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
806 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
807 static_cast<DefInit*>(OpsList->getArg(j))->
808 getDef()->getName() != "node")
809 P->error("Operands list should all be 'node' values.");
810 if (OpsList->getArgName(j).empty())
811 P->error("Operands list should have names for each operand!");
812 if (!OperandsMap.count(OpsList->getArgName(j)))
813 P->error("'" + OpsList->getArgName(j) +
814 "' does not occur in pattern or was multiply specified!");
815 OperandsMap.erase(OpsList->getArgName(j));
816 Args.push_back(OpsList->getArgName(j));
817 }
818
819 if (!OperandsMap.empty())
820 P->error("Operands list does not contain an entry for operand '" +
821 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000822
823 // If there is a code init for this fragment, emit the predicate code and
824 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000825 std::string Code = Fragments[i]->getValueAsCode("Predicate");
826 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000827 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000828 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000829 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000830 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
831
Chris Lattner1048b7a2005-09-13 22:03:37 +0000832 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000833 << "(SDNode *" << C2 << ") {\n";
834 if (ClassName != "SDNode")
835 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000836 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000837 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000838 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000839
840 // If there is a node transformation corresponding to this, keep track of
841 // it.
842 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
843 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000844 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000845 }
846
847 OS << "\n\n";
848
849 // Now that we've parsed all of the tree fragments, do a closure on them so
850 // that there are not references to PatFrags left inside of them.
851 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
852 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000853 TreePattern *ThePat = I->second;
854 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000855
Chris Lattner32707602005-09-08 23:22:48 +0000856 // Infer as many types as possible. Don't worry about it if we don't infer
857 // all of them, some may depend on the inputs of the pattern.
858 try {
859 ThePat->InferAllTypes();
860 } catch (...) {
861 // If this pattern fragment is not supported by this target (no types can
862 // satisfy its constraints), just ignore it. If the bogus pattern is
863 // actually used by instructions, the type consistency error will be
864 // reported there.
865 }
866
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000867 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000868 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000869 }
870}
871
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000872/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000873/// instruction input. Return true if this is a real use.
874static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000875 std::map<std::string, TreePatternNode*> &InstInputs) {
876 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000877 if (Pat->getName().empty()) {
878 if (Pat->isLeaf()) {
879 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
880 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
881 I->error("Input " + DI->getDef()->getName() + " must be named!");
882
883 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000884 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000885 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000886
887 Record *Rec;
888 if (Pat->isLeaf()) {
889 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
890 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
891 Rec = DI->getDef();
892 } else {
893 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
894 Rec = Pat->getOperator();
895 }
896
897 TreePatternNode *&Slot = InstInputs[Pat->getName()];
898 if (!Slot) {
899 Slot = Pat;
900 } else {
901 Record *SlotRec;
902 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000903 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000904 } else {
905 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
906 SlotRec = Slot->getOperator();
907 }
908
909 // Ensure that the inputs agree if we've already seen this input.
910 if (Rec != SlotRec)
911 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000912 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000913 I->error("All $" + Pat->getName() + " inputs must agree with each other");
914 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000915 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000916}
917
918/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
919/// part of "I", the instruction), computing the set of inputs and outputs of
920/// the pattern. Report errors if we see anything naughty.
921void DAGISelEmitter::
922FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
923 std::map<std::string, TreePatternNode*> &InstInputs,
924 std::map<std::string, Record*> &InstResults) {
925 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000926 bool isUse = HandleUse(I, Pat, InstInputs);
927 if (!isUse && Pat->getTransformFn())
928 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000929 return;
930 } else if (Pat->getOperator()->getName() != "set") {
931 // If this is not a set, verify that the children nodes are not void typed,
932 // and recurse.
933 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000934 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000935 I->error("Cannot have void nodes inside of patterns!");
936 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
937 }
938
939 // If this is a non-leaf node with no children, treat it basically as if
940 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000941 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000942 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000943 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000944
Chris Lattnerf1311842005-09-14 23:05:13 +0000945 if (!isUse && Pat->getTransformFn())
946 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000947 return;
948 }
949
950 // Otherwise, this is a set, validate and collect instruction results.
951 if (Pat->getNumChildren() == 0)
952 I->error("set requires operands!");
953 else if (Pat->getNumChildren() & 1)
954 I->error("set requires an even number of operands");
955
Chris Lattnerf1311842005-09-14 23:05:13 +0000956 if (Pat->getTransformFn())
957 I->error("Cannot specify a transform function on a set node!");
958
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000959 // Check the set destinations.
960 unsigned NumValues = Pat->getNumChildren()/2;
961 for (unsigned i = 0; i != NumValues; ++i) {
962 TreePatternNode *Dest = Pat->getChild(i);
963 if (!Dest->isLeaf())
964 I->error("set destination should be a virtual register!");
965
966 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
967 if (!Val)
968 I->error("set destination should be a virtual register!");
969
970 if (!Val->getDef()->isSubClassOf("RegisterClass"))
971 I->error("set destination should be a virtual register!");
972 if (Dest->getName().empty())
973 I->error("set destination must have a name!");
974 if (InstResults.count(Dest->getName()))
975 I->error("cannot set '" + Dest->getName() +"' multiple times");
976 InstResults[Dest->getName()] = Val->getDef();
977
978 // Verify and collect info from the computation.
979 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
980 InstInputs, InstResults);
981 }
982}
983
984
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000985/// ParseInstructions - Parse all of the instructions, inlining and resolving
986/// any fragments involved. This populates the Instructions list with fully
987/// resolved instructions.
988void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000989 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
990
991 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +0000992 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000993
Chris Lattner0c0cfa72005-10-19 01:27:22 +0000994 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
995 LI = Instrs[i]->getValueAsListInit("Pattern");
996
997 // If there is no pattern, only collect minimal information about the
998 // instruction for its operand list. We have to assume that there is one
999 // result, as we have no detailed info.
1000 if (!LI || LI->getSize() == 0) {
1001 std::vector<MVT::ValueType> ResultTypes;
1002 std::vector<MVT::ValueType> OperandTypes;
1003
1004 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1005
1006 // Doesn't even define a result?
1007 if (InstInfo.OperandList.size() == 0)
1008 continue;
1009
1010 // Assume the first operand is the result.
1011 ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1012
1013 // The rest are inputs.
1014 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1015 OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1016
1017 // Create and insert the instruction.
1018 Instructions.insert(std::make_pair(Instrs[i],
1019 DAGInstruction(0, ResultTypes, OperandTypes)));
1020 continue; // no pattern.
1021 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001022
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001023 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001024 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001025 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001026 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001027
Chris Lattner95f6b762005-09-08 23:26:30 +00001028 // Infer as many types as possible. If we cannot infer all of them, we can
1029 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001030 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001031 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001032
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001033 // InstInputs - Keep track of all of the inputs of the instruction, along
1034 // with the record they are declared as.
1035 std::map<std::string, TreePatternNode*> InstInputs;
1036
1037 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001038 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001039 std::map<std::string, Record*> InstResults;
1040
Chris Lattner1f39e292005-09-14 00:09:24 +00001041 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001042 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001043 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1044 TreePatternNode *Pat = I->getTree(j);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001045 if (Pat->getExtType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001046 I->dump();
1047 I->error("Top-level forms in instruction pattern should have"
1048 " void types");
1049 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001050
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001051 // Find inputs and outputs, and verify the structure of the uses/defs.
1052 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001053 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001054
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001055 // Now that we have inputs and outputs of the pattern, inspect the operands
1056 // list for the instruction. This determines the order that operands are
1057 // added to the machine instruction the node corresponds to.
1058 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001059
1060 // Parse the operands list from the (ops) list, validating it.
1061 std::vector<std::string> &Args = I->getArgList();
1062 assert(Args.empty() && "Args list should still be empty here!");
1063 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1064
1065 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +00001066 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +00001067 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001068 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001069 I->error("'" + InstResults.begin()->first +
1070 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001071 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001072
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001073 // Check that it exists in InstResults.
1074 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001075 if (R == 0)
1076 I->error("Operand $" + OpName + " should be a set destination: all "
1077 "outputs must occur before inputs in operand list!");
1078
1079 if (CGI.OperandList[i].Rec != R)
1080 I->error("Operand $" + OpName + " class mismatch!");
1081
Chris Lattnerae6d8282005-09-15 21:51:12 +00001082 // Remember the return type.
1083 ResultTypes.push_back(CGI.OperandList[i].Ty);
1084
Chris Lattner39e8af92005-09-14 18:19:25 +00001085 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001086 InstResults.erase(OpName);
1087 }
1088
Chris Lattner0b592252005-09-14 21:59:34 +00001089 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1090 // the copy while we're checking the inputs.
1091 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001092
1093 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +00001094 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001095 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1096 const std::string &OpName = CGI.OperandList[i].Name;
1097 if (OpName.empty())
1098 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1099
Chris Lattner0b592252005-09-14 21:59:34 +00001100 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001101 I->error("Operand $" + OpName +
1102 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001103 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001104 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001105 if (CGI.OperandList[i].Ty != InVal->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001106 I->error("Operand $" + OpName +
1107 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +00001108 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +00001109
Chris Lattner2175c182005-09-14 23:01:59 +00001110 // Construct the result for the dest-pattern operand list.
1111 TreePatternNode *OpNode = InVal->clone();
1112
1113 // No predicate is useful on the result.
1114 OpNode->setPredicateFn("");
1115
1116 // Promote the xform function to be an explicit node if set.
1117 if (Record *Xform = OpNode->getTransformFn()) {
1118 OpNode->setTransformFn(0);
1119 std::vector<TreePatternNode*> Children;
1120 Children.push_back(OpNode);
1121 OpNode = new TreePatternNode(Xform, Children);
1122 }
1123
1124 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001125 }
1126
Chris Lattner0b592252005-09-14 21:59:34 +00001127 if (!InstInputsCheck.empty())
1128 I->error("Input operand $" + InstInputsCheck.begin()->first +
1129 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001130
1131 TreePatternNode *ResultPattern =
1132 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001133
1134 // Create and insert the instruction.
1135 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1136 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1137
1138 // Use a temporary tree pattern to infer all types and make sure that the
1139 // constructed result is correct. This depends on the instruction already
1140 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001141 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001142 Temp.InferAllTypes();
1143
1144 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1145 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001146
Chris Lattner32707602005-09-08 23:22:48 +00001147 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001148 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001149
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001150 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001151 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1152 E = Instructions.end(); II != E; ++II) {
1153 TreePattern *I = II->second.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001154 if (I == 0) continue; // No pattern.
Chris Lattner1f39e292005-09-14 00:09:24 +00001155
1156 if (I->getNumTrees() != 1) {
1157 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1158 continue;
1159 }
1160 TreePatternNode *Pattern = I->getTree(0);
1161 if (Pattern->getOperator()->getName() != "set")
1162 continue; // Not a set (store or something?)
1163
1164 if (Pattern->getNumChildren() != 2)
1165 continue; // Not a set of a single value (not handled so far)
1166
1167 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001168
1169 std::string Reason;
1170 if (!SrcPattern->canPatternMatch(Reason, *this))
1171 I->error("Instruction can never match: " + Reason);
1172
Chris Lattnerae5b3502005-09-15 21:57:35 +00001173 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001174 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001175 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001176}
1177
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001178void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001179 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001180
Chris Lattnerabbb6052005-09-15 21:42:00 +00001181 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001182 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001183 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001184
Chris Lattnerabbb6052005-09-15 21:42:00 +00001185 // Inline pattern fragments into it.
1186 Pattern->InlinePatternFragments();
1187
1188 // Infer as many types as possible. If we cannot infer all of them, we can
1189 // never do anything with this pattern: report it to the user.
1190 if (!Pattern->InferAllTypes())
1191 Pattern->error("Could not infer all types in pattern!");
1192
1193 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1194 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001195
1196 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001197 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001198
1199 // Inline pattern fragments into it.
1200 Result->InlinePatternFragments();
1201
1202 // Infer as many types as possible. If we cannot infer all of them, we can
1203 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001204 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001205 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001206
1207 if (Result->getNumTrees() != 1)
1208 Result->error("Cannot handle instructions producing instructions "
1209 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001210
1211 std::string Reason;
1212 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1213 Pattern->error("Pattern can never match: " + Reason);
1214
Chris Lattnerabbb6052005-09-15 21:42:00 +00001215 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1216 Result->getOnlyTree()));
1217 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001218}
1219
Chris Lattnere46e17b2005-09-29 19:28:10 +00001220/// CombineChildVariants - Given a bunch of permutations of each child of the
1221/// 'operator' node, put them together in all possible ways.
1222static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001223 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001224 std::vector<TreePatternNode*> &OutVariants,
1225 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001226 // Make sure that each operand has at least one variant to choose from.
1227 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1228 if (ChildVariants[i].empty())
1229 return;
1230
Chris Lattnere46e17b2005-09-29 19:28:10 +00001231 // The end result is an all-pairs construction of the resultant pattern.
1232 std::vector<unsigned> Idxs;
1233 Idxs.resize(ChildVariants.size());
1234 bool NotDone = true;
1235 while (NotDone) {
1236 // Create the variant and add it to the output list.
1237 std::vector<TreePatternNode*> NewChildren;
1238 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1239 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1240 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1241
1242 // Copy over properties.
1243 R->setName(Orig->getName());
1244 R->setPredicateFn(Orig->getPredicateFn());
1245 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001246 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001247
1248 // If this pattern cannot every match, do not include it as a variant.
1249 std::string ErrString;
1250 if (!R->canPatternMatch(ErrString, ISE)) {
1251 delete R;
1252 } else {
1253 bool AlreadyExists = false;
1254
1255 // Scan to see if this pattern has already been emitted. We can get
1256 // duplication due to things like commuting:
1257 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1258 // which are the same pattern. Ignore the dups.
1259 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1260 if (R->isIsomorphicTo(OutVariants[i])) {
1261 AlreadyExists = true;
1262 break;
1263 }
1264
1265 if (AlreadyExists)
1266 delete R;
1267 else
1268 OutVariants.push_back(R);
1269 }
1270
1271 // Increment indices to the next permutation.
1272 NotDone = false;
1273 // Look for something we can increment without causing a wrap-around.
1274 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1275 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1276 NotDone = true; // Found something to increment.
1277 break;
1278 }
1279 Idxs[IdxsIdx] = 0;
1280 }
1281 }
1282}
1283
Chris Lattneraf302912005-09-29 22:36:54 +00001284/// CombineChildVariants - A helper function for binary operators.
1285///
1286static void CombineChildVariants(TreePatternNode *Orig,
1287 const std::vector<TreePatternNode*> &LHS,
1288 const std::vector<TreePatternNode*> &RHS,
1289 std::vector<TreePatternNode*> &OutVariants,
1290 DAGISelEmitter &ISE) {
1291 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1292 ChildVariants.push_back(LHS);
1293 ChildVariants.push_back(RHS);
1294 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1295}
1296
1297
1298static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1299 std::vector<TreePatternNode *> &Children) {
1300 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1301 Record *Operator = N->getOperator();
1302
1303 // Only permit raw nodes.
1304 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1305 N->getTransformFn()) {
1306 Children.push_back(N);
1307 return;
1308 }
1309
1310 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1311 Children.push_back(N->getChild(0));
1312 else
1313 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1314
1315 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1316 Children.push_back(N->getChild(1));
1317 else
1318 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1319}
1320
Chris Lattnere46e17b2005-09-29 19:28:10 +00001321/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1322/// the (potentially recursive) pattern by using algebraic laws.
1323///
1324static void GenerateVariantsOf(TreePatternNode *N,
1325 std::vector<TreePatternNode*> &OutVariants,
1326 DAGISelEmitter &ISE) {
1327 // We cannot permute leaves.
1328 if (N->isLeaf()) {
1329 OutVariants.push_back(N);
1330 return;
1331 }
1332
1333 // Look up interesting info about the node.
1334 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1335
1336 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001337 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1338 // Reassociate by pulling together all of the linked operators
1339 std::vector<TreePatternNode*> MaximalChildren;
1340 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1341
1342 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1343 // permutations.
1344 if (MaximalChildren.size() == 3) {
1345 // Find the variants of all of our maximal children.
1346 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1347 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1348 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1349 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1350
1351 // There are only two ways we can permute the tree:
1352 // (A op B) op C and A op (B op C)
1353 // Within these forms, we can also permute A/B/C.
1354
1355 // Generate legal pair permutations of A/B/C.
1356 std::vector<TreePatternNode*> ABVariants;
1357 std::vector<TreePatternNode*> BAVariants;
1358 std::vector<TreePatternNode*> ACVariants;
1359 std::vector<TreePatternNode*> CAVariants;
1360 std::vector<TreePatternNode*> BCVariants;
1361 std::vector<TreePatternNode*> CBVariants;
1362 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1363 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1364 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1365 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1366 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1367 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1368
1369 // Combine those into the result: (x op x) op x
1370 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1371 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1372 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1373 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1374 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1375 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1376
1377 // Combine those into the result: x op (x op x)
1378 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1379 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1380 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1381 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1382 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1383 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1384 return;
1385 }
1386 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001387
1388 // Compute permutations of all children.
1389 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1390 ChildVariants.resize(N->getNumChildren());
1391 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1392 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1393
1394 // Build all permutations based on how the children were formed.
1395 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1396
1397 // If this node is commutative, consider the commuted order.
1398 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1399 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001400 // Consider the commuted order.
1401 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1402 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001403 }
1404}
1405
1406
Chris Lattnere97603f2005-09-28 19:27:25 +00001407// GenerateVariants - Generate variants. For example, commutative patterns can
1408// match multiple ways. Add them to PatternsToMatch as well.
1409void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001410
1411 DEBUG(std::cerr << "Generating instruction variants.\n");
1412
1413 // Loop over all of the patterns we've collected, checking to see if we can
1414 // generate variants of the instruction, through the exploitation of
1415 // identities. This permits the target to provide agressive matching without
1416 // the .td file having to contain tons of variants of instructions.
1417 //
1418 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1419 // intentionally do not reconsider these. Any variants of added patterns have
1420 // already been added.
1421 //
1422 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1423 std::vector<TreePatternNode*> Variants;
1424 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1425
1426 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001427 Variants.erase(Variants.begin()); // Remove the original pattern.
1428
1429 if (Variants.empty()) // No variants for this pattern.
1430 continue;
1431
1432 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1433 PatternsToMatch[i].first->dump();
1434 std::cerr << "\n");
1435
1436 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1437 TreePatternNode *Variant = Variants[v];
1438
1439 DEBUG(std::cerr << " VAR#" << v << ": ";
1440 Variant->dump();
1441 std::cerr << "\n");
1442
1443 // Scan to see if an instruction or explicit pattern already matches this.
1444 bool AlreadyExists = false;
1445 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1446 // Check to see if this variant already exists.
1447 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1448 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1449 AlreadyExists = true;
1450 break;
1451 }
1452 }
1453 // If we already have it, ignore the variant.
1454 if (AlreadyExists) continue;
1455
1456 // Otherwise, add it to the list of patterns we have.
1457 PatternsToMatch.push_back(std::make_pair(Variant,
1458 PatternsToMatch[i].second));
1459 }
1460
1461 DEBUG(std::cerr << "\n");
1462 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001463}
1464
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001465
Chris Lattner05814af2005-09-28 17:57:56 +00001466/// getPatternSize - Return the 'size' of this pattern. We want to match large
1467/// patterns before small ones. This is used to determine the size of a
1468/// pattern.
1469static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001470 assert(isExtIntegerVT(P->getExtType()) ||
1471 isExtFloatingPointVT(P->getExtType()) &&
Chris Lattner05814af2005-09-28 17:57:56 +00001472 "Not a valid pattern node to size!");
1473 unsigned Size = 1; // The node itself.
1474
1475 // Count children in the count if they are also nodes.
1476 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1477 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001478 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001479 Size += getPatternSize(Child);
Chris Lattner2f041d42005-10-19 04:41:05 +00001480 else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1481 ++Size; // Matches a ConstantSDNode.
1482 }
Chris Lattner05814af2005-09-28 17:57:56 +00001483 }
1484
1485 return Size;
1486}
1487
1488/// getResultPatternCost - Compute the number of instructions for this pattern.
1489/// This is a temporary hack. We should really include the instruction
1490/// latencies in this calculation.
1491static unsigned getResultPatternCost(TreePatternNode *P) {
1492 if (P->isLeaf()) return 0;
1493
1494 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1495 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1496 Cost += getResultPatternCost(P->getChild(i));
1497 return Cost;
1498}
1499
1500// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1501// In particular, we want to match maximal patterns first and lowest cost within
1502// a particular complexity first.
1503struct PatternSortingPredicate {
1504 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1505 DAGISelEmitter::PatternToMatch *RHS) {
1506 unsigned LHSSize = getPatternSize(LHS->first);
1507 unsigned RHSSize = getPatternSize(RHS->first);
1508 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1509 if (LHSSize < RHSSize) return false;
1510
1511 // If the patterns have equal complexity, compare generated instruction cost
1512 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1513 }
1514};
1515
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001516/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1517/// if the match fails. At this point, we already know that the opcode for N
1518/// matches, and the SDNode for the result has the RootName specified name.
1519void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001520 const std::string &RootName,
1521 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001522 unsigned PatternNo, std::ostream &OS) {
1523 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001524
1525 // If this node has a name associated with it, capture it in VarMap. If
1526 // we already saw this in the pattern, emit code to verify dagness.
1527 if (!N->getName().empty()) {
1528 std::string &VarMapEntry = VarMap[N->getName()];
1529 if (VarMapEntry.empty()) {
1530 VarMapEntry = RootName;
1531 } else {
1532 // If we get here, this is a second reference to a specific name. Since
1533 // we already have checked that the first reference is valid, we don't
1534 // have to recursively match it, just check that it's the same as the
1535 // previously named thing.
1536 OS << " if (" << VarMapEntry << " != " << RootName
1537 << ") goto P" << PatternNo << "Fail;\n";
1538 return;
1539 }
1540 }
1541
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001542 // Emit code to load the child nodes and match their contents recursively.
1543 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001544 OS << " SDOperand " << RootName << i <<" = " << RootName
1545 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001546 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001547
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001548 if (!Child->isLeaf()) {
1549 // If it's not a leaf, recursively match.
1550 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001551 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001552 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001553 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001554 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001555 // If this child has a name associated with it, capture it in VarMap. If
1556 // we already saw this in the pattern, emit code to verify dagness.
1557 if (!Child->getName().empty()) {
1558 std::string &VarMapEntry = VarMap[Child->getName()];
1559 if (VarMapEntry.empty()) {
1560 VarMapEntry = RootName + utostr(i);
1561 } else {
1562 // If we get here, this is a second reference to a specific name. Since
1563 // we already have checked that the first reference is valid, we don't
1564 // have to recursively match it, just check that it's the same as the
1565 // previously named thing.
1566 OS << " if (" << VarMapEntry << " != " << RootName << i
1567 << ") goto P" << PatternNo << "Fail;\n";
1568 continue;
1569 }
1570 }
1571
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001572 // Handle leaves of various types.
Chris Lattner2f041d42005-10-19 04:41:05 +00001573 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1574 Record *LeafRec = DI->getDef();
1575 if (LeafRec->isSubClassOf("RegisterClass")) {
1576 // Handle register references. Nothing to do here.
1577 } else if (LeafRec->isSubClassOf("ValueType")) {
1578 // Make sure this is the specified value type.
1579 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1580 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1581 << "Fail;\n";
Chris Lattner1531f202005-10-26 16:59:37 +00001582 } else if (LeafRec->isSubClassOf("CondCode")) {
1583 // Make sure this is the specified cond code.
1584 OS << " if (cast<CondCodeSDNode>(" << RootName << i
Chris Lattnera7ad1982005-10-26 17:02:02 +00001585 << ")->get() != " << "ISD::" << LeafRec->getName()
Chris Lattner1531f202005-10-26 16:59:37 +00001586 << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner2f041d42005-10-19 04:41:05 +00001587 } else {
1588 Child->dump();
1589 assert(0 && "Unknown leaf type!");
1590 }
1591 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1592 OS << " if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1593 << " cast<ConstantSDNode>(" << RootName << i
1594 << ")->getValue() != " << II->getValue() << ")\n"
1595 << " goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001596 } else {
1597 Child->dump();
1598 assert(0 && "Unknown leaf type!");
1599 }
1600 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001601 }
1602
1603 // If there is a node predicate for this, emit the call.
1604 if (!N->getPredicateFn().empty())
1605 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001606 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001607}
1608
Chris Lattner6bc7e512005-09-26 21:53:26 +00001609/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1610/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001611unsigned DAGISelEmitter::
1612CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1613 std::map<std::string,std::string> &VariableMap,
Chris Lattner5024d932005-10-16 01:41:58 +00001614 std::ostream &OS, bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001615 // This is something selected from the pattern we matched.
1616 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001617 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001618 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001619 assert(!Val.empty() &&
1620 "Variable referenced but not defined and not caught earlier!");
1621 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1622 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001623 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001624 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001625
1626 unsigned ResNo = Ctr++;
1627 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1628 switch (N->getType()) {
1629 default: assert(0 && "Unknown type for constant node!");
1630 case MVT::i1: OS << " bool Tmp"; break;
1631 case MVT::i8: OS << " unsigned char Tmp"; break;
1632 case MVT::i16: OS << " unsigned short Tmp"; break;
1633 case MVT::i32: OS << " unsigned Tmp"; break;
1634 case MVT::i64: OS << " uint64_t Tmp"; break;
1635 }
1636 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1637 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1638 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1639 } else {
1640 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1641 }
1642 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1643 // value if used multiple times by this pattern result.
1644 Val = "Tmp"+utostr(ResNo);
1645 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001646 }
1647
1648 if (N->isLeaf()) {
Chris Lattner4c593092005-10-19 02:07:26 +00001649 // If this is an explicit register reference, handle it.
1650 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1651 unsigned ResNo = Ctr++;
1652 if (DI->getDef()->isSubClassOf("Register")) {
1653 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1654 << getQualifiedName(DI->getDef()) << ", MVT::"
1655 << getEnumName(N->getType())
1656 << ");\n";
1657 return ResNo;
1658 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001659 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1660 unsigned ResNo = Ctr++;
1661 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1662 << II->getValue() << ", MVT::"
1663 << getEnumName(N->getType())
1664 << ");\n";
1665 return ResNo;
Chris Lattner4c593092005-10-19 02:07:26 +00001666 }
1667
Chris Lattner72fe91c2005-09-24 00:40:24 +00001668 N->dump();
1669 assert(0 && "Unknown leaf type!");
1670 return ~0U;
1671 }
1672
1673 Record *Op = N->getOperator();
1674 if (Op->isSubClassOf("Instruction")) {
1675 // Emit all of the operands.
1676 std::vector<unsigned> Ops;
1677 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1678 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1679
1680 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1681 unsigned ResNo = Ctr++;
1682
Chris Lattner5024d932005-10-16 01:41:58 +00001683 if (!isRoot) {
1684 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1685 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1686 << getEnumName(N->getType());
1687 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1688 OS << ", Tmp" << Ops[i];
1689 OS << ");\n";
1690 } else {
1691 // If this instruction is the root, and if there is only one use of it,
1692 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1693 OS << " if (N.Val->hasOneUse()) {\n";
1694 OS << " CurDAG->SelectNodeTo(N.Val, "
1695 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1696 << getEnumName(N->getType());
1697 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1698 OS << ", Tmp" << Ops[i];
1699 OS << ");\n";
1700 OS << " return N;\n";
1701 OS << " } else {\n";
1702 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1703 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1704 << getEnumName(N->getType());
1705 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1706 OS << ", Tmp" << Ops[i];
1707 OS << ");\n";
1708 OS << " }\n";
1709 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001710 return ResNo;
1711 } else if (Op->isSubClassOf("SDNodeXForm")) {
1712 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1713 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1714
1715 unsigned ResNo = Ctr++;
1716 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1717 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001718 if (isRoot) {
1719 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1720 OS << " return Tmp" << ResNo << ";\n";
1721 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001722 return ResNo;
1723 } else {
1724 N->dump();
1725 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001726 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001727 }
1728}
1729
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001730/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1731/// type information from it.
1732static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001733 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001734 if (!N->isLeaf())
1735 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1736 RemoveAllTypes(N->getChild(i));
1737}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001738
Chris Lattner7e82f132005-10-15 21:34:21 +00001739/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1740/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1741/// 'Pat' may be missing types. If we find an unresolved type to add a check
1742/// for, this returns true otherwise false if Pat has all types.
1743static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1744 const std::string &Prefix, unsigned PatternNo,
1745 std::ostream &OS) {
1746 // Did we find one?
1747 if (!Pat->hasTypeSet()) {
1748 // Move a type over from 'other' to 'pat'.
1749 Pat->setType(Other->getType());
1750 OS << " if (" << Prefix << ".getValueType() != MVT::"
1751 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1752 return true;
1753 } else if (Pat->isLeaf()) {
1754 return false;
1755 }
1756
1757 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1758 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1759 Prefix + utostr(i), PatternNo, OS))
1760 return true;
1761 return false;
1762}
1763
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001764/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1765/// stream to match the pattern, and generate the code for the match if it
1766/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001767void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1768 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001769 static unsigned PatternCount = 0;
1770 unsigned PatternNo = PatternCount++;
1771 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001772 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001773 OS << "\n // Emits: ";
1774 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001775 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001776 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1777 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001778
Chris Lattner8fc35682005-09-23 23:16:51 +00001779 // Emit the matcher, capturing named arguments in VariableMap.
1780 std::map<std::string,std::string> VariableMap;
1781 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001782
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001783 // TP - Get *SOME* tree pattern, we don't care which.
1784 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001785
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001786 // At this point, we know that we structurally match the pattern, but the
1787 // types of the nodes may not match. Figure out the fewest number of type
1788 // comparisons we need to emit. For example, if there is only one integer
1789 // type supported by a target, there should be no type comparisons at all for
1790 // integer patterns!
1791 //
1792 // To figure out the fewest number of type checks needed, clone the pattern,
1793 // remove the types, then perform type inference on the pattern as a whole.
1794 // If there are unresolved types, emit an explicit check for those types,
1795 // apply the type to the tree, then rerun type inference. Iterate until all
1796 // types are resolved.
1797 //
1798 TreePatternNode *Pat = Pattern.first->clone();
1799 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001800
1801 do {
1802 // Resolve/propagate as many types as possible.
1803 try {
1804 bool MadeChange = true;
1805 while (MadeChange)
1806 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1807 } catch (...) {
1808 assert(0 && "Error: could not find consistent types for something we"
1809 " already decided was ok!");
1810 abort();
1811 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001812
Chris Lattner7e82f132005-10-15 21:34:21 +00001813 // Insert a check for an unresolved type and add it to the tree. If we find
1814 // an unresolved type to add a check for, this returns true and we iterate,
1815 // otherwise we are done.
1816 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001817
Chris Lattner5024d932005-10-16 01:41:58 +00001818 unsigned TmpNo = 0;
1819 CodeGenPatternResult(Pattern.second, TmpNo,
1820 VariableMap, OS, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001821 delete Pat;
1822
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001823 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001824}
1825
Chris Lattner37481472005-09-26 21:59:35 +00001826
1827namespace {
1828 /// CompareByRecordName - An ordering predicate that implements less-than by
1829 /// comparing the names records.
1830 struct CompareByRecordName {
1831 bool operator()(const Record *LHS, const Record *RHS) const {
1832 // Sort by name first.
1833 if (LHS->getName() < RHS->getName()) return true;
1834 // If both names are equal, sort by pointer.
1835 return LHS->getName() == RHS->getName() && LHS < RHS;
1836 }
1837 };
1838}
1839
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001840void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001841 std::string InstNS = Target.inst_begin()->second.Namespace;
1842 if (!InstNS.empty()) InstNS += "::";
1843
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001844 // Emit boilerplate.
1845 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001846 << "SDOperand SelectCode(SDOperand N) {\n"
1847 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001848 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1849 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001850 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001851 << " if (!N.Val->hasOneUse()) {\n"
1852 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1853 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1854 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001855 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001856 << " default: break;\n"
1857 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001858 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001859 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001860 << " case ISD::AssertZext: {\n"
1861 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1862 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1863 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001864 << " }\n"
1865 << " case ISD::TokenFactor:\n"
1866 << " if (N.getNumOperands() == 2) {\n"
1867 << " SDOperand Op0 = Select(N.getOperand(0));\n"
1868 << " SDOperand Op1 = Select(N.getOperand(1));\n"
1869 << " return CodeGenMap[N] =\n"
1870 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
1871 << " } else {\n"
1872 << " std::vector<SDOperand> Ops;\n"
1873 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1874 << " Ops.push_back(Select(N.getOperand(i)));\n"
1875 << " return CodeGenMap[N] = \n"
1876 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
1877 << " }\n"
1878 << " case ISD::CopyFromReg: {\n"
1879 << " SDOperand Chain = Select(N.getOperand(0));\n"
1880 << " if (Chain == N.getOperand(0)) return N; // No change\n"
1881 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
1882 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
1883 << " N.Val->getValueType(0));\n"
1884 << " return New.getValue(N.ResNo);\n"
1885 << " }\n"
1886 << " case ISD::CopyToReg: {\n"
1887 << " SDOperand Chain = Select(N.getOperand(0));\n"
1888 << " SDOperand Reg = N.getOperand(1);\n"
1889 << " SDOperand Val = Select(N.getOperand(2));\n"
1890 << " return CodeGenMap[N] = \n"
1891 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
1892 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001893 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001894
Chris Lattner81303322005-09-23 19:36:15 +00001895 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001896 std::map<Record*, std::vector<PatternToMatch*>,
1897 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001898 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1899 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1900 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001901
Chris Lattner3f7e9142005-09-23 20:52:47 +00001902 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001903 for (std::map<Record*, std::vector<PatternToMatch*>,
1904 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1905 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001906 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1907 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1908
1909 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001910
1911 // We want to emit all of the matching code now. However, we want to emit
1912 // the matches in order of minimal cost. Sort the patterns so the least
1913 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001914 std::stable_sort(Patterns.begin(), Patterns.end(),
1915 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001916
Chris Lattner3f7e9142005-09-23 20:52:47 +00001917 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1918 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001919 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001920 }
1921
1922
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001923 OS << " } // end of big switch.\n\n"
1924 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001925 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001926 << " std::cerr << '\\n';\n"
1927 << " abort();\n"
1928 << "}\n";
1929}
1930
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001931void DAGISelEmitter::run(std::ostream &OS) {
1932 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1933 " target", OS);
1934
Chris Lattner1f39e292005-09-14 00:09:24 +00001935 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1936 << "// *** instruction selector class. These functions are really "
1937 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001938
Chris Lattner296dfe32005-09-24 00:50:51 +00001939 OS << "// Instance var to keep track of multiply used nodes that have \n"
1940 << "// already been selected.\n"
1941 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1942
Chris Lattnerca559d02005-09-08 21:03:01 +00001943 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001944 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001945 ParsePatternFragments(OS);
1946 ParseInstructions();
1947 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001948
Chris Lattnere97603f2005-09-28 19:27:25 +00001949 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001950 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001951 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001952
Chris Lattnere46e17b2005-09-29 19:28:10 +00001953
1954 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1955 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1956 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1957 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1958 std::cerr << "\n";
1959 });
1960
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001961 // At this point, we have full information about the 'Patterns' we need to
1962 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001963 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001964 EmitInstructionSelector(OS);
1965
1966 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1967 E = PatternFragments.end(); I != E; ++I)
1968 delete I->second;
1969 PatternFragments.clear();
1970
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001971 Instructions.clear();
1972}