blob: 4b40561b2689a3ebf792fe23ec34b39e5f761f5d [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
Nate Begemanddb39542005-12-01 00:06:14 +0000534 Record *ResultNode = Inst.getResult(0);
535 assert(ResultNode->isSubClassOf("RegisterClass") &&
536 "Operands should be register classes!");
537
538 const CodeGenRegisterClass &RC =
539 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
540
541 bool MadeChange = UpdateNodeType(RC.VT, TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000542
543 if (getNumChildren() != Inst.getNumOperands())
544 TP.error("Instruction '" + getOperator()->getName() + " expects " +
545 utostr(Inst.getNumOperands()) + " operands, not " +
546 utostr(getNumChildren()) + " operands!");
547 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000548 Record *OperandNode = Inst.getOperand(i);
549 MVT::ValueType VT;
550 if (OperandNode->isSubClassOf("RegisterClass")) {
551 const CodeGenRegisterClass &RC =
552 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
553 VT = RC.VT;
554 } else if (OperandNode->isSubClassOf("Operand")) {
555 VT = getValueType(OperandNode->getValueAsDef("Type"));
556 } else {
557 assert(0 && "Unknown operand type!");
558 abort();
559 }
560
561 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000562 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000563 }
564 return MadeChange;
565 } else {
566 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
567
568 // Node transforms always take one operand, and take and return the same
569 // type.
570 if (getNumChildren() != 1)
571 TP.error("Node transform '" + getOperator()->getName() +
572 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000573 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
574 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000575 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000576 }
Chris Lattner32707602005-09-08 23:22:48 +0000577}
578
Chris Lattnere97603f2005-09-28 19:27:25 +0000579/// canPatternMatch - If it is impossible for this pattern to match on this
580/// target, fill in Reason and return false. Otherwise, return true. This is
581/// used as a santity check for .td files (to prevent people from writing stuff
582/// that can never possibly work), and to prevent the pattern permuter from
583/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000584bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000585 if (isLeaf()) return true;
586
587 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
588 if (!getChild(i)->canPatternMatch(Reason, ISE))
589 return false;
590
591 // If this node is a commutative operator, check that the LHS isn't an
592 // immediate.
593 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
594 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
595 // Scan all of the operands of the node and make sure that only the last one
596 // is a constant node.
597 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
598 if (!getChild(i)->isLeaf() &&
599 getChild(i)->getOperator()->getName() == "imm") {
600 Reason = "Immediate value must be on the RHS of commutative operators!";
601 return false;
602 }
603 }
604
605 return true;
606}
Chris Lattner32707602005-09-08 23:22:48 +0000607
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000608//===----------------------------------------------------------------------===//
609// TreePattern implementation
610//
611
Chris Lattneredbd8712005-10-21 01:19:59 +0000612TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000613 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000614 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000615 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
616 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000617}
618
Chris Lattneredbd8712005-10-21 01:19:59 +0000619TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000620 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000621 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000622 Trees.push_back(ParseTreePattern(Pat));
623}
624
Chris Lattneredbd8712005-10-21 01:19:59 +0000625TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000626 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000627 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000628 Trees.push_back(Pat);
629}
630
631
632
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000633void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000634 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000635 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000636}
637
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000638TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
639 Record *Operator = Dag->getNodeType();
640
641 if (Operator->isSubClassOf("ValueType")) {
642 // If the operator is a ValueType, then this must be "type cast" of a leaf
643 // node.
644 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000645 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000646
647 Init *Arg = Dag->getArg(0);
648 TreePatternNode *New;
649 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000650 Record *R = DI->getDef();
651 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
652 Dag->setArg(0, new DagInit(R,
653 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000654 return ParseTreePattern(Dag);
Chris Lattner72fe91c2005-09-24 00:40:24 +0000655 }
656
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000657 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000658 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
659 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000660 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
661 New = new TreePatternNode(II);
662 if (!Dag->getArgName(0).empty())
663 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000664 } else {
665 Arg->dump();
666 error("Unknown leaf value for tree pattern!");
667 return 0;
668 }
669
Chris Lattner32707602005-09-08 23:22:48 +0000670 // Apply the type cast.
671 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000672 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000673 return New;
674 }
675
676 // Verify that this is something that makes sense for an operator.
677 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000678 !Operator->isSubClassOf("Instruction") &&
679 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000680 Operator->getName() != "set")
681 error("Unrecognized node '" + Operator->getName() + "'!");
682
Chris Lattneredbd8712005-10-21 01:19:59 +0000683 // Check to see if this is something that is illegal in an input pattern.
684 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
685 Operator->isSubClassOf("SDNodeXForm")))
686 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
687
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000688 std::vector<TreePatternNode*> Children;
689
690 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
691 Init *Arg = Dag->getArg(i);
692 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
693 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000694 if (Children.back()->getName().empty())
695 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000696 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
697 Record *R = DefI->getDef();
698 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
699 // TreePatternNode if its own.
700 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
701 Dag->setArg(i, new DagInit(R,
702 std::vector<std::pair<Init*, std::string> >()));
703 --i; // Revisit this node...
704 } else {
705 TreePatternNode *Node = new TreePatternNode(DefI);
706 Node->setName(Dag->getArgName(i));
707 Children.push_back(Node);
708
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000709 // Input argument?
710 if (R->getName() == "node") {
711 if (Dag->getArgName(i).empty())
712 error("'node' argument requires a name to match with operand list");
713 Args.push_back(Dag->getArgName(i));
714 }
715 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000716 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
717 TreePatternNode *Node = new TreePatternNode(II);
718 if (!Dag->getArgName(i).empty())
719 error("Constant int argument should not have a name!");
720 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000721 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000722 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000723 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000724 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000725 error("Unknown leaf value for tree pattern!");
726 }
727 }
728
729 return new TreePatternNode(Operator, Children);
730}
731
Chris Lattner32707602005-09-08 23:22:48 +0000732/// InferAllTypes - Infer/propagate as many types throughout the expression
733/// patterns as possible. Return true if all types are infered, false
734/// otherwise. Throw an exception if a type contradiction is found.
735bool TreePattern::InferAllTypes() {
736 bool MadeChange = true;
737 while (MadeChange) {
738 MadeChange = false;
739 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000740 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000741 }
742
743 bool HasUnresolvedTypes = false;
744 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
745 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
746 return !HasUnresolvedTypes;
747}
748
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000749void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000750 OS << getRecord()->getName();
751 if (!Args.empty()) {
752 OS << "(" << Args[0];
753 for (unsigned i = 1, e = Args.size(); i != e; ++i)
754 OS << ", " << Args[i];
755 OS << ")";
756 }
757 OS << ": ";
758
759 if (Trees.size() > 1)
760 OS << "[\n";
761 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
762 OS << "\t";
763 Trees[i]->print(OS);
764 OS << "\n";
765 }
766
767 if (Trees.size() > 1)
768 OS << "]\n";
769}
770
771void TreePattern::dump() const { print(std::cerr); }
772
773
774
775//===----------------------------------------------------------------------===//
776// DAGISelEmitter implementation
777//
778
Chris Lattnerca559d02005-09-08 21:03:01 +0000779// Parse all of the SDNode definitions for the target, populating SDNodes.
780void DAGISelEmitter::ParseNodeInfo() {
781 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
782 while (!Nodes.empty()) {
783 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
784 Nodes.pop_back();
785 }
786}
787
Chris Lattner24eeeb82005-09-13 21:51:00 +0000788/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
789/// map, and emit them to the file as functions.
790void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
791 OS << "\n// Node transformations.\n";
792 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
793 while (!Xforms.empty()) {
794 Record *XFormNode = Xforms.back();
795 Record *SDNode = XFormNode->getValueAsDef("Opcode");
796 std::string Code = XFormNode->getValueAsCode("XFormFunction");
797 SDNodeXForms.insert(std::make_pair(XFormNode,
798 std::make_pair(SDNode, Code)));
799
Chris Lattner1048b7a2005-09-13 22:03:37 +0000800 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000801 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
802 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
803
Chris Lattner1048b7a2005-09-13 22:03:37 +0000804 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000805 << "(SDNode *" << C2 << ") {\n";
806 if (ClassName != "SDNode")
807 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
808 OS << Code << "\n}\n";
809 }
810
811 Xforms.pop_back();
812 }
813}
814
815
816
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000817/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
818/// file, building up the PatternFragments map. After we've collected them all,
819/// inline fragments together as necessary, so that there are no references left
820/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000821///
822/// This also emits all of the predicate functions to the output file.
823///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000824void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000825 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
826
827 // First step, parse all of the fragments and emit predicate functions.
828 OS << "\n// Predicate functions.\n";
829 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000830 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000831 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000832 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000833
834 // Validate the argument list, converting it to map, to discard duplicates.
835 std::vector<std::string> &Args = P->getArgList();
836 std::set<std::string> OperandsMap(Args.begin(), Args.end());
837
838 if (OperandsMap.count(""))
839 P->error("Cannot have unnamed 'node' values in pattern fragment!");
840
841 // Parse the operands list.
842 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
843 if (OpsList->getNodeType()->getName() != "ops")
844 P->error("Operands list should start with '(ops ... '!");
845
846 // Copy over the arguments.
847 Args.clear();
848 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
849 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
850 static_cast<DefInit*>(OpsList->getArg(j))->
851 getDef()->getName() != "node")
852 P->error("Operands list should all be 'node' values.");
853 if (OpsList->getArgName(j).empty())
854 P->error("Operands list should have names for each operand!");
855 if (!OperandsMap.count(OpsList->getArgName(j)))
856 P->error("'" + OpsList->getArgName(j) +
857 "' does not occur in pattern or was multiply specified!");
858 OperandsMap.erase(OpsList->getArgName(j));
859 Args.push_back(OpsList->getArgName(j));
860 }
861
862 if (!OperandsMap.empty())
863 P->error("Operands list does not contain an entry for operand '" +
864 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000865
866 // If there is a code init for this fragment, emit the predicate code and
867 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000868 std::string Code = Fragments[i]->getValueAsCode("Predicate");
869 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000870 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000871 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000872 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000873 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
874
Chris Lattner1048b7a2005-09-13 22:03:37 +0000875 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000876 << "(SDNode *" << C2 << ") {\n";
877 if (ClassName != "SDNode")
878 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000879 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000880 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000881 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000882
883 // If there is a node transformation corresponding to this, keep track of
884 // it.
885 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
886 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000887 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000888 }
889
890 OS << "\n\n";
891
892 // Now that we've parsed all of the tree fragments, do a closure on them so
893 // that there are not references to PatFrags left inside of them.
894 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
895 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000896 TreePattern *ThePat = I->second;
897 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000898
Chris Lattner32707602005-09-08 23:22:48 +0000899 // Infer as many types as possible. Don't worry about it if we don't infer
900 // all of them, some may depend on the inputs of the pattern.
901 try {
902 ThePat->InferAllTypes();
903 } catch (...) {
904 // If this pattern fragment is not supported by this target (no types can
905 // satisfy its constraints), just ignore it. If the bogus pattern is
906 // actually used by instructions, the type consistency error will be
907 // reported there.
908 }
909
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000910 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000911 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000912 }
913}
914
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000915/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000916/// instruction input. Return true if this is a real use.
917static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000918 std::map<std::string, TreePatternNode*> &InstInputs) {
919 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000920 if (Pat->getName().empty()) {
921 if (Pat->isLeaf()) {
922 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
923 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
924 I->error("Input " + DI->getDef()->getName() + " must be named!");
925
926 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000927 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000928 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000929
930 Record *Rec;
931 if (Pat->isLeaf()) {
932 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
933 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
934 Rec = DI->getDef();
935 } else {
936 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
937 Rec = Pat->getOperator();
938 }
939
940 TreePatternNode *&Slot = InstInputs[Pat->getName()];
941 if (!Slot) {
942 Slot = Pat;
943 } else {
944 Record *SlotRec;
945 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000946 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000947 } else {
948 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
949 SlotRec = Slot->getOperator();
950 }
951
952 // Ensure that the inputs agree if we've already seen this input.
953 if (Rec != SlotRec)
954 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000955 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000956 I->error("All $" + Pat->getName() + " inputs must agree with each other");
957 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000958 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000959}
960
961/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
962/// part of "I", the instruction), computing the set of inputs and outputs of
963/// the pattern. Report errors if we see anything naughty.
964void DAGISelEmitter::
965FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
966 std::map<std::string, TreePatternNode*> &InstInputs,
967 std::map<std::string, Record*> &InstResults) {
968 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000969 bool isUse = HandleUse(I, Pat, InstInputs);
970 if (!isUse && Pat->getTransformFn())
971 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000972 return;
973 } else if (Pat->getOperator()->getName() != "set") {
974 // If this is not a set, verify that the children nodes are not void typed,
975 // and recurse.
976 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000977 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000978 I->error("Cannot have void nodes inside of patterns!");
979 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
980 }
981
982 // If this is a non-leaf node with no children, treat it basically as if
983 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000984 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000985 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000986 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000987
Chris Lattnerf1311842005-09-14 23:05:13 +0000988 if (!isUse && Pat->getTransformFn())
989 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000990 return;
991 }
992
993 // Otherwise, this is a set, validate and collect instruction results.
994 if (Pat->getNumChildren() == 0)
995 I->error("set requires operands!");
996 else if (Pat->getNumChildren() & 1)
997 I->error("set requires an even number of operands");
998
Chris Lattnerf1311842005-09-14 23:05:13 +0000999 if (Pat->getTransformFn())
1000 I->error("Cannot specify a transform function on a set node!");
1001
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001002 // Check the set destinations.
1003 unsigned NumValues = Pat->getNumChildren()/2;
1004 for (unsigned i = 0; i != NumValues; ++i) {
1005 TreePatternNode *Dest = Pat->getChild(i);
1006 if (!Dest->isLeaf())
1007 I->error("set destination should be a virtual register!");
1008
1009 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1010 if (!Val)
1011 I->error("set destination should be a virtual register!");
1012
1013 if (!Val->getDef()->isSubClassOf("RegisterClass"))
1014 I->error("set destination should be a virtual register!");
1015 if (Dest->getName().empty())
1016 I->error("set destination must have a name!");
1017 if (InstResults.count(Dest->getName()))
1018 I->error("cannot set '" + Dest->getName() +"' multiple times");
1019 InstResults[Dest->getName()] = Val->getDef();
1020
1021 // Verify and collect info from the computation.
1022 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1023 InstInputs, InstResults);
1024 }
1025}
1026
1027
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001028/// ParseInstructions - Parse all of the instructions, inlining and resolving
1029/// any fragments involved. This populates the Instructions list with fully
1030/// resolved instructions.
1031void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001032 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1033
1034 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001035 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001036
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001037 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1038 LI = Instrs[i]->getValueAsListInit("Pattern");
1039
1040 // If there is no pattern, only collect minimal information about the
1041 // instruction for its operand list. We have to assume that there is one
1042 // result, as we have no detailed info.
1043 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001044 std::vector<Record*> Results;
1045 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001046
1047 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1048
1049 // Doesn't even define a result?
1050 if (InstInfo.OperandList.size() == 0)
1051 continue;
1052
1053 // Assume the first operand is the result.
Nate Begemanddb39542005-12-01 00:06:14 +00001054 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001055
1056 // The rest are inputs.
1057 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
Nate Begemanddb39542005-12-01 00:06:14 +00001058 Operands.push_back(InstInfo.OperandList[j].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001059
1060 // Create and insert the instruction.
1061 Instructions.insert(std::make_pair(Instrs[i],
Nate Begemanddb39542005-12-01 00:06:14 +00001062 DAGInstruction(0, Results, Operands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001063 continue; // no pattern.
1064 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001065
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001066 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001067 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001068 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001069 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001070
Chris Lattner95f6b762005-09-08 23:26:30 +00001071 // Infer as many types as possible. If we cannot infer all of them, we can
1072 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001073 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001074 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001075
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001076 // InstInputs - Keep track of all of the inputs of the instruction, along
1077 // with the record they are declared as.
1078 std::map<std::string, TreePatternNode*> InstInputs;
1079
1080 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001081 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001082 std::map<std::string, Record*> InstResults;
1083
Chris Lattner1f39e292005-09-14 00:09:24 +00001084 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001085 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001086 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1087 TreePatternNode *Pat = I->getTree(j);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001088 if (Pat->getExtType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001089 I->dump();
1090 I->error("Top-level forms in instruction pattern should have"
1091 " void types");
1092 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001093
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001094 // Find inputs and outputs, and verify the structure of the uses/defs.
1095 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001096 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001097
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001098 // Now that we have inputs and outputs of the pattern, inspect the operands
1099 // list for the instruction. This determines the order that operands are
1100 // added to the machine instruction the node corresponds to.
1101 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001102
1103 // Parse the operands list from the (ops) list, validating it.
1104 std::vector<std::string> &Args = I->getArgList();
1105 assert(Args.empty() && "Args list should still be empty here!");
1106 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1107
1108 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001109 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001110 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001111 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001112 I->error("'" + InstResults.begin()->first +
1113 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001114 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001115
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001116 // Check that it exists in InstResults.
1117 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001118 if (R == 0)
1119 I->error("Operand $" + OpName + " should be a set destination: all "
1120 "outputs must occur before inputs in operand list!");
1121
1122 if (CGI.OperandList[i].Rec != R)
1123 I->error("Operand $" + OpName + " class mismatch!");
1124
Chris Lattnerae6d8282005-09-15 21:51:12 +00001125 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001126 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001127
Chris Lattner39e8af92005-09-14 18:19:25 +00001128 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001129 InstResults.erase(OpName);
1130 }
1131
Chris Lattner0b592252005-09-14 21:59:34 +00001132 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1133 // the copy while we're checking the inputs.
1134 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001135
1136 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001137 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001138 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1139 const std::string &OpName = CGI.OperandList[i].Name;
1140 if (OpName.empty())
1141 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1142
Chris Lattner0b592252005-09-14 21:59:34 +00001143 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001144 I->error("Operand $" + OpName +
1145 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001146 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001147 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001148
1149 if (InVal->isLeaf() &&
1150 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1151 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1152 if (CGI.OperandList[i].Rec != InRec)
1153 I->error("Operand $" + OpName +
1154 "'s register class disagrees between the operand and pattern");
1155 }
1156 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001157
Chris Lattner2175c182005-09-14 23:01:59 +00001158 // Construct the result for the dest-pattern operand list.
1159 TreePatternNode *OpNode = InVal->clone();
1160
1161 // No predicate is useful on the result.
1162 OpNode->setPredicateFn("");
1163
1164 // Promote the xform function to be an explicit node if set.
1165 if (Record *Xform = OpNode->getTransformFn()) {
1166 OpNode->setTransformFn(0);
1167 std::vector<TreePatternNode*> Children;
1168 Children.push_back(OpNode);
1169 OpNode = new TreePatternNode(Xform, Children);
1170 }
1171
1172 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001173 }
1174
Chris Lattner0b592252005-09-14 21:59:34 +00001175 if (!InstInputsCheck.empty())
1176 I->error("Input operand $" + InstInputsCheck.begin()->first +
1177 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001178
1179 TreePatternNode *ResultPattern =
1180 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001181
1182 // Create and insert the instruction.
Nate Begemanddb39542005-12-01 00:06:14 +00001183 DAGInstruction TheInst(I, Results, Operands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001184 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1185
1186 // Use a temporary tree pattern to infer all types and make sure that the
1187 // constructed result is correct. This depends on the instruction already
1188 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001189 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001190 Temp.InferAllTypes();
1191
1192 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1193 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001194
Chris Lattner32707602005-09-08 23:22:48 +00001195 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001196 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001197
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001198 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001199 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1200 E = Instructions.end(); II != E; ++II) {
1201 TreePattern *I = II->second.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001202 if (I == 0) continue; // No pattern.
Chris Lattner1f39e292005-09-14 00:09:24 +00001203
1204 if (I->getNumTrees() != 1) {
1205 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1206 continue;
1207 }
1208 TreePatternNode *Pattern = I->getTree(0);
1209 if (Pattern->getOperator()->getName() != "set")
1210 continue; // Not a set (store or something?)
1211
1212 if (Pattern->getNumChildren() != 2)
1213 continue; // Not a set of a single value (not handled so far)
1214
1215 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001216
1217 std::string Reason;
1218 if (!SrcPattern->canPatternMatch(Reason, *this))
1219 I->error("Instruction can never match: " + Reason);
1220
Chris Lattnerae5b3502005-09-15 21:57:35 +00001221 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001222 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001223 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001224}
1225
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001226void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001227 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001228
Chris Lattnerabbb6052005-09-15 21:42:00 +00001229 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001230 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001231 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001232
Chris Lattnerabbb6052005-09-15 21:42:00 +00001233 // Inline pattern fragments into it.
1234 Pattern->InlinePatternFragments();
1235
1236 // Infer as many types as possible. If we cannot infer all of them, we can
1237 // never do anything with this pattern: report it to the user.
1238 if (!Pattern->InferAllTypes())
1239 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001240
1241 // Validate that the input pattern is correct.
1242 {
1243 std::map<std::string, TreePatternNode*> InstInputs;
1244 std::map<std::string, Record*> InstResults;
1245 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1246 InstInputs, InstResults);
1247 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001248
1249 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1250 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001251
1252 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001253 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001254
1255 // Inline pattern fragments into it.
1256 Result->InlinePatternFragments();
1257
1258 // Infer as many types as possible. If we cannot infer all of them, we can
1259 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001260 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001261 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001262
1263 if (Result->getNumTrees() != 1)
1264 Result->error("Cannot handle instructions producing instructions "
1265 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001266
1267 std::string Reason;
1268 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1269 Pattern->error("Pattern can never match: " + Reason);
1270
Chris Lattnerabbb6052005-09-15 21:42:00 +00001271 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1272 Result->getOnlyTree()));
1273 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001274}
1275
Chris Lattnere46e17b2005-09-29 19:28:10 +00001276/// CombineChildVariants - Given a bunch of permutations of each child of the
1277/// 'operator' node, put them together in all possible ways.
1278static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001279 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001280 std::vector<TreePatternNode*> &OutVariants,
1281 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001282 // Make sure that each operand has at least one variant to choose from.
1283 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1284 if (ChildVariants[i].empty())
1285 return;
1286
Chris Lattnere46e17b2005-09-29 19:28:10 +00001287 // The end result is an all-pairs construction of the resultant pattern.
1288 std::vector<unsigned> Idxs;
1289 Idxs.resize(ChildVariants.size());
1290 bool NotDone = true;
1291 while (NotDone) {
1292 // Create the variant and add it to the output list.
1293 std::vector<TreePatternNode*> NewChildren;
1294 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1295 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1296 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1297
1298 // Copy over properties.
1299 R->setName(Orig->getName());
1300 R->setPredicateFn(Orig->getPredicateFn());
1301 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001302 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001303
1304 // If this pattern cannot every match, do not include it as a variant.
1305 std::string ErrString;
1306 if (!R->canPatternMatch(ErrString, ISE)) {
1307 delete R;
1308 } else {
1309 bool AlreadyExists = false;
1310
1311 // Scan to see if this pattern has already been emitted. We can get
1312 // duplication due to things like commuting:
1313 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1314 // which are the same pattern. Ignore the dups.
1315 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1316 if (R->isIsomorphicTo(OutVariants[i])) {
1317 AlreadyExists = true;
1318 break;
1319 }
1320
1321 if (AlreadyExists)
1322 delete R;
1323 else
1324 OutVariants.push_back(R);
1325 }
1326
1327 // Increment indices to the next permutation.
1328 NotDone = false;
1329 // Look for something we can increment without causing a wrap-around.
1330 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1331 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1332 NotDone = true; // Found something to increment.
1333 break;
1334 }
1335 Idxs[IdxsIdx] = 0;
1336 }
1337 }
1338}
1339
Chris Lattneraf302912005-09-29 22:36:54 +00001340/// CombineChildVariants - A helper function for binary operators.
1341///
1342static void CombineChildVariants(TreePatternNode *Orig,
1343 const std::vector<TreePatternNode*> &LHS,
1344 const std::vector<TreePatternNode*> &RHS,
1345 std::vector<TreePatternNode*> &OutVariants,
1346 DAGISelEmitter &ISE) {
1347 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1348 ChildVariants.push_back(LHS);
1349 ChildVariants.push_back(RHS);
1350 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1351}
1352
1353
1354static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1355 std::vector<TreePatternNode *> &Children) {
1356 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1357 Record *Operator = N->getOperator();
1358
1359 // Only permit raw nodes.
1360 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1361 N->getTransformFn()) {
1362 Children.push_back(N);
1363 return;
1364 }
1365
1366 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1367 Children.push_back(N->getChild(0));
1368 else
1369 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1370
1371 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1372 Children.push_back(N->getChild(1));
1373 else
1374 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1375}
1376
Chris Lattnere46e17b2005-09-29 19:28:10 +00001377/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1378/// the (potentially recursive) pattern by using algebraic laws.
1379///
1380static void GenerateVariantsOf(TreePatternNode *N,
1381 std::vector<TreePatternNode*> &OutVariants,
1382 DAGISelEmitter &ISE) {
1383 // We cannot permute leaves.
1384 if (N->isLeaf()) {
1385 OutVariants.push_back(N);
1386 return;
1387 }
1388
1389 // Look up interesting info about the node.
1390 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1391
1392 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001393 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1394 // Reassociate by pulling together all of the linked operators
1395 std::vector<TreePatternNode*> MaximalChildren;
1396 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1397
1398 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1399 // permutations.
1400 if (MaximalChildren.size() == 3) {
1401 // Find the variants of all of our maximal children.
1402 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1403 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1404 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1405 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1406
1407 // There are only two ways we can permute the tree:
1408 // (A op B) op C and A op (B op C)
1409 // Within these forms, we can also permute A/B/C.
1410
1411 // Generate legal pair permutations of A/B/C.
1412 std::vector<TreePatternNode*> ABVariants;
1413 std::vector<TreePatternNode*> BAVariants;
1414 std::vector<TreePatternNode*> ACVariants;
1415 std::vector<TreePatternNode*> CAVariants;
1416 std::vector<TreePatternNode*> BCVariants;
1417 std::vector<TreePatternNode*> CBVariants;
1418 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1419 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1420 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1421 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1422 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1423 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1424
1425 // Combine those into the result: (x op x) op x
1426 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1427 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1428 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1429 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1430 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1431 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1432
1433 // Combine those into the result: x op (x op x)
1434 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1435 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1436 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1437 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1438 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1439 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1440 return;
1441 }
1442 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001443
1444 // Compute permutations of all children.
1445 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1446 ChildVariants.resize(N->getNumChildren());
1447 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1448 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1449
1450 // Build all permutations based on how the children were formed.
1451 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1452
1453 // If this node is commutative, consider the commuted order.
1454 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1455 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001456 // Consider the commuted order.
1457 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1458 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001459 }
1460}
1461
1462
Chris Lattnere97603f2005-09-28 19:27:25 +00001463// GenerateVariants - Generate variants. For example, commutative patterns can
1464// match multiple ways. Add them to PatternsToMatch as well.
1465void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001466
1467 DEBUG(std::cerr << "Generating instruction variants.\n");
1468
1469 // Loop over all of the patterns we've collected, checking to see if we can
1470 // generate variants of the instruction, through the exploitation of
1471 // identities. This permits the target to provide agressive matching without
1472 // the .td file having to contain tons of variants of instructions.
1473 //
1474 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1475 // intentionally do not reconsider these. Any variants of added patterns have
1476 // already been added.
1477 //
1478 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1479 std::vector<TreePatternNode*> Variants;
1480 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1481
1482 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001483 Variants.erase(Variants.begin()); // Remove the original pattern.
1484
1485 if (Variants.empty()) // No variants for this pattern.
1486 continue;
1487
1488 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1489 PatternsToMatch[i].first->dump();
1490 std::cerr << "\n");
1491
1492 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1493 TreePatternNode *Variant = Variants[v];
1494
1495 DEBUG(std::cerr << " VAR#" << v << ": ";
1496 Variant->dump();
1497 std::cerr << "\n");
1498
1499 // Scan to see if an instruction or explicit pattern already matches this.
1500 bool AlreadyExists = false;
1501 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1502 // Check to see if this variant already exists.
1503 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1504 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1505 AlreadyExists = true;
1506 break;
1507 }
1508 }
1509 // If we already have it, ignore the variant.
1510 if (AlreadyExists) continue;
1511
1512 // Otherwise, add it to the list of patterns we have.
1513 PatternsToMatch.push_back(std::make_pair(Variant,
1514 PatternsToMatch[i].second));
1515 }
1516
1517 DEBUG(std::cerr << "\n");
1518 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001519}
1520
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001521
Chris Lattner05814af2005-09-28 17:57:56 +00001522/// getPatternSize - Return the 'size' of this pattern. We want to match large
1523/// patterns before small ones. This is used to determine the size of a
1524/// pattern.
1525static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001526 assert(isExtIntegerVT(P->getExtType()) ||
1527 isExtFloatingPointVT(P->getExtType()) &&
Chris Lattner05814af2005-09-28 17:57:56 +00001528 "Not a valid pattern node to size!");
1529 unsigned Size = 1; // The node itself.
1530
1531 // Count children in the count if they are also nodes.
1532 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1533 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001534 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001535 Size += getPatternSize(Child);
Chris Lattner2f041d42005-10-19 04:41:05 +00001536 else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1537 ++Size; // Matches a ConstantSDNode.
1538 }
Chris Lattner05814af2005-09-28 17:57:56 +00001539 }
1540
1541 return Size;
1542}
1543
1544/// getResultPatternCost - Compute the number of instructions for this pattern.
1545/// This is a temporary hack. We should really include the instruction
1546/// latencies in this calculation.
1547static unsigned getResultPatternCost(TreePatternNode *P) {
1548 if (P->isLeaf()) return 0;
1549
1550 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1551 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1552 Cost += getResultPatternCost(P->getChild(i));
1553 return Cost;
1554}
1555
1556// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1557// In particular, we want to match maximal patterns first and lowest cost within
1558// a particular complexity first.
1559struct PatternSortingPredicate {
1560 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1561 DAGISelEmitter::PatternToMatch *RHS) {
1562 unsigned LHSSize = getPatternSize(LHS->first);
1563 unsigned RHSSize = getPatternSize(RHS->first);
1564 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1565 if (LHSSize < RHSSize) return false;
1566
1567 // If the patterns have equal complexity, compare generated instruction cost
1568 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1569 }
1570};
1571
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001572/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1573/// if the match fails. At this point, we already know that the opcode for N
1574/// matches, and the SDNode for the result has the RootName specified name.
1575void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001576 const std::string &RootName,
Evan Cheng66a48bb2005-12-01 00:18:45 +00001577 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001578 unsigned PatternNo, std::ostream &OS) {
Chris Lattner0614b622005-11-02 06:49:14 +00001579 if (N->isLeaf()) {
1580 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1581 OS << " if (cast<ConstantSDNode>(" << RootName
1582 << ")->getSignExtended() != " << II->getValue() << ")\n"
1583 << " goto P" << PatternNo << "Fail;\n";
1584 return;
1585 }
1586 assert(0 && "Cannot match this as a leaf value!");
1587 abort();
1588 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001589
1590 // If this node has a name associated with it, capture it in VarMap. If
1591 // we already saw this in the pattern, emit code to verify dagness.
1592 if (!N->getName().empty()) {
1593 std::string &VarMapEntry = VarMap[N->getName()];
1594 if (VarMapEntry.empty()) {
1595 VarMapEntry = RootName;
1596 } else {
1597 // If we get here, this is a second reference to a specific name. Since
1598 // we already have checked that the first reference is valid, we don't
1599 // have to recursively match it, just check that it's the same as the
1600 // previously named thing.
1601 OS << " if (" << VarMapEntry << " != " << RootName
1602 << ") goto P" << PatternNo << "Fail;\n";
1603 return;
1604 }
1605 }
1606
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001607 // Emit code to load the child nodes and match their contents recursively.
1608 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001609 OS << " SDOperand " << RootName << i <<" = " << RootName
1610 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001611 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001612
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001613 if (!Child->isLeaf()) {
1614 // If it's not a leaf, recursively match.
1615 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001616 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001617 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001618 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001619 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001620 // If this child has a name associated with it, capture it in VarMap. If
1621 // we already saw this in the pattern, emit code to verify dagness.
1622 if (!Child->getName().empty()) {
1623 std::string &VarMapEntry = VarMap[Child->getName()];
1624 if (VarMapEntry.empty()) {
1625 VarMapEntry = RootName + utostr(i);
1626 } else {
1627 // If we get here, this is a second reference to a specific name. Since
1628 // we already have checked that the first reference is valid, we don't
1629 // have to recursively match it, just check that it's the same as the
1630 // previously named thing.
1631 OS << " if (" << VarMapEntry << " != " << RootName << i
1632 << ") goto P" << PatternNo << "Fail;\n";
1633 continue;
1634 }
1635 }
1636
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001637 // Handle leaves of various types.
Chris Lattner2f041d42005-10-19 04:41:05 +00001638 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1639 Record *LeafRec = DI->getDef();
Evan Cheng66a48bb2005-12-01 00:18:45 +00001640 if (LeafRec->isSubClassOf("RegisterClass") ||
1641 LeafRec->isSubClassOf("Register")) {
Chris Lattner2f041d42005-10-19 04:41:05 +00001642 // Handle register references. Nothing to do here.
1643 } else if (LeafRec->isSubClassOf("ValueType")) {
1644 // Make sure this is the specified value type.
1645 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1646 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1647 << "Fail;\n";
Chris Lattner1531f202005-10-26 16:59:37 +00001648 } else if (LeafRec->isSubClassOf("CondCode")) {
1649 // Make sure this is the specified cond code.
1650 OS << " if (cast<CondCodeSDNode>(" << RootName << i
Chris Lattnera7ad1982005-10-26 17:02:02 +00001651 << ")->get() != " << "ISD::" << LeafRec->getName()
Chris Lattner1531f202005-10-26 16:59:37 +00001652 << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner2f041d42005-10-19 04:41:05 +00001653 } else {
1654 Child->dump();
1655 assert(0 && "Unknown leaf type!");
1656 }
1657 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1658 OS << " if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1659 << " cast<ConstantSDNode>(" << RootName << i
Chris Lattner9d1a0232005-10-29 16:39:40 +00001660 << ")->getSignExtended() != " << II->getValue() << ")\n"
Chris Lattner2f041d42005-10-19 04:41:05 +00001661 << " goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001662 } else {
1663 Child->dump();
1664 assert(0 && "Unknown leaf type!");
1665 }
1666 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001667 }
1668
1669 // If there is a node predicate for this, emit the call.
1670 if (!N->getPredicateFn().empty())
1671 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001672 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001673}
1674
Evan Cheng66a48bb2005-12-01 00:18:45 +00001675/// getRegisterValueType - Look up and return ValueType of specified record
1676static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1677 const std::vector<CodeGenRegisterClass> &RegisterClasses =
1678 T.getRegisterClasses();
1679
1680 for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
1681 const CodeGenRegisterClass &RC = RegisterClasses[i];
1682 for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
1683 if (R == RC.Elements[ei]) {
1684 return RC.VT;
1685 }
1686 }
1687 }
1688
1689 return MVT::Other;
1690}
1691
1692
1693/// EmitCopyToRegsForPattern - Emit the flag operands for the DAG that will be
1694/// built in CodeGenPatternResult.
1695void DAGISelEmitter::EmitCopyToRegsForPattern(TreePatternNode *N,
1696 const std::string &RootName,
1697 std::ostream &OS, bool &InFlag) {
1698 const CodeGenTarget &T = getTargetInfo();
1699 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1700 TreePatternNode *Child = N->getChild(i);
1701 if (!Child->isLeaf()) {
1702 EmitCopyToRegsForPattern(Child, RootName + utostr(i), OS, InFlag);
1703 } else {
1704 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1705 Record *RR = DI->getDef();
1706 if (RR->isSubClassOf("Register")) {
1707 MVT::ValueType RVT = getRegisterValueType(RR, T);
1708 if (!InFlag) {
1709 OS << " SDOperand InFlag; // Null incoming flag value.\n";
1710 InFlag = true;
1711 }
1712 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
1713 << ", CurDAG->getRegister(" << getQualifiedName(RR)
1714 << ", MVT::" << getEnumName(RVT) << ")"
1715 << ", " << RootName << i << ", InFlag).getValue(1);\n";
1716
1717 }
1718 }
1719 }
1720 }
1721}
1722
Chris Lattner6bc7e512005-09-26 21:53:26 +00001723/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1724/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001725unsigned DAGISelEmitter::
1726CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1727 std::map<std::string,std::string> &VariableMap,
Evan Cheng66a48bb2005-12-01 00:18:45 +00001728 std::ostream &OS, bool InFlag, bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001729 // This is something selected from the pattern we matched.
1730 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001731 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001732 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001733 assert(!Val.empty() &&
1734 "Variable referenced but not defined and not caught earlier!");
1735 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1736 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001737 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001738 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001739
1740 unsigned ResNo = Ctr++;
1741 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1742 switch (N->getType()) {
1743 default: assert(0 && "Unknown type for constant node!");
1744 case MVT::i1: OS << " bool Tmp"; break;
1745 case MVT::i8: OS << " unsigned char Tmp"; break;
1746 case MVT::i16: OS << " unsigned short Tmp"; break;
1747 case MVT::i32: OS << " unsigned Tmp"; break;
1748 case MVT::i64: OS << " uint64_t Tmp"; break;
1749 }
1750 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1751 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1752 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
Chris Lattnerb120a642005-11-17 07:39:45 +00001753 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1754 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Chris Lattnerf6f94162005-09-28 16:58:06 +00001755 } else {
1756 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1757 }
1758 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1759 // value if used multiple times by this pattern result.
1760 Val = "Tmp"+utostr(ResNo);
1761 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001762 }
1763
1764 if (N->isLeaf()) {
Chris Lattner4c593092005-10-19 02:07:26 +00001765 // If this is an explicit register reference, handle it.
1766 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1767 unsigned ResNo = Ctr++;
1768 if (DI->getDef()->isSubClassOf("Register")) {
1769 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1770 << getQualifiedName(DI->getDef()) << ", MVT::"
1771 << getEnumName(N->getType())
1772 << ");\n";
1773 return ResNo;
1774 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001775 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1776 unsigned ResNo = Ctr++;
1777 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1778 << II->getValue() << ", MVT::"
1779 << getEnumName(N->getType())
1780 << ");\n";
1781 return ResNo;
Chris Lattner4c593092005-10-19 02:07:26 +00001782 }
1783
Chris Lattner72fe91c2005-09-24 00:40:24 +00001784 N->dump();
1785 assert(0 && "Unknown leaf type!");
1786 return ~0U;
1787 }
1788
1789 Record *Op = N->getOperator();
1790 if (Op->isSubClassOf("Instruction")) {
1791 // Emit all of the operands.
1792 std::vector<unsigned> Ops;
1793 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Evan Cheng66a48bb2005-12-01 00:18:45 +00001794 Ops.push_back(CodeGenPatternResult(N->getChild(i),
1795 Ctr, VariableMap, OS, InFlag));
Chris Lattner72fe91c2005-09-24 00:40:24 +00001796
1797 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1798 unsigned ResNo = Ctr++;
1799
Chris Lattner5024d932005-10-16 01:41:58 +00001800 if (!isRoot) {
1801 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1802 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1803 << getEnumName(N->getType());
1804 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1805 OS << ", Tmp" << Ops[i];
1806 OS << ");\n";
1807 } else {
1808 // If this instruction is the root, and if there is only one use of it,
1809 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1810 OS << " if (N.Val->hasOneUse()) {\n";
Chris Lattner5d28ffd2005-11-30 23:08:45 +00001811 OS << " return CurDAG->SelectNodeTo(N.Val, "
Chris Lattner5024d932005-10-16 01:41:58 +00001812 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1813 << getEnumName(N->getType());
1814 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1815 OS << ", Tmp" << Ops[i];
Evan Cheng66a48bb2005-12-01 00:18:45 +00001816 if (InFlag)
1817 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00001818 OS << ");\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001819 OS << " } else {\n";
1820 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1821 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1822 << getEnumName(N->getType());
1823 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1824 OS << ", Tmp" << Ops[i];
Evan Cheng66a48bb2005-12-01 00:18:45 +00001825 if (InFlag)
1826 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00001827 OS << ");\n";
1828 OS << " }\n";
1829 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001830 return ResNo;
1831 } else if (Op->isSubClassOf("SDNodeXForm")) {
1832 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng66a48bb2005-12-01 00:18:45 +00001833 unsigned OpVal = CodeGenPatternResult(N->getChild(0),
1834 Ctr, VariableMap, OS, InFlag);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001835
1836 unsigned ResNo = Ctr++;
1837 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1838 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001839 if (isRoot) {
1840 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1841 OS << " return Tmp" << ResNo << ";\n";
1842 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001843 return ResNo;
1844 } else {
1845 N->dump();
1846 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001847 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001848 }
1849}
1850
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001851/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1852/// type information from it.
1853static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001854 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001855 if (!N->isLeaf())
1856 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1857 RemoveAllTypes(N->getChild(i));
1858}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001859
Chris Lattner7e82f132005-10-15 21:34:21 +00001860/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1861/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1862/// 'Pat' may be missing types. If we find an unresolved type to add a check
1863/// for, this returns true otherwise false if Pat has all types.
1864static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1865 const std::string &Prefix, unsigned PatternNo,
1866 std::ostream &OS) {
1867 // Did we find one?
1868 if (!Pat->hasTypeSet()) {
1869 // Move a type over from 'other' to 'pat'.
1870 Pat->setType(Other->getType());
1871 OS << " if (" << Prefix << ".getValueType() != MVT::"
1872 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1873 return true;
1874 } else if (Pat->isLeaf()) {
1875 return false;
1876 }
1877
1878 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1879 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1880 Prefix + utostr(i), PatternNo, OS))
1881 return true;
1882 return false;
1883}
1884
Chris Lattner0614b622005-11-02 06:49:14 +00001885Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1886 Record *N = Records.getDef(Name);
1887 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1888 return N;
1889}
1890
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001891/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1892/// stream to match the pattern, and generate the code for the match if it
1893/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001894void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1895 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001896 static unsigned PatternCount = 0;
1897 unsigned PatternNo = PatternCount++;
1898 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001899 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001900 OS << "\n // Emits: ";
1901 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001902 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001903 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1904 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001905
Chris Lattner8fc35682005-09-23 23:16:51 +00001906 // Emit the matcher, capturing named arguments in VariableMap.
1907 std::map<std::string,std::string> VariableMap;
1908 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001909
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001910 // TP - Get *SOME* tree pattern, we don't care which.
1911 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001912
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001913 // At this point, we know that we structurally match the pattern, but the
1914 // types of the nodes may not match. Figure out the fewest number of type
1915 // comparisons we need to emit. For example, if there is only one integer
1916 // type supported by a target, there should be no type comparisons at all for
1917 // integer patterns!
1918 //
1919 // To figure out the fewest number of type checks needed, clone the pattern,
1920 // remove the types, then perform type inference on the pattern as a whole.
1921 // If there are unresolved types, emit an explicit check for those types,
1922 // apply the type to the tree, then rerun type inference. Iterate until all
1923 // types are resolved.
1924 //
1925 TreePatternNode *Pat = Pattern.first->clone();
1926 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001927
1928 do {
1929 // Resolve/propagate as many types as possible.
1930 try {
1931 bool MadeChange = true;
1932 while (MadeChange)
1933 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1934 } catch (...) {
1935 assert(0 && "Error: could not find consistent types for something we"
1936 " already decided was ok!");
1937 abort();
1938 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001939
Chris Lattner7e82f132005-10-15 21:34:21 +00001940 // Insert a check for an unresolved type and add it to the tree. If we find
1941 // an unresolved type to add a check for, this returns true and we iterate,
1942 // otherwise we are done.
1943 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
Evan Cheng66a48bb2005-12-01 00:18:45 +00001944
1945 bool InFlag = false;
1946 EmitCopyToRegsForPattern(Pattern.first, "N", OS, InFlag);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001947
Chris Lattner5024d932005-10-16 01:41:58 +00001948 unsigned TmpNo = 0;
Evan Cheng66a48bb2005-12-01 00:18:45 +00001949 CodeGenPatternResult(Pattern.second,
1950 TmpNo, VariableMap, OS, InFlag, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001951 delete Pat;
1952
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001953 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001954}
1955
Chris Lattner37481472005-09-26 21:59:35 +00001956
1957namespace {
1958 /// CompareByRecordName - An ordering predicate that implements less-than by
1959 /// comparing the names records.
1960 struct CompareByRecordName {
1961 bool operator()(const Record *LHS, const Record *RHS) const {
1962 // Sort by name first.
1963 if (LHS->getName() < RHS->getName()) return true;
1964 // If both names are equal, sort by pointer.
1965 return LHS->getName() == RHS->getName() && LHS < RHS;
1966 }
1967 };
1968}
1969
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001970void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001971 std::string InstNS = Target.inst_begin()->second.Namespace;
1972 if (!InstNS.empty()) InstNS += "::";
1973
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001974 // Emit boilerplate.
1975 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001976 << "SDOperand SelectCode(SDOperand N) {\n"
1977 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001978 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1979 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001980 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001981 << " if (!N.Val->hasOneUse()) {\n"
1982 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1983 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1984 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001985 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001986 << " default: break;\n"
1987 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001988 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001989 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001990 << " case ISD::AssertZext: {\n"
1991 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1992 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1993 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001994 << " }\n"
1995 << " case ISD::TokenFactor:\n"
1996 << " if (N.getNumOperands() == 2) {\n"
1997 << " SDOperand Op0 = Select(N.getOperand(0));\n"
1998 << " SDOperand Op1 = Select(N.getOperand(1));\n"
1999 << " return CodeGenMap[N] =\n"
2000 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2001 << " } else {\n"
2002 << " std::vector<SDOperand> Ops;\n"
2003 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2004 << " Ops.push_back(Select(N.getOperand(i)));\n"
2005 << " return CodeGenMap[N] = \n"
2006 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2007 << " }\n"
2008 << " case ISD::CopyFromReg: {\n"
2009 << " SDOperand Chain = Select(N.getOperand(0));\n"
2010 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2011 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
2012 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
2013 << " N.Val->getValueType(0));\n"
2014 << " return New.getValue(N.ResNo);\n"
2015 << " }\n"
2016 << " case ISD::CopyToReg: {\n"
2017 << " SDOperand Chain = Select(N.getOperand(0));\n"
2018 << " SDOperand Reg = N.getOperand(1);\n"
2019 << " SDOperand Val = Select(N.getOperand(2));\n"
2020 << " return CodeGenMap[N] = \n"
2021 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
2022 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002023 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002024
Chris Lattner81303322005-09-23 19:36:15 +00002025 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00002026 std::map<Record*, std::vector<PatternToMatch*>,
2027 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00002028 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
Chris Lattner0614b622005-11-02 06:49:14 +00002029 if (!PatternsToMatch[i].first->isLeaf()) {
2030 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
2031 .push_back(&PatternsToMatch[i]);
2032 } else {
2033 if (IntInit *II =
2034 dynamic_cast<IntInit*>(PatternsToMatch[i].first->getLeafValue())) {
2035 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2036 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00002037 std::cerr << "Unrecognized opcode '";
2038 PatternsToMatch[i].first->dump();
2039 std::cerr << "' on tree pattern '";
2040 std::cerr << PatternsToMatch[i].second->getOperator()->getName();
2041 std::cerr << "'!\n";
2042 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00002043 }
2044 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002045
Chris Lattner3f7e9142005-09-23 20:52:47 +00002046 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00002047 for (std::map<Record*, std::vector<PatternToMatch*>,
2048 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2049 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002050 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2051 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2052
2053 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002054
2055 // We want to emit all of the matching code now. However, we want to emit
2056 // the matches in order of minimal cost. Sort the patterns so the least
2057 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002058 std::stable_sort(Patterns.begin(), Patterns.end(),
2059 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00002060
Chris Lattner3f7e9142005-09-23 20:52:47 +00002061 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2062 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002063 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00002064 }
2065
2066
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002067 OS << " } // end of big switch.\n\n"
2068 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002069 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002070 << " std::cerr << '\\n';\n"
2071 << " abort();\n"
2072 << "}\n";
2073}
2074
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002075void DAGISelEmitter::run(std::ostream &OS) {
2076 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2077 " target", OS);
2078
Chris Lattner1f39e292005-09-14 00:09:24 +00002079 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2080 << "// *** instruction selector class. These functions are really "
2081 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002082
Chris Lattner296dfe32005-09-24 00:50:51 +00002083 OS << "// Instance var to keep track of multiply used nodes that have \n"
2084 << "// already been selected.\n"
2085 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2086
Chris Lattnerca559d02005-09-08 21:03:01 +00002087 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002088 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002089 ParsePatternFragments(OS);
2090 ParseInstructions();
2091 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002092
Chris Lattnere97603f2005-09-28 19:27:25 +00002093 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002094 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002095 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002096
Chris Lattnere46e17b2005-09-29 19:28:10 +00002097
2098 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2099 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2100 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
2101 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
2102 std::cerr << "\n";
2103 });
2104
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002105 // At this point, we have full information about the 'Patterns' we need to
2106 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002107 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002108 EmitInstructionSelector(OS);
2109
2110 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2111 E = PatternFragments.end(); I != E; ++I)
2112 delete I->second;
2113 PatternFragments.clear();
2114
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002115 Instructions.clear();
2116}