blob: 85ebfdece9a7555b334e00ef203a8fd3e41b5e37 [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 Cheng7b05bd52005-12-23 22:11:47 +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 Cheng7b05bd52005-12-23 22:11:47 +0000963 else if (DI && DI->getDef()->isSubClassOf("Register"))
964 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +0000965 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000966 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000967 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000968
969 Record *Rec;
970 if (Pat->isLeaf()) {
971 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
972 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
973 Rec = DI->getDef();
974 } else {
975 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
976 Rec = Pat->getOperator();
977 }
978
Evan Cheng01f318b2005-12-14 02:21:57 +0000979 // SRCVALUE nodes are ignored.
980 if (Rec->getName() == "srcvalue")
981 return false;
982
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000983 TreePatternNode *&Slot = InstInputs[Pat->getName()];
984 if (!Slot) {
985 Slot = Pat;
986 } else {
987 Record *SlotRec;
988 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000989 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000990 } else {
991 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
992 SlotRec = Slot->getOperator();
993 }
994
995 // Ensure that the inputs agree if we've already seen this input.
996 if (Rec != SlotRec)
997 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000998 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000999 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1000 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001001 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001002}
1003
1004/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1005/// part of "I", the instruction), computing the set of inputs and outputs of
1006/// the pattern. Report errors if we see anything naughty.
1007void DAGISelEmitter::
1008FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1009 std::map<std::string, TreePatternNode*> &InstInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001010 std::map<std::string, Record*> &InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001011 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001012 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001013 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001014 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001015 if (!isUse && Pat->getTransformFn())
1016 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001017 return;
1018 } else if (Pat->getOperator()->getName() != "set") {
1019 // If this is not a set, verify that the children nodes are not void typed,
1020 // and recurse.
1021 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001022 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001023 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001024 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001025 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001026 }
1027
1028 // If this is a non-leaf node with no children, treat it basically as if
1029 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001030 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001031 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001032 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001033
Chris Lattnerf1311842005-09-14 23:05:13 +00001034 if (!isUse && Pat->getTransformFn())
1035 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001036 return;
1037 }
1038
1039 // Otherwise, this is a set, validate and collect instruction results.
1040 if (Pat->getNumChildren() == 0)
1041 I->error("set requires operands!");
1042 else if (Pat->getNumChildren() & 1)
1043 I->error("set requires an even number of operands");
1044
Chris Lattnerf1311842005-09-14 23:05:13 +00001045 if (Pat->getTransformFn())
1046 I->error("Cannot specify a transform function on a set node!");
1047
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001048 // Check the set destinations.
1049 unsigned NumValues = Pat->getNumChildren()/2;
1050 for (unsigned i = 0; i != NumValues; ++i) {
1051 TreePatternNode *Dest = Pat->getChild(i);
1052 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001053 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001054
1055 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1056 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001057 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001058
Evan Chengbcecf332005-12-17 01:19:28 +00001059 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1060 if (Dest->getName().empty())
1061 I->error("set destination must have a name!");
1062 if (InstResults.count(Dest->getName()))
1063 I->error("cannot set '" + Dest->getName() +"' multiple times");
1064 InstResults[Dest->getName()] = Val->getDef();
Evan Cheng7b05bd52005-12-23 22:11:47 +00001065 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001066 InstImpResults.push_back(Val->getDef());
1067 } else {
1068 I->error("set destination should be a register!");
1069 }
1070
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001071 // Verify and collect info from the computation.
1072 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001073 InstInputs, InstResults,
1074 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001075 }
1076}
1077
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001078/// ParseInstructions - Parse all of the instructions, inlining and resolving
1079/// any fragments involved. This populates the Instructions list with fully
1080/// resolved instructions.
1081void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001082 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1083
1084 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001085 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001086
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001087 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1088 LI = Instrs[i]->getValueAsListInit("Pattern");
1089
1090 // If there is no pattern, only collect minimal information about the
1091 // instruction for its operand list. We have to assume that there is one
1092 // result, as we have no detailed info.
1093 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001094 std::vector<Record*> Results;
1095 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001096
1097 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001098
Evan Cheng3a217f32005-12-22 02:35:21 +00001099 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001100 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001101 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001102 // These produce no results
1103 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1104 Operands.push_back(InstInfo.OperandList[j].Rec);
1105 } else {
1106 // Assume the first operand is the result.
1107 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001108
Evan Cheng3a217f32005-12-22 02:35:21 +00001109 // The rest are inputs.
1110 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1111 Operands.push_back(InstInfo.OperandList[j].Rec);
1112 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001113 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001114
1115 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001116 std::vector<Record*> ImpResults;
1117 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001118 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001119 DAGInstruction(0, Results, Operands, ImpResults,
1120 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001121 continue; // no pattern.
1122 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001123
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001124 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001125 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001126 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001127 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001128
Chris Lattner95f6b762005-09-08 23:26:30 +00001129 // Infer as many types as possible. If we cannot infer all of them, we can
1130 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001131 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001132 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001133
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001134 // InstInputs - Keep track of all of the inputs of the instruction, along
1135 // with the record they are declared as.
1136 std::map<std::string, TreePatternNode*> InstInputs;
1137
1138 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001139 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001140 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001141
1142 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001143 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001144
Chris Lattner1f39e292005-09-14 00:09:24 +00001145 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001146 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001147 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1148 TreePatternNode *Pat = I->getTree(j);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001149 if (Pat->getExtType() != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001150 I->error("Top-level forms in instruction pattern should have"
1151 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001152
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001153 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001154 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001155 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001156 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001157
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001158 // Now that we have inputs and outputs of the pattern, inspect the operands
1159 // list for the instruction. This determines the order that operands are
1160 // added to the machine instruction the node corresponds to.
1161 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001162
1163 // Parse the operands list from the (ops) list, validating it.
1164 std::vector<std::string> &Args = I->getArgList();
1165 assert(Args.empty() && "Args list should still be empty here!");
1166 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1167
1168 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001169 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001170 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001171 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001172 I->error("'" + InstResults.begin()->first +
1173 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001174 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001175
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001176 // Check that it exists in InstResults.
1177 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001178 if (R == 0)
1179 I->error("Operand $" + OpName + " should be a set destination: all "
1180 "outputs must occur before inputs in operand list!");
1181
1182 if (CGI.OperandList[i].Rec != R)
1183 I->error("Operand $" + OpName + " class mismatch!");
1184
Chris Lattnerae6d8282005-09-15 21:51:12 +00001185 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001186 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001187
Chris Lattner39e8af92005-09-14 18:19:25 +00001188 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001189 InstResults.erase(OpName);
1190 }
1191
Chris Lattner0b592252005-09-14 21:59:34 +00001192 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1193 // the copy while we're checking the inputs.
1194 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001195
1196 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001197 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001198 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1199 const std::string &OpName = CGI.OperandList[i].Name;
1200 if (OpName.empty())
1201 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1202
Chris Lattner0b592252005-09-14 21:59:34 +00001203 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001204 I->error("Operand $" + OpName +
1205 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001206 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001207 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001208
1209 if (InVal->isLeaf() &&
1210 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1211 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001212 if (CGI.OperandList[i].Rec != InRec &&
1213 !InRec->isSubClassOf("ComplexPattern"))
Nate Begemanddb39542005-12-01 00:06:14 +00001214 I->error("Operand $" + OpName +
Evan Cheng0fc71982005-12-08 02:00:36 +00001215 "'s register class disagrees between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001216 }
1217 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001218
Chris Lattner2175c182005-09-14 23:01:59 +00001219 // Construct the result for the dest-pattern operand list.
1220 TreePatternNode *OpNode = InVal->clone();
1221
1222 // No predicate is useful on the result.
1223 OpNode->setPredicateFn("");
1224
1225 // Promote the xform function to be an explicit node if set.
1226 if (Record *Xform = OpNode->getTransformFn()) {
1227 OpNode->setTransformFn(0);
1228 std::vector<TreePatternNode*> Children;
1229 Children.push_back(OpNode);
1230 OpNode = new TreePatternNode(Xform, Children);
1231 }
1232
1233 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001234 }
1235
Chris Lattner0b592252005-09-14 21:59:34 +00001236 if (!InstInputsCheck.empty())
1237 I->error("Input operand $" + InstInputsCheck.begin()->first +
1238 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001239
1240 TreePatternNode *ResultPattern =
1241 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001242
1243 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001244 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001245 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1246
1247 // Use a temporary tree pattern to infer all types and make sure that the
1248 // constructed result is correct. This depends on the instruction already
1249 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001250 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001251 Temp.InferAllTypes();
1252
1253 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1254 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001255
Chris Lattner32707602005-09-08 23:22:48 +00001256 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001257 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001258
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001259 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001260 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1261 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001262 DAGInstruction &TheInst = II->second;
1263 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001264 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001265
Chris Lattner1f39e292005-09-14 00:09:24 +00001266 if (I->getNumTrees() != 1) {
1267 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1268 continue;
1269 }
1270 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001271 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001272 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001273 if (Pattern->getNumChildren() != 2)
1274 continue; // Not a set of a single value (not handled so far)
1275
1276 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001277 } else{
1278 // Not a set (store or something?)
1279 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001280 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001281
1282 std::string Reason;
1283 if (!SrcPattern->canPatternMatch(Reason, *this))
1284 I->error("Instruction can never match: " + Reason);
1285
Evan Cheng58e84a62005-12-14 22:02:59 +00001286 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001287 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001288 PatternsToMatch.
1289 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1290 SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001291 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001292}
1293
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001294void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001295 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001296
Chris Lattnerabbb6052005-09-15 21:42:00 +00001297 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001298 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001299 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001300
Chris Lattnerabbb6052005-09-15 21:42:00 +00001301 // Inline pattern fragments into it.
1302 Pattern->InlinePatternFragments();
1303
1304 // Infer as many types as possible. If we cannot infer all of them, we can
1305 // never do anything with this pattern: report it to the user.
1306 if (!Pattern->InferAllTypes())
1307 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001308
1309 // Validate that the input pattern is correct.
1310 {
1311 std::map<std::string, TreePatternNode*> InstInputs;
1312 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001313 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001314 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001315 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001316 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001317 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001318 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001319
1320 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1321 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001322
1323 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001324 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001325
1326 // Inline pattern fragments into it.
1327 Result->InlinePatternFragments();
1328
1329 // Infer as many types as possible. If we cannot infer all of them, we can
1330 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001331 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001332 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001333
1334 if (Result->getNumTrees() != 1)
1335 Result->error("Cannot handle instructions producing instructions "
1336 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001337
1338 std::string Reason;
1339 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1340 Pattern->error("Pattern can never match: " + Reason);
1341
Evan Cheng58e84a62005-12-14 22:02:59 +00001342 PatternsToMatch.
1343 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1344 Pattern->getOnlyTree(),
1345 Result->getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001346 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001347}
1348
Chris Lattnere46e17b2005-09-29 19:28:10 +00001349/// CombineChildVariants - Given a bunch of permutations of each child of the
1350/// 'operator' node, put them together in all possible ways.
1351static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001352 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001353 std::vector<TreePatternNode*> &OutVariants,
1354 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001355 // Make sure that each operand has at least one variant to choose from.
1356 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1357 if (ChildVariants[i].empty())
1358 return;
1359
Chris Lattnere46e17b2005-09-29 19:28:10 +00001360 // The end result is an all-pairs construction of the resultant pattern.
1361 std::vector<unsigned> Idxs;
1362 Idxs.resize(ChildVariants.size());
1363 bool NotDone = true;
1364 while (NotDone) {
1365 // Create the variant and add it to the output list.
1366 std::vector<TreePatternNode*> NewChildren;
1367 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1368 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1369 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1370
1371 // Copy over properties.
1372 R->setName(Orig->getName());
1373 R->setPredicateFn(Orig->getPredicateFn());
1374 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001375 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001376
1377 // If this pattern cannot every match, do not include it as a variant.
1378 std::string ErrString;
1379 if (!R->canPatternMatch(ErrString, ISE)) {
1380 delete R;
1381 } else {
1382 bool AlreadyExists = false;
1383
1384 // Scan to see if this pattern has already been emitted. We can get
1385 // duplication due to things like commuting:
1386 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1387 // which are the same pattern. Ignore the dups.
1388 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1389 if (R->isIsomorphicTo(OutVariants[i])) {
1390 AlreadyExists = true;
1391 break;
1392 }
1393
1394 if (AlreadyExists)
1395 delete R;
1396 else
1397 OutVariants.push_back(R);
1398 }
1399
1400 // Increment indices to the next permutation.
1401 NotDone = false;
1402 // Look for something we can increment without causing a wrap-around.
1403 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1404 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1405 NotDone = true; // Found something to increment.
1406 break;
1407 }
1408 Idxs[IdxsIdx] = 0;
1409 }
1410 }
1411}
1412
Chris Lattneraf302912005-09-29 22:36:54 +00001413/// CombineChildVariants - A helper function for binary operators.
1414///
1415static void CombineChildVariants(TreePatternNode *Orig,
1416 const std::vector<TreePatternNode*> &LHS,
1417 const std::vector<TreePatternNode*> &RHS,
1418 std::vector<TreePatternNode*> &OutVariants,
1419 DAGISelEmitter &ISE) {
1420 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1421 ChildVariants.push_back(LHS);
1422 ChildVariants.push_back(RHS);
1423 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1424}
1425
1426
1427static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1428 std::vector<TreePatternNode *> &Children) {
1429 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1430 Record *Operator = N->getOperator();
1431
1432 // Only permit raw nodes.
1433 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1434 N->getTransformFn()) {
1435 Children.push_back(N);
1436 return;
1437 }
1438
1439 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1440 Children.push_back(N->getChild(0));
1441 else
1442 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1443
1444 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1445 Children.push_back(N->getChild(1));
1446 else
1447 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1448}
1449
Chris Lattnere46e17b2005-09-29 19:28:10 +00001450/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1451/// the (potentially recursive) pattern by using algebraic laws.
1452///
1453static void GenerateVariantsOf(TreePatternNode *N,
1454 std::vector<TreePatternNode*> &OutVariants,
1455 DAGISelEmitter &ISE) {
1456 // We cannot permute leaves.
1457 if (N->isLeaf()) {
1458 OutVariants.push_back(N);
1459 return;
1460 }
1461
1462 // Look up interesting info about the node.
1463 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1464
1465 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001466 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1467 // Reassociate by pulling together all of the linked operators
1468 std::vector<TreePatternNode*> MaximalChildren;
1469 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1470
1471 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1472 // permutations.
1473 if (MaximalChildren.size() == 3) {
1474 // Find the variants of all of our maximal children.
1475 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1476 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1477 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1478 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1479
1480 // There are only two ways we can permute the tree:
1481 // (A op B) op C and A op (B op C)
1482 // Within these forms, we can also permute A/B/C.
1483
1484 // Generate legal pair permutations of A/B/C.
1485 std::vector<TreePatternNode*> ABVariants;
1486 std::vector<TreePatternNode*> BAVariants;
1487 std::vector<TreePatternNode*> ACVariants;
1488 std::vector<TreePatternNode*> CAVariants;
1489 std::vector<TreePatternNode*> BCVariants;
1490 std::vector<TreePatternNode*> CBVariants;
1491 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1492 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1493 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1494 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1495 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1496 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1497
1498 // Combine those into the result: (x op x) op x
1499 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1500 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1501 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1502 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1503 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1504 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1505
1506 // Combine those into the result: x op (x op x)
1507 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1508 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1509 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1510 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1511 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1512 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1513 return;
1514 }
1515 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001516
1517 // Compute permutations of all children.
1518 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1519 ChildVariants.resize(N->getNumChildren());
1520 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1521 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1522
1523 // Build all permutations based on how the children were formed.
1524 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1525
1526 // If this node is commutative, consider the commuted order.
1527 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1528 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001529 // Consider the commuted order.
1530 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1531 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001532 }
1533}
1534
1535
Chris Lattnere97603f2005-09-28 19:27:25 +00001536// GenerateVariants - Generate variants. For example, commutative patterns can
1537// match multiple ways. Add them to PatternsToMatch as well.
1538void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001539
1540 DEBUG(std::cerr << "Generating instruction variants.\n");
1541
1542 // Loop over all of the patterns we've collected, checking to see if we can
1543 // generate variants of the instruction, through the exploitation of
1544 // identities. This permits the target to provide agressive matching without
1545 // the .td file having to contain tons of variants of instructions.
1546 //
1547 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1548 // intentionally do not reconsider these. Any variants of added patterns have
1549 // already been added.
1550 //
1551 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1552 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001553 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001554
1555 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001556 Variants.erase(Variants.begin()); // Remove the original pattern.
1557
1558 if (Variants.empty()) // No variants for this pattern.
1559 continue;
1560
1561 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001562 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001563 std::cerr << "\n");
1564
1565 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1566 TreePatternNode *Variant = Variants[v];
1567
1568 DEBUG(std::cerr << " VAR#" << v << ": ";
1569 Variant->dump();
1570 std::cerr << "\n");
1571
1572 // Scan to see if an instruction or explicit pattern already matches this.
1573 bool AlreadyExists = false;
1574 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1575 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001576 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001577 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1578 AlreadyExists = true;
1579 break;
1580 }
1581 }
1582 // If we already have it, ignore the variant.
1583 if (AlreadyExists) continue;
1584
1585 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001586 PatternsToMatch.
1587 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1588 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001589 }
1590
1591 DEBUG(std::cerr << "\n");
1592 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001593}
1594
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001595
Evan Cheng0fc71982005-12-08 02:00:36 +00001596// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1597// ComplexPattern.
1598static bool NodeIsComplexPattern(TreePatternNode *N)
1599{
1600 return (N->isLeaf() &&
1601 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1602 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1603 isSubClassOf("ComplexPattern"));
1604}
1605
1606// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1607// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1608static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1609 DAGISelEmitter &ISE)
1610{
1611 if (N->isLeaf() &&
1612 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1613 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1614 isSubClassOf("ComplexPattern")) {
1615 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1616 ->getDef());
1617 }
1618 return NULL;
1619}
1620
Chris Lattner05814af2005-09-28 17:57:56 +00001621/// getPatternSize - Return the 'size' of this pattern. We want to match large
1622/// patterns before small ones. This is used to determine the size of a
1623/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001624static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001625 assert(isExtIntegerVT(P->getExtType()) ||
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001626 isExtFloatingPointVT(P->getExtType()) ||
Evan Chengbcecf332005-12-17 01:19:28 +00001627 P->getExtType() == MVT::isVoid ||
1628 P->getExtType() == MVT::Flag && "Not a valid pattern node to size!");
Chris Lattner05814af2005-09-28 17:57:56 +00001629 unsigned Size = 1; // The node itself.
Evan Cheng0fc71982005-12-08 02:00:36 +00001630
1631 // FIXME: This is a hack to statically increase the priority of patterns
1632 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1633 // Later we can allow complexity / cost for each pattern to be (optionally)
1634 // specified. To get best possible pattern match we'll need to dynamically
1635 // calculate the complexity of all patterns a dag can potentially map to.
1636 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1637 if (AM)
1638 Size += AM->getNumOperands();
1639
Chris Lattner05814af2005-09-28 17:57:56 +00001640 // Count children in the count if they are also nodes.
1641 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1642 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001643 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001644 Size += getPatternSize(Child, ISE);
1645 else if (Child->isLeaf()) {
1646 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1647 ++Size; // Matches a ConstantSDNode.
1648 else if (NodeIsComplexPattern(Child))
1649 Size += getPatternSize(Child, ISE);
Chris Lattner2f041d42005-10-19 04:41:05 +00001650 }
Chris Lattner05814af2005-09-28 17:57:56 +00001651 }
1652
1653 return Size;
1654}
1655
1656/// getResultPatternCost - Compute the number of instructions for this pattern.
1657/// This is a temporary hack. We should really include the instruction
1658/// latencies in this calculation.
1659static unsigned getResultPatternCost(TreePatternNode *P) {
1660 if (P->isLeaf()) return 0;
1661
1662 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1663 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1664 Cost += getResultPatternCost(P->getChild(i));
1665 return Cost;
1666}
1667
1668// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1669// In particular, we want to match maximal patterns first and lowest cost within
1670// a particular complexity first.
1671struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001672 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1673 DAGISelEmitter &ISE;
1674
Evan Cheng58e84a62005-12-14 22:02:59 +00001675 bool operator()(PatternToMatch *LHS,
1676 PatternToMatch *RHS) {
1677 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1678 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001679 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1680 if (LHSSize < RHSSize) return false;
1681
1682 // If the patterns have equal complexity, compare generated instruction cost
Evan Cheng58e84a62005-12-14 22:02:59 +00001683 return getResultPatternCost(LHS->getDstPattern()) <
1684 getResultPatternCost(RHS->getDstPattern());
Chris Lattner05814af2005-09-28 17:57:56 +00001685 }
1686};
1687
Nate Begeman6510b222005-12-01 04:51:06 +00001688/// getRegisterValueType - Look up and return the first ValueType of specified
1689/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001690static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001691 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1692 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001693 return MVT::Other;
1694}
1695
Chris Lattner72fe91c2005-09-24 00:40:24 +00001696
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001697/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1698/// type information from it.
1699static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001700 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001701 if (!N->isLeaf())
1702 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1703 RemoveAllTypes(N->getChild(i));
1704}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001705
Chris Lattner0614b622005-11-02 06:49:14 +00001706Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1707 Record *N = Records.getDef(Name);
1708 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1709 return N;
1710}
1711
Evan Cheng7b05bd52005-12-23 22:11:47 +00001712/// NodeHasChain - return true if TreePatternNode has the property
1713/// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1714/// a chain result.
1715static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1716{
1717 if (N->isLeaf()) return false;
1718 Record *Operator = N->getOperator();
1719 if (!Operator->isSubClassOf("SDNode")) return false;
1720
1721 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1722 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1723}
1724
1725static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1726{
1727 if (NodeHasChain(N, ISE))
1728 return true;
1729 else {
1730 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1731 TreePatternNode *Child = N->getChild(i);
1732 if (PatternHasCtrlDep(Child, ISE))
1733 return true;
1734 }
1735 }
1736
1737 return false;
1738}
1739
Evan Chengb915f312005-12-09 22:45:35 +00001740class PatternCodeEmitter {
1741private:
1742 DAGISelEmitter &ISE;
1743
Evan Cheng58e84a62005-12-14 22:02:59 +00001744 // Predicates.
1745 ListInit *Predicates;
1746 // Instruction selector pattern.
1747 TreePatternNode *Pattern;
1748 // Matched instruction.
1749 TreePatternNode *Instruction;
Evan Chengb915f312005-12-09 22:45:35 +00001750 unsigned PatternNo;
1751 std::ostream &OS;
1752 // Node to name mapping
1753 std::map<std::string,std::string> VariableMap;
Evan Chengb915f312005-12-09 22:45:35 +00001754 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001755 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb915f312005-12-09 22:45:35 +00001756 unsigned TmpNo;
1757
1758public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001759 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1760 TreePatternNode *pattern, TreePatternNode *instr,
Evan Chengb915f312005-12-09 22:45:35 +00001761 unsigned PatNum, std::ostream &os) :
Evan Cheng58e84a62005-12-14 22:02:59 +00001762 ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001763 PatternNo(PatNum), OS(os), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001764
Chris Lattner4e6a1d22005-12-21 05:31:05 +00001765 /// isPredeclaredSDOperand - Return true if this is one of the predeclared
1766 /// SDOperands.
1767 bool isPredeclaredSDOperand(const std::string &OpName) const {
1768 return OpName == "N0" || OpName == "N1" || OpName == "N2" ||
1769 OpName == "N00" || OpName == "N01" ||
1770 OpName == "N10" || OpName == "N11" ||
1771 OpName == "Tmp0" || OpName == "Tmp1" ||
1772 OpName == "Tmp2" || OpName == "Tmp3";
1773 }
1774
Chris Lattner2f0f9a62005-12-20 19:41:03 +00001775 /// DeclareSDOperand - Emit "SDOperand <opname>" or "<opname>". This works
1776 /// around an ugly GCC bug where SelectCode is using too much stack space
1777 void DeclareSDOperand(const std::string &OpName) const {
1778 // If it's one of the common cases declared at the top of SelectCode, just
1779 // use the existing declaration.
Chris Lattner4e6a1d22005-12-21 05:31:05 +00001780 if (isPredeclaredSDOperand(OpName))
Chris Lattner2f0f9a62005-12-20 19:41:03 +00001781 OS << OpName;
1782 else
1783 OS << "SDOperand " << OpName;
1784 }
1785
Evan Chengb915f312005-12-09 22:45:35 +00001786 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1787 /// if the match fails. At this point, we already know that the opcode for N
1788 /// matches, and the SDNode for the result has the RootName specified name.
1789 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001790 bool &FoundChain, bool isRoot = false) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001791
1792 // Emit instruction predicates. Each predicate is just a string for now.
1793 if (isRoot) {
1794 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1795 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1796 Record *Def = Pred->getDef();
1797 if (Def->isSubClassOf("Predicate")) {
1798 if (i == 0)
1799 OS << " if (";
1800 else
1801 OS << " && ";
Evan Cheng5fb5e102005-12-20 20:08:01 +00001802 OS << "!(" << Def->getValueAsString("CondString") << ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001803 if (i == e-1)
1804 OS << ") goto P" << PatternNo << "Fail;\n";
1805 } else {
1806 Def->dump();
1807 assert(0 && "Unknown predicate type!");
1808 }
1809 }
1810 }
1811 }
1812
Evan Chengb915f312005-12-09 22:45:35 +00001813 if (N->isLeaf()) {
1814 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1815 OS << " if (cast<ConstantSDNode>(" << RootName
1816 << ")->getSignExtended() != " << II->getValue() << ")\n"
1817 << " goto P" << PatternNo << "Fail;\n";
1818 return;
1819 } else if (!NodeIsComplexPattern(N)) {
1820 assert(0 && "Cannot match this as a leaf value!");
1821 abort();
1822 }
1823 }
1824
1825 // If this node has a name associated with it, capture it in VariableMap. If
1826 // we already saw this in the pattern, emit code to verify dagness.
1827 if (!N->getName().empty()) {
1828 std::string &VarMapEntry = VariableMap[N->getName()];
1829 if (VarMapEntry.empty()) {
1830 VarMapEntry = RootName;
1831 } else {
1832 // If we get here, this is a second reference to a specific name. Since
1833 // we already have checked that the first reference is valid, we don't
1834 // have to recursively match it, just check that it's the same as the
1835 // previously named thing.
1836 OS << " if (" << VarMapEntry << " != " << RootName
1837 << ") goto P" << PatternNo << "Fail;\n";
1838 return;
1839 }
1840 }
1841
1842
1843 // Emit code to load the child nodes and match their contents recursively.
1844 unsigned OpNo = 0;
Evan Cheng86217892005-12-12 19:37:43 +00001845 bool HasChain = NodeHasChain(N, ISE);
1846 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00001847 OpNo = 1;
1848 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001849 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Chengb915f312005-12-09 22:45:35 +00001850 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1851 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1852 OS << " if (CodeGenMap.count(" << RootName
Evan Cheng1129e872005-12-10 00:09:17 +00001853 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
Evan Chengb915f312005-12-09 22:45:35 +00001854 << PatternNo << "Fail; // Already selected for a chain use?\n";
1855 }
Evan Chengb915f312005-12-09 22:45:35 +00001856 }
1857
1858 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00001859 OS << " ";
1860 DeclareSDOperand(RootName+utostr(OpNo));
1861 OS << " = " << RootName << ".getOperand(" << OpNo << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00001862 TreePatternNode *Child = N->getChild(i);
1863
1864 if (!Child->isLeaf()) {
1865 // If it's not a leaf, recursively match.
1866 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1867 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1868 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00001869 EmitMatchCode(Child, RootName + utostr(OpNo), FoundChain);
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001870 if (NodeHasChain(Child, ISE)) {
1871 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1872 CInfo.getNumResults()));
1873 }
Evan Chengb915f312005-12-09 22:45:35 +00001874 } else {
1875 // If this child has a name associated with it, capture it in VarMap. If
1876 // we already saw this in the pattern, emit code to verify dagness.
1877 if (!Child->getName().empty()) {
1878 std::string &VarMapEntry = VariableMap[Child->getName()];
1879 if (VarMapEntry.empty()) {
1880 VarMapEntry = RootName + utostr(OpNo);
1881 } else {
1882 // If we get here, this is a second reference to a specific name. Since
1883 // we already have checked that the first reference is valid, we don't
1884 // have to recursively match it, just check that it's the same as the
1885 // previously named thing.
1886 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1887 << ") goto P" << PatternNo << "Fail;\n";
1888 continue;
1889 }
1890 }
1891
1892 // Handle leaves of various types.
1893 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1894 Record *LeafRec = DI->getDef();
1895 if (LeafRec->isSubClassOf("RegisterClass")) {
1896 // Handle register references. Nothing to do here.
1897 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00001898 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00001899 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1900 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00001901 } else if (LeafRec->getName() == "srcvalue") {
1902 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00001903 } else if (LeafRec->isSubClassOf("ValueType")) {
1904 // Make sure this is the specified value type.
1905 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1906 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1907 << "Fail;\n";
1908 } else if (LeafRec->isSubClassOf("CondCode")) {
1909 // Make sure this is the specified cond code.
1910 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1911 << ")->get() != " << "ISD::" << LeafRec->getName()
1912 << ") goto P" << PatternNo << "Fail;\n";
1913 } else {
1914 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00001915 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00001916 assert(0 && "Unknown leaf type!");
1917 }
1918 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1919 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1920 << " cast<ConstantSDNode>(" << RootName << OpNo
1921 << ")->getSignExtended() != " << II->getValue() << ")\n"
1922 << " goto P" << PatternNo << "Fail;\n";
1923 } else {
1924 Child->dump();
1925 assert(0 && "Unknown leaf type!");
1926 }
1927 }
1928 }
1929
Evan Cheng86217892005-12-12 19:37:43 +00001930 if (HasChain) {
1931 if (!FoundChain) {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00001932 OS << " Chain = " << RootName << ".getOperand(0);\n";
Evan Cheng86217892005-12-12 19:37:43 +00001933 FoundChain = true;
1934 }
1935 }
1936
Evan Chengb915f312005-12-09 22:45:35 +00001937 // If there is a node predicate for this, emit the call.
1938 if (!N->getPredicateFn().empty())
1939 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1940 << ".Val)) goto P" << PatternNo << "Fail;\n";
1941 }
1942
1943 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1944 /// we actually have to build a DAG!
1945 std::pair<unsigned, unsigned>
1946 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1947 // This is something selected from the pattern we matched.
1948 if (!N->getName().empty()) {
1949 assert(!isRoot && "Root of pattern cannot be a leaf!");
1950 std::string &Val = VariableMap[N->getName()];
1951 assert(!Val.empty() &&
1952 "Variable referenced but not defined and not caught earlier!");
1953 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1954 // Already selected this operand, just return the tmpval.
1955 return std::make_pair(1, atoi(Val.c_str()+3));
1956 }
1957
1958 const ComplexPattern *CP;
1959 unsigned ResNo = TmpNo++;
1960 unsigned NumRes = 1;
1961 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1962 switch (N->getType()) {
1963 default: assert(0 && "Unknown type for constant node!");
1964 case MVT::i1: OS << " bool Tmp"; break;
1965 case MVT::i8: OS << " unsigned char Tmp"; break;
1966 case MVT::i16: OS << " unsigned short Tmp"; break;
1967 case MVT::i32: OS << " unsigned Tmp"; break;
1968 case MVT::i64: OS << " uint64_t Tmp"; break;
1969 }
1970 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
Chris Lattner2f0f9a62005-12-20 19:41:03 +00001971 OS << " ";
1972 DeclareSDOperand("Tmp"+utostr(ResNo));
1973 OS << " = CurDAG->getTargetConstant(Tmp"
Evan Chengb915f312005-12-09 22:45:35 +00001974 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1975 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00001976 OS << " ";
1977 DeclareSDOperand("Tmp"+utostr(ResNo));
1978 OS << " = " << Val << ";\n";
Nate Begeman28a6b022005-12-10 02:36:00 +00001979 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00001980 OS << " ";
1981 DeclareSDOperand("Tmp"+utostr(ResNo));
1982 OS << " = " << Val << ";\n";
Andrew Lenharth330851a2005-12-24 23:36:59 +00001983 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym") {
1984 OS << " ";
1985 DeclareSDOperand("Tmp"+utostr(ResNo));
1986 OS << " = " << Val << ";\n";
Evan Chengb915f312005-12-09 22:45:35 +00001987 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
1988 std::string Fn = CP->getSelectFunc();
1989 NumRes = CP->getNumOperands();
Chris Lattner2f0f9a62005-12-20 19:41:03 +00001990 for (unsigned i = 0; i != NumRes; ++i) {
Chris Lattner4e6a1d22005-12-21 05:31:05 +00001991 if (!isPredeclaredSDOperand("Tmp" + utostr(i+ResNo))) {
1992 OS << " ";
1993 DeclareSDOperand("Tmp" + utostr(i+ResNo));
1994 OS << ";\n";
1995 }
Evan Chengb915f312005-12-09 22:45:35 +00001996 }
Evan Chengb915f312005-12-09 22:45:35 +00001997 OS << " if (!" << Fn << "(" << Val;
1998 for (unsigned i = 0; i < NumRes; i++)
Evan Chengbcecf332005-12-17 01:19:28 +00001999 OS << ", Tmp" << i + ResNo;
Evan Chengb915f312005-12-09 22:45:35 +00002000 OS << ")) goto P" << PatternNo << "Fail;\n";
2001 TmpNo = ResNo + NumRes;
2002 } else {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002003 OS << " ";
2004 DeclareSDOperand("Tmp"+utostr(ResNo));
2005 OS << " = Select(" << Val << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00002006 }
2007 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2008 // value if used multiple times by this pattern result.
2009 Val = "Tmp"+utostr(ResNo);
2010 return std::make_pair(NumRes, ResNo);
2011 }
2012
2013 if (N->isLeaf()) {
2014 // If this is an explicit register reference, handle it.
2015 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2016 unsigned ResNo = TmpNo++;
2017 if (DI->getDef()->isSubClassOf("Register")) {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002018 OS << " ";
2019 DeclareSDOperand("Tmp"+utostr(ResNo));
2020 OS << " = CurDAG->getRegister("
Evan Chengb915f312005-12-09 22:45:35 +00002021 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
2022 << getEnumName(N->getType())
2023 << ");\n";
2024 return std::make_pair(1, ResNo);
2025 }
2026 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2027 unsigned ResNo = TmpNo++;
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002028 OS << " ";
2029 DeclareSDOperand("Tmp"+utostr(ResNo));
2030 OS << " = CurDAG->getTargetConstant("
Evan Chengb915f312005-12-09 22:45:35 +00002031 << II->getValue() << ", MVT::"
2032 << getEnumName(N->getType())
2033 << ");\n";
2034 return std::make_pair(1, ResNo);
2035 }
2036
2037 N->dump();
2038 assert(0 && "Unknown leaf type!");
2039 return std::make_pair(1, ~0U);
2040 }
2041
2042 Record *Op = N->getOperator();
2043 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002044 const CodeGenTarget &CGT = ISE.getTargetInfo();
2045 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002046 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002047 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2048 bool HasImpResults = Inst.getNumImpResults() > 0;
2049 bool HasInFlag = II.hasInFlag || HasImpInputs;
2050 bool HasOutFlag = II.hasOutFlag || HasImpResults;
2051 bool HasChain = II.hasCtrlDep;
Evan Cheng4fba2812005-12-20 07:37:41 +00002052
Evan Cheng7b05bd52005-12-23 22:11:47 +00002053 if (isRoot && PatternHasCtrlDep(Pattern, ISE))
2054 HasChain = true;
2055 if (HasInFlag || HasOutFlag)
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002056 OS << " InFlag = SDOperand(0, 0);\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002057
Evan Chengb915f312005-12-09 22:45:35 +00002058 // Determine operand emission order. Complex pattern first.
2059 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2060 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2061 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2062 TreePatternNode *Child = N->getChild(i);
2063 if (i == 0) {
2064 EmitOrder.push_back(std::make_pair(i, Child));
2065 OI = EmitOrder.begin();
2066 } else if (NodeIsComplexPattern(Child)) {
2067 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2068 } else {
2069 EmitOrder.push_back(std::make_pair(i, Child));
2070 }
2071 }
2072
2073 // Emit all of the operands.
2074 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2075 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2076 unsigned OpOrder = EmitOrder[i].first;
2077 TreePatternNode *Child = EmitOrder[i].second;
2078 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2079 NumTemps[OpOrder] = NumTemp;
2080 }
2081
2082 // List all the operands in the right order.
2083 std::vector<unsigned> Ops;
2084 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2085 for (unsigned j = 0; j < NumTemps[i].first; j++)
2086 Ops.push_back(NumTemps[i].second + j);
2087 }
2088
Evan Chengb915f312005-12-09 22:45:35 +00002089 // Emit all the chain and CopyToReg stuff.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002090 if (HasChain)
Evan Cheng86217892005-12-12 19:37:43 +00002091 OS << " Chain = Select(Chain);\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002092 if (HasInFlag)
2093 EmitInFlags(Pattern, "N", HasChain, II.hasInFlag, true);
Evan Chengb915f312005-12-09 22:45:35 +00002094
Evan Chengb915f312005-12-09 22:45:35 +00002095 unsigned NumResults = Inst.getNumResults();
2096 unsigned ResNo = TmpNo++;
2097 if (!isRoot) {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002098 OS << " ";
2099 DeclareSDOperand("Tmp"+utostr(ResNo));
2100 OS << " = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002101 << II.Namespace << "::" << II.TheDef->getName();
2102 if (N->getType() != MVT::isVoid)
2103 OS << ", MVT::" << getEnumName(N->getType());
Evan Cheng7b05bd52005-12-23 22:11:47 +00002104 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002105 OS << ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002106
Evan Chengb915f312005-12-09 22:45:35 +00002107 unsigned LastOp = 0;
2108 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2109 LastOp = Ops[i];
2110 OS << ", Tmp" << LastOp;
2111 }
2112 OS << ");\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002113 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002114 // Must have at least one result
2115 OS << " Chain = Tmp" << LastOp << ".getValue("
2116 << NumResults << ");\n";
2117 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002118 } else if (HasChain || HasOutFlag) {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002119 OS << " Result = CurDAG->getTargetNode("
Evan Chengb915f312005-12-09 22:45:35 +00002120 << II.Namespace << "::" << II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002121
2122 // Output order: results, chain, flags
2123 // Result types.
Evan Chengbcecf332005-12-17 01:19:28 +00002124 if (NumResults > 0) {
2125 // TODO: multiple results?
2126 if (N->getType() != MVT::isVoid)
2127 OS << ", MVT::" << getEnumName(N->getType());
2128 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002129 if (HasChain)
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002130 OS << ", MVT::Other";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002131 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002132 OS << ", MVT::Flag";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002133
2134 // Inputs.
Evan Chengb915f312005-12-09 22:45:35 +00002135 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2136 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002137 if (HasChain) OS << ", Chain";
2138 if (HasInFlag) OS << ", InFlag";
Evan Chengb915f312005-12-09 22:45:35 +00002139 OS << ");\n";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002140
2141 unsigned ValNo = 0;
Evan Chengf9fc25d2005-12-19 22:40:04 +00002142 for (unsigned i = 0; i < NumResults; i++) {
2143 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = Result"
2144 << ".getValue(" << ValNo << ");\n";
2145 ValNo++;
2146 }
2147
Evan Cheng7b05bd52005-12-23 22:11:47 +00002148 if (HasChain)
Evan Cheng4fba2812005-12-20 07:37:41 +00002149 OS << " Chain = Result.getValue(" << ValNo << ");\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002150
Evan Cheng7b05bd52005-12-23 22:11:47 +00002151 if (HasOutFlag)
Evan Cheng97938882005-12-22 02:24:50 +00002152 OS << " InFlag = Result.getValue("
Evan Cheng7b05bd52005-12-23 22:11:47 +00002153 << ValNo + (unsigned)HasChain << ");\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002154
Evan Cheng7b05bd52005-12-23 22:11:47 +00002155 if (HasImpResults) {
2156 if (EmitCopyFromRegs(N, HasChain)) {
Evan Cheng97938882005-12-22 02:24:50 +00002157 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = "
2158 << "Result.getValue(" << ValNo << ");\n";
2159 ValNo++;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002160 HasChain = true;
Evan Cheng97938882005-12-22 02:24:50 +00002161 }
2162 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002163
Evan Cheng7b05bd52005-12-23 22:11:47 +00002164 // User does not expect that the instruction produces a chain!
2165 bool AddedChain = HasChain && !NodeHasChain(Pattern, ISE);
Evan Cheng97938882005-12-22 02:24:50 +00002166 if (NodeHasChain(Pattern, ISE))
2167 OS << " CodeGenMap[N.getValue(" << ValNo++ << ")] = Chain;\n";
2168
2169 if (FoldedChains.size() > 0) {
Evan Cheng4fba2812005-12-20 07:37:41 +00002170 OS << " ";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002171 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng4fba2812005-12-20 07:37:41 +00002172 OS << "CodeGenMap[" << FoldedChains[j].first << ".getValue("
2173 << FoldedChains[j].second << ")] = ";
2174 OS << "Chain;\n";
Evan Chengb915f312005-12-09 22:45:35 +00002175 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002176
Evan Cheng7b05bd52005-12-23 22:11:47 +00002177 if (HasOutFlag)
Evan Cheng97938882005-12-22 02:24:50 +00002178 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = InFlag;\n";
2179
Evan Cheng7b05bd52005-12-23 22:11:47 +00002180 if (AddedChain && HasOutFlag) {
Evan Cheng97938882005-12-22 02:24:50 +00002181 if (NumResults == 0) {
2182 OS << " return Result.getValue(N.ResNo+1);\n";
2183 } else {
2184 OS << " if (N.ResNo < " << NumResults << ")\n";
2185 OS << " return Result.getValue(N.ResNo);\n";
2186 OS << " else\n";
2187 OS << " return Result.getValue(N.ResNo+1);\n";
2188 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002189 } else {
Evan Chenge0870512005-12-20 00:06:17 +00002190 OS << " return Result.getValue(N.ResNo);\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002191 }
Evan Chengb915f312005-12-09 22:45:35 +00002192 } else {
2193 // If this instruction is the root, and if there is only one use of it,
2194 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2195 OS << " if (N.Val->hasOneUse()) {\n";
2196 OS << " return CurDAG->SelectNodeTo(N.Val, "
Evan Chengbcecf332005-12-17 01:19:28 +00002197 << II.Namespace << "::" << II.TheDef->getName();
2198 if (N->getType() != MVT::isVoid)
2199 OS << ", MVT::" << getEnumName(N->getType());
Evan Cheng7b05bd52005-12-23 22:11:47 +00002200 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002201 OS << ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002202 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2203 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002204 if (HasInFlag)
Evan Chengb915f312005-12-09 22:45:35 +00002205 OS << ", InFlag";
2206 OS << ");\n";
2207 OS << " } else {\n";
2208 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002209 << II.Namespace << "::" << II.TheDef->getName();
2210 if (N->getType() != MVT::isVoid)
2211 OS << ", MVT::" << getEnumName(N->getType());
Evan Cheng7b05bd52005-12-23 22:11:47 +00002212 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002213 OS << ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002214 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2215 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002216 if (HasInFlag)
Evan Chengb915f312005-12-09 22:45:35 +00002217 OS << ", InFlag";
2218 OS << ");\n";
2219 OS << " }\n";
2220 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002221
Evan Chengb915f312005-12-09 22:45:35 +00002222 return std::make_pair(1, ResNo);
2223 } else if (Op->isSubClassOf("SDNodeXForm")) {
2224 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002225 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002226 unsigned ResNo = TmpNo++;
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002227 OS << " ";
2228 DeclareSDOperand("Tmp"+utostr(ResNo));
2229 OS << " = Transform_" << Op->getName()
Evan Chengb915f312005-12-09 22:45:35 +00002230 << "(Tmp" << OpVal << ".Val);\n";
2231 if (isRoot) {
2232 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2233 OS << " return Tmp" << ResNo << ";\n";
2234 }
2235 return std::make_pair(1, ResNo);
2236 } else {
2237 N->dump();
2238 assert(0 && "Unknown node in result pattern!");
2239 return std::make_pair(1, ~0U);
2240 }
2241 }
2242
2243 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2244 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2245 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2246 /// for, this returns true otherwise false if Pat has all types.
2247 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2248 const std::string &Prefix) {
2249 // Did we find one?
2250 if (!Pat->hasTypeSet()) {
2251 // Move a type over from 'other' to 'pat'.
2252 Pat->setType(Other->getType());
2253 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2254 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2255 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002256 }
2257
2258 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2259 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2260 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2261 Prefix + utostr(OpNo)))
2262 return true;
2263 return false;
2264 }
2265
2266private:
Evan Cheng7b05bd52005-12-23 22:11:47 +00002267 /// EmitInFlags - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002268 /// being built.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002269 void EmitInFlags(TreePatternNode *N, const std::string &RootName,
2270 bool HasChain, bool HasInFlag, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002271 const CodeGenTarget &T = ISE.getTargetInfo();
2272 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2273 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2274 TreePatternNode *Child = N->getChild(i);
2275 if (!Child->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002276 EmitInFlags(Child, RootName + utostr(OpNo), HasChain, HasInFlag);
Evan Chengb915f312005-12-09 22:45:35 +00002277 } else {
2278 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2279 Record *RR = DI->getDef();
2280 if (RR->isSubClassOf("Register")) {
2281 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002282 if (RVT == MVT::Flag) {
2283 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002284 } else if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002285 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2286 OS << " " << RootName << "CR" << i
2287 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2288 << ISE.getQualifiedName(RR) << ", MVT::"
2289 << getEnumName(RVT) << ")"
2290 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2291 OS << " Chain = " << RootName << "CR" << i
2292 << ".getValue(0);\n";
2293 OS << " InFlag = " << RootName << "CR" << i
2294 << ".getValue(1);\n";
2295 } else {
2296 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2297 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2298 << ", MVT::" << getEnumName(RVT) << ")"
2299 << ", Select(" << RootName << OpNo
2300 << "), InFlag).getValue(1);\n";
2301 }
2302 }
2303 }
2304 }
2305 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002306
2307 if (isRoot && HasInFlag) {
2308 OS << " " << RootName << OpNo << " = " << RootName
2309 << ".getOperand(" << OpNo << ");\n";
2310 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
2311 }
Evan Chengb915f312005-12-09 22:45:35 +00002312 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002313
2314 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002315 /// as specified by the instruction. It returns true if any copy is
2316 /// emitted.
2317 bool EmitCopyFromRegs(TreePatternNode *N, bool HasChain) {
2318 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002319 Record *Op = N->getOperator();
2320 if (Op->isSubClassOf("Instruction")) {
2321 const DAGInstruction &Inst = ISE.getInstruction(Op);
2322 const CodeGenTarget &CGT = ISE.getTargetInfo();
2323 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2324 unsigned NumImpResults = Inst.getNumImpResults();
2325 for (unsigned i = 0; i < NumImpResults; i++) {
2326 Record *RR = Inst.getImpResult(i);
2327 if (RR->isSubClassOf("Register")) {
2328 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2329 if (RVT != MVT::Flag) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002330 if (HasChain) {
Evan Cheng4fba2812005-12-20 07:37:41 +00002331 OS << " Result = CurDAG->getCopyFromReg(Chain, "
2332 << ISE.getQualifiedName(RR)
2333 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2334 OS << " Chain = Result.getValue(1);\n";
2335 OS << " InFlag = Result.getValue(2);\n";
2336 } else {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002337 OS << " Chain;\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002338 OS << " Result = CurDAG->getCopyFromReg("
2339 << "CurDAG->getEntryNode(), ISE.getQualifiedName(RR)"
2340 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2341 OS << " Chain = Result.getValue(1);\n";
2342 OS << " InFlag = Result.getValue(2);\n";
2343 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002344 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002345 }
2346 }
2347 }
2348 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002349 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002350 }
Evan Chengb915f312005-12-09 22:45:35 +00002351};
2352
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002353/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2354/// stream to match the pattern, and generate the code for the match if it
2355/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002356void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2357 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002358 static unsigned PatternCount = 0;
2359 unsigned PatternNo = PatternCount++;
2360 OS << " { // Pattern #" << PatternNo << ": ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002361 Pattern.getSrcPattern()->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002362 OS << "\n // Emits: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002363 Pattern.getDstPattern()->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002364 OS << "\n";
Evan Cheng58e84a62005-12-14 22:02:59 +00002365 OS << " // Pattern complexity = "
2366 << getPatternSize(Pattern.getSrcPattern(), *this)
2367 << " cost = "
2368 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002369
Evan Cheng58e84a62005-12-14 22:02:59 +00002370 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2371 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2372 PatternNo, OS);
Evan Chengb915f312005-12-09 22:45:35 +00002373
Chris Lattner8fc35682005-09-23 23:16:51 +00002374 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002375 bool FoundChain = false;
2376 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", FoundChain,
2377 true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002378
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002379 // TP - Get *SOME* tree pattern, we don't care which.
2380 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002381
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002382 // At this point, we know that we structurally match the pattern, but the
2383 // types of the nodes may not match. Figure out the fewest number of type
2384 // comparisons we need to emit. For example, if there is only one integer
2385 // type supported by a target, there should be no type comparisons at all for
2386 // integer patterns!
2387 //
2388 // To figure out the fewest number of type checks needed, clone the pattern,
2389 // remove the types, then perform type inference on the pattern as a whole.
2390 // If there are unresolved types, emit an explicit check for those types,
2391 // apply the type to the tree, then rerun type inference. Iterate until all
2392 // types are resolved.
2393 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002394 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002395 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002396
2397 do {
2398 // Resolve/propagate as many types as possible.
2399 try {
2400 bool MadeChange = true;
2401 while (MadeChange)
2402 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2403 } catch (...) {
2404 assert(0 && "Error: could not find consistent types for something we"
2405 " already decided was ok!");
2406 abort();
2407 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002408
Chris Lattner7e82f132005-10-15 21:34:21 +00002409 // Insert a check for an unresolved type and add it to the tree. If we find
2410 // an unresolved type to add a check for, this returns true and we iterate,
2411 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002412 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002413
Evan Cheng58e84a62005-12-14 22:02:59 +00002414 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002415
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002416 delete Pat;
2417
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002418 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002419}
2420
Chris Lattner37481472005-09-26 21:59:35 +00002421
2422namespace {
2423 /// CompareByRecordName - An ordering predicate that implements less-than by
2424 /// comparing the names records.
2425 struct CompareByRecordName {
2426 bool operator()(const Record *LHS, const Record *RHS) const {
2427 // Sort by name first.
2428 if (LHS->getName() < RHS->getName()) return true;
2429 // If both names are equal, sort by pointer.
2430 return LHS->getName() == RHS->getName() && LHS < RHS;
2431 }
2432 };
2433}
2434
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002435void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002436 std::string InstNS = Target.inst_begin()->second.Namespace;
2437 if (!InstNS.empty()) InstNS += "::";
2438
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002439 // Emit boilerplate.
2440 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002441 << "SDOperand SelectCode(SDOperand N) {\n"
2442 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002443 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2444 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002445 << " return N; // Already selected.\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002446 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng481c8e02005-12-12 23:22:48 +00002447 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002448 << " // Work arounds for GCC stack overflow bugs.\n"
2449 << " SDOperand N0, N1, N2, N00, N01, N10, N11, Tmp0, Tmp1, Tmp2, Tmp3;\n"
2450 << " SDOperand Chain, InFlag, Result;\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002451 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002452 << " default: break;\n"
2453 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00002454 << " case ISD::BasicBlock:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002455 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002456 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002457 << " case ISD::AssertZext: {\n"
2458 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2459 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2460 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002461 << " }\n"
2462 << " case ISD::TokenFactor:\n"
2463 << " if (N.getNumOperands() == 2) {\n"
2464 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2465 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2466 << " return CodeGenMap[N] =\n"
2467 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2468 << " } else {\n"
2469 << " std::vector<SDOperand> Ops;\n"
2470 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2471 << " Ops.push_back(Select(N.getOperand(i)));\n"
2472 << " return CodeGenMap[N] = \n"
2473 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2474 << " }\n"
2475 << " case ISD::CopyFromReg: {\n"
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002476 << " Chain = Select(N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002477 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2478 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002479 << " if (N.Val->getNumValues() == 2) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002480 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2481 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2482 << " CodeGenMap[N.getValue(0)] = New;\n"
2483 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2484 << " return New.getValue(N.ResNo);\n"
2485 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002486 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002487 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2488 << " if (Chain == N.getOperand(0) &&\n"
2489 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002490 << " return N; // No change\n"
2491 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2492 << " CodeGenMap[N.getValue(0)] = New;\n"
2493 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2494 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2495 << " return New.getValue(N.ResNo);\n"
2496 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002497 << " }\n"
2498 << " case ISD::CopyToReg: {\n"
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002499 << " Chain = Select(N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002500 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002501 << " SDOperand Val = Select(N.getOperand(2));\n"
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002502 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002503 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002504 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002505 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002506 << " return CodeGenMap[N] = Result;\n"
2507 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002508 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002509 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002510 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002511 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2512 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002513 << " CodeGenMap[N.getValue(0)] = Result;\n"
2514 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2515 << " return Result.getValue(N.ResNo);\n"
2516 << " }\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002517 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002518
Chris Lattner81303322005-09-23 19:36:15 +00002519 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00002520 std::map<Record*, std::vector<PatternToMatch*>,
2521 CompareByRecordName> PatternsByOpcode;
Evan Cheng0fc71982005-12-08 02:00:36 +00002522 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002523 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
Evan Cheng0fc71982005-12-08 02:00:36 +00002524 if (!Node->isLeaf()) {
2525 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
Chris Lattner0614b622005-11-02 06:49:14 +00002526 } else {
Evan Cheng0fc71982005-12-08 02:00:36 +00002527 const ComplexPattern *CP;
Chris Lattner0614b622005-11-02 06:49:14 +00002528 if (IntInit *II =
Evan Cheng0fc71982005-12-08 02:00:36 +00002529 dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner0614b622005-11-02 06:49:14 +00002530 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
Evan Cheng0fc71982005-12-08 02:00:36 +00002531 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
Evan Cheng3aa39f42005-12-08 02:14:08 +00002532 std::vector<Record*> OpNodes = CP->getRootNodes();
Evan Cheng0fc71982005-12-08 02:00:36 +00002533 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2534 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2535 &PatternsToMatch[i]);
2536 }
Chris Lattner0614b622005-11-02 06:49:14 +00002537 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00002538 std::cerr << "Unrecognized opcode '";
Evan Cheng0fc71982005-12-08 02:00:36 +00002539 Node->dump();
Evan Cheng76021f02005-11-29 18:44:58 +00002540 std::cerr << "' on tree pattern '";
Evan Cheng58e84a62005-12-14 22:02:59 +00002541 std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Evan Cheng76021f02005-11-29 18:44:58 +00002542 std::cerr << "'!\n";
2543 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00002544 }
2545 }
Evan Cheng0fc71982005-12-08 02:00:36 +00002546 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002547
Chris Lattner3f7e9142005-09-23 20:52:47 +00002548 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00002549 for (std::map<Record*, std::vector<PatternToMatch*>,
2550 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2551 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002552 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2553 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2554
2555 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002556
2557 // We want to emit all of the matching code now. However, we want to emit
2558 // the matches in order of minimal cost. Sort the patterns so the least
2559 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002560 std::stable_sort(Patterns.begin(), Patterns.end(),
Evan Cheng0fc71982005-12-08 02:00:36 +00002561 PatternSortingPredicate(*this));
Chris Lattner81303322005-09-23 19:36:15 +00002562
Chris Lattner3f7e9142005-09-23 20:52:47 +00002563 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2564 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002565 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00002566 }
2567
2568
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002569 OS << " } // end of big switch.\n\n"
2570 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00002571 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002572 << " std::cerr << '\\n';\n"
2573 << " abort();\n"
2574 << "}\n";
2575}
2576
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002577void DAGISelEmitter::run(std::ostream &OS) {
2578 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2579 " target", OS);
2580
Chris Lattner1f39e292005-09-14 00:09:24 +00002581 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2582 << "// *** instruction selector class. These functions are really "
2583 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002584
Chris Lattner296dfe32005-09-24 00:50:51 +00002585 OS << "// Instance var to keep track of multiply used nodes that have \n"
2586 << "// already been selected.\n"
2587 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2588
Chris Lattnerca559d02005-09-08 21:03:01 +00002589 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002590 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00002591 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002592 ParsePatternFragments(OS);
2593 ParseInstructions();
2594 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002595
Chris Lattnere97603f2005-09-28 19:27:25 +00002596 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002597 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002598 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002599
Chris Lattnere46e17b2005-09-29 19:28:10 +00002600
2601 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2602 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002603 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2604 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00002605 std::cerr << "\n";
2606 });
2607
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002608 // At this point, we have full information about the 'Patterns' we need to
2609 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002610 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002611 EmitInstructionSelector(OS);
2612
2613 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2614 E = PatternFragments.end(); I != E; ++I)
2615 delete I->second;
2616 PatternFragments.clear();
2617
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002618 Instructions.clear();
2619}