blob: a560bf01977433647fea967e3bfa0d5f59e8464a [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 Lattnerb0e103d2005-10-28 22:49:02 +0000231 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000232 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 Lattnerb0e103d2005-10-28 22:49:02 +0000246 std::vector<Record*> ConstraintList =
247 TypeProfile->getValueAsListOfDefs("Constraints");
248 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000249}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000250
251//===----------------------------------------------------------------------===//
252// TreePatternNode implementation
253//
254
255TreePatternNode::~TreePatternNode() {
256#if 0 // FIXME: implement refcounted tree nodes!
257 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
258 delete getChild(i);
259#endif
260}
261
Chris Lattner32707602005-09-08 23:22:48 +0000262/// UpdateNodeType - Set the node type of N to VT if VT contains
263/// information. If N already contains a conflicting type, then throw an
264/// exception. This returns true if any information was updated.
265///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000266bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
267 if (VT == MVT::isUnknown || getExtType() == VT) return false;
268 if (getExtType() == MVT::isUnknown) {
Chris Lattner32707602005-09-08 23:22:48 +0000269 setType(VT);
270 return true;
271 }
272
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000273 // If we are told this is to be an int or FP type, and it already is, ignore
274 // the advice.
275 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
276 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
277 return false;
278
279 // If we know this is an int or fp type, and we are told it is a specific one,
280 // take the advice.
281 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
282 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
283 setType(VT);
284 return true;
285 }
286
Chris Lattner1531f202005-10-26 16:59:37 +0000287 if (isLeaf()) {
288 dump();
289 TP.error("Type inference contradiction found in node!");
290 } else {
291 TP.error("Type inference contradiction found in node " +
292 getOperator()->getName() + "!");
293 }
Chris Lattner32707602005-09-08 23:22:48 +0000294 return true; // unreachable
295}
296
297
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000298void TreePatternNode::print(std::ostream &OS) const {
299 if (isLeaf()) {
300 OS << *getLeafValue();
301 } else {
302 OS << "(" << getOperator()->getName();
303 }
304
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000305 switch (getExtType()) {
306 case MVT::Other: OS << ":Other"; break;
307 case MVT::isInt: OS << ":isInt"; break;
308 case MVT::isFP : OS << ":isFP"; break;
309 case MVT::isUnknown: ; /*OS << ":?";*/ break;
310 default: OS << ":" << getType(); break;
311 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000312
313 if (!isLeaf()) {
314 if (getNumChildren() != 0) {
315 OS << " ";
316 getChild(0)->print(OS);
317 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
318 OS << ", ";
319 getChild(i)->print(OS);
320 }
321 }
322 OS << ")";
323 }
324
325 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000326 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000327 if (TransformFn)
328 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000329 if (!getName().empty())
330 OS << ":$" << getName();
331
332}
333void TreePatternNode::dump() const {
334 print(std::cerr);
335}
336
Chris Lattnere46e17b2005-09-29 19:28:10 +0000337/// isIsomorphicTo - Return true if this node is recursively isomorphic to
338/// the specified node. For this comparison, all of the state of the node
339/// is considered, except for the assigned name. Nodes with differing names
340/// that are otherwise identical are considered isomorphic.
341bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
342 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000343 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000344 getPredicateFn() != N->getPredicateFn() ||
345 getTransformFn() != N->getTransformFn())
346 return false;
347
348 if (isLeaf()) {
349 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
350 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
351 return DI->getDef() == NDI->getDef();
352 return getLeafValue() == N->getLeafValue();
353 }
354
355 if (N->getOperator() != getOperator() ||
356 N->getNumChildren() != getNumChildren()) return false;
357 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
358 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
359 return false;
360 return true;
361}
362
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000363/// clone - Make a copy of this tree and all of its children.
364///
365TreePatternNode *TreePatternNode::clone() const {
366 TreePatternNode *New;
367 if (isLeaf()) {
368 New = new TreePatternNode(getLeafValue());
369 } else {
370 std::vector<TreePatternNode*> CChildren;
371 CChildren.reserve(Children.size());
372 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
373 CChildren.push_back(getChild(i)->clone());
374 New = new TreePatternNode(getOperator(), CChildren);
375 }
376 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000377 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000378 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000379 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000380 return New;
381}
382
Chris Lattner32707602005-09-08 23:22:48 +0000383/// SubstituteFormalArguments - Replace the formal arguments in this tree
384/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000385void TreePatternNode::
386SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
387 if (isLeaf()) return;
388
389 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
390 TreePatternNode *Child = getChild(i);
391 if (Child->isLeaf()) {
392 Init *Val = Child->getLeafValue();
393 if (dynamic_cast<DefInit*>(Val) &&
394 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
395 // We found a use of a formal argument, replace it with its value.
396 Child = ArgMap[Child->getName()];
397 assert(Child && "Couldn't find formal argument!");
398 setChild(i, Child);
399 }
400 } else {
401 getChild(i)->SubstituteFormalArguments(ArgMap);
402 }
403 }
404}
405
406
407/// InlinePatternFragments - If this pattern refers to any pattern
408/// fragments, inline them into place, giving us a pattern without any
409/// PatFrag references.
410TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
411 if (isLeaf()) return this; // nothing to do.
412 Record *Op = getOperator();
413
414 if (!Op->isSubClassOf("PatFrag")) {
415 // Just recursively inline children nodes.
416 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
417 setChild(i, getChild(i)->InlinePatternFragments(TP));
418 return this;
419 }
420
421 // Otherwise, we found a reference to a fragment. First, look up its
422 // TreePattern record.
423 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
424
425 // Verify that we are passing the right number of operands.
426 if (Frag->getNumArgs() != Children.size())
427 TP.error("'" + Op->getName() + "' fragment requires " +
428 utostr(Frag->getNumArgs()) + " operands!");
429
Chris Lattner37937092005-09-09 01:15:01 +0000430 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000431
432 // Resolve formal arguments to their actual value.
433 if (Frag->getNumArgs()) {
434 // Compute the map of formal to actual arguments.
435 std::map<std::string, TreePatternNode*> ArgMap;
436 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
437 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
438
439 FragTree->SubstituteFormalArguments(ArgMap);
440 }
441
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000442 FragTree->setName(getName());
443
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000444 // Get a new copy of this fragment to stitch into here.
445 //delete this; // FIXME: implement refcounting!
446 return FragTree;
447}
448
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000449/// getIntrinsicType - Check to see if the specified record has an intrinsic
450/// type which should be applied to it. This infer the type of register
451/// references from the register file information, for example.
452///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000453static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
454 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000455 // Check to see if this is a register or a register class...
456 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000457 if (NotRegisters) return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000458 return getValueType(R->getValueAsDef("RegType"));
459 } else if (R->isSubClassOf("PatFrag")) {
460 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000461 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000462 } else if (R->isSubClassOf("Register")) {
Chris Lattnerab1bf272005-10-19 01:55:23 +0000463 //const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
464 // TODO: if a register appears in exactly one regclass, we could use that
465 // type info.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000466 return MVT::isUnknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000467 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
468 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000469 return MVT::Other;
470 } else if (R->getName() == "node") {
471 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000472 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000473 }
474
475 TP.error("Unknown node flavor used in pattern: " + R->getName());
476 return MVT::Other;
477}
478
Chris Lattner32707602005-09-08 23:22:48 +0000479/// ApplyTypeConstraints - Apply all of the type constraints relevent to
480/// this node and its children in the tree. This returns true if it makes a
481/// change, false otherwise. If a type contradiction is found, throw an
482/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000483bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
484 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000485 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000486 // If it's a regclass or something else known, include the type.
487 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
488 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000489 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
490 // Int inits are always integers. :)
491 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
492
493 if (hasTypeSet()) {
494 unsigned Size = MVT::getSizeInBits(getType());
495 // Make sure that the value is representable for this type.
496 if (Size < 32) {
497 int Val = (II->getValue() << (32-Size)) >> (32-Size);
498 if (Val != II->getValue())
499 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
500 "' is out of range for type 'MVT::" +
501 getEnumName(getType()) + "'!");
502 }
503 }
504
505 return MadeChange;
506 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000507 return false;
508 }
Chris Lattner32707602005-09-08 23:22:48 +0000509
510 // special handling for set, which isn't really an SDNode.
511 if (getOperator()->getName() == "set") {
512 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000513 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
514 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000515
516 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000517 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
518 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000519 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
520 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000521 } else if (getOperator()->isSubClassOf("SDNode")) {
522 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
523
524 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
525 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000526 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000527 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000528 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000529 const DAGInstruction &Inst =
530 TP.getDAGISelEmitter().getInstruction(getOperator());
531
Chris Lattnera28aec12005-09-15 22:23:50 +0000532 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
533 // Apply the result type to the node
534 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
535
536 if (getNumChildren() != Inst.getNumOperands())
537 TP.error("Instruction '" + getOperator()->getName() + " expects " +
538 utostr(Inst.getNumOperands()) + " operands, not " +
539 utostr(getNumChildren()) + " operands!");
540 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
541 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000542 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000543 }
544 return MadeChange;
545 } else {
546 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
547
548 // Node transforms always take one operand, and take and return the same
549 // type.
550 if (getNumChildren() != 1)
551 TP.error("Node transform '" + getOperator()->getName() +
552 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000553 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
554 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000555 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000556 }
Chris Lattner32707602005-09-08 23:22:48 +0000557}
558
Chris Lattnere97603f2005-09-28 19:27:25 +0000559/// canPatternMatch - If it is impossible for this pattern to match on this
560/// target, fill in Reason and return false. Otherwise, return true. This is
561/// used as a santity check for .td files (to prevent people from writing stuff
562/// that can never possibly work), and to prevent the pattern permuter from
563/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000564bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000565 if (isLeaf()) return true;
566
567 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
568 if (!getChild(i)->canPatternMatch(Reason, ISE))
569 return false;
570
571 // If this node is a commutative operator, check that the LHS isn't an
572 // immediate.
573 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
574 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
575 // Scan all of the operands of the node and make sure that only the last one
576 // is a constant node.
577 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
578 if (!getChild(i)->isLeaf() &&
579 getChild(i)->getOperator()->getName() == "imm") {
580 Reason = "Immediate value must be on the RHS of commutative operators!";
581 return false;
582 }
583 }
584
585 return true;
586}
Chris Lattner32707602005-09-08 23:22:48 +0000587
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000588//===----------------------------------------------------------------------===//
589// TreePattern implementation
590//
591
Chris Lattneredbd8712005-10-21 01:19:59 +0000592TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000593 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000594 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000595 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
596 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000597}
598
Chris Lattneredbd8712005-10-21 01:19:59 +0000599TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000600 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000601 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000602 Trees.push_back(ParseTreePattern(Pat));
603}
604
Chris Lattneredbd8712005-10-21 01:19:59 +0000605TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000606 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000607 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000608 Trees.push_back(Pat);
609}
610
611
612
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000613void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000614 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000615 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000616}
617
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000618TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
619 Record *Operator = Dag->getNodeType();
620
621 if (Operator->isSubClassOf("ValueType")) {
622 // If the operator is a ValueType, then this must be "type cast" of a leaf
623 // node.
624 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000625 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000626
627 Init *Arg = Dag->getArg(0);
628 TreePatternNode *New;
629 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000630 Record *R = DI->getDef();
631 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
632 Dag->setArg(0, new DagInit(R,
633 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000634 return ParseTreePattern(Dag);
Chris Lattner72fe91c2005-09-24 00:40:24 +0000635 }
636
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000637 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000638 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
639 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000640 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
641 New = new TreePatternNode(II);
642 if (!Dag->getArgName(0).empty())
643 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000644 } else {
645 Arg->dump();
646 error("Unknown leaf value for tree pattern!");
647 return 0;
648 }
649
Chris Lattner32707602005-09-08 23:22:48 +0000650 // Apply the type cast.
651 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000652 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000653 return New;
654 }
655
656 // Verify that this is something that makes sense for an operator.
657 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000658 !Operator->isSubClassOf("Instruction") &&
659 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000660 Operator->getName() != "set")
661 error("Unrecognized node '" + Operator->getName() + "'!");
662
Chris Lattneredbd8712005-10-21 01:19:59 +0000663 // Check to see if this is something that is illegal in an input pattern.
664 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
665 Operator->isSubClassOf("SDNodeXForm")))
666 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
667
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000668 std::vector<TreePatternNode*> Children;
669
670 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
671 Init *Arg = Dag->getArg(i);
672 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
673 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000674 if (Children.back()->getName().empty())
675 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000676 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
677 Record *R = DefI->getDef();
678 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
679 // TreePatternNode if its own.
680 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
681 Dag->setArg(i, new DagInit(R,
682 std::vector<std::pair<Init*, std::string> >()));
683 --i; // Revisit this node...
684 } else {
685 TreePatternNode *Node = new TreePatternNode(DefI);
686 Node->setName(Dag->getArgName(i));
687 Children.push_back(Node);
688
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000689 // Input argument?
690 if (R->getName() == "node") {
691 if (Dag->getArgName(i).empty())
692 error("'node' argument requires a name to match with operand list");
693 Args.push_back(Dag->getArgName(i));
694 }
695 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000696 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
697 TreePatternNode *Node = new TreePatternNode(II);
698 if (!Dag->getArgName(i).empty())
699 error("Constant int argument should not have a name!");
700 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000701 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000702 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000703 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000704 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000705 error("Unknown leaf value for tree pattern!");
706 }
707 }
708
709 return new TreePatternNode(Operator, Children);
710}
711
Chris Lattner32707602005-09-08 23:22:48 +0000712/// InferAllTypes - Infer/propagate as many types throughout the expression
713/// patterns as possible. Return true if all types are infered, false
714/// otherwise. Throw an exception if a type contradiction is found.
715bool TreePattern::InferAllTypes() {
716 bool MadeChange = true;
717 while (MadeChange) {
718 MadeChange = false;
719 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000720 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000721 }
722
723 bool HasUnresolvedTypes = false;
724 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
725 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
726 return !HasUnresolvedTypes;
727}
728
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000729void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000730 OS << getRecord()->getName();
731 if (!Args.empty()) {
732 OS << "(" << Args[0];
733 for (unsigned i = 1, e = Args.size(); i != e; ++i)
734 OS << ", " << Args[i];
735 OS << ")";
736 }
737 OS << ": ";
738
739 if (Trees.size() > 1)
740 OS << "[\n";
741 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
742 OS << "\t";
743 Trees[i]->print(OS);
744 OS << "\n";
745 }
746
747 if (Trees.size() > 1)
748 OS << "]\n";
749}
750
751void TreePattern::dump() const { print(std::cerr); }
752
753
754
755//===----------------------------------------------------------------------===//
756// DAGISelEmitter implementation
757//
758
Chris Lattnerca559d02005-09-08 21:03:01 +0000759// Parse all of the SDNode definitions for the target, populating SDNodes.
760void DAGISelEmitter::ParseNodeInfo() {
761 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
762 while (!Nodes.empty()) {
763 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
764 Nodes.pop_back();
765 }
766}
767
Chris Lattner24eeeb82005-09-13 21:51:00 +0000768/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
769/// map, and emit them to the file as functions.
770void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
771 OS << "\n// Node transformations.\n";
772 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
773 while (!Xforms.empty()) {
774 Record *XFormNode = Xforms.back();
775 Record *SDNode = XFormNode->getValueAsDef("Opcode");
776 std::string Code = XFormNode->getValueAsCode("XFormFunction");
777 SDNodeXForms.insert(std::make_pair(XFormNode,
778 std::make_pair(SDNode, Code)));
779
Chris Lattner1048b7a2005-09-13 22:03:37 +0000780 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000781 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
782 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
783
Chris Lattner1048b7a2005-09-13 22:03:37 +0000784 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000785 << "(SDNode *" << C2 << ") {\n";
786 if (ClassName != "SDNode")
787 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
788 OS << Code << "\n}\n";
789 }
790
791 Xforms.pop_back();
792 }
793}
794
795
796
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000797/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
798/// file, building up the PatternFragments map. After we've collected them all,
799/// inline fragments together as necessary, so that there are no references left
800/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000801///
802/// This also emits all of the predicate functions to the output file.
803///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000804void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000805 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
806
807 // First step, parse all of the fragments and emit predicate functions.
808 OS << "\n// Predicate functions.\n";
809 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000810 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000811 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000812 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000813
814 // Validate the argument list, converting it to map, to discard duplicates.
815 std::vector<std::string> &Args = P->getArgList();
816 std::set<std::string> OperandsMap(Args.begin(), Args.end());
817
818 if (OperandsMap.count(""))
819 P->error("Cannot have unnamed 'node' values in pattern fragment!");
820
821 // Parse the operands list.
822 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
823 if (OpsList->getNodeType()->getName() != "ops")
824 P->error("Operands list should start with '(ops ... '!");
825
826 // Copy over the arguments.
827 Args.clear();
828 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
829 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
830 static_cast<DefInit*>(OpsList->getArg(j))->
831 getDef()->getName() != "node")
832 P->error("Operands list should all be 'node' values.");
833 if (OpsList->getArgName(j).empty())
834 P->error("Operands list should have names for each operand!");
835 if (!OperandsMap.count(OpsList->getArgName(j)))
836 P->error("'" + OpsList->getArgName(j) +
837 "' does not occur in pattern or was multiply specified!");
838 OperandsMap.erase(OpsList->getArgName(j));
839 Args.push_back(OpsList->getArgName(j));
840 }
841
842 if (!OperandsMap.empty())
843 P->error("Operands list does not contain an entry for operand '" +
844 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000845
846 // If there is a code init for this fragment, emit the predicate code and
847 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000848 std::string Code = Fragments[i]->getValueAsCode("Predicate");
849 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000850 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000851 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000852 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000853 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
854
Chris Lattner1048b7a2005-09-13 22:03:37 +0000855 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000856 << "(SDNode *" << C2 << ") {\n";
857 if (ClassName != "SDNode")
858 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000859 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000860 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000861 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000862
863 // If there is a node transformation corresponding to this, keep track of
864 // it.
865 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
866 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000867 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000868 }
869
870 OS << "\n\n";
871
872 // Now that we've parsed all of the tree fragments, do a closure on them so
873 // that there are not references to PatFrags left inside of them.
874 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
875 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000876 TreePattern *ThePat = I->second;
877 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000878
Chris Lattner32707602005-09-08 23:22:48 +0000879 // Infer as many types as possible. Don't worry about it if we don't infer
880 // all of them, some may depend on the inputs of the pattern.
881 try {
882 ThePat->InferAllTypes();
883 } catch (...) {
884 // If this pattern fragment is not supported by this target (no types can
885 // satisfy its constraints), just ignore it. If the bogus pattern is
886 // actually used by instructions, the type consistency error will be
887 // reported there.
888 }
889
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000890 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000891 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000892 }
893}
894
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000895/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000896/// instruction input. Return true if this is a real use.
897static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000898 std::map<std::string, TreePatternNode*> &InstInputs) {
899 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000900 if (Pat->getName().empty()) {
901 if (Pat->isLeaf()) {
902 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
903 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
904 I->error("Input " + DI->getDef()->getName() + " must be named!");
905
906 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000907 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000908 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000909
910 Record *Rec;
911 if (Pat->isLeaf()) {
912 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
913 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
914 Rec = DI->getDef();
915 } else {
916 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
917 Rec = Pat->getOperator();
918 }
919
920 TreePatternNode *&Slot = InstInputs[Pat->getName()];
921 if (!Slot) {
922 Slot = Pat;
923 } else {
924 Record *SlotRec;
925 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000926 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000927 } else {
928 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
929 SlotRec = Slot->getOperator();
930 }
931
932 // Ensure that the inputs agree if we've already seen this input.
933 if (Rec != SlotRec)
934 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000935 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000936 I->error("All $" + Pat->getName() + " inputs must agree with each other");
937 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000938 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000939}
940
941/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
942/// part of "I", the instruction), computing the set of inputs and outputs of
943/// the pattern. Report errors if we see anything naughty.
944void DAGISelEmitter::
945FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
946 std::map<std::string, TreePatternNode*> &InstInputs,
947 std::map<std::string, Record*> &InstResults) {
948 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000949 bool isUse = HandleUse(I, Pat, InstInputs);
950 if (!isUse && Pat->getTransformFn())
951 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000952 return;
953 } else if (Pat->getOperator()->getName() != "set") {
954 // If this is not a set, verify that the children nodes are not void typed,
955 // and recurse.
956 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000957 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000958 I->error("Cannot have void nodes inside of patterns!");
959 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
960 }
961
962 // If this is a non-leaf node with no children, treat it basically as if
963 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000964 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000965 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000966 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000967
Chris Lattnerf1311842005-09-14 23:05:13 +0000968 if (!isUse && Pat->getTransformFn())
969 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000970 return;
971 }
972
973 // Otherwise, this is a set, validate and collect instruction results.
974 if (Pat->getNumChildren() == 0)
975 I->error("set requires operands!");
976 else if (Pat->getNumChildren() & 1)
977 I->error("set requires an even number of operands");
978
Chris Lattnerf1311842005-09-14 23:05:13 +0000979 if (Pat->getTransformFn())
980 I->error("Cannot specify a transform function on a set node!");
981
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000982 // Check the set destinations.
983 unsigned NumValues = Pat->getNumChildren()/2;
984 for (unsigned i = 0; i != NumValues; ++i) {
985 TreePatternNode *Dest = Pat->getChild(i);
986 if (!Dest->isLeaf())
987 I->error("set destination should be a virtual register!");
988
989 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
990 if (!Val)
991 I->error("set destination should be a virtual register!");
992
993 if (!Val->getDef()->isSubClassOf("RegisterClass"))
994 I->error("set destination should be a virtual register!");
995 if (Dest->getName().empty())
996 I->error("set destination must have a name!");
997 if (InstResults.count(Dest->getName()))
998 I->error("cannot set '" + Dest->getName() +"' multiple times");
999 InstResults[Dest->getName()] = Val->getDef();
1000
1001 // Verify and collect info from the computation.
1002 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1003 InstInputs, InstResults);
1004 }
1005}
1006
1007
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001008/// ParseInstructions - Parse all of the instructions, inlining and resolving
1009/// any fragments involved. This populates the Instructions list with fully
1010/// resolved instructions.
1011void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001012 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1013
1014 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001015 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001016
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001017 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1018 LI = Instrs[i]->getValueAsListInit("Pattern");
1019
1020 // If there is no pattern, only collect minimal information about the
1021 // instruction for its operand list. We have to assume that there is one
1022 // result, as we have no detailed info.
1023 if (!LI || LI->getSize() == 0) {
1024 std::vector<MVT::ValueType> ResultTypes;
1025 std::vector<MVT::ValueType> OperandTypes;
1026
1027 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1028
1029 // Doesn't even define a result?
1030 if (InstInfo.OperandList.size() == 0)
1031 continue;
1032
1033 // Assume the first operand is the result.
1034 ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1035
1036 // The rest are inputs.
1037 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1038 OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1039
1040 // Create and insert the instruction.
1041 Instructions.insert(std::make_pair(Instrs[i],
1042 DAGInstruction(0, ResultTypes, OperandTypes)));
1043 continue; // no pattern.
1044 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001045
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001046 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001047 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001048 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001049 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001050
Chris Lattner95f6b762005-09-08 23:26:30 +00001051 // Infer as many types as possible. If we cannot infer all of them, we can
1052 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001053 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001054 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001055
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001056 // InstInputs - Keep track of all of the inputs of the instruction, along
1057 // with the record they are declared as.
1058 std::map<std::string, TreePatternNode*> InstInputs;
1059
1060 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001061 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001062 std::map<std::string, Record*> InstResults;
1063
Chris Lattner1f39e292005-09-14 00:09:24 +00001064 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001065 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001066 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1067 TreePatternNode *Pat = I->getTree(j);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001068 if (Pat->getExtType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001069 I->dump();
1070 I->error("Top-level forms in instruction pattern should have"
1071 " void types");
1072 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001073
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001074 // Find inputs and outputs, and verify the structure of the uses/defs.
1075 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001076 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001077
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001078 // Now that we have inputs and outputs of the pattern, inspect the operands
1079 // list for the instruction. This determines the order that operands are
1080 // added to the machine instruction the node corresponds to.
1081 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001082
1083 // Parse the operands list from the (ops) list, validating it.
1084 std::vector<std::string> &Args = I->getArgList();
1085 assert(Args.empty() && "Args list should still be empty here!");
1086 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1087
1088 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +00001089 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +00001090 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001091 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001092 I->error("'" + InstResults.begin()->first +
1093 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001094 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001095
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001096 // Check that it exists in InstResults.
1097 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001098 if (R == 0)
1099 I->error("Operand $" + OpName + " should be a set destination: all "
1100 "outputs must occur before inputs in operand list!");
1101
1102 if (CGI.OperandList[i].Rec != R)
1103 I->error("Operand $" + OpName + " class mismatch!");
1104
Chris Lattnerae6d8282005-09-15 21:51:12 +00001105 // Remember the return type.
1106 ResultTypes.push_back(CGI.OperandList[i].Ty);
1107
Chris Lattner39e8af92005-09-14 18:19:25 +00001108 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001109 InstResults.erase(OpName);
1110 }
1111
Chris Lattner0b592252005-09-14 21:59:34 +00001112 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1113 // the copy while we're checking the inputs.
1114 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001115
1116 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +00001117 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001118 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1119 const std::string &OpName = CGI.OperandList[i].Name;
1120 if (OpName.empty())
1121 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1122
Chris Lattner0b592252005-09-14 21:59:34 +00001123 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001124 I->error("Operand $" + OpName +
1125 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001126 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001127 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001128 if (CGI.OperandList[i].Ty != InVal->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001129 I->error("Operand $" + OpName +
1130 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +00001131 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +00001132
Chris Lattner2175c182005-09-14 23:01:59 +00001133 // Construct the result for the dest-pattern operand list.
1134 TreePatternNode *OpNode = InVal->clone();
1135
1136 // No predicate is useful on the result.
1137 OpNode->setPredicateFn("");
1138
1139 // Promote the xform function to be an explicit node if set.
1140 if (Record *Xform = OpNode->getTransformFn()) {
1141 OpNode->setTransformFn(0);
1142 std::vector<TreePatternNode*> Children;
1143 Children.push_back(OpNode);
1144 OpNode = new TreePatternNode(Xform, Children);
1145 }
1146
1147 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001148 }
1149
Chris Lattner0b592252005-09-14 21:59:34 +00001150 if (!InstInputsCheck.empty())
1151 I->error("Input operand $" + InstInputsCheck.begin()->first +
1152 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001153
1154 TreePatternNode *ResultPattern =
1155 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001156
1157 // Create and insert the instruction.
1158 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1159 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1160
1161 // Use a temporary tree pattern to infer all types and make sure that the
1162 // constructed result is correct. This depends on the instruction already
1163 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001164 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001165 Temp.InferAllTypes();
1166
1167 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1168 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001169
Chris Lattner32707602005-09-08 23:22:48 +00001170 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001171 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001172
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001173 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001174 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1175 E = Instructions.end(); II != E; ++II) {
1176 TreePattern *I = II->second.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001177 if (I == 0) continue; // No pattern.
Chris Lattner1f39e292005-09-14 00:09:24 +00001178
1179 if (I->getNumTrees() != 1) {
1180 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1181 continue;
1182 }
1183 TreePatternNode *Pattern = I->getTree(0);
1184 if (Pattern->getOperator()->getName() != "set")
1185 continue; // Not a set (store or something?)
1186
1187 if (Pattern->getNumChildren() != 2)
1188 continue; // Not a set of a single value (not handled so far)
1189
1190 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001191
1192 std::string Reason;
1193 if (!SrcPattern->canPatternMatch(Reason, *this))
1194 I->error("Instruction can never match: " + Reason);
1195
Chris Lattnerae5b3502005-09-15 21:57:35 +00001196 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001197 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001198 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001199}
1200
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001201void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001202 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001203
Chris Lattnerabbb6052005-09-15 21:42:00 +00001204 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001205 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001206 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001207
Chris Lattnerabbb6052005-09-15 21:42:00 +00001208 // Inline pattern fragments into it.
1209 Pattern->InlinePatternFragments();
1210
1211 // Infer as many types as possible. If we cannot infer all of them, we can
1212 // never do anything with this pattern: report it to the user.
1213 if (!Pattern->InferAllTypes())
1214 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001215
1216 // Validate that the input pattern is correct.
1217 {
1218 std::map<std::string, TreePatternNode*> InstInputs;
1219 std::map<std::string, Record*> InstResults;
1220 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1221 InstInputs, InstResults);
1222 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001223
1224 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1225 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001226
1227 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001228 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001229
1230 // Inline pattern fragments into it.
1231 Result->InlinePatternFragments();
1232
1233 // Infer as many types as possible. If we cannot infer all of them, we can
1234 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001235 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001236 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001237
1238 if (Result->getNumTrees() != 1)
1239 Result->error("Cannot handle instructions producing instructions "
1240 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001241
1242 std::string Reason;
1243 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1244 Pattern->error("Pattern can never match: " + Reason);
1245
Chris Lattnerabbb6052005-09-15 21:42:00 +00001246 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1247 Result->getOnlyTree()));
1248 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001249}
1250
Chris Lattnere46e17b2005-09-29 19:28:10 +00001251/// CombineChildVariants - Given a bunch of permutations of each child of the
1252/// 'operator' node, put them together in all possible ways.
1253static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001254 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001255 std::vector<TreePatternNode*> &OutVariants,
1256 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001257 // Make sure that each operand has at least one variant to choose from.
1258 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1259 if (ChildVariants[i].empty())
1260 return;
1261
Chris Lattnere46e17b2005-09-29 19:28:10 +00001262 // The end result is an all-pairs construction of the resultant pattern.
1263 std::vector<unsigned> Idxs;
1264 Idxs.resize(ChildVariants.size());
1265 bool NotDone = true;
1266 while (NotDone) {
1267 // Create the variant and add it to the output list.
1268 std::vector<TreePatternNode*> NewChildren;
1269 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1270 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1271 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1272
1273 // Copy over properties.
1274 R->setName(Orig->getName());
1275 R->setPredicateFn(Orig->getPredicateFn());
1276 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001277 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001278
1279 // If this pattern cannot every match, do not include it as a variant.
1280 std::string ErrString;
1281 if (!R->canPatternMatch(ErrString, ISE)) {
1282 delete R;
1283 } else {
1284 bool AlreadyExists = false;
1285
1286 // Scan to see if this pattern has already been emitted. We can get
1287 // duplication due to things like commuting:
1288 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1289 // which are the same pattern. Ignore the dups.
1290 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1291 if (R->isIsomorphicTo(OutVariants[i])) {
1292 AlreadyExists = true;
1293 break;
1294 }
1295
1296 if (AlreadyExists)
1297 delete R;
1298 else
1299 OutVariants.push_back(R);
1300 }
1301
1302 // Increment indices to the next permutation.
1303 NotDone = false;
1304 // Look for something we can increment without causing a wrap-around.
1305 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1306 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1307 NotDone = true; // Found something to increment.
1308 break;
1309 }
1310 Idxs[IdxsIdx] = 0;
1311 }
1312 }
1313}
1314
Chris Lattneraf302912005-09-29 22:36:54 +00001315/// CombineChildVariants - A helper function for binary operators.
1316///
1317static void CombineChildVariants(TreePatternNode *Orig,
1318 const std::vector<TreePatternNode*> &LHS,
1319 const std::vector<TreePatternNode*> &RHS,
1320 std::vector<TreePatternNode*> &OutVariants,
1321 DAGISelEmitter &ISE) {
1322 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1323 ChildVariants.push_back(LHS);
1324 ChildVariants.push_back(RHS);
1325 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1326}
1327
1328
1329static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1330 std::vector<TreePatternNode *> &Children) {
1331 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1332 Record *Operator = N->getOperator();
1333
1334 // Only permit raw nodes.
1335 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1336 N->getTransformFn()) {
1337 Children.push_back(N);
1338 return;
1339 }
1340
1341 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1342 Children.push_back(N->getChild(0));
1343 else
1344 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1345
1346 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1347 Children.push_back(N->getChild(1));
1348 else
1349 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1350}
1351
Chris Lattnere46e17b2005-09-29 19:28:10 +00001352/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1353/// the (potentially recursive) pattern by using algebraic laws.
1354///
1355static void GenerateVariantsOf(TreePatternNode *N,
1356 std::vector<TreePatternNode*> &OutVariants,
1357 DAGISelEmitter &ISE) {
1358 // We cannot permute leaves.
1359 if (N->isLeaf()) {
1360 OutVariants.push_back(N);
1361 return;
1362 }
1363
1364 // Look up interesting info about the node.
1365 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1366
1367 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001368 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1369 // Reassociate by pulling together all of the linked operators
1370 std::vector<TreePatternNode*> MaximalChildren;
1371 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1372
1373 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1374 // permutations.
1375 if (MaximalChildren.size() == 3) {
1376 // Find the variants of all of our maximal children.
1377 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1378 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1379 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1380 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1381
1382 // There are only two ways we can permute the tree:
1383 // (A op B) op C and A op (B op C)
1384 // Within these forms, we can also permute A/B/C.
1385
1386 // Generate legal pair permutations of A/B/C.
1387 std::vector<TreePatternNode*> ABVariants;
1388 std::vector<TreePatternNode*> BAVariants;
1389 std::vector<TreePatternNode*> ACVariants;
1390 std::vector<TreePatternNode*> CAVariants;
1391 std::vector<TreePatternNode*> BCVariants;
1392 std::vector<TreePatternNode*> CBVariants;
1393 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1394 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1395 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1396 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1397 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1398 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1399
1400 // Combine those into the result: (x op x) op x
1401 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1402 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1403 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1404 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1405 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1406 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1407
1408 // Combine those into the result: x op (x op x)
1409 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1410 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1411 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1412 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1413 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1414 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1415 return;
1416 }
1417 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001418
1419 // Compute permutations of all children.
1420 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1421 ChildVariants.resize(N->getNumChildren());
1422 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1423 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1424
1425 // Build all permutations based on how the children were formed.
1426 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1427
1428 // If this node is commutative, consider the commuted order.
1429 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1430 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001431 // Consider the commuted order.
1432 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1433 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001434 }
1435}
1436
1437
Chris Lattnere97603f2005-09-28 19:27:25 +00001438// GenerateVariants - Generate variants. For example, commutative patterns can
1439// match multiple ways. Add them to PatternsToMatch as well.
1440void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001441
1442 DEBUG(std::cerr << "Generating instruction variants.\n");
1443
1444 // Loop over all of the patterns we've collected, checking to see if we can
1445 // generate variants of the instruction, through the exploitation of
1446 // identities. This permits the target to provide agressive matching without
1447 // the .td file having to contain tons of variants of instructions.
1448 //
1449 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1450 // intentionally do not reconsider these. Any variants of added patterns have
1451 // already been added.
1452 //
1453 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1454 std::vector<TreePatternNode*> Variants;
1455 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1456
1457 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001458 Variants.erase(Variants.begin()); // Remove the original pattern.
1459
1460 if (Variants.empty()) // No variants for this pattern.
1461 continue;
1462
1463 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1464 PatternsToMatch[i].first->dump();
1465 std::cerr << "\n");
1466
1467 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1468 TreePatternNode *Variant = Variants[v];
1469
1470 DEBUG(std::cerr << " VAR#" << v << ": ";
1471 Variant->dump();
1472 std::cerr << "\n");
1473
1474 // Scan to see if an instruction or explicit pattern already matches this.
1475 bool AlreadyExists = false;
1476 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1477 // Check to see if this variant already exists.
1478 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1479 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1480 AlreadyExists = true;
1481 break;
1482 }
1483 }
1484 // If we already have it, ignore the variant.
1485 if (AlreadyExists) continue;
1486
1487 // Otherwise, add it to the list of patterns we have.
1488 PatternsToMatch.push_back(std::make_pair(Variant,
1489 PatternsToMatch[i].second));
1490 }
1491
1492 DEBUG(std::cerr << "\n");
1493 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001494}
1495
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001496
Chris Lattner05814af2005-09-28 17:57:56 +00001497/// getPatternSize - Return the 'size' of this pattern. We want to match large
1498/// patterns before small ones. This is used to determine the size of a
1499/// pattern.
1500static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001501 assert(isExtIntegerVT(P->getExtType()) ||
1502 isExtFloatingPointVT(P->getExtType()) &&
Chris Lattner05814af2005-09-28 17:57:56 +00001503 "Not a valid pattern node to size!");
1504 unsigned Size = 1; // The node itself.
1505
1506 // Count children in the count if they are also nodes.
1507 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1508 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001509 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001510 Size += getPatternSize(Child);
Chris Lattner2f041d42005-10-19 04:41:05 +00001511 else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1512 ++Size; // Matches a ConstantSDNode.
1513 }
Chris Lattner05814af2005-09-28 17:57:56 +00001514 }
1515
1516 return Size;
1517}
1518
1519/// getResultPatternCost - Compute the number of instructions for this pattern.
1520/// This is a temporary hack. We should really include the instruction
1521/// latencies in this calculation.
1522static unsigned getResultPatternCost(TreePatternNode *P) {
1523 if (P->isLeaf()) return 0;
1524
1525 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1526 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1527 Cost += getResultPatternCost(P->getChild(i));
1528 return Cost;
1529}
1530
1531// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1532// In particular, we want to match maximal patterns first and lowest cost within
1533// a particular complexity first.
1534struct PatternSortingPredicate {
1535 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1536 DAGISelEmitter::PatternToMatch *RHS) {
1537 unsigned LHSSize = getPatternSize(LHS->first);
1538 unsigned RHSSize = getPatternSize(RHS->first);
1539 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1540 if (LHSSize < RHSSize) return false;
1541
1542 // If the patterns have equal complexity, compare generated instruction cost
1543 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1544 }
1545};
1546
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001547/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1548/// if the match fails. At this point, we already know that the opcode for N
1549/// matches, and the SDNode for the result has the RootName specified name.
1550void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001551 const std::string &RootName,
1552 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001553 unsigned PatternNo, std::ostream &OS) {
Chris Lattner0614b622005-11-02 06:49:14 +00001554 if (N->isLeaf()) {
1555 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1556 OS << " if (cast<ConstantSDNode>(" << RootName
1557 << ")->getSignExtended() != " << II->getValue() << ")\n"
1558 << " goto P" << PatternNo << "Fail;\n";
1559 return;
1560 }
1561 assert(0 && "Cannot match this as a leaf value!");
1562 abort();
1563 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001564
1565 // If this node has a name associated with it, capture it in VarMap. If
1566 // we already saw this in the pattern, emit code to verify dagness.
1567 if (!N->getName().empty()) {
1568 std::string &VarMapEntry = VarMap[N->getName()];
1569 if (VarMapEntry.empty()) {
1570 VarMapEntry = RootName;
1571 } else {
1572 // If we get here, this is a second reference to a specific name. Since
1573 // we already have checked that the first reference is valid, we don't
1574 // have to recursively match it, just check that it's the same as the
1575 // previously named thing.
1576 OS << " if (" << VarMapEntry << " != " << RootName
1577 << ") goto P" << PatternNo << "Fail;\n";
1578 return;
1579 }
1580 }
1581
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001582 // Emit code to load the child nodes and match their contents recursively.
1583 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001584 OS << " SDOperand " << RootName << i <<" = " << RootName
1585 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001586 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001587
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001588 if (!Child->isLeaf()) {
1589 // If it's not a leaf, recursively match.
1590 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001591 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001592 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001593 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001594 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001595 // If this child has a name associated with it, capture it in VarMap. If
1596 // we already saw this in the pattern, emit code to verify dagness.
1597 if (!Child->getName().empty()) {
1598 std::string &VarMapEntry = VarMap[Child->getName()];
1599 if (VarMapEntry.empty()) {
1600 VarMapEntry = RootName + utostr(i);
1601 } else {
1602 // If we get here, this is a second reference to a specific name. Since
1603 // we already have checked that the first reference is valid, we don't
1604 // have to recursively match it, just check that it's the same as the
1605 // previously named thing.
1606 OS << " if (" << VarMapEntry << " != " << RootName << i
1607 << ") goto P" << PatternNo << "Fail;\n";
1608 continue;
1609 }
1610 }
1611
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001612 // Handle leaves of various types.
Chris Lattner2f041d42005-10-19 04:41:05 +00001613 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1614 Record *LeafRec = DI->getDef();
1615 if (LeafRec->isSubClassOf("RegisterClass")) {
1616 // Handle register references. Nothing to do here.
1617 } else if (LeafRec->isSubClassOf("ValueType")) {
1618 // Make sure this is the specified value type.
1619 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1620 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1621 << "Fail;\n";
Chris Lattner1531f202005-10-26 16:59:37 +00001622 } else if (LeafRec->isSubClassOf("CondCode")) {
1623 // Make sure this is the specified cond code.
1624 OS << " if (cast<CondCodeSDNode>(" << RootName << i
Chris Lattnera7ad1982005-10-26 17:02:02 +00001625 << ")->get() != " << "ISD::" << LeafRec->getName()
Chris Lattner1531f202005-10-26 16:59:37 +00001626 << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner2f041d42005-10-19 04:41:05 +00001627 } else {
1628 Child->dump();
1629 assert(0 && "Unknown leaf type!");
1630 }
1631 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1632 OS << " if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1633 << " cast<ConstantSDNode>(" << RootName << i
Chris Lattner9d1a0232005-10-29 16:39:40 +00001634 << ")->getSignExtended() != " << II->getValue() << ")\n"
Chris Lattner2f041d42005-10-19 04:41:05 +00001635 << " goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001636 } else {
1637 Child->dump();
1638 assert(0 && "Unknown leaf type!");
1639 }
1640 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001641 }
1642
1643 // If there is a node predicate for this, emit the call.
1644 if (!N->getPredicateFn().empty())
1645 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001646 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001647}
1648
Chris Lattner6bc7e512005-09-26 21:53:26 +00001649/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1650/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001651unsigned DAGISelEmitter::
1652CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1653 std::map<std::string,std::string> &VariableMap,
Chris Lattner5024d932005-10-16 01:41:58 +00001654 std::ostream &OS, bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001655 // This is something selected from the pattern we matched.
1656 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001657 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001658 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001659 assert(!Val.empty() &&
1660 "Variable referenced but not defined and not caught earlier!");
1661 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1662 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001663 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001664 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001665
1666 unsigned ResNo = Ctr++;
1667 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1668 switch (N->getType()) {
1669 default: assert(0 && "Unknown type for constant node!");
1670 case MVT::i1: OS << " bool Tmp"; break;
1671 case MVT::i8: OS << " unsigned char Tmp"; break;
1672 case MVT::i16: OS << " unsigned short Tmp"; break;
1673 case MVT::i32: OS << " unsigned Tmp"; break;
1674 case MVT::i64: OS << " uint64_t Tmp"; break;
1675 }
1676 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1677 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1678 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
Chris Lattnerb120a642005-11-17 07:39:45 +00001679 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1680 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Chris Lattnerf6f94162005-09-28 16:58:06 +00001681 } else {
1682 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1683 }
1684 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1685 // value if used multiple times by this pattern result.
1686 Val = "Tmp"+utostr(ResNo);
1687 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001688 }
1689
1690 if (N->isLeaf()) {
Chris Lattner4c593092005-10-19 02:07:26 +00001691 // If this is an explicit register reference, handle it.
1692 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1693 unsigned ResNo = Ctr++;
1694 if (DI->getDef()->isSubClassOf("Register")) {
1695 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1696 << getQualifiedName(DI->getDef()) << ", MVT::"
1697 << getEnumName(N->getType())
1698 << ");\n";
1699 return ResNo;
1700 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001701 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1702 unsigned ResNo = Ctr++;
1703 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1704 << II->getValue() << ", MVT::"
1705 << getEnumName(N->getType())
1706 << ");\n";
1707 return ResNo;
Chris Lattner4c593092005-10-19 02:07:26 +00001708 }
1709
Chris Lattner72fe91c2005-09-24 00:40:24 +00001710 N->dump();
1711 assert(0 && "Unknown leaf type!");
1712 return ~0U;
1713 }
1714
1715 Record *Op = N->getOperator();
1716 if (Op->isSubClassOf("Instruction")) {
1717 // Emit all of the operands.
1718 std::vector<unsigned> Ops;
1719 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1720 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1721
1722 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1723 unsigned ResNo = Ctr++;
1724
Chris Lattner5024d932005-10-16 01:41:58 +00001725 if (!isRoot) {
1726 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1727 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1728 << getEnumName(N->getType());
1729 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1730 OS << ", Tmp" << Ops[i];
1731 OS << ");\n";
1732 } else {
1733 // If this instruction is the root, and if there is only one use of it,
1734 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1735 OS << " if (N.Val->hasOneUse()) {\n";
1736 OS << " CurDAG->SelectNodeTo(N.Val, "
1737 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1738 << getEnumName(N->getType());
1739 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1740 OS << ", Tmp" << Ops[i];
1741 OS << ");\n";
1742 OS << " return N;\n";
1743 OS << " } else {\n";
1744 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1745 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1746 << getEnumName(N->getType());
1747 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1748 OS << ", Tmp" << Ops[i];
1749 OS << ");\n";
1750 OS << " }\n";
1751 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001752 return ResNo;
1753 } else if (Op->isSubClassOf("SDNodeXForm")) {
1754 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1755 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1756
1757 unsigned ResNo = Ctr++;
1758 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1759 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001760 if (isRoot) {
1761 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1762 OS << " return Tmp" << ResNo << ";\n";
1763 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001764 return ResNo;
1765 } else {
1766 N->dump();
1767 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001768 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001769 }
1770}
1771
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001772/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1773/// type information from it.
1774static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001775 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001776 if (!N->isLeaf())
1777 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1778 RemoveAllTypes(N->getChild(i));
1779}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001780
Chris Lattner7e82f132005-10-15 21:34:21 +00001781/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1782/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1783/// 'Pat' may be missing types. If we find an unresolved type to add a check
1784/// for, this returns true otherwise false if Pat has all types.
1785static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1786 const std::string &Prefix, unsigned PatternNo,
1787 std::ostream &OS) {
1788 // Did we find one?
1789 if (!Pat->hasTypeSet()) {
1790 // Move a type over from 'other' to 'pat'.
1791 Pat->setType(Other->getType());
1792 OS << " if (" << Prefix << ".getValueType() != MVT::"
1793 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1794 return true;
1795 } else if (Pat->isLeaf()) {
1796 return false;
1797 }
1798
1799 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1800 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1801 Prefix + utostr(i), PatternNo, OS))
1802 return true;
1803 return false;
1804}
1805
Chris Lattner0614b622005-11-02 06:49:14 +00001806Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1807 Record *N = Records.getDef(Name);
1808 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1809 return N;
1810}
1811
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001812/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1813/// stream to match the pattern, and generate the code for the match if it
1814/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001815void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1816 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001817 static unsigned PatternCount = 0;
1818 unsigned PatternNo = PatternCount++;
1819 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001820 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001821 OS << "\n // Emits: ";
1822 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001823 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001824 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1825 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001826
Chris Lattner8fc35682005-09-23 23:16:51 +00001827 // Emit the matcher, capturing named arguments in VariableMap.
1828 std::map<std::string,std::string> VariableMap;
1829 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001830
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001831 // TP - Get *SOME* tree pattern, we don't care which.
1832 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001833
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001834 // At this point, we know that we structurally match the pattern, but the
1835 // types of the nodes may not match. Figure out the fewest number of type
1836 // comparisons we need to emit. For example, if there is only one integer
1837 // type supported by a target, there should be no type comparisons at all for
1838 // integer patterns!
1839 //
1840 // To figure out the fewest number of type checks needed, clone the pattern,
1841 // remove the types, then perform type inference on the pattern as a whole.
1842 // If there are unresolved types, emit an explicit check for those types,
1843 // apply the type to the tree, then rerun type inference. Iterate until all
1844 // types are resolved.
1845 //
1846 TreePatternNode *Pat = Pattern.first->clone();
1847 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001848
1849 do {
1850 // Resolve/propagate as many types as possible.
1851 try {
1852 bool MadeChange = true;
1853 while (MadeChange)
1854 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1855 } catch (...) {
1856 assert(0 && "Error: could not find consistent types for something we"
1857 " already decided was ok!");
1858 abort();
1859 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001860
Chris Lattner7e82f132005-10-15 21:34:21 +00001861 // Insert a check for an unresolved type and add it to the tree. If we find
1862 // an unresolved type to add a check for, this returns true and we iterate,
1863 // otherwise we are done.
1864 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001865
Chris Lattner5024d932005-10-16 01:41:58 +00001866 unsigned TmpNo = 0;
1867 CodeGenPatternResult(Pattern.second, TmpNo,
1868 VariableMap, OS, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001869 delete Pat;
1870
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001871 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001872}
1873
Chris Lattner37481472005-09-26 21:59:35 +00001874
1875namespace {
1876 /// CompareByRecordName - An ordering predicate that implements less-than by
1877 /// comparing the names records.
1878 struct CompareByRecordName {
1879 bool operator()(const Record *LHS, const Record *RHS) const {
1880 // Sort by name first.
1881 if (LHS->getName() < RHS->getName()) return true;
1882 // If both names are equal, sort by pointer.
1883 return LHS->getName() == RHS->getName() && LHS < RHS;
1884 }
1885 };
1886}
1887
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001888void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001889 std::string InstNS = Target.inst_begin()->second.Namespace;
1890 if (!InstNS.empty()) InstNS += "::";
1891
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001892 // Emit boilerplate.
1893 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001894 << "SDOperand SelectCode(SDOperand N) {\n"
1895 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001896 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1897 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001898 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001899 << " if (!N.Val->hasOneUse()) {\n"
1900 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1901 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1902 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001903 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001904 << " default: break;\n"
1905 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001906 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001907 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001908 << " case ISD::AssertZext: {\n"
1909 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1910 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1911 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001912 << " }\n"
1913 << " case ISD::TokenFactor:\n"
1914 << " if (N.getNumOperands() == 2) {\n"
1915 << " SDOperand Op0 = Select(N.getOperand(0));\n"
1916 << " SDOperand Op1 = Select(N.getOperand(1));\n"
1917 << " return CodeGenMap[N] =\n"
1918 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
1919 << " } else {\n"
1920 << " std::vector<SDOperand> Ops;\n"
1921 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1922 << " Ops.push_back(Select(N.getOperand(i)));\n"
1923 << " return CodeGenMap[N] = \n"
1924 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
1925 << " }\n"
1926 << " case ISD::CopyFromReg: {\n"
1927 << " SDOperand Chain = Select(N.getOperand(0));\n"
1928 << " if (Chain == N.getOperand(0)) return N; // No change\n"
1929 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
1930 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
1931 << " N.Val->getValueType(0));\n"
1932 << " return New.getValue(N.ResNo);\n"
1933 << " }\n"
1934 << " case ISD::CopyToReg: {\n"
1935 << " SDOperand Chain = Select(N.getOperand(0));\n"
1936 << " SDOperand Reg = N.getOperand(1);\n"
1937 << " SDOperand Val = Select(N.getOperand(2));\n"
1938 << " return CodeGenMap[N] = \n"
1939 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
1940 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001941 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001942
Chris Lattner81303322005-09-23 19:36:15 +00001943 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001944 std::map<Record*, std::vector<PatternToMatch*>,
1945 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001946 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
Chris Lattner0614b622005-11-02 06:49:14 +00001947 if (!PatternsToMatch[i].first->isLeaf()) {
1948 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1949 .push_back(&PatternsToMatch[i]);
1950 } else {
1951 if (IntInit *II =
1952 dynamic_cast<IntInit*>(PatternsToMatch[i].first->getLeafValue())) {
1953 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
1954 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00001955 std::cerr << "Unrecognized opcode '";
1956 PatternsToMatch[i].first->dump();
1957 std::cerr << "' on tree pattern '";
1958 std::cerr << PatternsToMatch[i].second->getOperator()->getName();
1959 std::cerr << "'!\n";
1960 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00001961 }
1962 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001963
Chris Lattner3f7e9142005-09-23 20:52:47 +00001964 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001965 for (std::map<Record*, std::vector<PatternToMatch*>,
1966 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1967 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001968 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1969 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1970
1971 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001972
1973 // We want to emit all of the matching code now. However, we want to emit
1974 // the matches in order of minimal cost. Sort the patterns so the least
1975 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001976 std::stable_sort(Patterns.begin(), Patterns.end(),
1977 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001978
Chris Lattner3f7e9142005-09-23 20:52:47 +00001979 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1980 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001981 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001982 }
1983
1984
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001985 OS << " } // end of big switch.\n\n"
1986 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001987 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001988 << " std::cerr << '\\n';\n"
1989 << " abort();\n"
1990 << "}\n";
1991}
1992
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001993void DAGISelEmitter::run(std::ostream &OS) {
1994 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1995 " target", OS);
1996
Chris Lattner1f39e292005-09-14 00:09:24 +00001997 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1998 << "// *** instruction selector class. These functions are really "
1999 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002000
Chris Lattner296dfe32005-09-24 00:50:51 +00002001 OS << "// Instance var to keep track of multiply used nodes that have \n"
2002 << "// already been selected.\n"
2003 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2004
Chris Lattnerca559d02005-09-08 21:03:01 +00002005 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002006 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002007 ParsePatternFragments(OS);
2008 ParseInstructions();
2009 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002010
Chris Lattnere97603f2005-09-28 19:27:25 +00002011 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002012 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002013 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002014
Chris Lattnere46e17b2005-09-29 19:28:10 +00002015
2016 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2017 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2018 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
2019 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
2020 std::cerr << "\n";
2021 });
2022
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002023 // At this point, we have full information about the 'Patterns' we need to
2024 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002025 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002026 EmitInstructionSelector(OS);
2027
2028 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2029 E = PatternFragments.end(); I != E; ++I)
2030 delete I->second;
2031 PatternFragments.clear();
2032
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002033 Instructions.clear();
2034}