blob: 155dfad3730538ee587b00ad38f95fca77e8c6a0 [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();
Evan Chengbcecf332005-12-17 01:19:28 +0000299 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000300 TP.error("Type inference contradiction found in node!");
301 } else {
302 TP.error("Type inference contradiction found in node " +
303 getOperator()->getName() + "!");
304 }
Chris Lattner32707602005-09-08 23:22:48 +0000305 return true; // unreachable
306}
307
308
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000309void TreePatternNode::print(std::ostream &OS) const {
310 if (isLeaf()) {
311 OS << *getLeafValue();
312 } else {
313 OS << "(" << getOperator()->getName();
314 }
315
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000316 switch (getExtType()) {
317 case MVT::Other: OS << ":Other"; break;
318 case MVT::isInt: OS << ":isInt"; break;
319 case MVT::isFP : OS << ":isFP"; break;
320 case MVT::isUnknown: ; /*OS << ":?";*/ break;
321 default: OS << ":" << getType(); break;
322 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000323
324 if (!isLeaf()) {
325 if (getNumChildren() != 0) {
326 OS << " ";
327 getChild(0)->print(OS);
328 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
329 OS << ", ";
330 getChild(i)->print(OS);
331 }
332 }
333 OS << ")";
334 }
335
336 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000337 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000338 if (TransformFn)
339 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000340 if (!getName().empty())
341 OS << ":$" << getName();
342
343}
344void TreePatternNode::dump() const {
345 print(std::cerr);
346}
347
Chris Lattnere46e17b2005-09-29 19:28:10 +0000348/// isIsomorphicTo - Return true if this node is recursively isomorphic to
349/// the specified node. For this comparison, all of the state of the node
350/// is considered, except for the assigned name. Nodes with differing names
351/// that are otherwise identical are considered isomorphic.
352bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
353 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000354 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000355 getPredicateFn() != N->getPredicateFn() ||
356 getTransformFn() != N->getTransformFn())
357 return false;
358
359 if (isLeaf()) {
360 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
361 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
362 return DI->getDef() == NDI->getDef();
363 return getLeafValue() == N->getLeafValue();
364 }
365
366 if (N->getOperator() != getOperator() ||
367 N->getNumChildren() != getNumChildren()) return false;
368 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
369 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
370 return false;
371 return true;
372}
373
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000374/// clone - Make a copy of this tree and all of its children.
375///
376TreePatternNode *TreePatternNode::clone() const {
377 TreePatternNode *New;
378 if (isLeaf()) {
379 New = new TreePatternNode(getLeafValue());
380 } else {
381 std::vector<TreePatternNode*> CChildren;
382 CChildren.reserve(Children.size());
383 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
384 CChildren.push_back(getChild(i)->clone());
385 New = new TreePatternNode(getOperator(), CChildren);
386 }
387 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000388 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000389 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000390 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000391 return New;
392}
393
Chris Lattner32707602005-09-08 23:22:48 +0000394/// SubstituteFormalArguments - Replace the formal arguments in this tree
395/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000396void TreePatternNode::
397SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
398 if (isLeaf()) return;
399
400 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
401 TreePatternNode *Child = getChild(i);
402 if (Child->isLeaf()) {
403 Init *Val = Child->getLeafValue();
404 if (dynamic_cast<DefInit*>(Val) &&
405 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
406 // We found a use of a formal argument, replace it with its value.
407 Child = ArgMap[Child->getName()];
408 assert(Child && "Couldn't find formal argument!");
409 setChild(i, Child);
410 }
411 } else {
412 getChild(i)->SubstituteFormalArguments(ArgMap);
413 }
414 }
415}
416
417
418/// InlinePatternFragments - If this pattern refers to any pattern
419/// fragments, inline them into place, giving us a pattern without any
420/// PatFrag references.
421TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
422 if (isLeaf()) return this; // nothing to do.
423 Record *Op = getOperator();
424
425 if (!Op->isSubClassOf("PatFrag")) {
426 // Just recursively inline children nodes.
427 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
428 setChild(i, getChild(i)->InlinePatternFragments(TP));
429 return this;
430 }
431
432 // Otherwise, we found a reference to a fragment. First, look up its
433 // TreePattern record.
434 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
435
436 // Verify that we are passing the right number of operands.
437 if (Frag->getNumArgs() != Children.size())
438 TP.error("'" + Op->getName() + "' fragment requires " +
439 utostr(Frag->getNumArgs()) + " operands!");
440
Chris Lattner37937092005-09-09 01:15:01 +0000441 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000442
443 // Resolve formal arguments to their actual value.
444 if (Frag->getNumArgs()) {
445 // Compute the map of formal to actual arguments.
446 std::map<std::string, TreePatternNode*> ArgMap;
447 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
448 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
449
450 FragTree->SubstituteFormalArguments(ArgMap);
451 }
452
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000453 FragTree->setName(getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000454 FragTree->UpdateNodeType(getExtType(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000455
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000456 // Get a new copy of this fragment to stitch into here.
457 //delete this; // FIXME: implement refcounting!
458 return FragTree;
459}
460
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000461/// getIntrinsicType - Check to see if the specified record has an intrinsic
462/// type which should be applied to it. This infer the type of register
463/// references from the register file information, for example.
464///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000465static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
466 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000467 // Check to see if this is a register or a register class...
468 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000469 if (NotRegisters) return MVT::isUnknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000470 const CodeGenRegisterClass &RC =
471 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
472 return RC.getValueTypeNum(0);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000473 } else if (R->isSubClassOf("PatFrag")) {
474 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000475 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000476 } else if (R->isSubClassOf("Register")) {
Chris Lattner22faeab2005-12-05 02:36:37 +0000477 // If the register appears in exactly one regclass, and the regclass has one
478 // value type, use it as the known type.
479 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
480 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
481 if (RC->getNumValueTypes() == 1)
482 return RC->getValueTypeNum(0);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000483 return MVT::isUnknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000484 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
485 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000486 return MVT::Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000487 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng3aa39f42005-12-08 02:14:08 +0000488 return TP.getDAGISelEmitter().getComplexPattern(R).getValueType();
Evan Cheng01f318b2005-12-14 02:21:57 +0000489 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000490 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000491 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000492 }
493
494 TP.error("Unknown node flavor used in pattern: " + R->getName());
495 return MVT::Other;
496}
497
Chris Lattner32707602005-09-08 23:22:48 +0000498/// ApplyTypeConstraints - Apply all of the type constraints relevent to
499/// this node and its children in the tree. This returns true if it makes a
500/// change, false otherwise. If a type contradiction is found, throw an
501/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000502bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
503 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000504 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000505 // If it's a regclass or something else known, include the type.
506 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
507 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000508 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
509 // Int inits are always integers. :)
510 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
511
512 if (hasTypeSet()) {
513 unsigned Size = MVT::getSizeInBits(getType());
514 // Make sure that the value is representable for this type.
515 if (Size < 32) {
516 int Val = (II->getValue() << (32-Size)) >> (32-Size);
517 if (Val != II->getValue())
518 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
519 "' is out of range for type 'MVT::" +
520 getEnumName(getType()) + "'!");
521 }
522 }
523
524 return MadeChange;
525 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000526 return false;
527 }
Chris Lattner32707602005-09-08 23:22:48 +0000528
529 // special handling for set, which isn't really an SDNode.
530 if (getOperator()->getName() == "set") {
531 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000532 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
533 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000534
535 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000536 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
537 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000538 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
539 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000540 } else if (getOperator()->isSubClassOf("SDNode")) {
541 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
542
543 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
544 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000545 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000546 // Branch, etc. do not produce results and top-level forms in instr pattern
547 // must have void types.
548 if (NI.getNumResults() == 0)
549 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000550 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000551 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000552 const DAGInstruction &Inst =
553 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000554 bool MadeChange = false;
555 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000556
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000557 assert(NumResults <= 1 &&
558 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000559 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000560 if (NumResults == 0) {
561 MadeChange = UpdateNodeType(MVT::isVoid, TP);
562 } else {
563 Record *ResultNode = Inst.getResult(0);
564 assert(ResultNode->isSubClassOf("RegisterClass") &&
565 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000566
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000567 const CodeGenRegisterClass &RC =
568 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000569
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000570 // Get the first ValueType in the RegClass, it's as good as any.
571 MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
572 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000573
574 if (getNumChildren() != Inst.getNumOperands())
575 TP.error("Instruction '" + getOperator()->getName() + " expects " +
576 utostr(Inst.getNumOperands()) + " operands, not " +
577 utostr(getNumChildren()) + " operands!");
578 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000579 Record *OperandNode = Inst.getOperand(i);
580 MVT::ValueType VT;
581 if (OperandNode->isSubClassOf("RegisterClass")) {
582 const CodeGenRegisterClass &RC =
583 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000584 VT = RC.getValueTypeNum(0);
Nate Begemanddb39542005-12-01 00:06:14 +0000585 } else if (OperandNode->isSubClassOf("Operand")) {
586 VT = getValueType(OperandNode->getValueAsDef("Type"));
587 } else {
588 assert(0 && "Unknown operand type!");
589 abort();
590 }
591
592 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000593 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000594 }
595 return MadeChange;
596 } else {
597 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
598
599 // Node transforms always take one operand, and take and return the same
600 // type.
601 if (getNumChildren() != 1)
602 TP.error("Node transform '" + getOperator()->getName() +
603 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000604 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
605 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000606 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000607 }
Chris Lattner32707602005-09-08 23:22:48 +0000608}
609
Chris Lattnere97603f2005-09-28 19:27:25 +0000610/// canPatternMatch - If it is impossible for this pattern to match on this
611/// target, fill in Reason and return false. Otherwise, return true. This is
612/// used as a santity check for .td files (to prevent people from writing stuff
613/// that can never possibly work), and to prevent the pattern permuter from
614/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000615bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000616 if (isLeaf()) return true;
617
618 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
619 if (!getChild(i)->canPatternMatch(Reason, ISE))
620 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000621
Chris Lattnere97603f2005-09-28 19:27:25 +0000622 // If this node is a commutative operator, check that the LHS isn't an
623 // immediate.
624 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
625 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
626 // Scan all of the operands of the node and make sure that only the last one
627 // is a constant node.
628 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
629 if (!getChild(i)->isLeaf() &&
630 getChild(i)->getOperator()->getName() == "imm") {
631 Reason = "Immediate value must be on the RHS of commutative operators!";
632 return false;
633 }
634 }
635
636 return true;
637}
Chris Lattner32707602005-09-08 23:22:48 +0000638
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000639//===----------------------------------------------------------------------===//
640// TreePattern implementation
641//
642
Chris Lattneredbd8712005-10-21 01:19:59 +0000643TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000644 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000645 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000646 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
647 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000648}
649
Chris Lattneredbd8712005-10-21 01:19:59 +0000650TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000651 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000652 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000653 Trees.push_back(ParseTreePattern(Pat));
654}
655
Chris Lattneredbd8712005-10-21 01:19:59 +0000656TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000657 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000658 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000659 Trees.push_back(Pat);
660}
661
662
663
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000664void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000665 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000666 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000667}
668
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000669TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
670 Record *Operator = Dag->getNodeType();
671
672 if (Operator->isSubClassOf("ValueType")) {
673 // If the operator is a ValueType, then this must be "type cast" of a leaf
674 // node.
675 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000676 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000677
678 Init *Arg = Dag->getArg(0);
679 TreePatternNode *New;
680 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000681 Record *R = DI->getDef();
682 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
683 Dag->setArg(0, new DagInit(R,
684 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000685 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000686 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000687 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000688 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
689 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000690 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
691 New = new TreePatternNode(II);
692 if (!Dag->getArgName(0).empty())
693 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000694 } else {
695 Arg->dump();
696 error("Unknown leaf value for tree pattern!");
697 return 0;
698 }
699
Chris Lattner32707602005-09-08 23:22:48 +0000700 // Apply the type cast.
701 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000702 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000703 return New;
704 }
705
706 // Verify that this is something that makes sense for an operator.
707 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000708 !Operator->isSubClassOf("Instruction") &&
709 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000710 Operator->getName() != "set")
711 error("Unrecognized node '" + Operator->getName() + "'!");
712
Chris Lattneredbd8712005-10-21 01:19:59 +0000713 // Check to see if this is something that is illegal in an input pattern.
714 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
715 Operator->isSubClassOf("SDNodeXForm")))
716 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
717
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000718 std::vector<TreePatternNode*> Children;
719
720 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
721 Init *Arg = Dag->getArg(i);
722 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
723 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000724 if (Children.back()->getName().empty())
725 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000726 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
727 Record *R = DefI->getDef();
728 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
729 // TreePatternNode if its own.
730 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
731 Dag->setArg(i, new DagInit(R,
732 std::vector<std::pair<Init*, std::string> >()));
733 --i; // Revisit this node...
734 } else {
735 TreePatternNode *Node = new TreePatternNode(DefI);
736 Node->setName(Dag->getArgName(i));
737 Children.push_back(Node);
738
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000739 // Input argument?
740 if (R->getName() == "node") {
741 if (Dag->getArgName(i).empty())
742 error("'node' argument requires a name to match with operand list");
743 Args.push_back(Dag->getArgName(i));
744 }
745 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000746 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
747 TreePatternNode *Node = new TreePatternNode(II);
748 if (!Dag->getArgName(i).empty())
749 error("Constant int argument should not have a name!");
750 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000751 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000752 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000753 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000754 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000755 error("Unknown leaf value for tree pattern!");
756 }
757 }
758
759 return new TreePatternNode(Operator, Children);
760}
761
Chris Lattner32707602005-09-08 23:22:48 +0000762/// InferAllTypes - Infer/propagate as many types throughout the expression
763/// patterns as possible. Return true if all types are infered, false
764/// otherwise. Throw an exception if a type contradiction is found.
765bool TreePattern::InferAllTypes() {
766 bool MadeChange = true;
767 while (MadeChange) {
768 MadeChange = false;
769 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000770 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000771 }
772
773 bool HasUnresolvedTypes = false;
774 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
775 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
776 return !HasUnresolvedTypes;
777}
778
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000779void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000780 OS << getRecord()->getName();
781 if (!Args.empty()) {
782 OS << "(" << Args[0];
783 for (unsigned i = 1, e = Args.size(); i != e; ++i)
784 OS << ", " << Args[i];
785 OS << ")";
786 }
787 OS << ": ";
788
789 if (Trees.size() > 1)
790 OS << "[\n";
791 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
792 OS << "\t";
793 Trees[i]->print(OS);
794 OS << "\n";
795 }
796
797 if (Trees.size() > 1)
798 OS << "]\n";
799}
800
801void TreePattern::dump() const { print(std::cerr); }
802
803
804
805//===----------------------------------------------------------------------===//
806// DAGISelEmitter implementation
807//
808
Chris Lattnerca559d02005-09-08 21:03:01 +0000809// Parse all of the SDNode definitions for the target, populating SDNodes.
810void DAGISelEmitter::ParseNodeInfo() {
811 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
812 while (!Nodes.empty()) {
813 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
814 Nodes.pop_back();
815 }
816}
817
Chris Lattner24eeeb82005-09-13 21:51:00 +0000818/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
819/// map, and emit them to the file as functions.
820void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
821 OS << "\n// Node transformations.\n";
822 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
823 while (!Xforms.empty()) {
824 Record *XFormNode = Xforms.back();
825 Record *SDNode = XFormNode->getValueAsDef("Opcode");
826 std::string Code = XFormNode->getValueAsCode("XFormFunction");
827 SDNodeXForms.insert(std::make_pair(XFormNode,
828 std::make_pair(SDNode, Code)));
829
Chris Lattner1048b7a2005-09-13 22:03:37 +0000830 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000831 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
832 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
833
Chris Lattner1048b7a2005-09-13 22:03:37 +0000834 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000835 << "(SDNode *" << C2 << ") {\n";
836 if (ClassName != "SDNode")
837 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
838 OS << Code << "\n}\n";
839 }
840
841 Xforms.pop_back();
842 }
843}
844
Evan Cheng0fc71982005-12-08 02:00:36 +0000845void DAGISelEmitter::ParseComplexPatterns() {
846 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
847 while (!AMs.empty()) {
848 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
849 AMs.pop_back();
850 }
851}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000852
853
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000854/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
855/// file, building up the PatternFragments map. After we've collected them all,
856/// inline fragments together as necessary, so that there are no references left
857/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000858///
859/// This also emits all of the predicate functions to the output file.
860///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000861void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000862 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
863
864 // First step, parse all of the fragments and emit predicate functions.
865 OS << "\n// Predicate functions.\n";
866 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000867 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000868 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000869 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000870
871 // Validate the argument list, converting it to map, to discard duplicates.
872 std::vector<std::string> &Args = P->getArgList();
873 std::set<std::string> OperandsMap(Args.begin(), Args.end());
874
875 if (OperandsMap.count(""))
876 P->error("Cannot have unnamed 'node' values in pattern fragment!");
877
878 // Parse the operands list.
879 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
880 if (OpsList->getNodeType()->getName() != "ops")
881 P->error("Operands list should start with '(ops ... '!");
882
883 // Copy over the arguments.
884 Args.clear();
885 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
886 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
887 static_cast<DefInit*>(OpsList->getArg(j))->
888 getDef()->getName() != "node")
889 P->error("Operands list should all be 'node' values.");
890 if (OpsList->getArgName(j).empty())
891 P->error("Operands list should have names for each operand!");
892 if (!OperandsMap.count(OpsList->getArgName(j)))
893 P->error("'" + OpsList->getArgName(j) +
894 "' does not occur in pattern or was multiply specified!");
895 OperandsMap.erase(OpsList->getArgName(j));
896 Args.push_back(OpsList->getArgName(j));
897 }
898
899 if (!OperandsMap.empty())
900 P->error("Operands list does not contain an entry for operand '" +
901 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000902
903 // If there is a code init for this fragment, emit the predicate code and
904 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000905 std::string Code = Fragments[i]->getValueAsCode("Predicate");
906 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000907 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000908 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000909 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000910 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
911
Chris Lattner1048b7a2005-09-13 22:03:37 +0000912 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000913 << "(SDNode *" << C2 << ") {\n";
914 if (ClassName != "SDNode")
915 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000916 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000917 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000918 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000919
920 // If there is a node transformation corresponding to this, keep track of
921 // it.
922 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
923 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000924 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000925 }
926
927 OS << "\n\n";
928
929 // Now that we've parsed all of the tree fragments, do a closure on them so
930 // that there are not references to PatFrags left inside of them.
931 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
932 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000933 TreePattern *ThePat = I->second;
934 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000935
Chris Lattner32707602005-09-08 23:22:48 +0000936 // Infer as many types as possible. Don't worry about it if we don't infer
937 // all of them, some may depend on the inputs of the pattern.
938 try {
939 ThePat->InferAllTypes();
940 } catch (...) {
941 // If this pattern fragment is not supported by this target (no types can
942 // satisfy its constraints), just ignore it. If the bogus pattern is
943 // actually used by instructions, the type consistency error will be
944 // reported there.
945 }
946
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000947 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000948 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000949 }
950}
951
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000952/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000953/// instruction input. Return true if this is a real use.
954static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Chengbcecf332005-12-17 01:19:28 +0000955 std::map<std::string, TreePatternNode*> &InstInputs,
956 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000957 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000958 if (Pat->getName().empty()) {
959 if (Pat->isLeaf()) {
960 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
961 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
962 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Chengbcecf332005-12-17 01:19:28 +0000963 else if (DI && DI->getDef()->isSubClassOf("Register")) {
964 InstImpInputs.push_back(DI->getDef());
965 }
Chris Lattner7da852f2005-09-14 22:06:36 +0000966 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000967 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000968 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000969
970 Record *Rec;
971 if (Pat->isLeaf()) {
972 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
973 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
974 Rec = DI->getDef();
975 } else {
976 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
977 Rec = Pat->getOperator();
978 }
979
Evan Cheng01f318b2005-12-14 02:21:57 +0000980 // SRCVALUE nodes are ignored.
981 if (Rec->getName() == "srcvalue")
982 return false;
983
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000984 TreePatternNode *&Slot = InstInputs[Pat->getName()];
985 if (!Slot) {
986 Slot = Pat;
987 } else {
988 Record *SlotRec;
989 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000990 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000991 } else {
992 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
993 SlotRec = Slot->getOperator();
994 }
995
996 // Ensure that the inputs agree if we've already seen this input.
997 if (Rec != SlotRec)
998 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000999 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001000 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1001 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001002 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001003}
1004
1005/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1006/// part of "I", the instruction), computing the set of inputs and outputs of
1007/// the pattern. Report errors if we see anything naughty.
1008void DAGISelEmitter::
1009FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1010 std::map<std::string, TreePatternNode*> &InstInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001011 std::map<std::string, Record*> &InstResults,
1012 std::vector<Record*> &InstImpInputs,
1013 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001014 if (Pat->isLeaf()) {
Evan Chengbcecf332005-12-17 01:19:28 +00001015 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001016 if (!isUse && Pat->getTransformFn())
1017 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001018 return;
1019 } else if (Pat->getOperator()->getName() != "set") {
1020 // If this is not a set, verify that the children nodes are not void typed,
1021 // and recurse.
1022 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001023 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001024 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001025 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1026 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001027 }
1028
1029 // If this is a non-leaf node with no children, treat it basically as if
1030 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001031 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001032 if (Pat->getNumChildren() == 0)
Evan Chengbcecf332005-12-17 01:19:28 +00001033 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001034
Chris Lattnerf1311842005-09-14 23:05:13 +00001035 if (!isUse && Pat->getTransformFn())
1036 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001037 return;
1038 }
1039
1040 // Otherwise, this is a set, validate and collect instruction results.
1041 if (Pat->getNumChildren() == 0)
1042 I->error("set requires operands!");
1043 else if (Pat->getNumChildren() & 1)
1044 I->error("set requires an even number of operands");
1045
Chris Lattnerf1311842005-09-14 23:05:13 +00001046 if (Pat->getTransformFn())
1047 I->error("Cannot specify a transform function on a set node!");
1048
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001049 // Check the set destinations.
1050 unsigned NumValues = Pat->getNumChildren()/2;
1051 for (unsigned i = 0; i != NumValues; ++i) {
1052 TreePatternNode *Dest = Pat->getChild(i);
1053 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001054 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001055
1056 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1057 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001058 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001059
Evan Chengbcecf332005-12-17 01:19:28 +00001060 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1061 if (Dest->getName().empty())
1062 I->error("set destination must have a name!");
1063 if (InstResults.count(Dest->getName()))
1064 I->error("cannot set '" + Dest->getName() +"' multiple times");
1065 InstResults[Dest->getName()] = Val->getDef();
1066 } else if (Val->getDef()->isSubClassOf("Register")) {
1067 InstImpResults.push_back(Val->getDef());
1068 } else {
1069 I->error("set destination should be a register!");
1070 }
1071
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001072 // Verify and collect info from the computation.
1073 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Chengbcecf332005-12-17 01:19:28 +00001074 InstInputs, InstResults, InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001075 }
1076}
1077
Evan Chengdd304dd2005-12-05 23:08:55 +00001078/// NodeHasChain - return true if TreePatternNode has the property
1079/// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1080/// a chain result.
1081static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1082{
1083 if (N->isLeaf()) return false;
1084 Record *Operator = N->getOperator();
1085 if (!Operator->isSubClassOf("SDNode")) return false;
1086
1087 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1088 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1089}
1090
1091static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1092{
1093 if (NodeHasChain(N, ISE))
1094 return true;
1095 else {
1096 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1097 TreePatternNode *Child = N->getChild(i);
1098 if (PatternHasCtrlDep(Child, ISE))
1099 return true;
1100 }
1101 }
1102
1103 return false;
1104}
1105
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001106
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001107/// ParseInstructions - Parse all of the instructions, inlining and resolving
1108/// any fragments involved. This populates the Instructions list with fully
1109/// resolved instructions.
1110void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001111 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1112
1113 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001114 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001115
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001116 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1117 LI = Instrs[i]->getValueAsListInit("Pattern");
1118
1119 // If there is no pattern, only collect minimal information about the
1120 // instruction for its operand list. We have to assume that there is one
1121 // result, as we have no detailed info.
1122 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001123 std::vector<Record*> Results;
1124 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001125
1126 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1127
1128 // Doesn't even define a result?
1129 if (InstInfo.OperandList.size() == 0)
1130 continue;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001131
1132 // FIXME: temporary hack...
1133 if (InstInfo.isReturn || InstInfo.isBranch || InstInfo.isCall ||
1134 InstInfo.isStore) {
1135 // These produce no results
1136 for (unsigned j = 0, e = InstInfo.OperandList.size(); j != e; ++j)
1137 Operands.push_back(InstInfo.OperandList[j].Rec);
1138 } else {
1139 // Assume the first operand is the result.
1140 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001141
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001142 // The rest are inputs.
1143 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1144 Operands.push_back(InstInfo.OperandList[j].Rec);
1145 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001146
1147 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001148 std::vector<Record*> ImpResults;
1149 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001150 Instructions.insert(std::make_pair(Instrs[i],
Evan Chengbcecf332005-12-17 01:19:28 +00001151 DAGInstruction(0, Results, Operands,
1152 ImpResults, ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001153 continue; // no pattern.
1154 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001155
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001156 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001157 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001158 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001159 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001160
Chris Lattner95f6b762005-09-08 23:26:30 +00001161 // Infer as many types as possible. If we cannot infer all of them, we can
1162 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001163 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001164 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001165
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001166 // InstInputs - Keep track of all of the inputs of the instruction, along
1167 // with the record they are declared as.
1168 std::map<std::string, TreePatternNode*> InstInputs;
1169
1170 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001171 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001172 std::map<std::string, Record*> InstResults;
Evan Chengbcecf332005-12-17 01:19:28 +00001173
1174 std::vector<Record*> InstImpInputs;
1175 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001176
Chris Lattner1f39e292005-09-14 00:09:24 +00001177 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001178 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001179 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1180 TreePatternNode *Pat = I->getTree(j);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001181 if (Pat->getExtType() != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001182 I->error("Top-level forms in instruction pattern should have"
1183 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001184
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001185 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001186 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1187 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001188 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001189
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001190 // Now that we have inputs and outputs of the pattern, inspect the operands
1191 // list for the instruction. This determines the order that operands are
1192 // added to the machine instruction the node corresponds to.
1193 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001194
1195 // Parse the operands list from the (ops) list, validating it.
1196 std::vector<std::string> &Args = I->getArgList();
1197 assert(Args.empty() && "Args list should still be empty here!");
1198 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1199
1200 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001201 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001202 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001203 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001204 I->error("'" + InstResults.begin()->first +
1205 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001206 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001207
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001208 // Check that it exists in InstResults.
1209 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001210 if (R == 0)
1211 I->error("Operand $" + OpName + " should be a set destination: all "
1212 "outputs must occur before inputs in operand list!");
1213
1214 if (CGI.OperandList[i].Rec != R)
1215 I->error("Operand $" + OpName + " class mismatch!");
1216
Chris Lattnerae6d8282005-09-15 21:51:12 +00001217 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001218 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001219
Chris Lattner39e8af92005-09-14 18:19:25 +00001220 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001221 InstResults.erase(OpName);
1222 }
1223
Chris Lattner0b592252005-09-14 21:59:34 +00001224 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1225 // the copy while we're checking the inputs.
1226 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001227
1228 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001229 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001230 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1231 const std::string &OpName = CGI.OperandList[i].Name;
1232 if (OpName.empty())
1233 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1234
Chris Lattner0b592252005-09-14 21:59:34 +00001235 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001236 I->error("Operand $" + OpName +
1237 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001238 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001239 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001240
1241 if (InVal->isLeaf() &&
1242 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1243 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001244 if (CGI.OperandList[i].Rec != InRec &&
1245 !InRec->isSubClassOf("ComplexPattern"))
Nate Begemanddb39542005-12-01 00:06:14 +00001246 I->error("Operand $" + OpName +
Evan Cheng0fc71982005-12-08 02:00:36 +00001247 "'s register class disagrees between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001248 }
1249 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001250
Chris Lattner2175c182005-09-14 23:01:59 +00001251 // Construct the result for the dest-pattern operand list.
1252 TreePatternNode *OpNode = InVal->clone();
1253
1254 // No predicate is useful on the result.
1255 OpNode->setPredicateFn("");
1256
1257 // Promote the xform function to be an explicit node if set.
1258 if (Record *Xform = OpNode->getTransformFn()) {
1259 OpNode->setTransformFn(0);
1260 std::vector<TreePatternNode*> Children;
1261 Children.push_back(OpNode);
1262 OpNode = new TreePatternNode(Xform, Children);
1263 }
1264
1265 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001266 }
1267
Chris Lattner0b592252005-09-14 21:59:34 +00001268 if (!InstInputsCheck.empty())
1269 I->error("Input operand $" + InstInputsCheck.begin()->first +
1270 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001271
1272 TreePatternNode *ResultPattern =
1273 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001274
1275 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001276 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001277 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1278
1279 // Use a temporary tree pattern to infer all types and make sure that the
1280 // constructed result is correct. This depends on the instruction already
1281 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001282 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001283 Temp.InferAllTypes();
1284
1285 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1286 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001287
Chris Lattner32707602005-09-08 23:22:48 +00001288 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001289 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001290
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001291 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001292 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1293 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001294 DAGInstruction &TheInst = II->second;
1295 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001296 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001297
Chris Lattner1f39e292005-09-14 00:09:24 +00001298 if (I->getNumTrees() != 1) {
1299 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1300 continue;
1301 }
1302 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001303 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001304 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001305 if (Pattern->getNumChildren() != 2)
1306 continue; // Not a set of a single value (not handled so far)
1307
1308 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001309 } else{
1310 // Not a set (store or something?)
1311 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001312 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001313
1314 std::string Reason;
1315 if (!SrcPattern->canPatternMatch(Reason, *this))
1316 I->error("Instruction can never match: " + Reason);
1317
Evan Cheng58e84a62005-12-14 22:02:59 +00001318 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001319 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001320 PatternsToMatch.
1321 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1322 SrcPattern, DstPattern));
Evan Chengdd304dd2005-12-05 23:08:55 +00001323
1324 if (PatternHasCtrlDep(Pattern, *this)) {
Evan Chengdd304dd2005-12-05 23:08:55 +00001325 CodeGenInstruction &InstInfo = Target.getInstruction(Instr->getName());
1326 InstInfo.hasCtrlDep = true;
1327 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001328 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001329}
1330
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001331void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001332 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001333
Chris Lattnerabbb6052005-09-15 21:42:00 +00001334 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001335 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001336 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001337
Chris Lattnerabbb6052005-09-15 21:42:00 +00001338 // Inline pattern fragments into it.
1339 Pattern->InlinePatternFragments();
1340
1341 // Infer as many types as possible. If we cannot infer all of them, we can
1342 // never do anything with this pattern: report it to the user.
1343 if (!Pattern->InferAllTypes())
1344 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001345
1346 // Validate that the input pattern is correct.
1347 {
1348 std::map<std::string, TreePatternNode*> InstInputs;
1349 std::map<std::string, Record*> InstResults;
Evan Chengbcecf332005-12-17 01:19:28 +00001350 std::vector<Record*> InstImpInputs;
1351 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001352 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001353 InstInputs, InstResults,
1354 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001355 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001356
1357 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1358 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001359
1360 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001361 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001362
1363 // Inline pattern fragments into it.
1364 Result->InlinePatternFragments();
1365
1366 // Infer as many types as possible. If we cannot infer all of them, we can
1367 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001368 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001369 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001370
1371 if (Result->getNumTrees() != 1)
1372 Result->error("Cannot handle instructions producing instructions "
1373 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001374
1375 std::string Reason;
1376 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1377 Pattern->error("Pattern can never match: " + Reason);
1378
Evan Cheng58e84a62005-12-14 22:02:59 +00001379 PatternsToMatch.
1380 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1381 Pattern->getOnlyTree(),
1382 Result->getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001383 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001384}
1385
Chris Lattnere46e17b2005-09-29 19:28:10 +00001386/// CombineChildVariants - Given a bunch of permutations of each child of the
1387/// 'operator' node, put them together in all possible ways.
1388static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001389 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001390 std::vector<TreePatternNode*> &OutVariants,
1391 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001392 // Make sure that each operand has at least one variant to choose from.
1393 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1394 if (ChildVariants[i].empty())
1395 return;
1396
Chris Lattnere46e17b2005-09-29 19:28:10 +00001397 // The end result is an all-pairs construction of the resultant pattern.
1398 std::vector<unsigned> Idxs;
1399 Idxs.resize(ChildVariants.size());
1400 bool NotDone = true;
1401 while (NotDone) {
1402 // Create the variant and add it to the output list.
1403 std::vector<TreePatternNode*> NewChildren;
1404 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1405 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1406 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1407
1408 // Copy over properties.
1409 R->setName(Orig->getName());
1410 R->setPredicateFn(Orig->getPredicateFn());
1411 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001412 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001413
1414 // If this pattern cannot every match, do not include it as a variant.
1415 std::string ErrString;
1416 if (!R->canPatternMatch(ErrString, ISE)) {
1417 delete R;
1418 } else {
1419 bool AlreadyExists = false;
1420
1421 // Scan to see if this pattern has already been emitted. We can get
1422 // duplication due to things like commuting:
1423 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1424 // which are the same pattern. Ignore the dups.
1425 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1426 if (R->isIsomorphicTo(OutVariants[i])) {
1427 AlreadyExists = true;
1428 break;
1429 }
1430
1431 if (AlreadyExists)
1432 delete R;
1433 else
1434 OutVariants.push_back(R);
1435 }
1436
1437 // Increment indices to the next permutation.
1438 NotDone = false;
1439 // Look for something we can increment without causing a wrap-around.
1440 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1441 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1442 NotDone = true; // Found something to increment.
1443 break;
1444 }
1445 Idxs[IdxsIdx] = 0;
1446 }
1447 }
1448}
1449
Chris Lattneraf302912005-09-29 22:36:54 +00001450/// CombineChildVariants - A helper function for binary operators.
1451///
1452static void CombineChildVariants(TreePatternNode *Orig,
1453 const std::vector<TreePatternNode*> &LHS,
1454 const std::vector<TreePatternNode*> &RHS,
1455 std::vector<TreePatternNode*> &OutVariants,
1456 DAGISelEmitter &ISE) {
1457 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1458 ChildVariants.push_back(LHS);
1459 ChildVariants.push_back(RHS);
1460 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1461}
1462
1463
1464static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1465 std::vector<TreePatternNode *> &Children) {
1466 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1467 Record *Operator = N->getOperator();
1468
1469 // Only permit raw nodes.
1470 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1471 N->getTransformFn()) {
1472 Children.push_back(N);
1473 return;
1474 }
1475
1476 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1477 Children.push_back(N->getChild(0));
1478 else
1479 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1480
1481 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1482 Children.push_back(N->getChild(1));
1483 else
1484 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1485}
1486
Chris Lattnere46e17b2005-09-29 19:28:10 +00001487/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1488/// the (potentially recursive) pattern by using algebraic laws.
1489///
1490static void GenerateVariantsOf(TreePatternNode *N,
1491 std::vector<TreePatternNode*> &OutVariants,
1492 DAGISelEmitter &ISE) {
1493 // We cannot permute leaves.
1494 if (N->isLeaf()) {
1495 OutVariants.push_back(N);
1496 return;
1497 }
1498
1499 // Look up interesting info about the node.
1500 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1501
1502 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001503 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1504 // Reassociate by pulling together all of the linked operators
1505 std::vector<TreePatternNode*> MaximalChildren;
1506 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1507
1508 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1509 // permutations.
1510 if (MaximalChildren.size() == 3) {
1511 // Find the variants of all of our maximal children.
1512 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1513 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1514 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1515 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1516
1517 // There are only two ways we can permute the tree:
1518 // (A op B) op C and A op (B op C)
1519 // Within these forms, we can also permute A/B/C.
1520
1521 // Generate legal pair permutations of A/B/C.
1522 std::vector<TreePatternNode*> ABVariants;
1523 std::vector<TreePatternNode*> BAVariants;
1524 std::vector<TreePatternNode*> ACVariants;
1525 std::vector<TreePatternNode*> CAVariants;
1526 std::vector<TreePatternNode*> BCVariants;
1527 std::vector<TreePatternNode*> CBVariants;
1528 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1529 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1530 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1531 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1532 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1533 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1534
1535 // Combine those into the result: (x op x) op x
1536 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1537 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1538 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1539 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1540 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1541 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1542
1543 // Combine those into the result: x op (x op x)
1544 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1545 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1546 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1547 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1548 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1549 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1550 return;
1551 }
1552 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001553
1554 // Compute permutations of all children.
1555 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1556 ChildVariants.resize(N->getNumChildren());
1557 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1558 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1559
1560 // Build all permutations based on how the children were formed.
1561 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1562
1563 // If this node is commutative, consider the commuted order.
1564 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1565 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001566 // Consider the commuted order.
1567 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1568 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001569 }
1570}
1571
1572
Chris Lattnere97603f2005-09-28 19:27:25 +00001573// GenerateVariants - Generate variants. For example, commutative patterns can
1574// match multiple ways. Add them to PatternsToMatch as well.
1575void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001576
1577 DEBUG(std::cerr << "Generating instruction variants.\n");
1578
1579 // Loop over all of the patterns we've collected, checking to see if we can
1580 // generate variants of the instruction, through the exploitation of
1581 // identities. This permits the target to provide agressive matching without
1582 // the .td file having to contain tons of variants of instructions.
1583 //
1584 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1585 // intentionally do not reconsider these. Any variants of added patterns have
1586 // already been added.
1587 //
1588 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1589 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001590 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001591
1592 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001593 Variants.erase(Variants.begin()); // Remove the original pattern.
1594
1595 if (Variants.empty()) // No variants for this pattern.
1596 continue;
1597
1598 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001599 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001600 std::cerr << "\n");
1601
1602 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1603 TreePatternNode *Variant = Variants[v];
1604
1605 DEBUG(std::cerr << " VAR#" << v << ": ";
1606 Variant->dump();
1607 std::cerr << "\n");
1608
1609 // Scan to see if an instruction or explicit pattern already matches this.
1610 bool AlreadyExists = false;
1611 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1612 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001613 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001614 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1615 AlreadyExists = true;
1616 break;
1617 }
1618 }
1619 // If we already have it, ignore the variant.
1620 if (AlreadyExists) continue;
1621
1622 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001623 PatternsToMatch.
1624 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1625 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001626 }
1627
1628 DEBUG(std::cerr << "\n");
1629 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001630}
1631
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001632
Evan Cheng0fc71982005-12-08 02:00:36 +00001633// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1634// ComplexPattern.
1635static bool NodeIsComplexPattern(TreePatternNode *N)
1636{
1637 return (N->isLeaf() &&
1638 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1639 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1640 isSubClassOf("ComplexPattern"));
1641}
1642
1643// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1644// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1645static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1646 DAGISelEmitter &ISE)
1647{
1648 if (N->isLeaf() &&
1649 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1650 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1651 isSubClassOf("ComplexPattern")) {
1652 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1653 ->getDef());
1654 }
1655 return NULL;
1656}
1657
Chris Lattner05814af2005-09-28 17:57:56 +00001658/// getPatternSize - Return the 'size' of this pattern. We want to match large
1659/// patterns before small ones. This is used to determine the size of a
1660/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001661static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001662 assert(isExtIntegerVT(P->getExtType()) ||
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001663 isExtFloatingPointVT(P->getExtType()) ||
Evan Chengbcecf332005-12-17 01:19:28 +00001664 P->getExtType() == MVT::isVoid ||
1665 P->getExtType() == MVT::Flag && "Not a valid pattern node to size!");
Chris Lattner05814af2005-09-28 17:57:56 +00001666 unsigned Size = 1; // The node itself.
Evan Cheng0fc71982005-12-08 02:00:36 +00001667
1668 // FIXME: This is a hack to statically increase the priority of patterns
1669 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1670 // Later we can allow complexity / cost for each pattern to be (optionally)
1671 // specified. To get best possible pattern match we'll need to dynamically
1672 // calculate the complexity of all patterns a dag can potentially map to.
1673 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1674 if (AM)
1675 Size += AM->getNumOperands();
1676
Chris Lattner05814af2005-09-28 17:57:56 +00001677 // Count children in the count if they are also nodes.
1678 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1679 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001680 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001681 Size += getPatternSize(Child, ISE);
1682 else if (Child->isLeaf()) {
1683 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1684 ++Size; // Matches a ConstantSDNode.
1685 else if (NodeIsComplexPattern(Child))
1686 Size += getPatternSize(Child, ISE);
Chris Lattner2f041d42005-10-19 04:41:05 +00001687 }
Chris Lattner05814af2005-09-28 17:57:56 +00001688 }
1689
1690 return Size;
1691}
1692
1693/// getResultPatternCost - Compute the number of instructions for this pattern.
1694/// This is a temporary hack. We should really include the instruction
1695/// latencies in this calculation.
1696static unsigned getResultPatternCost(TreePatternNode *P) {
1697 if (P->isLeaf()) return 0;
1698
1699 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1700 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1701 Cost += getResultPatternCost(P->getChild(i));
1702 return Cost;
1703}
1704
1705// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1706// In particular, we want to match maximal patterns first and lowest cost within
1707// a particular complexity first.
1708struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001709 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1710 DAGISelEmitter &ISE;
1711
Evan Cheng58e84a62005-12-14 22:02:59 +00001712 bool operator()(PatternToMatch *LHS,
1713 PatternToMatch *RHS) {
1714 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1715 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001716 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1717 if (LHSSize < RHSSize) return false;
1718
1719 // If the patterns have equal complexity, compare generated instruction cost
Evan Cheng58e84a62005-12-14 22:02:59 +00001720 return getResultPatternCost(LHS->getDstPattern()) <
1721 getResultPatternCost(RHS->getDstPattern());
Chris Lattner05814af2005-09-28 17:57:56 +00001722 }
1723};
1724
Nate Begeman6510b222005-12-01 04:51:06 +00001725/// getRegisterValueType - Look up and return the first ValueType of specified
1726/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001727static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001728 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1729 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001730 return MVT::Other;
1731}
1732
Chris Lattner72fe91c2005-09-24 00:40:24 +00001733
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001734/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1735/// type information from it.
1736static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001737 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001738 if (!N->isLeaf())
1739 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1740 RemoveAllTypes(N->getChild(i));
1741}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001742
Chris Lattner0614b622005-11-02 06:49:14 +00001743Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1744 Record *N = Records.getDef(Name);
1745 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1746 return N;
1747}
1748
Evan Chengb915f312005-12-09 22:45:35 +00001749class PatternCodeEmitter {
1750private:
1751 DAGISelEmitter &ISE;
1752
Evan Cheng58e84a62005-12-14 22:02:59 +00001753 // Predicates.
1754 ListInit *Predicates;
1755 // Instruction selector pattern.
1756 TreePatternNode *Pattern;
1757 // Matched instruction.
1758 TreePatternNode *Instruction;
Evan Chengb915f312005-12-09 22:45:35 +00001759 unsigned PatternNo;
1760 std::ostream &OS;
1761 // Node to name mapping
1762 std::map<std::string,std::string> VariableMap;
Evan Chengb915f312005-12-09 22:45:35 +00001763 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001764 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng86217892005-12-12 19:37:43 +00001765 bool FoundChain;
Evan Chengb915f312005-12-09 22:45:35 +00001766 bool InFlag;
1767 unsigned TmpNo;
1768
1769public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001770 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1771 TreePatternNode *pattern, TreePatternNode *instr,
Evan Chengb915f312005-12-09 22:45:35 +00001772 unsigned PatNum, std::ostream &os) :
Evan Cheng58e84a62005-12-14 22:02:59 +00001773 ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1774 PatternNo(PatNum), OS(os), FoundChain(false), InFlag(false), TmpNo(0) {};
Evan Chengb915f312005-12-09 22:45:35 +00001775
1776 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1777 /// if the match fails. At this point, we already know that the opcode for N
1778 /// matches, and the SDNode for the result has the RootName specified name.
1779 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1780 bool isRoot = false) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001781
1782 // Emit instruction predicates. Each predicate is just a string for now.
1783 if (isRoot) {
1784 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1785 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1786 Record *Def = Pred->getDef();
1787 if (Def->isSubClassOf("Predicate")) {
1788 if (i == 0)
1789 OS << " if (";
1790 else
1791 OS << " && ";
1792 OS << "(" << Def->getValueAsString("CondString") << ")";
1793 if (i == e-1)
1794 OS << ") goto P" << PatternNo << "Fail;\n";
1795 } else {
1796 Def->dump();
1797 assert(0 && "Unknown predicate type!");
1798 }
1799 }
1800 }
1801 }
1802
Evan Chengb915f312005-12-09 22:45:35 +00001803 if (N->isLeaf()) {
1804 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1805 OS << " if (cast<ConstantSDNode>(" << RootName
1806 << ")->getSignExtended() != " << II->getValue() << ")\n"
1807 << " goto P" << PatternNo << "Fail;\n";
1808 return;
1809 } else if (!NodeIsComplexPattern(N)) {
1810 assert(0 && "Cannot match this as a leaf value!");
1811 abort();
1812 }
1813 }
1814
1815 // If this node has a name associated with it, capture it in VariableMap. If
1816 // we already saw this in the pattern, emit code to verify dagness.
1817 if (!N->getName().empty()) {
1818 std::string &VarMapEntry = VariableMap[N->getName()];
1819 if (VarMapEntry.empty()) {
1820 VarMapEntry = RootName;
1821 } else {
1822 // If we get here, this is a second reference to a specific name. Since
1823 // we already have checked that the first reference is valid, we don't
1824 // have to recursively match it, just check that it's the same as the
1825 // previously named thing.
1826 OS << " if (" << VarMapEntry << " != " << RootName
1827 << ") goto P" << PatternNo << "Fail;\n";
1828 return;
1829 }
1830 }
1831
1832
1833 // Emit code to load the child nodes and match their contents recursively.
1834 unsigned OpNo = 0;
Evan Cheng86217892005-12-12 19:37:43 +00001835 bool HasChain = NodeHasChain(N, ISE);
1836 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00001837 OpNo = 1;
1838 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001839 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Chengb915f312005-12-09 22:45:35 +00001840 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1841 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1842 OS << " if (CodeGenMap.count(" << RootName
Evan Cheng1129e872005-12-10 00:09:17 +00001843 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
Evan Chengb915f312005-12-09 22:45:35 +00001844 << PatternNo << "Fail; // Already selected for a chain use?\n";
1845 }
Evan Chengb915f312005-12-09 22:45:35 +00001846 }
1847
1848 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1849 OS << " SDOperand " << RootName << OpNo <<" = " << RootName
1850 << ".getOperand(" << OpNo << ");\n";
1851 TreePatternNode *Child = N->getChild(i);
1852
1853 if (!Child->isLeaf()) {
1854 // If it's not a leaf, recursively match.
1855 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1856 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1857 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1858 EmitMatchCode(Child, RootName + utostr(OpNo));
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001859 if (NodeHasChain(Child, ISE)) {
1860 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1861 CInfo.getNumResults()));
1862 }
Evan Chengb915f312005-12-09 22:45:35 +00001863 } else {
1864 // If this child has a name associated with it, capture it in VarMap. If
1865 // we already saw this in the pattern, emit code to verify dagness.
1866 if (!Child->getName().empty()) {
1867 std::string &VarMapEntry = VariableMap[Child->getName()];
1868 if (VarMapEntry.empty()) {
1869 VarMapEntry = RootName + utostr(OpNo);
1870 } else {
1871 // If we get here, this is a second reference to a specific name. Since
1872 // we already have checked that the first reference is valid, we don't
1873 // have to recursively match it, just check that it's the same as the
1874 // previously named thing.
1875 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1876 << ") goto P" << PatternNo << "Fail;\n";
1877 continue;
1878 }
1879 }
1880
1881 // Handle leaves of various types.
1882 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1883 Record *LeafRec = DI->getDef();
1884 if (LeafRec->isSubClassOf("RegisterClass")) {
1885 // Handle register references. Nothing to do here.
1886 } else if (LeafRec->isSubClassOf("Register")) {
1887 if (!InFlag) {
1888 OS << " SDOperand InFlag = SDOperand(0,0);\n";
1889 InFlag = true;
1890 }
1891 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1892 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00001893 } else if (LeafRec->getName() == "srcvalue") {
1894 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00001895 } else if (LeafRec->isSubClassOf("ValueType")) {
1896 // Make sure this is the specified value type.
1897 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1898 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1899 << "Fail;\n";
1900 } else if (LeafRec->isSubClassOf("CondCode")) {
1901 // Make sure this is the specified cond code.
1902 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1903 << ")->get() != " << "ISD::" << LeafRec->getName()
1904 << ") goto P" << PatternNo << "Fail;\n";
1905 } else {
1906 Child->dump();
1907 assert(0 && "Unknown leaf type!");
1908 }
1909 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1910 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1911 << " cast<ConstantSDNode>(" << RootName << OpNo
1912 << ")->getSignExtended() != " << II->getValue() << ")\n"
1913 << " goto P" << PatternNo << "Fail;\n";
1914 } else {
1915 Child->dump();
1916 assert(0 && "Unknown leaf type!");
1917 }
1918 }
1919 }
1920
Evan Cheng86217892005-12-12 19:37:43 +00001921 if (HasChain) {
1922 if (!FoundChain) {
1923 OS << " SDOperand Chain = " << RootName << ".getOperand(0);\n";
1924 FoundChain = true;
1925 }
1926 }
1927
Evan Chengb915f312005-12-09 22:45:35 +00001928 // If there is a node predicate for this, emit the call.
1929 if (!N->getPredicateFn().empty())
1930 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1931 << ".Val)) goto P" << PatternNo << "Fail;\n";
1932 }
1933
1934 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1935 /// we actually have to build a DAG!
1936 std::pair<unsigned, unsigned>
1937 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1938 // This is something selected from the pattern we matched.
1939 if (!N->getName().empty()) {
1940 assert(!isRoot && "Root of pattern cannot be a leaf!");
1941 std::string &Val = VariableMap[N->getName()];
1942 assert(!Val.empty() &&
1943 "Variable referenced but not defined and not caught earlier!");
1944 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1945 // Already selected this operand, just return the tmpval.
1946 return std::make_pair(1, atoi(Val.c_str()+3));
1947 }
1948
1949 const ComplexPattern *CP;
1950 unsigned ResNo = TmpNo++;
1951 unsigned NumRes = 1;
1952 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1953 switch (N->getType()) {
1954 default: assert(0 && "Unknown type for constant node!");
1955 case MVT::i1: OS << " bool Tmp"; break;
1956 case MVT::i8: OS << " unsigned char Tmp"; break;
1957 case MVT::i16: OS << " unsigned short Tmp"; break;
1958 case MVT::i32: OS << " unsigned Tmp"; break;
1959 case MVT::i64: OS << " uint64_t Tmp"; break;
1960 }
1961 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1962 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1963 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1964 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1965 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Nate Begeman28a6b022005-12-10 02:36:00 +00001966 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
1967 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Evan Chengb915f312005-12-09 22:45:35 +00001968 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
1969 std::string Fn = CP->getSelectFunc();
1970 NumRes = CP->getNumOperands();
1971 OS << " SDOperand ";
1972 for (unsigned i = 0; i < NumRes; i++) {
1973 if (i != 0) OS << ", ";
1974 OS << "Tmp" << i + ResNo;
1975 }
1976 OS << ";\n";
1977 OS << " if (!" << Fn << "(" << Val;
1978 for (unsigned i = 0; i < NumRes; i++)
Evan Chengbcecf332005-12-17 01:19:28 +00001979 OS << ", Tmp" << i + ResNo;
Evan Chengb915f312005-12-09 22:45:35 +00001980 OS << ")) goto P" << PatternNo << "Fail;\n";
1981 TmpNo = ResNo + NumRes;
1982 } else {
1983 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1984 }
1985 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1986 // value if used multiple times by this pattern result.
1987 Val = "Tmp"+utostr(ResNo);
1988 return std::make_pair(NumRes, ResNo);
1989 }
1990
1991 if (N->isLeaf()) {
1992 // If this is an explicit register reference, handle it.
1993 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1994 unsigned ResNo = TmpNo++;
1995 if (DI->getDef()->isSubClassOf("Register")) {
1996 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1997 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
1998 << getEnumName(N->getType())
1999 << ");\n";
2000 return std::make_pair(1, ResNo);
2001 }
2002 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2003 unsigned ResNo = TmpNo++;
2004 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
2005 << II->getValue() << ", MVT::"
2006 << getEnumName(N->getType())
2007 << ");\n";
2008 return std::make_pair(1, ResNo);
2009 }
2010
2011 N->dump();
2012 assert(0 && "Unknown leaf type!");
2013 return std::make_pair(1, ~0U);
2014 }
2015
2016 Record *Op = N->getOperator();
2017 if (Op->isSubClassOf("Instruction")) {
2018 // Determine operand emission order. Complex pattern first.
2019 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2020 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2021 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2022 TreePatternNode *Child = N->getChild(i);
2023 if (i == 0) {
2024 EmitOrder.push_back(std::make_pair(i, Child));
2025 OI = EmitOrder.begin();
2026 } else if (NodeIsComplexPattern(Child)) {
2027 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2028 } else {
2029 EmitOrder.push_back(std::make_pair(i, Child));
2030 }
2031 }
2032
2033 // Emit all of the operands.
2034 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2035 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2036 unsigned OpOrder = EmitOrder[i].first;
2037 TreePatternNode *Child = EmitOrder[i].second;
2038 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2039 NumTemps[OpOrder] = NumTemp;
2040 }
2041
2042 // List all the operands in the right order.
2043 std::vector<unsigned> Ops;
2044 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2045 for (unsigned j = 0; j < NumTemps[i].first; j++)
2046 Ops.push_back(NumTemps[i].second + j);
2047 }
2048
Evan Chengbcecf332005-12-17 01:19:28 +00002049 const CodeGenTarget &CGT = ISE.getTargetInfo();
2050 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002051
2052 // Emit all the chain and CopyToReg stuff.
2053 if (II.hasCtrlDep)
Evan Cheng86217892005-12-12 19:37:43 +00002054 OS << " Chain = Select(Chain);\n";
Evan Cheng58e84a62005-12-14 22:02:59 +00002055 EmitCopyToRegs(Pattern, "N", II.hasCtrlDep);
Evan Chengb915f312005-12-09 22:45:35 +00002056
2057 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Chengbcecf332005-12-17 01:19:28 +00002058 unsigned NumImpResults = Inst.getNumImpResults();
Evan Chengb915f312005-12-09 22:45:35 +00002059 unsigned NumResults = Inst.getNumResults();
2060 unsigned ResNo = TmpNo++;
2061 if (!isRoot) {
2062 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002063 << II.Namespace << "::" << II.TheDef->getName();
2064 if (N->getType() != MVT::isVoid)
2065 OS << ", MVT::" << getEnumName(N->getType());
2066 for (unsigned i = 0; i < NumImpResults; i++) {
2067 Record *ImpResult = Inst.getImpResult(i);
2068 MVT::ValueType RVT = getRegisterValueType(ImpResult, CGT);
2069 OS << ", MVT::" << getEnumName(RVT);
2070 }
2071
Evan Chengb915f312005-12-09 22:45:35 +00002072 unsigned LastOp = 0;
2073 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2074 LastOp = Ops[i];
2075 OS << ", Tmp" << LastOp;
2076 }
2077 OS << ");\n";
2078 if (II.hasCtrlDep) {
2079 // Must have at least one result
2080 OS << " Chain = Tmp" << LastOp << ".getValue("
2081 << NumResults << ");\n";
2082 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002083 } else if (II.hasCtrlDep || NumImpResults > 0) {
2084 OS << " SDOperand Result = CurDAG->getTargetNode("
Evan Chengb915f312005-12-09 22:45:35 +00002085 << II.Namespace << "::" << II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002086
2087 // Output order: results, chain, flags
2088 // Result types.
Evan Chengbcecf332005-12-17 01:19:28 +00002089 if (NumResults > 0) {
2090 // TODO: multiple results?
2091 if (N->getType() != MVT::isVoid)
2092 OS << ", MVT::" << getEnumName(N->getType());
2093 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002094 if (II.hasCtrlDep)
2095 OS << ", MVT::Other";
Evan Chengbcecf332005-12-17 01:19:28 +00002096 for (unsigned i = 0; i < NumImpResults; i++) {
2097 Record *ImpResult = Inst.getImpResult(i);
2098 MVT::ValueType RVT = getRegisterValueType(ImpResult, CGT);
2099 OS << ", MVT::" << getEnumName(RVT);
2100 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002101
2102 // Inputs.
Evan Chengb915f312005-12-09 22:45:35 +00002103 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2104 OS << ", Tmp" << Ops[i];
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002105 if (II.hasCtrlDep) OS << ", Chain";
2106 if (InFlag) OS << ", InFlag";
Evan Chengb915f312005-12-09 22:45:35 +00002107 OS << ");\n";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002108
2109 unsigned ValNo = 0;
Evan Chengf9fc25d2005-12-19 22:40:04 +00002110 for (unsigned i = 0; i < NumResults; i++) {
2111 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = Result"
2112 << ".getValue(" << ValNo << ");\n";
2113 ValNo++;
2114 }
2115
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002116 if (II.hasCtrlDep) {
2117 OS << " Chain ";
2118 if (NodeHasChain(Pattern, ISE))
Evan Chengf9fc25d2005-12-19 22:40:04 +00002119 OS << "= CodeGenMap[N.getValue(" << ValNo + NumImpResults << ")] ";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002120 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2121 OS << "= CodeGenMap[" << FoldedChains[j].first << ".getValue("
2122 << FoldedChains[j].second << ")] ";
Evan Chengf9fc25d2005-12-19 22:40:04 +00002123 OS << "= Result.getValue(" << ValNo << ");\n";
2124 for (unsigned i = 0; i < NumImpResults; i++) {
2125 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = Result";
2126 OS << ".getValue(" << ValNo+1 << ");\n";
2127 ValNo++;
2128 }
2129 } else {
2130 for (unsigned i = 0; i < NumImpResults; i++) {
2131 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = Result";
2132 OS << ".getValue(" << ValNo << ");\n";
2133 ValNo++;
2134 }
Evan Chengb915f312005-12-09 22:45:35 +00002135 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002136
Evan Chenge0870512005-12-20 00:06:17 +00002137 // FIXME: this only works because (for now) an instruction can either
2138 // produce a single result or a single flag.
2139 if (II.hasCtrlDep && NumImpResults > 0)
2140 OS << " return (N.ResNo) ? Chain : Result.getValue(1);"
2141 << " // Chain comes before flag.\n";
2142 else
2143 OS << " return Result.getValue(N.ResNo);\n";
Evan Chengb915f312005-12-09 22:45:35 +00002144 } else {
2145 // If this instruction is the root, and if there is only one use of it,
2146 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2147 OS << " if (N.Val->hasOneUse()) {\n";
2148 OS << " return CurDAG->SelectNodeTo(N.Val, "
Evan Chengbcecf332005-12-17 01:19:28 +00002149 << II.Namespace << "::" << II.TheDef->getName();
2150 if (N->getType() != MVT::isVoid)
2151 OS << ", MVT::" << getEnumName(N->getType());
2152 for (unsigned i = 0; i < NumImpResults; i++) {
2153 Record *ImpResult = Inst.getImpResult(i);
2154 MVT::ValueType RVT = getRegisterValueType(ImpResult, CGT);
2155 OS << ", MVT::" << getEnumName(RVT);
2156 }
Evan Chengb915f312005-12-09 22:45:35 +00002157 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2158 OS << ", Tmp" << Ops[i];
2159 if (InFlag)
2160 OS << ", InFlag";
2161 OS << ");\n";
2162 OS << " } else {\n";
2163 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002164 << II.Namespace << "::" << II.TheDef->getName();
2165 if (N->getType() != MVT::isVoid)
2166 OS << ", MVT::" << getEnumName(N->getType());
2167 for (unsigned i = 0; i < NumImpResults; i++) {
2168 Record *ImpResult = Inst.getImpResult(i);
2169 MVT::ValueType RVT = getRegisterValueType(ImpResult, CGT);
2170 OS << ", MVT::" << getEnumName(RVT);
2171 }
Evan Chengb915f312005-12-09 22:45:35 +00002172 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2173 OS << ", Tmp" << Ops[i];
2174 if (InFlag)
2175 OS << ", InFlag";
2176 OS << ");\n";
2177 OS << " }\n";
2178 }
2179 return std::make_pair(1, ResNo);
2180 } else if (Op->isSubClassOf("SDNodeXForm")) {
2181 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002182 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002183 unsigned ResNo = TmpNo++;
2184 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
2185 << "(Tmp" << OpVal << ".Val);\n";
2186 if (isRoot) {
2187 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2188 OS << " return Tmp" << ResNo << ";\n";
2189 }
2190 return std::make_pair(1, ResNo);
2191 } else {
2192 N->dump();
2193 assert(0 && "Unknown node in result pattern!");
2194 return std::make_pair(1, ~0U);
2195 }
2196 }
2197
2198 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2199 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2200 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2201 /// for, this returns true otherwise false if Pat has all types.
2202 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2203 const std::string &Prefix) {
2204 // Did we find one?
2205 if (!Pat->hasTypeSet()) {
2206 // Move a type over from 'other' to 'pat'.
2207 Pat->setType(Other->getType());
2208 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2209 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2210 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002211 }
2212
2213 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2214 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2215 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2216 Prefix + utostr(OpNo)))
2217 return true;
2218 return false;
2219 }
2220
2221private:
2222 /// EmitCopyToRegs - Emit the flag operands for the DAG that is
2223 /// being built.
2224 void EmitCopyToRegs(TreePatternNode *N, const std::string &RootName,
2225 bool HasCtrlDep) {
2226 const CodeGenTarget &T = ISE.getTargetInfo();
2227 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2228 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2229 TreePatternNode *Child = N->getChild(i);
2230 if (!Child->isLeaf()) {
2231 EmitCopyToRegs(Child, RootName + utostr(OpNo), HasCtrlDep);
2232 } else {
2233 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2234 Record *RR = DI->getDef();
2235 if (RR->isSubClassOf("Register")) {
2236 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002237 if (RVT == MVT::Flag) {
2238 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
2239 } else if (HasCtrlDep) {
Evan Chengb915f312005-12-09 22:45:35 +00002240 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2241 OS << " " << RootName << "CR" << i
2242 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2243 << ISE.getQualifiedName(RR) << ", MVT::"
2244 << getEnumName(RVT) << ")"
2245 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2246 OS << " Chain = " << RootName << "CR" << i
2247 << ".getValue(0);\n";
2248 OS << " InFlag = " << RootName << "CR" << i
2249 << ".getValue(1);\n";
2250 } else {
2251 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2252 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2253 << ", MVT::" << getEnumName(RVT) << ")"
2254 << ", Select(" << RootName << OpNo
2255 << "), InFlag).getValue(1);\n";
2256 }
2257 }
2258 }
2259 }
2260 }
2261 }
2262};
2263
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002264/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2265/// stream to match the pattern, and generate the code for the match if it
2266/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002267void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2268 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002269 static unsigned PatternCount = 0;
2270 unsigned PatternNo = PatternCount++;
2271 OS << " { // Pattern #" << PatternNo << ": ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002272 Pattern.getSrcPattern()->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002273 OS << "\n // Emits: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002274 Pattern.getDstPattern()->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002275 OS << "\n";
Evan Cheng58e84a62005-12-14 22:02:59 +00002276 OS << " // Pattern complexity = "
2277 << getPatternSize(Pattern.getSrcPattern(), *this)
2278 << " cost = "
2279 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002280
Evan Cheng58e84a62005-12-14 22:02:59 +00002281 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2282 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2283 PatternNo, OS);
Evan Chengb915f312005-12-09 22:45:35 +00002284
Chris Lattner8fc35682005-09-23 23:16:51 +00002285 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng58e84a62005-12-14 22:02:59 +00002286 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002287
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002288 // TP - Get *SOME* tree pattern, we don't care which.
2289 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002290
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002291 // At this point, we know that we structurally match the pattern, but the
2292 // types of the nodes may not match. Figure out the fewest number of type
2293 // comparisons we need to emit. For example, if there is only one integer
2294 // type supported by a target, there should be no type comparisons at all for
2295 // integer patterns!
2296 //
2297 // To figure out the fewest number of type checks needed, clone the pattern,
2298 // remove the types, then perform type inference on the pattern as a whole.
2299 // If there are unresolved types, emit an explicit check for those types,
2300 // apply the type to the tree, then rerun type inference. Iterate until all
2301 // types are resolved.
2302 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002303 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002304 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002305
2306 do {
2307 // Resolve/propagate as many types as possible.
2308 try {
2309 bool MadeChange = true;
2310 while (MadeChange)
2311 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2312 } catch (...) {
2313 assert(0 && "Error: could not find consistent types for something we"
2314 " already decided was ok!");
2315 abort();
2316 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002317
Chris Lattner7e82f132005-10-15 21:34:21 +00002318 // Insert a check for an unresolved type and add it to the tree. If we find
2319 // an unresolved type to add a check for, this returns true and we iterate,
2320 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002321 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002322
Evan Cheng58e84a62005-12-14 22:02:59 +00002323 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002324
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002325 delete Pat;
2326
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002327 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002328}
2329
Chris Lattner37481472005-09-26 21:59:35 +00002330
2331namespace {
2332 /// CompareByRecordName - An ordering predicate that implements less-than by
2333 /// comparing the names records.
2334 struct CompareByRecordName {
2335 bool operator()(const Record *LHS, const Record *RHS) const {
2336 // Sort by name first.
2337 if (LHS->getName() < RHS->getName()) return true;
2338 // If both names are equal, sort by pointer.
2339 return LHS->getName() == RHS->getName() && LHS < RHS;
2340 }
2341 };
2342}
2343
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002344void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002345 std::string InstNS = Target.inst_begin()->second.Namespace;
2346 if (!InstNS.empty()) InstNS += "::";
2347
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002348 // Emit boilerplate.
2349 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002350 << "SDOperand SelectCode(SDOperand N) {\n"
2351 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002352 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2353 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002354 << " return N; // Already selected.\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002355 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng481c8e02005-12-12 23:22:48 +00002356 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002357 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002358 << " default: break;\n"
2359 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00002360 << " case ISD::BasicBlock:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002361 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002362 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002363 << " case ISD::AssertZext: {\n"
2364 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2365 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2366 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002367 << " }\n"
2368 << " case ISD::TokenFactor:\n"
2369 << " if (N.getNumOperands() == 2) {\n"
2370 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2371 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2372 << " return CodeGenMap[N] =\n"
2373 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2374 << " } else {\n"
2375 << " std::vector<SDOperand> Ops;\n"
2376 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2377 << " Ops.push_back(Select(N.getOperand(i)));\n"
2378 << " return CodeGenMap[N] = \n"
2379 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2380 << " }\n"
2381 << " case ISD::CopyFromReg: {\n"
2382 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002383 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2384 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002385 << " if (N.Val->getNumValues() == 2) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002386 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2387 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2388 << " CodeGenMap[N.getValue(0)] = New;\n"
2389 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2390 << " return New.getValue(N.ResNo);\n"
2391 << " } else {\n"
2392 << " SDOperand Flag;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002393 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2394 << " if (Chain == N.getOperand(0) &&\n"
2395 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002396 << " return N; // No change\n"
2397 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2398 << " CodeGenMap[N.getValue(0)] = New;\n"
2399 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2400 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2401 << " return New.getValue(N.ResNo);\n"
2402 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002403 << " }\n"
2404 << " case ISD::CopyToReg: {\n"
2405 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002406 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002407 << " SDOperand Val = Select(N.getOperand(2));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002408 << " SDOperand Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002409 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002410 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002411 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002412 << " return CodeGenMap[N] = Result;\n"
2413 << " } else {\n"
2414 << " SDOperand Flag;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002415 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002416 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002417 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2418 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002419 << " CodeGenMap[N.getValue(0)] = Result;\n"
2420 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2421 << " return Result.getValue(N.ResNo);\n"
2422 << " }\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002423 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002424
Chris Lattner81303322005-09-23 19:36:15 +00002425 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00002426 std::map<Record*, std::vector<PatternToMatch*>,
2427 CompareByRecordName> PatternsByOpcode;
Evan Cheng0fc71982005-12-08 02:00:36 +00002428 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002429 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
Evan Cheng0fc71982005-12-08 02:00:36 +00002430 if (!Node->isLeaf()) {
2431 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
Chris Lattner0614b622005-11-02 06:49:14 +00002432 } else {
Evan Cheng0fc71982005-12-08 02:00:36 +00002433 const ComplexPattern *CP;
Chris Lattner0614b622005-11-02 06:49:14 +00002434 if (IntInit *II =
Evan Cheng0fc71982005-12-08 02:00:36 +00002435 dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner0614b622005-11-02 06:49:14 +00002436 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
Evan Cheng0fc71982005-12-08 02:00:36 +00002437 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
Evan Cheng3aa39f42005-12-08 02:14:08 +00002438 std::vector<Record*> OpNodes = CP->getRootNodes();
Evan Cheng0fc71982005-12-08 02:00:36 +00002439 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2440 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2441 &PatternsToMatch[i]);
2442 }
Chris Lattner0614b622005-11-02 06:49:14 +00002443 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00002444 std::cerr << "Unrecognized opcode '";
Evan Cheng0fc71982005-12-08 02:00:36 +00002445 Node->dump();
Evan Cheng76021f02005-11-29 18:44:58 +00002446 std::cerr << "' on tree pattern '";
Evan Cheng58e84a62005-12-14 22:02:59 +00002447 std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Evan Cheng76021f02005-11-29 18:44:58 +00002448 std::cerr << "'!\n";
2449 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00002450 }
2451 }
Evan Cheng0fc71982005-12-08 02:00:36 +00002452 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002453
Chris Lattner3f7e9142005-09-23 20:52:47 +00002454 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00002455 for (std::map<Record*, std::vector<PatternToMatch*>,
2456 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2457 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002458 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2459 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2460
2461 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002462
2463 // We want to emit all of the matching code now. However, we want to emit
2464 // the matches in order of minimal cost. Sort the patterns so the least
2465 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002466 std::stable_sort(Patterns.begin(), Patterns.end(),
Evan Cheng0fc71982005-12-08 02:00:36 +00002467 PatternSortingPredicate(*this));
Chris Lattner81303322005-09-23 19:36:15 +00002468
Chris Lattner3f7e9142005-09-23 20:52:47 +00002469 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2470 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002471 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00002472 }
2473
2474
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002475 OS << " } // end of big switch.\n\n"
2476 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002477 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002478 << " std::cerr << '\\n';\n"
2479 << " abort();\n"
2480 << "}\n";
2481}
2482
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002483void DAGISelEmitter::run(std::ostream &OS) {
2484 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2485 " target", OS);
2486
Chris Lattner1f39e292005-09-14 00:09:24 +00002487 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2488 << "// *** instruction selector class. These functions are really "
2489 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002490
Chris Lattner296dfe32005-09-24 00:50:51 +00002491 OS << "// Instance var to keep track of multiply used nodes that have \n"
2492 << "// already been selected.\n"
2493 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2494
Chris Lattnerca559d02005-09-08 21:03:01 +00002495 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002496 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00002497 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002498 ParsePatternFragments(OS);
2499 ParseInstructions();
2500 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002501
Chris Lattnere97603f2005-09-28 19:27:25 +00002502 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002503 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002504 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002505
Chris Lattnere46e17b2005-09-29 19:28:10 +00002506
2507 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2508 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002509 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2510 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00002511 std::cerr << "\n";
2512 });
2513
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002514 // At this point, we have full information about the 'Patterns' we need to
2515 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002516 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002517 EmitInstructionSelector(OS);
2518
2519 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2520 E = PatternFragments.end(); I != E; ++I)
2521 delete I->second;
2522 PatternFragments.clear();
2523
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002524 Instructions.clear();
2525}