blob: 07d35d4b7d3042121f1b1a88c13bcc93e3493b43 [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"));
Chris Lattner5b21be72005-12-09 22:57:42 +000061 } else if (R->isSubClassOf("SDTCisPtrTy")) {
62 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000063 } else if (R->isSubClassOf("SDTCisInt")) {
64 ConstraintType = SDTCisInt;
65 } else if (R->isSubClassOf("SDTCisFP")) {
66 ConstraintType = SDTCisFP;
67 } else if (R->isSubClassOf("SDTCisSameAs")) {
68 ConstraintType = SDTCisSameAs;
69 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
70 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
71 ConstraintType = SDTCisVTSmallerThanOp;
72 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
73 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +000074 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
75 ConstraintType = SDTCisOpSmallerThanOp;
76 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
77 R->getValueAsInt("BigOperandNum");
Chris Lattner33c92e92005-09-08 21:27:15 +000078 } else {
79 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
80 exit(1);
81 }
82}
83
Chris Lattner32707602005-09-08 23:22:48 +000084/// getOperandNum - Return the node corresponding to operand #OpNo in tree
85/// N, which has NumResults results.
86TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
87 TreePatternNode *N,
88 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +000089 assert(NumResults <= 1 &&
90 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +000091
92 if (OpNo < NumResults)
93 return N; // FIXME: need value #
94 else
95 return N->getChild(OpNo-NumResults);
96}
97
98/// ApplyTypeConstraint - Given a node in a pattern, apply this type
99/// constraint to the nodes operands. This returns true if it makes a
100/// change, false otherwise. If a type contradiction is found, throw an
101/// exception.
102bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
103 const SDNodeInfo &NodeInfo,
104 TreePattern &TP) const {
105 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000106 assert(NumResults <= 1 &&
107 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000108
109 // Check that the number of operands is sane.
110 if (NodeInfo.getNumOperands() >= 0) {
111 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
112 TP.error(N->getOperator()->getName() + " node requires exactly " +
113 itostr(NodeInfo.getNumOperands()) + " operands!");
114 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000115
116 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000117
118 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
119
120 switch (ConstraintType) {
121 default: assert(0 && "Unknown constraint type!");
122 case SDTCisVT:
123 // Operand must be a particular type.
124 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000125 case SDTCisPtrTy: {
126 // Operand must be same as target pointer type.
127 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
128 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000129 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000130 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000131 std::vector<MVT::ValueType> IntVTs =
132 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000133
134 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000135 if (IntVTs.size() == 1)
136 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000137 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000138 }
139 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000140 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000141 std::vector<MVT::ValueType> FPVTs =
142 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000143
144 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000145 if (FPVTs.size() == 1)
146 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000147 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000148 }
Chris Lattner32707602005-09-08 23:22:48 +0000149 case SDTCisSameAs: {
150 TreePatternNode *OtherNode =
151 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000152 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
153 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000154 }
155 case SDTCisVTSmallerThanOp: {
156 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
157 // have an integer type that is smaller than the VT.
158 if (!NodeToApply->isLeaf() ||
159 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
160 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
161 ->isSubClassOf("ValueType"))
162 TP.error(N->getOperator()->getName() + " expects a VT operand!");
163 MVT::ValueType VT =
164 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
165 if (!MVT::isInteger(VT))
166 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
167
168 TreePatternNode *OtherNode =
169 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000170
171 // It must be integer.
172 bool MadeChange = false;
173 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
174
175 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000176 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
177 return false;
178 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000179 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000180 TreePatternNode *BigOperand =
181 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
182
183 // Both operands must be integer or FP, but we don't care which.
184 bool MadeChange = false;
185
186 if (isExtIntegerVT(NodeToApply->getExtType()))
187 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
188 else if (isExtFloatingPointVT(NodeToApply->getExtType()))
189 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
190 if (isExtIntegerVT(BigOperand->getExtType()))
191 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
192 else if (isExtFloatingPointVT(BigOperand->getExtType()))
193 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
194
195 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
196
197 if (isExtIntegerVT(NodeToApply->getExtType())) {
198 VTs = FilterVTs(VTs, MVT::isInteger);
199 } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
200 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
201 } else {
202 VTs.clear();
203 }
204
205 switch (VTs.size()) {
206 default: // Too many VT's to pick from.
207 case 0: break; // No info yet.
208 case 1:
209 // Only one VT of this flavor. Cannot ever satisify the constraints.
210 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
211 case 2:
212 // If we have exactly two possible types, the little operand must be the
213 // small one, the big operand should be the big one. Common with
214 // float/double for example.
215 assert(VTs[0] < VTs[1] && "Should be sorted!");
216 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
217 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
218 break;
219 }
220 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000221 }
Chris Lattner32707602005-09-08 23:22:48 +0000222 }
223 return false;
224}
225
226
Chris Lattner33c92e92005-09-08 21:27:15 +0000227//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000228// SDNodeInfo implementation
229//
230SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
231 EnumName = R->getValueAsString("Opcode");
232 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000233 Record *TypeProfile = R->getValueAsDef("TypeProfile");
234 NumResults = TypeProfile->getValueAsInt("NumResults");
235 NumOperands = TypeProfile->getValueAsInt("NumOperands");
236
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000237 // Parse the properties.
238 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000239 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000240 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
241 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000242 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000243 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000244 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000245 } else if (PropList[i]->getName() == "SDNPHasChain") {
246 Properties |= 1 << SDNPHasChain;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000247 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000248 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000249 << "' on node '" << R->getName() << "'!\n";
250 exit(1);
251 }
252 }
253
254
Chris Lattner33c92e92005-09-08 21:27:15 +0000255 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000256 std::vector<Record*> ConstraintList =
257 TypeProfile->getValueAsListOfDefs("Constraints");
258 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000259}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000260
261//===----------------------------------------------------------------------===//
262// TreePatternNode implementation
263//
264
265TreePatternNode::~TreePatternNode() {
266#if 0 // FIXME: implement refcounted tree nodes!
267 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
268 delete getChild(i);
269#endif
270}
271
Chris Lattner32707602005-09-08 23:22:48 +0000272/// UpdateNodeType - Set the node type of N to VT if VT contains
273/// information. If N already contains a conflicting type, then throw an
274/// exception. This returns true if any information was updated.
275///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000276bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
277 if (VT == MVT::isUnknown || getExtType() == VT) return false;
278 if (getExtType() == MVT::isUnknown) {
Chris Lattner32707602005-09-08 23:22:48 +0000279 setType(VT);
280 return true;
281 }
282
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000283 // If we are told this is to be an int or FP type, and it already is, ignore
284 // the advice.
285 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
286 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
287 return false;
288
289 // If we know this is an int or fp type, and we are told it is a specific one,
290 // take the advice.
291 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
292 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
293 setType(VT);
294 return true;
295 }
296
Chris Lattner1531f202005-10-26 16:59:37 +0000297 if (isLeaf()) {
298 dump();
299 TP.error("Type inference contradiction found in node!");
300 } else {
301 TP.error("Type inference contradiction found in node " +
302 getOperator()->getName() + "!");
303 }
Chris Lattner32707602005-09-08 23:22:48 +0000304 return true; // unreachable
305}
306
307
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000308void TreePatternNode::print(std::ostream &OS) const {
309 if (isLeaf()) {
310 OS << *getLeafValue();
311 } else {
312 OS << "(" << getOperator()->getName();
313 }
314
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000315 switch (getExtType()) {
316 case MVT::Other: OS << ":Other"; break;
317 case MVT::isInt: OS << ":isInt"; break;
318 case MVT::isFP : OS << ":isFP"; break;
319 case MVT::isUnknown: ; /*OS << ":?";*/ break;
320 default: OS << ":" << getType(); break;
321 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000322
323 if (!isLeaf()) {
324 if (getNumChildren() != 0) {
325 OS << " ";
326 getChild(0)->print(OS);
327 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
328 OS << ", ";
329 getChild(i)->print(OS);
330 }
331 }
332 OS << ")";
333 }
334
335 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000336 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000337 if (TransformFn)
338 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000339 if (!getName().empty())
340 OS << ":$" << getName();
341
342}
343void TreePatternNode::dump() const {
344 print(std::cerr);
345}
346
Chris Lattnere46e17b2005-09-29 19:28:10 +0000347/// isIsomorphicTo - Return true if this node is recursively isomorphic to
348/// the specified node. For this comparison, all of the state of the node
349/// is considered, except for the assigned name. Nodes with differing names
350/// that are otherwise identical are considered isomorphic.
351bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
352 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000353 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000354 getPredicateFn() != N->getPredicateFn() ||
355 getTransformFn() != N->getTransformFn())
356 return false;
357
358 if (isLeaf()) {
359 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
360 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
361 return DI->getDef() == NDI->getDef();
362 return getLeafValue() == N->getLeafValue();
363 }
364
365 if (N->getOperator() != getOperator() ||
366 N->getNumChildren() != getNumChildren()) return false;
367 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
368 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
369 return false;
370 return true;
371}
372
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000373/// clone - Make a copy of this tree and all of its children.
374///
375TreePatternNode *TreePatternNode::clone() const {
376 TreePatternNode *New;
377 if (isLeaf()) {
378 New = new TreePatternNode(getLeafValue());
379 } else {
380 std::vector<TreePatternNode*> CChildren;
381 CChildren.reserve(Children.size());
382 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
383 CChildren.push_back(getChild(i)->clone());
384 New = new TreePatternNode(getOperator(), CChildren);
385 }
386 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000387 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000388 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000389 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000390 return New;
391}
392
Chris Lattner32707602005-09-08 23:22:48 +0000393/// SubstituteFormalArguments - Replace the formal arguments in this tree
394/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000395void TreePatternNode::
396SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
397 if (isLeaf()) return;
398
399 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
400 TreePatternNode *Child = getChild(i);
401 if (Child->isLeaf()) {
402 Init *Val = Child->getLeafValue();
403 if (dynamic_cast<DefInit*>(Val) &&
404 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
405 // We found a use of a formal argument, replace it with its value.
406 Child = ArgMap[Child->getName()];
407 assert(Child && "Couldn't find formal argument!");
408 setChild(i, Child);
409 }
410 } else {
411 getChild(i)->SubstituteFormalArguments(ArgMap);
412 }
413 }
414}
415
416
417/// InlinePatternFragments - If this pattern refers to any pattern
418/// fragments, inline them into place, giving us a pattern without any
419/// PatFrag references.
420TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
421 if (isLeaf()) return this; // nothing to do.
422 Record *Op = getOperator();
423
424 if (!Op->isSubClassOf("PatFrag")) {
425 // Just recursively inline children nodes.
426 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
427 setChild(i, getChild(i)->InlinePatternFragments(TP));
428 return this;
429 }
430
431 // Otherwise, we found a reference to a fragment. First, look up its
432 // TreePattern record.
433 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
434
435 // Verify that we are passing the right number of operands.
436 if (Frag->getNumArgs() != Children.size())
437 TP.error("'" + Op->getName() + "' fragment requires " +
438 utostr(Frag->getNumArgs()) + " operands!");
439
Chris Lattner37937092005-09-09 01:15:01 +0000440 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000441
442 // Resolve formal arguments to their actual value.
443 if (Frag->getNumArgs()) {
444 // Compute the map of formal to actual arguments.
445 std::map<std::string, TreePatternNode*> ArgMap;
446 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
447 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
448
449 FragTree->SubstituteFormalArguments(ArgMap);
450 }
451
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000452 FragTree->setName(getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000453 FragTree->UpdateNodeType(getExtType(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000454
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000455 // Get a new copy of this fragment to stitch into here.
456 //delete this; // FIXME: implement refcounting!
457 return FragTree;
458}
459
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000460/// getIntrinsicType - Check to see if the specified record has an intrinsic
461/// type which should be applied to it. This infer the type of register
462/// references from the register file information, for example.
463///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000464static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
465 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000466 // Check to see if this is a register or a register class...
467 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000468 if (NotRegisters) return MVT::isUnknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000469 const CodeGenRegisterClass &RC =
470 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
471 return RC.getValueTypeNum(0);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000472 } else if (R->isSubClassOf("PatFrag")) {
473 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000474 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000475 } else if (R->isSubClassOf("Register")) {
Chris Lattner22faeab2005-12-05 02:36:37 +0000476 // If the register appears in exactly one regclass, and the regclass has one
477 // value type, use it as the known type.
478 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
479 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
480 if (RC->getNumValueTypes() == 1)
481 return RC->getValueTypeNum(0);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000482 return MVT::isUnknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000483 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
484 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000485 return MVT::Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000486 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng3aa39f42005-12-08 02:14:08 +0000487 return TP.getDAGISelEmitter().getComplexPattern(R).getValueType();
Evan Cheng01f318b2005-12-14 02:21:57 +0000488 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000489 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000490 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000491 }
492
493 TP.error("Unknown node flavor used in pattern: " + R->getName());
494 return MVT::Other;
495}
496
Chris Lattner32707602005-09-08 23:22:48 +0000497/// ApplyTypeConstraints - Apply all of the type constraints relevent to
498/// this node and its children in the tree. This returns true if it makes a
499/// change, false otherwise. If a type contradiction is found, throw an
500/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000501bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
502 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000503 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000504 // If it's a regclass or something else known, include the type.
505 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
506 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000507 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
508 // Int inits are always integers. :)
509 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
510
511 if (hasTypeSet()) {
512 unsigned Size = MVT::getSizeInBits(getType());
513 // Make sure that the value is representable for this type.
514 if (Size < 32) {
515 int Val = (II->getValue() << (32-Size)) >> (32-Size);
516 if (Val != II->getValue())
517 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
518 "' is out of range for type 'MVT::" +
519 getEnumName(getType()) + "'!");
520 }
521 }
522
523 return MadeChange;
524 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000525 return false;
526 }
Chris Lattner32707602005-09-08 23:22:48 +0000527
528 // special handling for set, which isn't really an SDNode.
529 if (getOperator()->getName() == "set") {
530 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000531 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
532 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000533
534 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000535 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
536 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000537 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
538 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000539 } else if (getOperator()->isSubClassOf("SDNode")) {
540 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
541
542 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
543 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000544 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000545 // Branch, etc. do not produce results and top-level forms in instr pattern
546 // must have void types.
547 if (NI.getNumResults() == 0)
548 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000549 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000550 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000551 const DAGInstruction &Inst =
552 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000553 bool MadeChange = false;
554 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000555
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000556 assert(NumResults <= 1 &&
557 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000558 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000559 if (NumResults == 0) {
560 MadeChange = UpdateNodeType(MVT::isVoid, TP);
561 } else {
562 Record *ResultNode = Inst.getResult(0);
563 assert(ResultNode->isSubClassOf("RegisterClass") &&
564 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000565
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000566 const CodeGenRegisterClass &RC =
567 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000568
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000569 // Get the first ValueType in the RegClass, it's as good as any.
570 MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
571 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000572
573 if (getNumChildren() != Inst.getNumOperands())
574 TP.error("Instruction '" + getOperator()->getName() + " expects " +
575 utostr(Inst.getNumOperands()) + " operands, not " +
576 utostr(getNumChildren()) + " operands!");
577 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000578 Record *OperandNode = Inst.getOperand(i);
579 MVT::ValueType VT;
580 if (OperandNode->isSubClassOf("RegisterClass")) {
581 const CodeGenRegisterClass &RC =
582 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000583 VT = RC.getValueTypeNum(0);
Nate Begemanddb39542005-12-01 00:06:14 +0000584 } else if (OperandNode->isSubClassOf("Operand")) {
585 VT = getValueType(OperandNode->getValueAsDef("Type"));
586 } else {
587 assert(0 && "Unknown operand type!");
588 abort();
589 }
590
591 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000592 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000593 }
594 return MadeChange;
595 } else {
596 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
597
598 // Node transforms always take one operand, and take and return the same
599 // type.
600 if (getNumChildren() != 1)
601 TP.error("Node transform '" + getOperator()->getName() +
602 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000603 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
604 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000605 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000606 }
Chris Lattner32707602005-09-08 23:22:48 +0000607}
608
Chris Lattnere97603f2005-09-28 19:27:25 +0000609/// canPatternMatch - If it is impossible for this pattern to match on this
610/// target, fill in Reason and return false. Otherwise, return true. This is
611/// used as a santity check for .td files (to prevent people from writing stuff
612/// that can never possibly work), and to prevent the pattern permuter from
613/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000614bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000615 if (isLeaf()) return true;
616
617 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
618 if (!getChild(i)->canPatternMatch(Reason, ISE))
619 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000620
Chris Lattnere97603f2005-09-28 19:27:25 +0000621 // If this node is a commutative operator, check that the LHS isn't an
622 // immediate.
623 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
624 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
625 // Scan all of the operands of the node and make sure that only the last one
626 // is a constant node.
627 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
628 if (!getChild(i)->isLeaf() &&
629 getChild(i)->getOperator()->getName() == "imm") {
630 Reason = "Immediate value must be on the RHS of commutative operators!";
631 return false;
632 }
633 }
634
635 return true;
636}
Chris Lattner32707602005-09-08 23:22:48 +0000637
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000638//===----------------------------------------------------------------------===//
639// TreePattern implementation
640//
641
Chris Lattneredbd8712005-10-21 01:19:59 +0000642TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000643 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000644 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000645 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
646 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000647}
648
Chris Lattneredbd8712005-10-21 01:19:59 +0000649TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000650 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000651 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000652 Trees.push_back(ParseTreePattern(Pat));
653}
654
Chris Lattneredbd8712005-10-21 01:19:59 +0000655TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000656 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000657 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000658 Trees.push_back(Pat);
659}
660
661
662
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000663void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000664 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000665 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000666}
667
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000668TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
669 Record *Operator = Dag->getNodeType();
670
671 if (Operator->isSubClassOf("ValueType")) {
672 // If the operator is a ValueType, then this must be "type cast" of a leaf
673 // node.
674 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000675 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000676
677 Init *Arg = Dag->getArg(0);
678 TreePatternNode *New;
679 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000680 Record *R = DI->getDef();
681 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
682 Dag->setArg(0, new DagInit(R,
683 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000684 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000685 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000686 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000687 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
688 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000689 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
690 New = new TreePatternNode(II);
691 if (!Dag->getArgName(0).empty())
692 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000693 } else {
694 Arg->dump();
695 error("Unknown leaf value for tree pattern!");
696 return 0;
697 }
698
Chris Lattner32707602005-09-08 23:22:48 +0000699 // Apply the type cast.
700 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000701 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000702 return New;
703 }
704
705 // Verify that this is something that makes sense for an operator.
706 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000707 !Operator->isSubClassOf("Instruction") &&
708 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000709 Operator->getName() != "set")
710 error("Unrecognized node '" + Operator->getName() + "'!");
711
Chris Lattneredbd8712005-10-21 01:19:59 +0000712 // Check to see if this is something that is illegal in an input pattern.
713 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
714 Operator->isSubClassOf("SDNodeXForm")))
715 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
716
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000717 std::vector<TreePatternNode*> Children;
718
719 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
720 Init *Arg = Dag->getArg(i);
721 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
722 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000723 if (Children.back()->getName().empty())
724 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000725 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
726 Record *R = DefI->getDef();
727 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
728 // TreePatternNode if its own.
729 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
730 Dag->setArg(i, new DagInit(R,
731 std::vector<std::pair<Init*, std::string> >()));
732 --i; // Revisit this node...
733 } else {
734 TreePatternNode *Node = new TreePatternNode(DefI);
735 Node->setName(Dag->getArgName(i));
736 Children.push_back(Node);
737
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000738 // Input argument?
739 if (R->getName() == "node") {
740 if (Dag->getArgName(i).empty())
741 error("'node' argument requires a name to match with operand list");
742 Args.push_back(Dag->getArgName(i));
743 }
744 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000745 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
746 TreePatternNode *Node = new TreePatternNode(II);
747 if (!Dag->getArgName(i).empty())
748 error("Constant int argument should not have a name!");
749 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000750 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000751 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000752 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000753 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000754 error("Unknown leaf value for tree pattern!");
755 }
756 }
757
758 return new TreePatternNode(Operator, Children);
759}
760
Chris Lattner32707602005-09-08 23:22:48 +0000761/// InferAllTypes - Infer/propagate as many types throughout the expression
762/// patterns as possible. Return true if all types are infered, false
763/// otherwise. Throw an exception if a type contradiction is found.
764bool TreePattern::InferAllTypes() {
765 bool MadeChange = true;
766 while (MadeChange) {
767 MadeChange = false;
768 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000769 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000770 }
771
772 bool HasUnresolvedTypes = false;
773 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
774 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
775 return !HasUnresolvedTypes;
776}
777
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000778void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000779 OS << getRecord()->getName();
780 if (!Args.empty()) {
781 OS << "(" << Args[0];
782 for (unsigned i = 1, e = Args.size(); i != e; ++i)
783 OS << ", " << Args[i];
784 OS << ")";
785 }
786 OS << ": ";
787
788 if (Trees.size() > 1)
789 OS << "[\n";
790 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
791 OS << "\t";
792 Trees[i]->print(OS);
793 OS << "\n";
794 }
795
796 if (Trees.size() > 1)
797 OS << "]\n";
798}
799
800void TreePattern::dump() const { print(std::cerr); }
801
802
803
804//===----------------------------------------------------------------------===//
805// DAGISelEmitter implementation
806//
807
Chris Lattnerca559d02005-09-08 21:03:01 +0000808// Parse all of the SDNode definitions for the target, populating SDNodes.
809void DAGISelEmitter::ParseNodeInfo() {
810 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
811 while (!Nodes.empty()) {
812 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
813 Nodes.pop_back();
814 }
815}
816
Chris Lattner24eeeb82005-09-13 21:51:00 +0000817/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
818/// map, and emit them to the file as functions.
819void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
820 OS << "\n// Node transformations.\n";
821 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
822 while (!Xforms.empty()) {
823 Record *XFormNode = Xforms.back();
824 Record *SDNode = XFormNode->getValueAsDef("Opcode");
825 std::string Code = XFormNode->getValueAsCode("XFormFunction");
826 SDNodeXForms.insert(std::make_pair(XFormNode,
827 std::make_pair(SDNode, Code)));
828
Chris Lattner1048b7a2005-09-13 22:03:37 +0000829 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000830 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
831 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
832
Chris Lattner1048b7a2005-09-13 22:03:37 +0000833 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000834 << "(SDNode *" << C2 << ") {\n";
835 if (ClassName != "SDNode")
836 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
837 OS << Code << "\n}\n";
838 }
839
840 Xforms.pop_back();
841 }
842}
843
Evan Cheng0fc71982005-12-08 02:00:36 +0000844void DAGISelEmitter::ParseComplexPatterns() {
845 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
846 while (!AMs.empty()) {
847 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
848 AMs.pop_back();
849 }
850}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000851
852
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000853/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
854/// file, building up the PatternFragments map. After we've collected them all,
855/// inline fragments together as necessary, so that there are no references left
856/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000857///
858/// This also emits all of the predicate functions to the output file.
859///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000860void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000861 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
862
863 // First step, parse all of the fragments and emit predicate functions.
864 OS << "\n// Predicate functions.\n";
865 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000866 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000867 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000868 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000869
870 // Validate the argument list, converting it to map, to discard duplicates.
871 std::vector<std::string> &Args = P->getArgList();
872 std::set<std::string> OperandsMap(Args.begin(), Args.end());
873
874 if (OperandsMap.count(""))
875 P->error("Cannot have unnamed 'node' values in pattern fragment!");
876
877 // Parse the operands list.
878 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
879 if (OpsList->getNodeType()->getName() != "ops")
880 P->error("Operands list should start with '(ops ... '!");
881
882 // Copy over the arguments.
883 Args.clear();
884 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
885 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
886 static_cast<DefInit*>(OpsList->getArg(j))->
887 getDef()->getName() != "node")
888 P->error("Operands list should all be 'node' values.");
889 if (OpsList->getArgName(j).empty())
890 P->error("Operands list should have names for each operand!");
891 if (!OperandsMap.count(OpsList->getArgName(j)))
892 P->error("'" + OpsList->getArgName(j) +
893 "' does not occur in pattern or was multiply specified!");
894 OperandsMap.erase(OpsList->getArgName(j));
895 Args.push_back(OpsList->getArgName(j));
896 }
897
898 if (!OperandsMap.empty())
899 P->error("Operands list does not contain an entry for operand '" +
900 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000901
902 // If there is a code init for this fragment, emit the predicate code and
903 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000904 std::string Code = Fragments[i]->getValueAsCode("Predicate");
905 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000906 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000907 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000908 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000909 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
910
Chris Lattner1048b7a2005-09-13 22:03:37 +0000911 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000912 << "(SDNode *" << C2 << ") {\n";
913 if (ClassName != "SDNode")
914 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000915 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000916 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000917 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000918
919 // If there is a node transformation corresponding to this, keep track of
920 // it.
921 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
922 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000923 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000924 }
925
926 OS << "\n\n";
927
928 // Now that we've parsed all of the tree fragments, do a closure on them so
929 // that there are not references to PatFrags left inside of them.
930 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
931 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000932 TreePattern *ThePat = I->second;
933 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000934
Chris Lattner32707602005-09-08 23:22:48 +0000935 // Infer as many types as possible. Don't worry about it if we don't infer
936 // all of them, some may depend on the inputs of the pattern.
937 try {
938 ThePat->InferAllTypes();
939 } catch (...) {
940 // If this pattern fragment is not supported by this target (no types can
941 // satisfy its constraints), just ignore it. If the bogus pattern is
942 // actually used by instructions, the type consistency error will be
943 // reported there.
944 }
945
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000946 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000947 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000948 }
949}
950
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000951/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000952/// instruction input. Return true if this is a real use.
953static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000954 std::map<std::string, TreePatternNode*> &InstInputs) {
955 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000956 if (Pat->getName().empty()) {
957 if (Pat->isLeaf()) {
958 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
959 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
960 I->error("Input " + DI->getDef()->getName() + " must be named!");
961
962 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000963 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000964 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000965
966 Record *Rec;
967 if (Pat->isLeaf()) {
968 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
969 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
970 Rec = DI->getDef();
971 } else {
972 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
973 Rec = Pat->getOperator();
974 }
975
Evan Cheng01f318b2005-12-14 02:21:57 +0000976 // SRCVALUE nodes are ignored.
977 if (Rec->getName() == "srcvalue")
978 return false;
979
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000980 TreePatternNode *&Slot = InstInputs[Pat->getName()];
981 if (!Slot) {
982 Slot = Pat;
983 } else {
984 Record *SlotRec;
985 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000986 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000987 } else {
988 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
989 SlotRec = Slot->getOperator();
990 }
991
992 // Ensure that the inputs agree if we've already seen this input.
993 if (Rec != SlotRec)
994 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000995 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000996 I->error("All $" + Pat->getName() + " inputs must agree with each other");
997 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000998 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000999}
1000
1001/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1002/// part of "I", the instruction), computing the set of inputs and outputs of
1003/// the pattern. Report errors if we see anything naughty.
1004void DAGISelEmitter::
1005FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1006 std::map<std::string, TreePatternNode*> &InstInputs,
1007 std::map<std::string, Record*> &InstResults) {
1008 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +00001009 bool isUse = HandleUse(I, Pat, InstInputs);
1010 if (!isUse && Pat->getTransformFn())
1011 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001012 return;
1013 } else if (Pat->getOperator()->getName() != "set") {
1014 // If this is not a set, verify that the children nodes are not void typed,
1015 // and recurse.
1016 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001017 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001018 I->error("Cannot have void nodes inside of patterns!");
1019 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
1020 }
1021
1022 // If this is a non-leaf node with no children, treat it basically as if
1023 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001024 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001025 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +00001026 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001027
Chris Lattnerf1311842005-09-14 23:05:13 +00001028 if (!isUse && Pat->getTransformFn())
1029 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001030 return;
1031 }
1032
1033 // Otherwise, this is a set, validate and collect instruction results.
1034 if (Pat->getNumChildren() == 0)
1035 I->error("set requires operands!");
1036 else if (Pat->getNumChildren() & 1)
1037 I->error("set requires an even number of operands");
1038
Chris Lattnerf1311842005-09-14 23:05:13 +00001039 if (Pat->getTransformFn())
1040 I->error("Cannot specify a transform function on a set node!");
1041
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001042 // Check the set destinations.
1043 unsigned NumValues = Pat->getNumChildren()/2;
1044 for (unsigned i = 0; i != NumValues; ++i) {
1045 TreePatternNode *Dest = Pat->getChild(i);
1046 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001047 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001048
1049 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1050 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001051 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001052
Evan Cheng86217892005-12-12 19:37:43 +00001053 if (!Val->getDef()->isSubClassOf("RegisterClass") &&
1054 !Val->getDef()->isSubClassOf("Register"))
1055 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001056 if (Dest->getName().empty())
1057 I->error("set destination must have a name!");
1058 if (InstResults.count(Dest->getName()))
1059 I->error("cannot set '" + Dest->getName() +"' multiple times");
1060 InstResults[Dest->getName()] = Val->getDef();
1061
1062 // Verify and collect info from the computation.
1063 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1064 InstInputs, InstResults);
1065 }
1066}
1067
Evan Chengdd304dd2005-12-05 23:08:55 +00001068/// NodeHasChain - return true if TreePatternNode has the property
1069/// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1070/// a chain result.
1071static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1072{
1073 if (N->isLeaf()) return false;
1074 Record *Operator = N->getOperator();
1075 if (!Operator->isSubClassOf("SDNode")) return false;
1076
1077 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1078 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1079}
1080
1081static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1082{
1083 if (NodeHasChain(N, ISE))
1084 return true;
1085 else {
1086 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1087 TreePatternNode *Child = N->getChild(i);
1088 if (PatternHasCtrlDep(Child, ISE))
1089 return true;
1090 }
1091 }
1092
1093 return false;
1094}
1095
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001096
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001097/// ParseInstructions - Parse all of the instructions, inlining and resolving
1098/// any fragments involved. This populates the Instructions list with fully
1099/// resolved instructions.
1100void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001101 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1102
1103 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001104 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001105
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001106 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1107 LI = Instrs[i]->getValueAsListInit("Pattern");
1108
1109 // If there is no pattern, only collect minimal information about the
1110 // instruction for its operand list. We have to assume that there is one
1111 // result, as we have no detailed info.
1112 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001113 std::vector<Record*> Results;
1114 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001115
1116 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1117
1118 // Doesn't even define a result?
1119 if (InstInfo.OperandList.size() == 0)
1120 continue;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001121
1122 // FIXME: temporary hack...
1123 if (InstInfo.isReturn || InstInfo.isBranch || InstInfo.isCall ||
1124 InstInfo.isStore) {
1125 // These produce no results
1126 for (unsigned j = 0, e = InstInfo.OperandList.size(); j != e; ++j)
1127 Operands.push_back(InstInfo.OperandList[j].Rec);
1128 } else {
1129 // Assume the first operand is the result.
1130 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001131
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001132 // The rest are inputs.
1133 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1134 Operands.push_back(InstInfo.OperandList[j].Rec);
1135 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001136
1137 // Create and insert the instruction.
1138 Instructions.insert(std::make_pair(Instrs[i],
Nate Begemanddb39542005-12-01 00:06:14 +00001139 DAGInstruction(0, Results, Operands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001140 continue; // no pattern.
1141 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001142
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001143 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001144 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001145 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001146 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001147
Chris Lattner95f6b762005-09-08 23:26:30 +00001148 // Infer as many types as possible. If we cannot infer all of them, we can
1149 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001150 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001151 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001152
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001153 // InstInputs - Keep track of all of the inputs of the instruction, along
1154 // with the record they are declared as.
1155 std::map<std::string, TreePatternNode*> InstInputs;
1156
1157 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001158 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001159 std::map<std::string, Record*> InstResults;
1160
Chris Lattner1f39e292005-09-14 00:09:24 +00001161 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001162 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001163 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1164 TreePatternNode *Pat = I->getTree(j);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001165 if (Pat->getExtType() != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001166 I->error("Top-level forms in instruction pattern should have"
1167 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001168
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001169 // Find inputs and outputs, and verify the structure of the uses/defs.
1170 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001171 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001172
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001173 // Now that we have inputs and outputs of the pattern, inspect the operands
1174 // list for the instruction. This determines the order that operands are
1175 // added to the machine instruction the node corresponds to.
1176 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001177
1178 // Parse the operands list from the (ops) list, validating it.
1179 std::vector<std::string> &Args = I->getArgList();
1180 assert(Args.empty() && "Args list should still be empty here!");
1181 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1182
1183 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001184 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001185 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001186 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001187 I->error("'" + InstResults.begin()->first +
1188 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001189 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001190
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001191 // Check that it exists in InstResults.
1192 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001193 if (R == 0)
1194 I->error("Operand $" + OpName + " should be a set destination: all "
1195 "outputs must occur before inputs in operand list!");
1196
1197 if (CGI.OperandList[i].Rec != R)
1198 I->error("Operand $" + OpName + " class mismatch!");
1199
Chris Lattnerae6d8282005-09-15 21:51:12 +00001200 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001201 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001202
Chris Lattner39e8af92005-09-14 18:19:25 +00001203 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001204 InstResults.erase(OpName);
1205 }
1206
Chris Lattner0b592252005-09-14 21:59:34 +00001207 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1208 // the copy while we're checking the inputs.
1209 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001210
1211 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001212 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001213 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1214 const std::string &OpName = CGI.OperandList[i].Name;
1215 if (OpName.empty())
1216 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1217
Chris Lattner0b592252005-09-14 21:59:34 +00001218 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001219 I->error("Operand $" + OpName +
1220 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001221 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001222 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001223
1224 if (InVal->isLeaf() &&
1225 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1226 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001227 if (CGI.OperandList[i].Rec != InRec &&
1228 !InRec->isSubClassOf("ComplexPattern"))
Nate Begemanddb39542005-12-01 00:06:14 +00001229 I->error("Operand $" + OpName +
Evan Cheng0fc71982005-12-08 02:00:36 +00001230 "'s register class disagrees between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001231 }
1232 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001233
Chris Lattner2175c182005-09-14 23:01:59 +00001234 // Construct the result for the dest-pattern operand list.
1235 TreePatternNode *OpNode = InVal->clone();
1236
1237 // No predicate is useful on the result.
1238 OpNode->setPredicateFn("");
1239
1240 // Promote the xform function to be an explicit node if set.
1241 if (Record *Xform = OpNode->getTransformFn()) {
1242 OpNode->setTransformFn(0);
1243 std::vector<TreePatternNode*> Children;
1244 Children.push_back(OpNode);
1245 OpNode = new TreePatternNode(Xform, Children);
1246 }
1247
1248 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001249 }
1250
Chris Lattner0b592252005-09-14 21:59:34 +00001251 if (!InstInputsCheck.empty())
1252 I->error("Input operand $" + InstInputsCheck.begin()->first +
1253 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001254
1255 TreePatternNode *ResultPattern =
1256 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001257
1258 // Create and insert the instruction.
Nate Begemanddb39542005-12-01 00:06:14 +00001259 DAGInstruction TheInst(I, Results, Operands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001260 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1261
1262 // Use a temporary tree pattern to infer all types and make sure that the
1263 // constructed result is correct. This depends on the instruction already
1264 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001265 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001266 Temp.InferAllTypes();
1267
1268 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1269 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001270
Chris Lattner32707602005-09-08 23:22:48 +00001271 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001272 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001273
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001274 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001275 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1276 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001277 DAGInstruction &TheInst = II->second;
1278 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001279 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001280
Chris Lattner1f39e292005-09-14 00:09:24 +00001281 if (I->getNumTrees() != 1) {
1282 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1283 continue;
1284 }
1285 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001286 TreePatternNode *SrcPattern;
1287 if (TheInst.getNumResults() == 0) {
1288 SrcPattern = Pattern;
1289 } else {
1290 if (Pattern->getOperator()->getName() != "set")
1291 continue; // Not a set (store or something?)
Chris Lattner1f39e292005-09-14 00:09:24 +00001292
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001293 if (Pattern->getNumChildren() != 2)
1294 continue; // Not a set of a single value (not handled so far)
1295
1296 SrcPattern = Pattern->getChild(1)->clone();
1297 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001298
1299 std::string Reason;
1300 if (!SrcPattern->canPatternMatch(Reason, *this))
1301 I->error("Instruction can never match: " + Reason);
1302
Evan Cheng58e84a62005-12-14 22:02:59 +00001303 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001304 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001305 PatternsToMatch.
1306 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1307 SrcPattern, DstPattern));
Evan Chengdd304dd2005-12-05 23:08:55 +00001308
1309 if (PatternHasCtrlDep(Pattern, *this)) {
Evan Chengdd304dd2005-12-05 23:08:55 +00001310 CodeGenInstruction &InstInfo = Target.getInstruction(Instr->getName());
1311 InstInfo.hasCtrlDep = true;
1312 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001313 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001314}
1315
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001316void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001317 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001318
Chris Lattnerabbb6052005-09-15 21:42:00 +00001319 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001320 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001321 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001322
Chris Lattnerabbb6052005-09-15 21:42:00 +00001323 // Inline pattern fragments into it.
1324 Pattern->InlinePatternFragments();
1325
1326 // Infer as many types as possible. If we cannot infer all of them, we can
1327 // never do anything with this pattern: report it to the user.
1328 if (!Pattern->InferAllTypes())
1329 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001330
1331 // Validate that the input pattern is correct.
1332 {
1333 std::map<std::string, TreePatternNode*> InstInputs;
1334 std::map<std::string, Record*> InstResults;
1335 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1336 InstInputs, InstResults);
1337 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001338
1339 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1340 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001341
1342 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001343 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001344
1345 // Inline pattern fragments into it.
1346 Result->InlinePatternFragments();
1347
1348 // Infer as many types as possible. If we cannot infer all of them, we can
1349 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001350 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001351 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001352
1353 if (Result->getNumTrees() != 1)
1354 Result->error("Cannot handle instructions producing instructions "
1355 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001356
1357 std::string Reason;
1358 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1359 Pattern->error("Pattern can never match: " + Reason);
1360
Evan Cheng58e84a62005-12-14 22:02:59 +00001361 PatternsToMatch.
1362 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1363 Pattern->getOnlyTree(),
1364 Result->getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001365 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001366}
1367
Chris Lattnere46e17b2005-09-29 19:28:10 +00001368/// CombineChildVariants - Given a bunch of permutations of each child of the
1369/// 'operator' node, put them together in all possible ways.
1370static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001371 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001372 std::vector<TreePatternNode*> &OutVariants,
1373 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001374 // Make sure that each operand has at least one variant to choose from.
1375 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1376 if (ChildVariants[i].empty())
1377 return;
1378
Chris Lattnere46e17b2005-09-29 19:28:10 +00001379 // The end result is an all-pairs construction of the resultant pattern.
1380 std::vector<unsigned> Idxs;
1381 Idxs.resize(ChildVariants.size());
1382 bool NotDone = true;
1383 while (NotDone) {
1384 // Create the variant and add it to the output list.
1385 std::vector<TreePatternNode*> NewChildren;
1386 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1387 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1388 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1389
1390 // Copy over properties.
1391 R->setName(Orig->getName());
1392 R->setPredicateFn(Orig->getPredicateFn());
1393 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001394 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001395
1396 // If this pattern cannot every match, do not include it as a variant.
1397 std::string ErrString;
1398 if (!R->canPatternMatch(ErrString, ISE)) {
1399 delete R;
1400 } else {
1401 bool AlreadyExists = false;
1402
1403 // Scan to see if this pattern has already been emitted. We can get
1404 // duplication due to things like commuting:
1405 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1406 // which are the same pattern. Ignore the dups.
1407 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1408 if (R->isIsomorphicTo(OutVariants[i])) {
1409 AlreadyExists = true;
1410 break;
1411 }
1412
1413 if (AlreadyExists)
1414 delete R;
1415 else
1416 OutVariants.push_back(R);
1417 }
1418
1419 // Increment indices to the next permutation.
1420 NotDone = false;
1421 // Look for something we can increment without causing a wrap-around.
1422 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1423 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1424 NotDone = true; // Found something to increment.
1425 break;
1426 }
1427 Idxs[IdxsIdx] = 0;
1428 }
1429 }
1430}
1431
Chris Lattneraf302912005-09-29 22:36:54 +00001432/// CombineChildVariants - A helper function for binary operators.
1433///
1434static void CombineChildVariants(TreePatternNode *Orig,
1435 const std::vector<TreePatternNode*> &LHS,
1436 const std::vector<TreePatternNode*> &RHS,
1437 std::vector<TreePatternNode*> &OutVariants,
1438 DAGISelEmitter &ISE) {
1439 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1440 ChildVariants.push_back(LHS);
1441 ChildVariants.push_back(RHS);
1442 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1443}
1444
1445
1446static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1447 std::vector<TreePatternNode *> &Children) {
1448 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1449 Record *Operator = N->getOperator();
1450
1451 // Only permit raw nodes.
1452 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1453 N->getTransformFn()) {
1454 Children.push_back(N);
1455 return;
1456 }
1457
1458 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1459 Children.push_back(N->getChild(0));
1460 else
1461 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1462
1463 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1464 Children.push_back(N->getChild(1));
1465 else
1466 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1467}
1468
Chris Lattnere46e17b2005-09-29 19:28:10 +00001469/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1470/// the (potentially recursive) pattern by using algebraic laws.
1471///
1472static void GenerateVariantsOf(TreePatternNode *N,
1473 std::vector<TreePatternNode*> &OutVariants,
1474 DAGISelEmitter &ISE) {
1475 // We cannot permute leaves.
1476 if (N->isLeaf()) {
1477 OutVariants.push_back(N);
1478 return;
1479 }
1480
1481 // Look up interesting info about the node.
1482 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1483
1484 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001485 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1486 // Reassociate by pulling together all of the linked operators
1487 std::vector<TreePatternNode*> MaximalChildren;
1488 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1489
1490 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1491 // permutations.
1492 if (MaximalChildren.size() == 3) {
1493 // Find the variants of all of our maximal children.
1494 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1495 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1496 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1497 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1498
1499 // There are only two ways we can permute the tree:
1500 // (A op B) op C and A op (B op C)
1501 // Within these forms, we can also permute A/B/C.
1502
1503 // Generate legal pair permutations of A/B/C.
1504 std::vector<TreePatternNode*> ABVariants;
1505 std::vector<TreePatternNode*> BAVariants;
1506 std::vector<TreePatternNode*> ACVariants;
1507 std::vector<TreePatternNode*> CAVariants;
1508 std::vector<TreePatternNode*> BCVariants;
1509 std::vector<TreePatternNode*> CBVariants;
1510 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1511 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1512 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1513 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1514 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1515 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1516
1517 // Combine those into the result: (x op x) op x
1518 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1519 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1520 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1521 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1522 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1523 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1524
1525 // Combine those into the result: x op (x op x)
1526 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1527 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1528 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1529 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1530 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1531 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1532 return;
1533 }
1534 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001535
1536 // Compute permutations of all children.
1537 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1538 ChildVariants.resize(N->getNumChildren());
1539 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1540 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1541
1542 // Build all permutations based on how the children were formed.
1543 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1544
1545 // If this node is commutative, consider the commuted order.
1546 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1547 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001548 // Consider the commuted order.
1549 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1550 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001551 }
1552}
1553
1554
Chris Lattnere97603f2005-09-28 19:27:25 +00001555// GenerateVariants - Generate variants. For example, commutative patterns can
1556// match multiple ways. Add them to PatternsToMatch as well.
1557void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001558
1559 DEBUG(std::cerr << "Generating instruction variants.\n");
1560
1561 // Loop over all of the patterns we've collected, checking to see if we can
1562 // generate variants of the instruction, through the exploitation of
1563 // identities. This permits the target to provide agressive matching without
1564 // the .td file having to contain tons of variants of instructions.
1565 //
1566 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1567 // intentionally do not reconsider these. Any variants of added patterns have
1568 // already been added.
1569 //
1570 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1571 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001572 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001573
1574 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001575 Variants.erase(Variants.begin()); // Remove the original pattern.
1576
1577 if (Variants.empty()) // No variants for this pattern.
1578 continue;
1579
1580 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001581 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001582 std::cerr << "\n");
1583
1584 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1585 TreePatternNode *Variant = Variants[v];
1586
1587 DEBUG(std::cerr << " VAR#" << v << ": ";
1588 Variant->dump();
1589 std::cerr << "\n");
1590
1591 // Scan to see if an instruction or explicit pattern already matches this.
1592 bool AlreadyExists = false;
1593 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1594 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001595 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001596 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1597 AlreadyExists = true;
1598 break;
1599 }
1600 }
1601 // If we already have it, ignore the variant.
1602 if (AlreadyExists) continue;
1603
1604 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001605 PatternsToMatch.
1606 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1607 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001608 }
1609
1610 DEBUG(std::cerr << "\n");
1611 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001612}
1613
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001614
Evan Cheng0fc71982005-12-08 02:00:36 +00001615// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1616// ComplexPattern.
1617static bool NodeIsComplexPattern(TreePatternNode *N)
1618{
1619 return (N->isLeaf() &&
1620 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1621 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1622 isSubClassOf("ComplexPattern"));
1623}
1624
1625// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1626// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1627static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1628 DAGISelEmitter &ISE)
1629{
1630 if (N->isLeaf() &&
1631 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1632 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1633 isSubClassOf("ComplexPattern")) {
1634 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1635 ->getDef());
1636 }
1637 return NULL;
1638}
1639
Chris Lattner05814af2005-09-28 17:57:56 +00001640/// getPatternSize - Return the 'size' of this pattern. We want to match large
1641/// patterns before small ones. This is used to determine the size of a
1642/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001643static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001644 assert(isExtIntegerVT(P->getExtType()) ||
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001645 isExtFloatingPointVT(P->getExtType()) ||
1646 P->getExtType() == MVT::isVoid && "Not a valid pattern node to size!");
Chris Lattner05814af2005-09-28 17:57:56 +00001647 unsigned Size = 1; // The node itself.
Evan Cheng0fc71982005-12-08 02:00:36 +00001648
1649 // FIXME: This is a hack to statically increase the priority of patterns
1650 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1651 // Later we can allow complexity / cost for each pattern to be (optionally)
1652 // specified. To get best possible pattern match we'll need to dynamically
1653 // calculate the complexity of all patterns a dag can potentially map to.
1654 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1655 if (AM)
1656 Size += AM->getNumOperands();
1657
Chris Lattner05814af2005-09-28 17:57:56 +00001658 // Count children in the count if they are also nodes.
1659 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1660 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001661 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001662 Size += getPatternSize(Child, ISE);
1663 else if (Child->isLeaf()) {
1664 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1665 ++Size; // Matches a ConstantSDNode.
1666 else if (NodeIsComplexPattern(Child))
1667 Size += getPatternSize(Child, ISE);
Chris Lattner2f041d42005-10-19 04:41:05 +00001668 }
Chris Lattner05814af2005-09-28 17:57:56 +00001669 }
1670
1671 return Size;
1672}
1673
1674/// getResultPatternCost - Compute the number of instructions for this pattern.
1675/// This is a temporary hack. We should really include the instruction
1676/// latencies in this calculation.
1677static unsigned getResultPatternCost(TreePatternNode *P) {
1678 if (P->isLeaf()) return 0;
1679
1680 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1681 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1682 Cost += getResultPatternCost(P->getChild(i));
1683 return Cost;
1684}
1685
1686// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1687// In particular, we want to match maximal patterns first and lowest cost within
1688// a particular complexity first.
1689struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001690 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1691 DAGISelEmitter &ISE;
1692
Evan Cheng58e84a62005-12-14 22:02:59 +00001693 bool operator()(PatternToMatch *LHS,
1694 PatternToMatch *RHS) {
1695 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1696 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001697 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1698 if (LHSSize < RHSSize) return false;
1699
1700 // If the patterns have equal complexity, compare generated instruction cost
Evan Cheng58e84a62005-12-14 22:02:59 +00001701 return getResultPatternCost(LHS->getDstPattern()) <
1702 getResultPatternCost(RHS->getDstPattern());
Chris Lattner05814af2005-09-28 17:57:56 +00001703 }
1704};
1705
Nate Begeman6510b222005-12-01 04:51:06 +00001706/// getRegisterValueType - Look up and return the first ValueType of specified
1707/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001708static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001709 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1710 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001711 return MVT::Other;
1712}
1713
Chris Lattner72fe91c2005-09-24 00:40:24 +00001714
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001715/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1716/// type information from it.
1717static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001718 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001719 if (!N->isLeaf())
1720 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1721 RemoveAllTypes(N->getChild(i));
1722}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001723
Chris Lattner0614b622005-11-02 06:49:14 +00001724Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1725 Record *N = Records.getDef(Name);
1726 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1727 return N;
1728}
1729
Evan Chengb915f312005-12-09 22:45:35 +00001730class PatternCodeEmitter {
1731private:
1732 DAGISelEmitter &ISE;
1733
Evan Cheng58e84a62005-12-14 22:02:59 +00001734 // Predicates.
1735 ListInit *Predicates;
1736 // Instruction selector pattern.
1737 TreePatternNode *Pattern;
1738 // Matched instruction.
1739 TreePatternNode *Instruction;
Evan Chengb915f312005-12-09 22:45:35 +00001740 unsigned PatternNo;
1741 std::ostream &OS;
1742 // Node to name mapping
1743 std::map<std::string,std::string> VariableMap;
Evan Chengb915f312005-12-09 22:45:35 +00001744 // Names of all the folded nodes which produce chains.
1745 std::vector<std::string> FoldedChains;
Evan Cheng86217892005-12-12 19:37:43 +00001746 bool FoundChain;
Evan Chengb915f312005-12-09 22:45:35 +00001747 bool InFlag;
1748 unsigned TmpNo;
1749
1750public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001751 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1752 TreePatternNode *pattern, TreePatternNode *instr,
Evan Chengb915f312005-12-09 22:45:35 +00001753 unsigned PatNum, std::ostream &os) :
Evan Cheng58e84a62005-12-14 22:02:59 +00001754 ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1755 PatternNo(PatNum), OS(os), FoundChain(false), InFlag(false), TmpNo(0) {};
Evan Chengb915f312005-12-09 22:45:35 +00001756
1757 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1758 /// if the match fails. At this point, we already know that the opcode for N
1759 /// matches, and the SDNode for the result has the RootName specified name.
1760 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1761 bool isRoot = false) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001762
1763 // Emit instruction predicates. Each predicate is just a string for now.
1764 if (isRoot) {
1765 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1766 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1767 Record *Def = Pred->getDef();
1768 if (Def->isSubClassOf("Predicate")) {
1769 if (i == 0)
1770 OS << " if (";
1771 else
1772 OS << " && ";
1773 OS << "(" << Def->getValueAsString("CondString") << ")";
1774 if (i == e-1)
1775 OS << ") goto P" << PatternNo << "Fail;\n";
1776 } else {
1777 Def->dump();
1778 assert(0 && "Unknown predicate type!");
1779 }
1780 }
1781 }
1782 }
1783
Evan Chengb915f312005-12-09 22:45:35 +00001784 if (N->isLeaf()) {
1785 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1786 OS << " if (cast<ConstantSDNode>(" << RootName
1787 << ")->getSignExtended() != " << II->getValue() << ")\n"
1788 << " goto P" << PatternNo << "Fail;\n";
1789 return;
1790 } else if (!NodeIsComplexPattern(N)) {
1791 assert(0 && "Cannot match this as a leaf value!");
1792 abort();
1793 }
1794 }
1795
1796 // If this node has a name associated with it, capture it in VariableMap. If
1797 // we already saw this in the pattern, emit code to verify dagness.
1798 if (!N->getName().empty()) {
1799 std::string &VarMapEntry = VariableMap[N->getName()];
1800 if (VarMapEntry.empty()) {
1801 VarMapEntry = RootName;
1802 } else {
1803 // If we get here, this is a second reference to a specific name. Since
1804 // we already have checked that the first reference is valid, we don't
1805 // have to recursively match it, just check that it's the same as the
1806 // previously named thing.
1807 OS << " if (" << VarMapEntry << " != " << RootName
1808 << ") goto P" << PatternNo << "Fail;\n";
1809 return;
1810 }
1811 }
1812
1813
1814 // Emit code to load the child nodes and match their contents recursively.
1815 unsigned OpNo = 0;
Evan Cheng86217892005-12-12 19:37:43 +00001816 bool HasChain = NodeHasChain(N, ISE);
1817 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00001818 OpNo = 1;
1819 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001820 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Chengb915f312005-12-09 22:45:35 +00001821 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1822 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1823 OS << " if (CodeGenMap.count(" << RootName
Evan Cheng1129e872005-12-10 00:09:17 +00001824 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
Evan Chengb915f312005-12-09 22:45:35 +00001825 << PatternNo << "Fail; // Already selected for a chain use?\n";
1826 }
Evan Chengb915f312005-12-09 22:45:35 +00001827 }
1828
1829 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1830 OS << " SDOperand " << RootName << OpNo <<" = " << RootName
1831 << ".getOperand(" << OpNo << ");\n";
1832 TreePatternNode *Child = N->getChild(i);
1833
1834 if (!Child->isLeaf()) {
1835 // If it's not a leaf, recursively match.
1836 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1837 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1838 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1839 EmitMatchCode(Child, RootName + utostr(OpNo));
1840 if (NodeHasChain(Child, ISE))
1841 FoldedChains.push_back(RootName + utostr(OpNo));
1842 } else {
1843 // If this child has a name associated with it, capture it in VarMap. If
1844 // we already saw this in the pattern, emit code to verify dagness.
1845 if (!Child->getName().empty()) {
1846 std::string &VarMapEntry = VariableMap[Child->getName()];
1847 if (VarMapEntry.empty()) {
1848 VarMapEntry = RootName + utostr(OpNo);
1849 } else {
1850 // If we get here, this is a second reference to a specific name. Since
1851 // we already have checked that the first reference is valid, we don't
1852 // have to recursively match it, just check that it's the same as the
1853 // previously named thing.
1854 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1855 << ") goto P" << PatternNo << "Fail;\n";
1856 continue;
1857 }
1858 }
1859
1860 // Handle leaves of various types.
1861 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1862 Record *LeafRec = DI->getDef();
1863 if (LeafRec->isSubClassOf("RegisterClass")) {
1864 // Handle register references. Nothing to do here.
1865 } else if (LeafRec->isSubClassOf("Register")) {
1866 if (!InFlag) {
1867 OS << " SDOperand InFlag = SDOperand(0,0);\n";
1868 InFlag = true;
1869 }
1870 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1871 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00001872 } else if (LeafRec->getName() == "srcvalue") {
1873 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00001874 } else if (LeafRec->isSubClassOf("ValueType")) {
1875 // Make sure this is the specified value type.
1876 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1877 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1878 << "Fail;\n";
1879 } else if (LeafRec->isSubClassOf("CondCode")) {
1880 // Make sure this is the specified cond code.
1881 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1882 << ")->get() != " << "ISD::" << LeafRec->getName()
1883 << ") goto P" << PatternNo << "Fail;\n";
1884 } else {
1885 Child->dump();
1886 assert(0 && "Unknown leaf type!");
1887 }
1888 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1889 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1890 << " cast<ConstantSDNode>(" << RootName << OpNo
1891 << ")->getSignExtended() != " << II->getValue() << ")\n"
1892 << " goto P" << PatternNo << "Fail;\n";
1893 } else {
1894 Child->dump();
1895 assert(0 && "Unknown leaf type!");
1896 }
1897 }
1898 }
1899
Evan Cheng86217892005-12-12 19:37:43 +00001900 if (HasChain) {
1901 if (!FoundChain) {
1902 OS << " SDOperand Chain = " << RootName << ".getOperand(0);\n";
1903 FoundChain = true;
1904 }
1905 }
1906
Evan Chengb915f312005-12-09 22:45:35 +00001907 // If there is a node predicate for this, emit the call.
1908 if (!N->getPredicateFn().empty())
1909 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1910 << ".Val)) goto P" << PatternNo << "Fail;\n";
1911 }
1912
1913 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1914 /// we actually have to build a DAG!
1915 std::pair<unsigned, unsigned>
1916 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1917 // This is something selected from the pattern we matched.
1918 if (!N->getName().empty()) {
1919 assert(!isRoot && "Root of pattern cannot be a leaf!");
1920 std::string &Val = VariableMap[N->getName()];
1921 assert(!Val.empty() &&
1922 "Variable referenced but not defined and not caught earlier!");
1923 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1924 // Already selected this operand, just return the tmpval.
1925 return std::make_pair(1, atoi(Val.c_str()+3));
1926 }
1927
1928 const ComplexPattern *CP;
1929 unsigned ResNo = TmpNo++;
1930 unsigned NumRes = 1;
1931 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1932 switch (N->getType()) {
1933 default: assert(0 && "Unknown type for constant node!");
1934 case MVT::i1: OS << " bool Tmp"; break;
1935 case MVT::i8: OS << " unsigned char Tmp"; break;
1936 case MVT::i16: OS << " unsigned short Tmp"; break;
1937 case MVT::i32: OS << " unsigned Tmp"; break;
1938 case MVT::i64: OS << " uint64_t Tmp"; break;
1939 }
1940 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1941 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1942 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1943 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1944 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Nate Begeman28a6b022005-12-10 02:36:00 +00001945 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
1946 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Evan Chengb915f312005-12-09 22:45:35 +00001947 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
1948 std::string Fn = CP->getSelectFunc();
1949 NumRes = CP->getNumOperands();
1950 OS << " SDOperand ";
1951 for (unsigned i = 0; i < NumRes; i++) {
1952 if (i != 0) OS << ", ";
1953 OS << "Tmp" << i + ResNo;
1954 }
1955 OS << ";\n";
1956 OS << " if (!" << Fn << "(" << Val;
1957 for (unsigned i = 0; i < NumRes; i++)
1958 OS << " , Tmp" << i + ResNo;
1959 OS << ")) goto P" << PatternNo << "Fail;\n";
1960 TmpNo = ResNo + NumRes;
1961 } else {
1962 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1963 }
1964 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1965 // value if used multiple times by this pattern result.
1966 Val = "Tmp"+utostr(ResNo);
1967 return std::make_pair(NumRes, ResNo);
1968 }
1969
1970 if (N->isLeaf()) {
1971 // If this is an explicit register reference, handle it.
1972 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1973 unsigned ResNo = TmpNo++;
1974 if (DI->getDef()->isSubClassOf("Register")) {
1975 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1976 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
1977 << getEnumName(N->getType())
1978 << ");\n";
1979 return std::make_pair(1, ResNo);
1980 }
1981 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1982 unsigned ResNo = TmpNo++;
1983 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1984 << II->getValue() << ", MVT::"
1985 << getEnumName(N->getType())
1986 << ");\n";
1987 return std::make_pair(1, ResNo);
1988 }
1989
1990 N->dump();
1991 assert(0 && "Unknown leaf type!");
1992 return std::make_pair(1, ~0U);
1993 }
1994
1995 Record *Op = N->getOperator();
1996 if (Op->isSubClassOf("Instruction")) {
1997 // Determine operand emission order. Complex pattern first.
1998 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
1999 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2000 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2001 TreePatternNode *Child = N->getChild(i);
2002 if (i == 0) {
2003 EmitOrder.push_back(std::make_pair(i, Child));
2004 OI = EmitOrder.begin();
2005 } else if (NodeIsComplexPattern(Child)) {
2006 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2007 } else {
2008 EmitOrder.push_back(std::make_pair(i, Child));
2009 }
2010 }
2011
2012 // Emit all of the operands.
2013 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2014 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2015 unsigned OpOrder = EmitOrder[i].first;
2016 TreePatternNode *Child = EmitOrder[i].second;
2017 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2018 NumTemps[OpOrder] = NumTemp;
2019 }
2020
2021 // List all the operands in the right order.
2022 std::vector<unsigned> Ops;
2023 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2024 for (unsigned j = 0; j < NumTemps[i].first; j++)
2025 Ops.push_back(NumTemps[i].second + j);
2026 }
2027
2028 CodeGenInstruction &II =
2029 ISE.getTargetInfo().getInstruction(Op->getName());
2030
2031 // Emit all the chain and CopyToReg stuff.
2032 if (II.hasCtrlDep)
Evan Cheng86217892005-12-12 19:37:43 +00002033 OS << " Chain = Select(Chain);\n";
Evan Cheng58e84a62005-12-14 22:02:59 +00002034 EmitCopyToRegs(Pattern, "N", II.hasCtrlDep);
Evan Chengb915f312005-12-09 22:45:35 +00002035
2036 const DAGInstruction &Inst = ISE.getInstruction(Op);
2037 unsigned NumResults = Inst.getNumResults();
2038 unsigned ResNo = TmpNo++;
2039 if (!isRoot) {
2040 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
2041 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2042 << getEnumName(N->getType());
2043 unsigned LastOp = 0;
2044 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2045 LastOp = Ops[i];
2046 OS << ", Tmp" << LastOp;
2047 }
2048 OS << ");\n";
2049 if (II.hasCtrlDep) {
2050 // Must have at least one result
2051 OS << " Chain = Tmp" << LastOp << ".getValue("
2052 << NumResults << ");\n";
2053 }
2054 } else if (II.hasCtrlDep) {
2055 OS << " SDOperand Result = ";
2056 OS << "CurDAG->getTargetNode("
2057 << II.Namespace << "::" << II.TheDef->getName();
2058 if (NumResults > 0)
2059 OS << ", MVT::" << getEnumName(N->getType()); // TODO: multiple results?
2060 OS << ", MVT::Other";
2061 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2062 OS << ", Tmp" << Ops[i];
2063 OS << ", Chain";
2064 if (InFlag)
2065 OS << ", InFlag";
2066 OS << ");\n";
2067 if (NumResults != 0) {
Evan Cheng0e65b272005-12-12 23:45:21 +00002068 OS << " CodeGenMap[N.getValue(0)] = Result;\n";
Evan Chengb915f312005-12-09 22:45:35 +00002069 }
2070 OS << " Chain ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002071 if (NodeHasChain(Pattern, ISE))
Evan Cheng1129e872005-12-10 00:09:17 +00002072 OS << "= CodeGenMap[N.getValue(" << NumResults << ")] ";
Evan Chengb915f312005-12-09 22:45:35 +00002073 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng1129e872005-12-10 00:09:17 +00002074 OS << "= CodeGenMap[" << FoldedChains[j] << ".getValue("
2075 << NumResults << ")] ";
2076 OS << "= Result.getValue(" << NumResults << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00002077 if (NumResults == 0)
2078 OS << " return Chain;\n";
2079 else
2080 OS << " return (N.ResNo) ? Chain : Result.getValue(0);\n";
2081 } else {
2082 // If this instruction is the root, and if there is only one use of it,
2083 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2084 OS << " if (N.Val->hasOneUse()) {\n";
2085 OS << " return CurDAG->SelectNodeTo(N.Val, "
2086 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2087 << getEnumName(N->getType());
2088 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2089 OS << ", Tmp" << Ops[i];
2090 if (InFlag)
2091 OS << ", InFlag";
2092 OS << ");\n";
2093 OS << " } else {\n";
2094 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
2095 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2096 << getEnumName(N->getType());
2097 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2098 OS << ", Tmp" << Ops[i];
2099 if (InFlag)
2100 OS << ", InFlag";
2101 OS << ");\n";
2102 OS << " }\n";
2103 }
2104 return std::make_pair(1, ResNo);
2105 } else if (Op->isSubClassOf("SDNodeXForm")) {
2106 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002107 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002108 unsigned ResNo = TmpNo++;
2109 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
2110 << "(Tmp" << OpVal << ".Val);\n";
2111 if (isRoot) {
2112 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2113 OS << " return Tmp" << ResNo << ";\n";
2114 }
2115 return std::make_pair(1, ResNo);
2116 } else {
2117 N->dump();
2118 assert(0 && "Unknown node in result pattern!");
2119 return std::make_pair(1, ~0U);
2120 }
2121 }
2122
2123 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2124 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2125 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2126 /// for, this returns true otherwise false if Pat has all types.
2127 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2128 const std::string &Prefix) {
2129 // Did we find one?
2130 if (!Pat->hasTypeSet()) {
2131 // Move a type over from 'other' to 'pat'.
2132 Pat->setType(Other->getType());
2133 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2134 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2135 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002136 }
2137
2138 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2139 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2140 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2141 Prefix + utostr(OpNo)))
2142 return true;
2143 return false;
2144 }
2145
2146private:
2147 /// EmitCopyToRegs - Emit the flag operands for the DAG that is
2148 /// being built.
2149 void EmitCopyToRegs(TreePatternNode *N, const std::string &RootName,
2150 bool HasCtrlDep) {
2151 const CodeGenTarget &T = ISE.getTargetInfo();
2152 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2153 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2154 TreePatternNode *Child = N->getChild(i);
2155 if (!Child->isLeaf()) {
2156 EmitCopyToRegs(Child, RootName + utostr(OpNo), HasCtrlDep);
2157 } else {
2158 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2159 Record *RR = DI->getDef();
2160 if (RR->isSubClassOf("Register")) {
2161 MVT::ValueType RVT = getRegisterValueType(RR, T);
2162 if (HasCtrlDep) {
2163 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2164 OS << " " << RootName << "CR" << i
2165 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2166 << ISE.getQualifiedName(RR) << ", MVT::"
2167 << getEnumName(RVT) << ")"
2168 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2169 OS << " Chain = " << RootName << "CR" << i
2170 << ".getValue(0);\n";
2171 OS << " InFlag = " << RootName << "CR" << i
2172 << ".getValue(1);\n";
2173 } else {
2174 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2175 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2176 << ", MVT::" << getEnumName(RVT) << ")"
2177 << ", Select(" << RootName << OpNo
2178 << "), InFlag).getValue(1);\n";
2179 }
2180 }
2181 }
2182 }
2183 }
2184 }
2185};
2186
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002187/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2188/// stream to match the pattern, and generate the code for the match if it
2189/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002190void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2191 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002192 static unsigned PatternCount = 0;
2193 unsigned PatternNo = PatternCount++;
2194 OS << " { // Pattern #" << PatternNo << ": ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002195 Pattern.getSrcPattern()->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002196 OS << "\n // Emits: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002197 Pattern.getDstPattern()->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002198 OS << "\n";
Evan Cheng58e84a62005-12-14 22:02:59 +00002199 OS << " // Pattern complexity = "
2200 << getPatternSize(Pattern.getSrcPattern(), *this)
2201 << " cost = "
2202 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002203
Evan Cheng58e84a62005-12-14 22:02:59 +00002204 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2205 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2206 PatternNo, OS);
Evan Chengb915f312005-12-09 22:45:35 +00002207
Chris Lattner8fc35682005-09-23 23:16:51 +00002208 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng58e84a62005-12-14 22:02:59 +00002209 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002210
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002211 // TP - Get *SOME* tree pattern, we don't care which.
2212 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002213
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002214 // At this point, we know that we structurally match the pattern, but the
2215 // types of the nodes may not match. Figure out the fewest number of type
2216 // comparisons we need to emit. For example, if there is only one integer
2217 // type supported by a target, there should be no type comparisons at all for
2218 // integer patterns!
2219 //
2220 // To figure out the fewest number of type checks needed, clone the pattern,
2221 // remove the types, then perform type inference on the pattern as a whole.
2222 // If there are unresolved types, emit an explicit check for those types,
2223 // apply the type to the tree, then rerun type inference. Iterate until all
2224 // types are resolved.
2225 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002226 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002227 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002228
2229 do {
2230 // Resolve/propagate as many types as possible.
2231 try {
2232 bool MadeChange = true;
2233 while (MadeChange)
2234 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2235 } catch (...) {
2236 assert(0 && "Error: could not find consistent types for something we"
2237 " already decided was ok!");
2238 abort();
2239 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002240
Chris Lattner7e82f132005-10-15 21:34:21 +00002241 // Insert a check for an unresolved type and add it to the tree. If we find
2242 // an unresolved type to add a check for, this returns true and we iterate,
2243 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002244 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002245
Evan Cheng58e84a62005-12-14 22:02:59 +00002246 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002247
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002248 delete Pat;
2249
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002250 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002251}
2252
Chris Lattner37481472005-09-26 21:59:35 +00002253
2254namespace {
2255 /// CompareByRecordName - An ordering predicate that implements less-than by
2256 /// comparing the names records.
2257 struct CompareByRecordName {
2258 bool operator()(const Record *LHS, const Record *RHS) const {
2259 // Sort by name first.
2260 if (LHS->getName() < RHS->getName()) return true;
2261 // If both names are equal, sort by pointer.
2262 return LHS->getName() == RHS->getName() && LHS < RHS;
2263 }
2264 };
2265}
2266
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002267void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002268 std::string InstNS = Target.inst_begin()->second.Namespace;
2269 if (!InstNS.empty()) InstNS += "::";
2270
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002271 // Emit boilerplate.
2272 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002273 << "SDOperand SelectCode(SDOperand N) {\n"
2274 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002275 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2276 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002277 << " return N; // Already selected.\n\n"
Evan Cheng481c8e02005-12-12 23:22:48 +00002278 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2279 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002280 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002281 << " default: break;\n"
2282 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002283 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002284 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002285 << " case ISD::AssertZext: {\n"
2286 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2287 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2288 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002289 << " }\n"
2290 << " case ISD::TokenFactor:\n"
2291 << " if (N.getNumOperands() == 2) {\n"
2292 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2293 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2294 << " return CodeGenMap[N] =\n"
2295 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2296 << " } else {\n"
2297 << " std::vector<SDOperand> Ops;\n"
2298 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2299 << " Ops.push_back(Select(N.getOperand(i)));\n"
2300 << " return CodeGenMap[N] = \n"
2301 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2302 << " }\n"
2303 << " case ISD::CopyFromReg: {\n"
2304 << " SDOperand Chain = Select(N.getOperand(0));\n"
2305 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2306 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
2307 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
2308 << " N.Val->getValueType(0));\n"
2309 << " return New.getValue(N.ResNo);\n"
2310 << " }\n"
2311 << " case ISD::CopyToReg: {\n"
2312 << " SDOperand Chain = Select(N.getOperand(0));\n"
2313 << " SDOperand Reg = N.getOperand(1);\n"
2314 << " SDOperand Val = Select(N.getOperand(2));\n"
2315 << " return CodeGenMap[N] = \n"
2316 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
2317 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002318 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002319
Chris Lattner81303322005-09-23 19:36:15 +00002320 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00002321 std::map<Record*, std::vector<PatternToMatch*>,
2322 CompareByRecordName> PatternsByOpcode;
Evan Cheng0fc71982005-12-08 02:00:36 +00002323 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002324 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
Evan Cheng0fc71982005-12-08 02:00:36 +00002325 if (!Node->isLeaf()) {
2326 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
Chris Lattner0614b622005-11-02 06:49:14 +00002327 } else {
Evan Cheng0fc71982005-12-08 02:00:36 +00002328 const ComplexPattern *CP;
Chris Lattner0614b622005-11-02 06:49:14 +00002329 if (IntInit *II =
Evan Cheng0fc71982005-12-08 02:00:36 +00002330 dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner0614b622005-11-02 06:49:14 +00002331 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
Evan Cheng0fc71982005-12-08 02:00:36 +00002332 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
Evan Cheng3aa39f42005-12-08 02:14:08 +00002333 std::vector<Record*> OpNodes = CP->getRootNodes();
Evan Cheng0fc71982005-12-08 02:00:36 +00002334 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2335 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2336 &PatternsToMatch[i]);
2337 }
Chris Lattner0614b622005-11-02 06:49:14 +00002338 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00002339 std::cerr << "Unrecognized opcode '";
Evan Cheng0fc71982005-12-08 02:00:36 +00002340 Node->dump();
Evan Cheng76021f02005-11-29 18:44:58 +00002341 std::cerr << "' on tree pattern '";
Evan Cheng58e84a62005-12-14 22:02:59 +00002342 std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Evan Cheng76021f02005-11-29 18:44:58 +00002343 std::cerr << "'!\n";
2344 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00002345 }
2346 }
Evan Cheng0fc71982005-12-08 02:00:36 +00002347 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002348
Chris Lattner3f7e9142005-09-23 20:52:47 +00002349 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00002350 for (std::map<Record*, std::vector<PatternToMatch*>,
2351 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2352 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002353 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2354 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2355
2356 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002357
2358 // We want to emit all of the matching code now. However, we want to emit
2359 // the matches in order of minimal cost. Sort the patterns so the least
2360 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002361 std::stable_sort(Patterns.begin(), Patterns.end(),
Evan Cheng0fc71982005-12-08 02:00:36 +00002362 PatternSortingPredicate(*this));
Chris Lattner81303322005-09-23 19:36:15 +00002363
Chris Lattner3f7e9142005-09-23 20:52:47 +00002364 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2365 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002366 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00002367 }
2368
2369
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002370 OS << " } // end of big switch.\n\n"
2371 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002372 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002373 << " std::cerr << '\\n';\n"
2374 << " abort();\n"
2375 << "}\n";
2376}
2377
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002378void DAGISelEmitter::run(std::ostream &OS) {
2379 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2380 " target", OS);
2381
Chris Lattner1f39e292005-09-14 00:09:24 +00002382 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2383 << "// *** instruction selector class. These functions are really "
2384 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002385
Chris Lattner296dfe32005-09-24 00:50:51 +00002386 OS << "// Instance var to keep track of multiply used nodes that have \n"
2387 << "// already been selected.\n"
2388 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2389
Chris Lattnerca559d02005-09-08 21:03:01 +00002390 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002391 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00002392 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002393 ParsePatternFragments(OS);
2394 ParseInstructions();
2395 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002396
Chris Lattnere97603f2005-09-28 19:27:25 +00002397 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002398 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002399 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002400
Chris Lattnere46e17b2005-09-29 19:28:10 +00002401
2402 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2403 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002404 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2405 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00002406 std::cerr << "\n";
2407 });
2408
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002409 // At this point, we have full information about the 'Patterns' we need to
2410 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002411 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002412 EmitInstructionSelector(OS);
2413
2414 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2415 E = PatternFragments.end(); I != E; ++I)
2416 delete I->second;
2417 PatternFragments.clear();
2418
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002419 Instructions.clear();
2420}