blob: e3b2c8920e73934ded7b730e4fb1145ac4f689e0 [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000018#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include <set>
20using namespace llvm;
21
Chris Lattnerca559d02005-09-08 21:03:01 +000022//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000023// Helpers for working with extended types.
24
25/// FilterVTs - Filter a list of VT's according to a predicate.
26///
27template<typename T>
28static std::vector<MVT::ValueType>
29FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32 if (Filter(InVTs[i]))
33 Result.push_back(InVTs[i]);
34 return Result;
35}
36
37/// isExtIntegerVT - Return true if the specified extended value type is
38/// integer, or isInt.
39static bool isExtIntegerVT(unsigned char VT) {
40 return VT == MVT::isInt ||
41 (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
42}
43
44/// isExtFloatingPointVT - Return true if the specified extended value type is
45/// floating point, or isFP.
46static bool isExtFloatingPointVT(unsigned char VT) {
47 return VT == MVT::isFP ||
48 (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
49}
50
51//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000052// SDTypeConstraint implementation
53//
54
55SDTypeConstraint::SDTypeConstraint(Record *R) {
56 OperandNo = R->getValueAsInt("OperandNum");
57
58 if (R->isSubClassOf("SDTCisVT")) {
59 ConstraintType = SDTCisVT;
60 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61 } else if (R->isSubClassOf("SDTCisInt")) {
62 ConstraintType = SDTCisInt;
63 } else if (R->isSubClassOf("SDTCisFP")) {
64 ConstraintType = SDTCisFP;
65 } else if (R->isSubClassOf("SDTCisSameAs")) {
66 ConstraintType = SDTCisSameAs;
67 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
68 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
69 ConstraintType = SDTCisVTSmallerThanOp;
70 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
71 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +000072 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
73 ConstraintType = SDTCisOpSmallerThanOp;
74 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
75 R->getValueAsInt("BigOperandNum");
Chris Lattner33c92e92005-09-08 21:27:15 +000076 } else {
77 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
78 exit(1);
79 }
80}
81
Chris Lattner32707602005-09-08 23:22:48 +000082/// getOperandNum - Return the node corresponding to operand #OpNo in tree
83/// N, which has NumResults results.
84TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
85 TreePatternNode *N,
86 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +000087 assert(NumResults <= 1 &&
88 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +000089
90 if (OpNo < NumResults)
91 return N; // FIXME: need value #
92 else
93 return N->getChild(OpNo-NumResults);
94}
95
96/// ApplyTypeConstraint - Given a node in a pattern, apply this type
97/// constraint to the nodes operands. This returns true if it makes a
98/// change, false otherwise. If a type contradiction is found, throw an
99/// exception.
100bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
101 const SDNodeInfo &NodeInfo,
102 TreePattern &TP) const {
103 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000104 assert(NumResults <= 1 &&
105 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000106
107 // Check that the number of operands is sane.
108 if (NodeInfo.getNumOperands() >= 0) {
109 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
110 TP.error(N->getOperator()->getName() + " node requires exactly " +
111 itostr(NodeInfo.getNumOperands()) + " operands!");
112 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000113
114 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000115
116 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
117
118 switch (ConstraintType) {
119 default: assert(0 && "Unknown constraint type!");
120 case SDTCisVT:
121 // Operand must be a particular type.
122 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000123 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000124 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000125 std::vector<MVT::ValueType> IntVTs =
126 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000127
128 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000129 if (IntVTs.size() == 1)
130 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000131 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000132 }
133 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000134 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000135 std::vector<MVT::ValueType> FPVTs =
136 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000137
138 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000139 if (FPVTs.size() == 1)
140 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000141 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000142 }
Chris Lattner32707602005-09-08 23:22:48 +0000143 case SDTCisSameAs: {
144 TreePatternNode *OtherNode =
145 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000146 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
147 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000148 }
149 case SDTCisVTSmallerThanOp: {
150 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
151 // have an integer type that is smaller than the VT.
152 if (!NodeToApply->isLeaf() ||
153 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
154 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
155 ->isSubClassOf("ValueType"))
156 TP.error(N->getOperator()->getName() + " expects a VT operand!");
157 MVT::ValueType VT =
158 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
159 if (!MVT::isInteger(VT))
160 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
161
162 TreePatternNode *OtherNode =
163 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000164
165 // It must be integer.
166 bool MadeChange = false;
167 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
168
169 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000170 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
171 return false;
172 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000173 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000174 TreePatternNode *BigOperand =
175 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
176
177 // Both operands must be integer or FP, but we don't care which.
178 bool MadeChange = false;
179
180 if (isExtIntegerVT(NodeToApply->getExtType()))
181 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
182 else if (isExtFloatingPointVT(NodeToApply->getExtType()))
183 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
184 if (isExtIntegerVT(BigOperand->getExtType()))
185 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
186 else if (isExtFloatingPointVT(BigOperand->getExtType()))
187 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
188
189 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
190
191 if (isExtIntegerVT(NodeToApply->getExtType())) {
192 VTs = FilterVTs(VTs, MVT::isInteger);
193 } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
194 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
195 } else {
196 VTs.clear();
197 }
198
199 switch (VTs.size()) {
200 default: // Too many VT's to pick from.
201 case 0: break; // No info yet.
202 case 1:
203 // Only one VT of this flavor. Cannot ever satisify the constraints.
204 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
205 case 2:
206 // If we have exactly two possible types, the little operand must be the
207 // small one, the big operand should be the big one. Common with
208 // float/double for example.
209 assert(VTs[0] < VTs[1] && "Should be sorted!");
210 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
211 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
212 break;
213 }
214 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000215 }
Chris Lattner32707602005-09-08 23:22:48 +0000216 }
217 return false;
218}
219
220
Chris Lattner33c92e92005-09-08 21:27:15 +0000221//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000222// SDNodeInfo implementation
223//
224SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
225 EnumName = R->getValueAsString("Opcode");
226 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000227 Record *TypeProfile = R->getValueAsDef("TypeProfile");
228 NumResults = TypeProfile->getValueAsInt("NumResults");
229 NumOperands = TypeProfile->getValueAsInt("NumOperands");
230
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000231 // Parse the properties.
232 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000233 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000234 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
235 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000236 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000237 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000238 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000239 } else if (PropList[i]->getName() == "SDNPHasChain") {
240 Properties |= 1 << SDNPHasChain;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000241 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000242 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000243 << "' on node '" << R->getName() << "'!\n";
244 exit(1);
245 }
246 }
247
248
Chris Lattner33c92e92005-09-08 21:27:15 +0000249 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000250 std::vector<Record*> ConstraintList =
251 TypeProfile->getValueAsListOfDefs("Constraints");
252 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000253}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000254
255//===----------------------------------------------------------------------===//
256// TreePatternNode implementation
257//
258
259TreePatternNode::~TreePatternNode() {
260#if 0 // FIXME: implement refcounted tree nodes!
261 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
262 delete getChild(i);
263#endif
264}
265
Chris Lattner32707602005-09-08 23:22:48 +0000266/// UpdateNodeType - Set the node type of N to VT if VT contains
267/// information. If N already contains a conflicting type, then throw an
268/// exception. This returns true if any information was updated.
269///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000270bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
271 if (VT == MVT::isUnknown || getExtType() == VT) return false;
272 if (getExtType() == MVT::isUnknown) {
Chris Lattner32707602005-09-08 23:22:48 +0000273 setType(VT);
274 return true;
275 }
276
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000277 // If we are told this is to be an int or FP type, and it already is, ignore
278 // the advice.
279 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
280 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
281 return false;
282
283 // If we know this is an int or fp type, and we are told it is a specific one,
284 // take the advice.
285 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
286 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
287 setType(VT);
288 return true;
289 }
290
Chris Lattner1531f202005-10-26 16:59:37 +0000291 if (isLeaf()) {
292 dump();
293 TP.error("Type inference contradiction found in node!");
294 } else {
295 TP.error("Type inference contradiction found in node " +
296 getOperator()->getName() + "!");
297 }
Chris Lattner32707602005-09-08 23:22:48 +0000298 return true; // unreachable
299}
300
301
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000302void TreePatternNode::print(std::ostream &OS) const {
303 if (isLeaf()) {
304 OS << *getLeafValue();
305 } else {
306 OS << "(" << getOperator()->getName();
307 }
308
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000309 switch (getExtType()) {
310 case MVT::Other: OS << ":Other"; break;
311 case MVT::isInt: OS << ":isInt"; break;
312 case MVT::isFP : OS << ":isFP"; break;
313 case MVT::isUnknown: ; /*OS << ":?";*/ break;
314 default: OS << ":" << getType(); break;
315 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000316
317 if (!isLeaf()) {
318 if (getNumChildren() != 0) {
319 OS << " ";
320 getChild(0)->print(OS);
321 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
322 OS << ", ";
323 getChild(i)->print(OS);
324 }
325 }
326 OS << ")";
327 }
328
329 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000330 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000331 if (TransformFn)
332 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000333 if (!getName().empty())
334 OS << ":$" << getName();
335
336}
337void TreePatternNode::dump() const {
338 print(std::cerr);
339}
340
Chris Lattnere46e17b2005-09-29 19:28:10 +0000341/// isIsomorphicTo - Return true if this node is recursively isomorphic to
342/// the specified node. For this comparison, all of the state of the node
343/// is considered, except for the assigned name. Nodes with differing names
344/// that are otherwise identical are considered isomorphic.
345bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
346 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000347 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000348 getPredicateFn() != N->getPredicateFn() ||
349 getTransformFn() != N->getTransformFn())
350 return false;
351
352 if (isLeaf()) {
353 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
354 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
355 return DI->getDef() == NDI->getDef();
356 return getLeafValue() == N->getLeafValue();
357 }
358
359 if (N->getOperator() != getOperator() ||
360 N->getNumChildren() != getNumChildren()) return false;
361 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
362 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
363 return false;
364 return true;
365}
366
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000367/// clone - Make a copy of this tree and all of its children.
368///
369TreePatternNode *TreePatternNode::clone() const {
370 TreePatternNode *New;
371 if (isLeaf()) {
372 New = new TreePatternNode(getLeafValue());
373 } else {
374 std::vector<TreePatternNode*> CChildren;
375 CChildren.reserve(Children.size());
376 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
377 CChildren.push_back(getChild(i)->clone());
378 New = new TreePatternNode(getOperator(), CChildren);
379 }
380 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000381 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000382 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000383 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000384 return New;
385}
386
Chris Lattner32707602005-09-08 23:22:48 +0000387/// SubstituteFormalArguments - Replace the formal arguments in this tree
388/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000389void TreePatternNode::
390SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
391 if (isLeaf()) return;
392
393 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
394 TreePatternNode *Child = getChild(i);
395 if (Child->isLeaf()) {
396 Init *Val = Child->getLeafValue();
397 if (dynamic_cast<DefInit*>(Val) &&
398 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
399 // We found a use of a formal argument, replace it with its value.
400 Child = ArgMap[Child->getName()];
401 assert(Child && "Couldn't find formal argument!");
402 setChild(i, Child);
403 }
404 } else {
405 getChild(i)->SubstituteFormalArguments(ArgMap);
406 }
407 }
408}
409
410
411/// InlinePatternFragments - If this pattern refers to any pattern
412/// fragments, inline them into place, giving us a pattern without any
413/// PatFrag references.
414TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
415 if (isLeaf()) return this; // nothing to do.
416 Record *Op = getOperator();
417
418 if (!Op->isSubClassOf("PatFrag")) {
419 // Just recursively inline children nodes.
420 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
421 setChild(i, getChild(i)->InlinePatternFragments(TP));
422 return this;
423 }
424
425 // Otherwise, we found a reference to a fragment. First, look up its
426 // TreePattern record.
427 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
428
429 // Verify that we are passing the right number of operands.
430 if (Frag->getNumArgs() != Children.size())
431 TP.error("'" + Op->getName() + "' fragment requires " +
432 utostr(Frag->getNumArgs()) + " operands!");
433
Chris Lattner37937092005-09-09 01:15:01 +0000434 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000435
436 // Resolve formal arguments to their actual value.
437 if (Frag->getNumArgs()) {
438 // Compute the map of formal to actual arguments.
439 std::map<std::string, TreePatternNode*> ArgMap;
440 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
441 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
442
443 FragTree->SubstituteFormalArguments(ArgMap);
444 }
445
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000446 FragTree->setName(getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000447 FragTree->UpdateNodeType(getExtType(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000448
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000449 // Get a new copy of this fragment to stitch into here.
450 //delete this; // FIXME: implement refcounting!
451 return FragTree;
452}
453
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000454/// getIntrinsicType - Check to see if the specified record has an intrinsic
455/// type which should be applied to it. This infer the type of register
456/// references from the register file information, for example.
457///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000458static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
459 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000460 // Check to see if this is a register or a register class...
461 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000462 if (NotRegisters) return MVT::isUnknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000463 const CodeGenRegisterClass &RC =
464 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
465 return RC.getValueTypeNum(0);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000466 } else if (R->isSubClassOf("PatFrag")) {
467 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000468 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000469 } else if (R->isSubClassOf("Register")) {
Chris Lattner22faeab2005-12-05 02:36:37 +0000470 // If the register appears in exactly one regclass, and the regclass has one
471 // value type, use it as the known type.
472 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
473 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
474 if (RC->getNumValueTypes() == 1)
475 return RC->getValueTypeNum(0);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000476 return MVT::isUnknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000477 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
478 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000479 return MVT::Other;
480 } else if (R->getName() == "node") {
481 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000482 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000483 }
484
485 TP.error("Unknown node flavor used in pattern: " + R->getName());
486 return MVT::Other;
487}
488
Chris Lattner32707602005-09-08 23:22:48 +0000489/// ApplyTypeConstraints - Apply all of the type constraints relevent to
490/// this node and its children in the tree. This returns true if it makes a
491/// change, false otherwise. If a type contradiction is found, throw an
492/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000493bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
494 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000495 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000496 // If it's a regclass or something else known, include the type.
497 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
498 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000499 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
500 // Int inits are always integers. :)
501 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
502
503 if (hasTypeSet()) {
504 unsigned Size = MVT::getSizeInBits(getType());
505 // Make sure that the value is representable for this type.
506 if (Size < 32) {
507 int Val = (II->getValue() << (32-Size)) >> (32-Size);
508 if (Val != II->getValue())
509 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
510 "' is out of range for type 'MVT::" +
511 getEnumName(getType()) + "'!");
512 }
513 }
514
515 return MadeChange;
516 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000517 return false;
518 }
Chris Lattner32707602005-09-08 23:22:48 +0000519
520 // special handling for set, which isn't really an SDNode.
521 if (getOperator()->getName() == "set") {
522 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000523 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
524 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000525
526 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000527 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
528 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000529 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
530 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000531 } else if (getOperator()->isSubClassOf("SDNode")) {
532 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
533
534 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
535 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000536 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000537 // Branch, etc. do not produce results and top-level forms in instr pattern
538 // must have void types.
539 if (NI.getNumResults() == 0)
540 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000541 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000542 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000543 const DAGInstruction &Inst =
544 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000545 bool MadeChange = false;
546 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000547
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000548 assert(NumResults <= 1 &&
549 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000550 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000551 if (NumResults == 0) {
552 MadeChange = UpdateNodeType(MVT::isVoid, TP);
553 } else {
554 Record *ResultNode = Inst.getResult(0);
555 assert(ResultNode->isSubClassOf("RegisterClass") &&
556 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000557
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000558 const CodeGenRegisterClass &RC =
559 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000560
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000561 // Get the first ValueType in the RegClass, it's as good as any.
562 MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
563 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000564
565 if (getNumChildren() != Inst.getNumOperands())
566 TP.error("Instruction '" + getOperator()->getName() + " expects " +
567 utostr(Inst.getNumOperands()) + " operands, not " +
568 utostr(getNumChildren()) + " operands!");
569 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000570 Record *OperandNode = Inst.getOperand(i);
571 MVT::ValueType VT;
572 if (OperandNode->isSubClassOf("RegisterClass")) {
573 const CodeGenRegisterClass &RC =
574 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000575 VT = RC.getValueTypeNum(0);
Nate Begemanddb39542005-12-01 00:06:14 +0000576 } else if (OperandNode->isSubClassOf("Operand")) {
577 VT = getValueType(OperandNode->getValueAsDef("Type"));
578 } else {
579 assert(0 && "Unknown operand type!");
580 abort();
581 }
582
583 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000584 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000585 }
586 return MadeChange;
587 } else {
588 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
589
590 // Node transforms always take one operand, and take and return the same
591 // type.
592 if (getNumChildren() != 1)
593 TP.error("Node transform '" + getOperator()->getName() +
594 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000595 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
596 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000597 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000598 }
Chris Lattner32707602005-09-08 23:22:48 +0000599}
600
Chris Lattnere97603f2005-09-28 19:27:25 +0000601/// canPatternMatch - If it is impossible for this pattern to match on this
602/// target, fill in Reason and return false. Otherwise, return true. This is
603/// used as a santity check for .td files (to prevent people from writing stuff
604/// that can never possibly work), and to prevent the pattern permuter from
605/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000606bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000607 if (isLeaf()) return true;
608
609 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
610 if (!getChild(i)->canPatternMatch(Reason, ISE))
611 return false;
612
613 // If this node is a commutative operator, check that the LHS isn't an
614 // immediate.
615 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
616 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
617 // Scan all of the operands of the node and make sure that only the last one
618 // is a constant node.
619 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
620 if (!getChild(i)->isLeaf() &&
621 getChild(i)->getOperator()->getName() == "imm") {
622 Reason = "Immediate value must be on the RHS of commutative operators!";
623 return false;
624 }
625 }
626
627 return true;
628}
Chris Lattner32707602005-09-08 23:22:48 +0000629
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000630//===----------------------------------------------------------------------===//
631// TreePattern implementation
632//
633
Chris Lattneredbd8712005-10-21 01:19:59 +0000634TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000635 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000636 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000637 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
638 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000639}
640
Chris Lattneredbd8712005-10-21 01:19:59 +0000641TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000642 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000643 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000644 Trees.push_back(ParseTreePattern(Pat));
645}
646
Chris Lattneredbd8712005-10-21 01:19:59 +0000647TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000648 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000649 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000650 Trees.push_back(Pat);
651}
652
653
654
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000655void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000656 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000657 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000658}
659
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000660TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
661 Record *Operator = Dag->getNodeType();
662
663 if (Operator->isSubClassOf("ValueType")) {
664 // If the operator is a ValueType, then this must be "type cast" of a leaf
665 // node.
666 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000667 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000668
669 Init *Arg = Dag->getArg(0);
670 TreePatternNode *New;
671 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000672 Record *R = DI->getDef();
673 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
674 Dag->setArg(0, new DagInit(R,
675 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000676 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000677 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000678 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000679 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
680 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000681 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
682 New = new TreePatternNode(II);
683 if (!Dag->getArgName(0).empty())
684 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000685 } else {
686 Arg->dump();
687 error("Unknown leaf value for tree pattern!");
688 return 0;
689 }
690
Chris Lattner32707602005-09-08 23:22:48 +0000691 // Apply the type cast.
692 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000693 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000694 return New;
695 }
696
697 // Verify that this is something that makes sense for an operator.
698 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000699 !Operator->isSubClassOf("Instruction") &&
700 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000701 Operator->getName() != "set")
702 error("Unrecognized node '" + Operator->getName() + "'!");
703
Chris Lattneredbd8712005-10-21 01:19:59 +0000704 // Check to see if this is something that is illegal in an input pattern.
705 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
706 Operator->isSubClassOf("SDNodeXForm")))
707 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
708
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000709 std::vector<TreePatternNode*> Children;
710
711 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
712 Init *Arg = Dag->getArg(i);
713 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
714 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000715 if (Children.back()->getName().empty())
716 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000717 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
718 Record *R = DefI->getDef();
719 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
720 // TreePatternNode if its own.
721 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
722 Dag->setArg(i, new DagInit(R,
723 std::vector<std::pair<Init*, std::string> >()));
724 --i; // Revisit this node...
725 } else {
726 TreePatternNode *Node = new TreePatternNode(DefI);
727 Node->setName(Dag->getArgName(i));
728 Children.push_back(Node);
729
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000730 // Input argument?
731 if (R->getName() == "node") {
732 if (Dag->getArgName(i).empty())
733 error("'node' argument requires a name to match with operand list");
734 Args.push_back(Dag->getArgName(i));
735 }
736 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000737 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
738 TreePatternNode *Node = new TreePatternNode(II);
739 if (!Dag->getArgName(i).empty())
740 error("Constant int argument should not have a name!");
741 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000742 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000743 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000744 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000745 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746 error("Unknown leaf value for tree pattern!");
747 }
748 }
749
750 return new TreePatternNode(Operator, Children);
751}
752
Chris Lattner32707602005-09-08 23:22:48 +0000753/// InferAllTypes - Infer/propagate as many types throughout the expression
754/// patterns as possible. Return true if all types are infered, false
755/// otherwise. Throw an exception if a type contradiction is found.
756bool TreePattern::InferAllTypes() {
757 bool MadeChange = true;
758 while (MadeChange) {
759 MadeChange = false;
760 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000761 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000762 }
763
764 bool HasUnresolvedTypes = false;
765 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
766 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
767 return !HasUnresolvedTypes;
768}
769
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000770void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000771 OS << getRecord()->getName();
772 if (!Args.empty()) {
773 OS << "(" << Args[0];
774 for (unsigned i = 1, e = Args.size(); i != e; ++i)
775 OS << ", " << Args[i];
776 OS << ")";
777 }
778 OS << ": ";
779
780 if (Trees.size() > 1)
781 OS << "[\n";
782 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
783 OS << "\t";
784 Trees[i]->print(OS);
785 OS << "\n";
786 }
787
788 if (Trees.size() > 1)
789 OS << "]\n";
790}
791
792void TreePattern::dump() const { print(std::cerr); }
793
794
795
796//===----------------------------------------------------------------------===//
797// DAGISelEmitter implementation
798//
799
Chris Lattnerca559d02005-09-08 21:03:01 +0000800// Parse all of the SDNode definitions for the target, populating SDNodes.
801void DAGISelEmitter::ParseNodeInfo() {
802 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
803 while (!Nodes.empty()) {
804 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
805 Nodes.pop_back();
806 }
807}
808
Chris Lattner24eeeb82005-09-13 21:51:00 +0000809/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
810/// map, and emit them to the file as functions.
811void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
812 OS << "\n// Node transformations.\n";
813 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
814 while (!Xforms.empty()) {
815 Record *XFormNode = Xforms.back();
816 Record *SDNode = XFormNode->getValueAsDef("Opcode");
817 std::string Code = XFormNode->getValueAsCode("XFormFunction");
818 SDNodeXForms.insert(std::make_pair(XFormNode,
819 std::make_pair(SDNode, Code)));
820
Chris Lattner1048b7a2005-09-13 22:03:37 +0000821 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000822 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
823 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
824
Chris Lattner1048b7a2005-09-13 22:03:37 +0000825 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000826 << "(SDNode *" << C2 << ") {\n";
827 if (ClassName != "SDNode")
828 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
829 OS << Code << "\n}\n";
830 }
831
832 Xforms.pop_back();
833 }
834}
835
836
837
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000838/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
839/// file, building up the PatternFragments map. After we've collected them all,
840/// inline fragments together as necessary, so that there are no references left
841/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000842///
843/// This also emits all of the predicate functions to the output file.
844///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000845void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000846 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
847
848 // First step, parse all of the fragments and emit predicate functions.
849 OS << "\n// Predicate functions.\n";
850 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000851 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000852 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000853 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000854
855 // Validate the argument list, converting it to map, to discard duplicates.
856 std::vector<std::string> &Args = P->getArgList();
857 std::set<std::string> OperandsMap(Args.begin(), Args.end());
858
859 if (OperandsMap.count(""))
860 P->error("Cannot have unnamed 'node' values in pattern fragment!");
861
862 // Parse the operands list.
863 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
864 if (OpsList->getNodeType()->getName() != "ops")
865 P->error("Operands list should start with '(ops ... '!");
866
867 // Copy over the arguments.
868 Args.clear();
869 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
870 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
871 static_cast<DefInit*>(OpsList->getArg(j))->
872 getDef()->getName() != "node")
873 P->error("Operands list should all be 'node' values.");
874 if (OpsList->getArgName(j).empty())
875 P->error("Operands list should have names for each operand!");
876 if (!OperandsMap.count(OpsList->getArgName(j)))
877 P->error("'" + OpsList->getArgName(j) +
878 "' does not occur in pattern or was multiply specified!");
879 OperandsMap.erase(OpsList->getArgName(j));
880 Args.push_back(OpsList->getArgName(j));
881 }
882
883 if (!OperandsMap.empty())
884 P->error("Operands list does not contain an entry for operand '" +
885 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000886
887 // If there is a code init for this fragment, emit the predicate code and
888 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000889 std::string Code = Fragments[i]->getValueAsCode("Predicate");
890 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000891 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000892 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000893 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000894 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
895
Chris Lattner1048b7a2005-09-13 22:03:37 +0000896 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000897 << "(SDNode *" << C2 << ") {\n";
898 if (ClassName != "SDNode")
899 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000900 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000901 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000902 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000903
904 // If there is a node transformation corresponding to this, keep track of
905 // it.
906 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
907 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000908 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000909 }
910
911 OS << "\n\n";
912
913 // Now that we've parsed all of the tree fragments, do a closure on them so
914 // that there are not references to PatFrags left inside of them.
915 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
916 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000917 TreePattern *ThePat = I->second;
918 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000919
Chris Lattner32707602005-09-08 23:22:48 +0000920 // Infer as many types as possible. Don't worry about it if we don't infer
921 // all of them, some may depend on the inputs of the pattern.
922 try {
923 ThePat->InferAllTypes();
924 } catch (...) {
925 // If this pattern fragment is not supported by this target (no types can
926 // satisfy its constraints), just ignore it. If the bogus pattern is
927 // actually used by instructions, the type consistency error will be
928 // reported there.
929 }
930
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000931 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000932 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000933 }
934}
935
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000936/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000937/// instruction input. Return true if this is a real use.
938static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000939 std::map<std::string, TreePatternNode*> &InstInputs) {
940 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000941 if (Pat->getName().empty()) {
942 if (Pat->isLeaf()) {
943 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
944 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
945 I->error("Input " + DI->getDef()->getName() + " must be named!");
946
947 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000948 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000949 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000950
951 Record *Rec;
952 if (Pat->isLeaf()) {
953 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
954 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
955 Rec = DI->getDef();
956 } else {
957 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
958 Rec = Pat->getOperator();
959 }
960
961 TreePatternNode *&Slot = InstInputs[Pat->getName()];
962 if (!Slot) {
963 Slot = Pat;
964 } else {
965 Record *SlotRec;
966 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000967 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000968 } else {
969 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
970 SlotRec = Slot->getOperator();
971 }
972
973 // Ensure that the inputs agree if we've already seen this input.
974 if (Rec != SlotRec)
975 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000976 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000977 I->error("All $" + Pat->getName() + " inputs must agree with each other");
978 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000979 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000980}
981
982/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
983/// part of "I", the instruction), computing the set of inputs and outputs of
984/// the pattern. Report errors if we see anything naughty.
985void DAGISelEmitter::
986FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
987 std::map<std::string, TreePatternNode*> &InstInputs,
988 std::map<std::string, Record*> &InstResults) {
989 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000990 bool isUse = HandleUse(I, Pat, InstInputs);
991 if (!isUse && Pat->getTransformFn())
992 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000993 return;
994 } else if (Pat->getOperator()->getName() != "set") {
995 // If this is not a set, verify that the children nodes are not void typed,
996 // and recurse.
997 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000998 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000999 I->error("Cannot have void nodes inside of patterns!");
1000 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
1001 }
1002
1003 // If this is a non-leaf node with no children, treat it basically as if
1004 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001005 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001006 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +00001007 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001008
Chris Lattnerf1311842005-09-14 23:05:13 +00001009 if (!isUse && Pat->getTransformFn())
1010 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001011 return;
1012 }
1013
1014 // Otherwise, this is a set, validate and collect instruction results.
1015 if (Pat->getNumChildren() == 0)
1016 I->error("set requires operands!");
1017 else if (Pat->getNumChildren() & 1)
1018 I->error("set requires an even number of operands");
1019
Chris Lattnerf1311842005-09-14 23:05:13 +00001020 if (Pat->getTransformFn())
1021 I->error("Cannot specify a transform function on a set node!");
1022
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001023 // Check the set destinations.
1024 unsigned NumValues = Pat->getNumChildren()/2;
1025 for (unsigned i = 0; i != NumValues; ++i) {
1026 TreePatternNode *Dest = Pat->getChild(i);
1027 if (!Dest->isLeaf())
1028 I->error("set destination should be a virtual register!");
1029
1030 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1031 if (!Val)
1032 I->error("set destination should be a virtual register!");
1033
1034 if (!Val->getDef()->isSubClassOf("RegisterClass"))
1035 I->error("set destination should be a virtual register!");
1036 if (Dest->getName().empty())
1037 I->error("set destination must have a name!");
1038 if (InstResults.count(Dest->getName()))
1039 I->error("cannot set '" + Dest->getName() +"' multiple times");
1040 InstResults[Dest->getName()] = Val->getDef();
1041
1042 // Verify and collect info from the computation.
1043 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1044 InstInputs, InstResults);
1045 }
1046}
1047
1048
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001049/// ParseInstructions - Parse all of the instructions, inlining and resolving
1050/// any fragments involved. This populates the Instructions list with fully
1051/// resolved instructions.
1052void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001053 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1054
1055 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001056 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001057
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001058 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1059 LI = Instrs[i]->getValueAsListInit("Pattern");
1060
1061 // If there is no pattern, only collect minimal information about the
1062 // instruction for its operand list. We have to assume that there is one
1063 // result, as we have no detailed info.
1064 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001065 std::vector<Record*> Results;
1066 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001067
1068 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1069
1070 // Doesn't even define a result?
1071 if (InstInfo.OperandList.size() == 0)
1072 continue;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001073
1074 // FIXME: temporary hack...
1075 if (InstInfo.isReturn || InstInfo.isBranch || InstInfo.isCall ||
1076 InstInfo.isStore) {
1077 // These produce no results
1078 for (unsigned j = 0, e = InstInfo.OperandList.size(); j != e; ++j)
1079 Operands.push_back(InstInfo.OperandList[j].Rec);
1080 } else {
1081 // Assume the first operand is the result.
1082 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001083
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001084 // The rest are inputs.
1085 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1086 Operands.push_back(InstInfo.OperandList[j].Rec);
1087 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001088
1089 // Create and insert the instruction.
1090 Instructions.insert(std::make_pair(Instrs[i],
Nate Begemanddb39542005-12-01 00:06:14 +00001091 DAGInstruction(0, Results, Operands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001092 continue; // no pattern.
1093 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001094
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001095 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001096 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001097 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001098 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001099
Chris Lattner95f6b762005-09-08 23:26:30 +00001100 // Infer as many types as possible. If we cannot infer all of them, we can
1101 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001102 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001103 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001104
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001105 // InstInputs - Keep track of all of the inputs of the instruction, along
1106 // with the record they are declared as.
1107 std::map<std::string, TreePatternNode*> InstInputs;
1108
1109 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001110 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001111 std::map<std::string, Record*> InstResults;
1112
Chris Lattner1f39e292005-09-14 00:09:24 +00001113 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001114 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001115 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1116 TreePatternNode *Pat = I->getTree(j);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001117 if (Pat->getExtType() != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001118 I->error("Top-level forms in instruction pattern should have"
1119 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001120
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001121 // Find inputs and outputs, and verify the structure of the uses/defs.
1122 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001123 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001124
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001125 // Now that we have inputs and outputs of the pattern, inspect the operands
1126 // list for the instruction. This determines the order that operands are
1127 // added to the machine instruction the node corresponds to.
1128 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001129
1130 // Parse the operands list from the (ops) list, validating it.
1131 std::vector<std::string> &Args = I->getArgList();
1132 assert(Args.empty() && "Args list should still be empty here!");
1133 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1134
1135 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001136 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001137 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001138 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001139 I->error("'" + InstResults.begin()->first +
1140 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001141 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001142
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001143 // Check that it exists in InstResults.
1144 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001145 if (R == 0)
1146 I->error("Operand $" + OpName + " should be a set destination: all "
1147 "outputs must occur before inputs in operand list!");
1148
1149 if (CGI.OperandList[i].Rec != R)
1150 I->error("Operand $" + OpName + " class mismatch!");
1151
Chris Lattnerae6d8282005-09-15 21:51:12 +00001152 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001153 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001154
Chris Lattner39e8af92005-09-14 18:19:25 +00001155 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001156 InstResults.erase(OpName);
1157 }
1158
Chris Lattner0b592252005-09-14 21:59:34 +00001159 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1160 // the copy while we're checking the inputs.
1161 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001162
1163 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001164 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001165 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1166 const std::string &OpName = CGI.OperandList[i].Name;
1167 if (OpName.empty())
1168 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1169
Chris Lattner0b592252005-09-14 21:59:34 +00001170 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001171 I->error("Operand $" + OpName +
1172 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001173 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001174 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001175
1176 if (InVal->isLeaf() &&
1177 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1178 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1179 if (CGI.OperandList[i].Rec != InRec)
1180 I->error("Operand $" + OpName +
1181 "'s register class disagrees between the operand and pattern");
1182 }
1183 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001184
Chris Lattner2175c182005-09-14 23:01:59 +00001185 // Construct the result for the dest-pattern operand list.
1186 TreePatternNode *OpNode = InVal->clone();
1187
1188 // No predicate is useful on the result.
1189 OpNode->setPredicateFn("");
1190
1191 // Promote the xform function to be an explicit node if set.
1192 if (Record *Xform = OpNode->getTransformFn()) {
1193 OpNode->setTransformFn(0);
1194 std::vector<TreePatternNode*> Children;
1195 Children.push_back(OpNode);
1196 OpNode = new TreePatternNode(Xform, Children);
1197 }
1198
1199 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001200 }
1201
Chris Lattner0b592252005-09-14 21:59:34 +00001202 if (!InstInputsCheck.empty())
1203 I->error("Input operand $" + InstInputsCheck.begin()->first +
1204 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001205
1206 TreePatternNode *ResultPattern =
1207 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001208
1209 // Create and insert the instruction.
Nate Begemanddb39542005-12-01 00:06:14 +00001210 DAGInstruction TheInst(I, Results, Operands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001211 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1212
1213 // Use a temporary tree pattern to infer all types and make sure that the
1214 // constructed result is correct. This depends on the instruction already
1215 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001216 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001217 Temp.InferAllTypes();
1218
1219 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1220 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001221
Chris Lattner32707602005-09-08 23:22:48 +00001222 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001223 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001224
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001225 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001226 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1227 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001228 DAGInstruction &TheInst = II->second;
1229 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001230 if (I == 0) continue; // No pattern.
Chris Lattner1f39e292005-09-14 00:09:24 +00001231
1232 if (I->getNumTrees() != 1) {
1233 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1234 continue;
1235 }
1236 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001237 TreePatternNode *SrcPattern;
1238 if (TheInst.getNumResults() == 0) {
1239 SrcPattern = Pattern;
1240 } else {
1241 if (Pattern->getOperator()->getName() != "set")
1242 continue; // Not a set (store or something?)
Chris Lattner1f39e292005-09-14 00:09:24 +00001243
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001244 if (Pattern->getNumChildren() != 2)
1245 continue; // Not a set of a single value (not handled so far)
1246
1247 SrcPattern = Pattern->getChild(1)->clone();
1248 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001249
1250 std::string Reason;
1251 if (!SrcPattern->canPatternMatch(Reason, *this))
1252 I->error("Instruction can never match: " + Reason);
1253
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001254 TreePatternNode *DstPattern = TheInst.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001255 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001256 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001257}
1258
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001259void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001260 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001261
Chris Lattnerabbb6052005-09-15 21:42:00 +00001262 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001263 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001264 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001265
Chris Lattnerabbb6052005-09-15 21:42:00 +00001266 // Inline pattern fragments into it.
1267 Pattern->InlinePatternFragments();
1268
1269 // Infer as many types as possible. If we cannot infer all of them, we can
1270 // never do anything with this pattern: report it to the user.
1271 if (!Pattern->InferAllTypes())
1272 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001273
1274 // Validate that the input pattern is correct.
1275 {
1276 std::map<std::string, TreePatternNode*> InstInputs;
1277 std::map<std::string, Record*> InstResults;
1278 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1279 InstInputs, InstResults);
1280 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001281
1282 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1283 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001284
1285 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001286 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001287
1288 // Inline pattern fragments into it.
1289 Result->InlinePatternFragments();
1290
1291 // Infer as many types as possible. If we cannot infer all of them, we can
1292 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001293 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001294 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001295
1296 if (Result->getNumTrees() != 1)
1297 Result->error("Cannot handle instructions producing instructions "
1298 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001299
1300 std::string Reason;
1301 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1302 Pattern->error("Pattern can never match: " + Reason);
1303
Chris Lattnerabbb6052005-09-15 21:42:00 +00001304 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1305 Result->getOnlyTree()));
1306 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001307}
1308
Chris Lattnere46e17b2005-09-29 19:28:10 +00001309/// CombineChildVariants - Given a bunch of permutations of each child of the
1310/// 'operator' node, put them together in all possible ways.
1311static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001312 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001313 std::vector<TreePatternNode*> &OutVariants,
1314 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001315 // Make sure that each operand has at least one variant to choose from.
1316 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1317 if (ChildVariants[i].empty())
1318 return;
1319
Chris Lattnere46e17b2005-09-29 19:28:10 +00001320 // The end result is an all-pairs construction of the resultant pattern.
1321 std::vector<unsigned> Idxs;
1322 Idxs.resize(ChildVariants.size());
1323 bool NotDone = true;
1324 while (NotDone) {
1325 // Create the variant and add it to the output list.
1326 std::vector<TreePatternNode*> NewChildren;
1327 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1328 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1329 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1330
1331 // Copy over properties.
1332 R->setName(Orig->getName());
1333 R->setPredicateFn(Orig->getPredicateFn());
1334 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001335 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001336
1337 // If this pattern cannot every match, do not include it as a variant.
1338 std::string ErrString;
1339 if (!R->canPatternMatch(ErrString, ISE)) {
1340 delete R;
1341 } else {
1342 bool AlreadyExists = false;
1343
1344 // Scan to see if this pattern has already been emitted. We can get
1345 // duplication due to things like commuting:
1346 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1347 // which are the same pattern. Ignore the dups.
1348 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1349 if (R->isIsomorphicTo(OutVariants[i])) {
1350 AlreadyExists = true;
1351 break;
1352 }
1353
1354 if (AlreadyExists)
1355 delete R;
1356 else
1357 OutVariants.push_back(R);
1358 }
1359
1360 // Increment indices to the next permutation.
1361 NotDone = false;
1362 // Look for something we can increment without causing a wrap-around.
1363 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1364 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1365 NotDone = true; // Found something to increment.
1366 break;
1367 }
1368 Idxs[IdxsIdx] = 0;
1369 }
1370 }
1371}
1372
Chris Lattneraf302912005-09-29 22:36:54 +00001373/// CombineChildVariants - A helper function for binary operators.
1374///
1375static void CombineChildVariants(TreePatternNode *Orig,
1376 const std::vector<TreePatternNode*> &LHS,
1377 const std::vector<TreePatternNode*> &RHS,
1378 std::vector<TreePatternNode*> &OutVariants,
1379 DAGISelEmitter &ISE) {
1380 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1381 ChildVariants.push_back(LHS);
1382 ChildVariants.push_back(RHS);
1383 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1384}
1385
1386
1387static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1388 std::vector<TreePatternNode *> &Children) {
1389 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1390 Record *Operator = N->getOperator();
1391
1392 // Only permit raw nodes.
1393 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1394 N->getTransformFn()) {
1395 Children.push_back(N);
1396 return;
1397 }
1398
1399 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1400 Children.push_back(N->getChild(0));
1401 else
1402 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1403
1404 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1405 Children.push_back(N->getChild(1));
1406 else
1407 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1408}
1409
Chris Lattnere46e17b2005-09-29 19:28:10 +00001410/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1411/// the (potentially recursive) pattern by using algebraic laws.
1412///
1413static void GenerateVariantsOf(TreePatternNode *N,
1414 std::vector<TreePatternNode*> &OutVariants,
1415 DAGISelEmitter &ISE) {
1416 // We cannot permute leaves.
1417 if (N->isLeaf()) {
1418 OutVariants.push_back(N);
1419 return;
1420 }
1421
1422 // Look up interesting info about the node.
1423 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1424
1425 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001426 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1427 // Reassociate by pulling together all of the linked operators
1428 std::vector<TreePatternNode*> MaximalChildren;
1429 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1430
1431 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1432 // permutations.
1433 if (MaximalChildren.size() == 3) {
1434 // Find the variants of all of our maximal children.
1435 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1436 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1437 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1438 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1439
1440 // There are only two ways we can permute the tree:
1441 // (A op B) op C and A op (B op C)
1442 // Within these forms, we can also permute A/B/C.
1443
1444 // Generate legal pair permutations of A/B/C.
1445 std::vector<TreePatternNode*> ABVariants;
1446 std::vector<TreePatternNode*> BAVariants;
1447 std::vector<TreePatternNode*> ACVariants;
1448 std::vector<TreePatternNode*> CAVariants;
1449 std::vector<TreePatternNode*> BCVariants;
1450 std::vector<TreePatternNode*> CBVariants;
1451 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1452 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1453 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1454 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1455 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1456 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1457
1458 // Combine those into the result: (x op x) op x
1459 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1460 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1461 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1462 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1463 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1464 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1465
1466 // Combine those into the result: x op (x op x)
1467 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1468 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1469 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1470 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1471 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1472 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1473 return;
1474 }
1475 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001476
1477 // Compute permutations of all children.
1478 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1479 ChildVariants.resize(N->getNumChildren());
1480 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1481 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1482
1483 // Build all permutations based on how the children were formed.
1484 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1485
1486 // If this node is commutative, consider the commuted order.
1487 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1488 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001489 // Consider the commuted order.
1490 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1491 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001492 }
1493}
1494
1495
Chris Lattnere97603f2005-09-28 19:27:25 +00001496// GenerateVariants - Generate variants. For example, commutative patterns can
1497// match multiple ways. Add them to PatternsToMatch as well.
1498void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001499
1500 DEBUG(std::cerr << "Generating instruction variants.\n");
1501
1502 // Loop over all of the patterns we've collected, checking to see if we can
1503 // generate variants of the instruction, through the exploitation of
1504 // identities. This permits the target to provide agressive matching without
1505 // the .td file having to contain tons of variants of instructions.
1506 //
1507 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1508 // intentionally do not reconsider these. Any variants of added patterns have
1509 // already been added.
1510 //
1511 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1512 std::vector<TreePatternNode*> Variants;
1513 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1514
1515 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001516 Variants.erase(Variants.begin()); // Remove the original pattern.
1517
1518 if (Variants.empty()) // No variants for this pattern.
1519 continue;
1520
1521 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1522 PatternsToMatch[i].first->dump();
1523 std::cerr << "\n");
1524
1525 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1526 TreePatternNode *Variant = Variants[v];
1527
1528 DEBUG(std::cerr << " VAR#" << v << ": ";
1529 Variant->dump();
1530 std::cerr << "\n");
1531
1532 // Scan to see if an instruction or explicit pattern already matches this.
1533 bool AlreadyExists = false;
1534 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1535 // Check to see if this variant already exists.
1536 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1537 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1538 AlreadyExists = true;
1539 break;
1540 }
1541 }
1542 // If we already have it, ignore the variant.
1543 if (AlreadyExists) continue;
1544
1545 // Otherwise, add it to the list of patterns we have.
1546 PatternsToMatch.push_back(std::make_pair(Variant,
1547 PatternsToMatch[i].second));
1548 }
1549
1550 DEBUG(std::cerr << "\n");
1551 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001552}
1553
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001554
Chris Lattner05814af2005-09-28 17:57:56 +00001555/// getPatternSize - Return the 'size' of this pattern. We want to match large
1556/// patterns before small ones. This is used to determine the size of a
1557/// pattern.
1558static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001559 assert(isExtIntegerVT(P->getExtType()) ||
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001560 isExtFloatingPointVT(P->getExtType()) ||
1561 P->getExtType() == MVT::isVoid && "Not a valid pattern node to size!");
Chris Lattner05814af2005-09-28 17:57:56 +00001562 unsigned Size = 1; // The node itself.
1563
1564 // Count children in the count if they are also nodes.
1565 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1566 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001567 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001568 Size += getPatternSize(Child);
Chris Lattner2f041d42005-10-19 04:41:05 +00001569 else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1570 ++Size; // Matches a ConstantSDNode.
1571 }
Chris Lattner05814af2005-09-28 17:57:56 +00001572 }
1573
1574 return Size;
1575}
1576
1577/// getResultPatternCost - Compute the number of instructions for this pattern.
1578/// This is a temporary hack. We should really include the instruction
1579/// latencies in this calculation.
1580static unsigned getResultPatternCost(TreePatternNode *P) {
1581 if (P->isLeaf()) return 0;
1582
1583 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1584 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1585 Cost += getResultPatternCost(P->getChild(i));
1586 return Cost;
1587}
1588
1589// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1590// In particular, we want to match maximal patterns first and lowest cost within
1591// a particular complexity first.
1592struct PatternSortingPredicate {
1593 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1594 DAGISelEmitter::PatternToMatch *RHS) {
1595 unsigned LHSSize = getPatternSize(LHS->first);
1596 unsigned RHSSize = getPatternSize(RHS->first);
1597 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1598 if (LHSSize < RHSSize) return false;
1599
1600 // If the patterns have equal complexity, compare generated instruction cost
1601 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1602 }
1603};
1604
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001605/// nodeHasChain - return true if TreePatternNode has the property
1606/// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1607/// a chain result.
1608static bool nodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1609{
1610 if (N->isLeaf()) return false;
1611
1612 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1613 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1614}
1615
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001616/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1617/// if the match fails. At this point, we already know that the opcode for N
1618/// matches, and the SDNode for the result has the RootName specified name.
1619void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001620 const std::string &RootName,
Evan Cheng66a48bb2005-12-01 00:18:45 +00001621 std::map<std::string,std::string> &VarMap,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001622 unsigned PatternNo,std::ostream &OS) {
Chris Lattner0614b622005-11-02 06:49:14 +00001623 if (N->isLeaf()) {
1624 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1625 OS << " if (cast<ConstantSDNode>(" << RootName
1626 << ")->getSignExtended() != " << II->getValue() << ")\n"
1627 << " goto P" << PatternNo << "Fail;\n";
1628 return;
1629 }
1630 assert(0 && "Cannot match this as a leaf value!");
1631 abort();
1632 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001633
1634 // If this node has a name associated with it, capture it in VarMap. If
1635 // we already saw this in the pattern, emit code to verify dagness.
1636 if (!N->getName().empty()) {
1637 std::string &VarMapEntry = VarMap[N->getName()];
1638 if (VarMapEntry.empty()) {
1639 VarMapEntry = RootName;
1640 } else {
1641 // If we get here, this is a second reference to a specific name. Since
1642 // we already have checked that the first reference is valid, we don't
1643 // have to recursively match it, just check that it's the same as the
1644 // previously named thing.
1645 OS << " if (" << VarMapEntry << " != " << RootName
1646 << ") goto P" << PatternNo << "Fail;\n";
1647 return;
1648 }
1649 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001650
1651
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001652 // Emit code to load the child nodes and match their contents recursively.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001653 unsigned OpNo = (unsigned) nodeHasChain(N, *this);
1654 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1655 OS << " SDOperand " << RootName << OpNo <<" = " << RootName
1656 << ".getOperand(" << OpNo << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001657 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001658
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001659 if (!Child->isLeaf()) {
1660 // If it's not a leaf, recursively match.
1661 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001662 OS << " if (" << RootName << OpNo << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001663 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001664 EmitMatchForPattern(Child, RootName + utostr(OpNo), VarMap, PatternNo,
1665 OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001666 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001667 // If this child has a name associated with it, capture it in VarMap. If
1668 // we already saw this in the pattern, emit code to verify dagness.
1669 if (!Child->getName().empty()) {
1670 std::string &VarMapEntry = VarMap[Child->getName()];
1671 if (VarMapEntry.empty()) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001672 VarMapEntry = RootName + utostr(OpNo);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001673 } else {
1674 // If we get here, this is a second reference to a specific name. Since
1675 // we already have checked that the first reference is valid, we don't
1676 // have to recursively match it, just check that it's the same as the
1677 // previously named thing.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001678 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
Chris Lattner72fe91c2005-09-24 00:40:24 +00001679 << ") goto P" << PatternNo << "Fail;\n";
1680 continue;
1681 }
1682 }
1683
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001684 // Handle leaves of various types.
Chris Lattner2f041d42005-10-19 04:41:05 +00001685 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1686 Record *LeafRec = DI->getDef();
Evan Cheng66a48bb2005-12-01 00:18:45 +00001687 if (LeafRec->isSubClassOf("RegisterClass") ||
1688 LeafRec->isSubClassOf("Register")) {
Chris Lattner2f041d42005-10-19 04:41:05 +00001689 // Handle register references. Nothing to do here.
1690 } else if (LeafRec->isSubClassOf("ValueType")) {
1691 // Make sure this is the specified value type.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001692 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
Chris Lattner2f041d42005-10-19 04:41:05 +00001693 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1694 << "Fail;\n";
Chris Lattner1531f202005-10-26 16:59:37 +00001695 } else if (LeafRec->isSubClassOf("CondCode")) {
1696 // Make sure this is the specified cond code.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001697 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
Chris Lattnera7ad1982005-10-26 17:02:02 +00001698 << ")->get() != " << "ISD::" << LeafRec->getName()
Chris Lattner1531f202005-10-26 16:59:37 +00001699 << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner2f041d42005-10-19 04:41:05 +00001700 } else {
1701 Child->dump();
1702 assert(0 && "Unknown leaf type!");
1703 }
1704 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001705 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1706 << " cast<ConstantSDNode>(" << RootName << OpNo
Chris Lattner9d1a0232005-10-29 16:39:40 +00001707 << ")->getSignExtended() != " << II->getValue() << ")\n"
Chris Lattner2f041d42005-10-19 04:41:05 +00001708 << " goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001709 } else {
1710 Child->dump();
1711 assert(0 && "Unknown leaf type!");
1712 }
1713 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001714 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001715
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001716 // If there is a node predicate for this, emit the call.
1717 if (!N->getPredicateFn().empty())
1718 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001719 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001720}
1721
Nate Begeman6510b222005-12-01 04:51:06 +00001722/// getRegisterValueType - Look up and return the first ValueType of specified
1723/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001724static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001725 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1726 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001727 return MVT::Other;
1728}
1729
1730
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001731/// EmitLeadChainForPattern - Emit the flag operands for the DAG that will be
1732/// built in CodeGenPatternResult.
1733void DAGISelEmitter::EmitLeadChainForPattern(TreePatternNode *N,
1734 const std::string &RootName,
1735 std::ostream &OS,
1736 bool &HasChain) {
1737 if (!N->isLeaf()) {
1738 Record *Op = N->getOperator();
1739 if (Op->isSubClassOf("Instruction")) {
1740 bool HasCtrlDep = Op->getValueAsBit("hasCtrlDep");
1741 unsigned OpNo = (unsigned) HasCtrlDep;
1742 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1743 EmitLeadChainForPattern(N->getChild(i), RootName + utostr(OpNo),
1744 OS, HasChain);
1745
1746 if (!HasChain && HasCtrlDep) {
1747 OS << " SDOperand Chain = Select("
1748 << RootName << ".getOperand(0));\n";
1749 HasChain = true;
1750 }
1751 }
1752 }
1753}
1754
Evan Cheng66a48bb2005-12-01 00:18:45 +00001755/// EmitCopyToRegsForPattern - Emit the flag operands for the DAG that will be
1756/// built in CodeGenPatternResult.
1757void DAGISelEmitter::EmitCopyToRegsForPattern(TreePatternNode *N,
1758 const std::string &RootName,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001759 std::ostream &OS,
1760 bool &HasChain, bool &InFlag) {
Evan Cheng66a48bb2005-12-01 00:18:45 +00001761 const CodeGenTarget &T = getTargetInfo();
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001762 unsigned OpNo = (unsigned) nodeHasChain(N, *this);
1763 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng66a48bb2005-12-01 00:18:45 +00001764 TreePatternNode *Child = N->getChild(i);
1765 if (!Child->isLeaf()) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001766 EmitCopyToRegsForPattern(Child, RootName + utostr(OpNo), OS, HasChain,
1767 InFlag);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001768 } else {
1769 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1770 Record *RR = DI->getDef();
1771 if (RR->isSubClassOf("Register")) {
1772 MVT::ValueType RVT = getRegisterValueType(RR, T);
1773 if (!InFlag) {
Chris Lattner7292c5e2005-12-05 00:48:51 +00001774 OS << " SDOperand InFlag = SDOperand(0,0);\n";
Evan Cheng66a48bb2005-12-01 00:18:45 +00001775 InFlag = true;
1776 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001777 if (HasChain) {
1778 OS << " SDOperand " << RootName << "CR" << i << ";\n";
1779 OS << " " << RootName << "CR" << i
1780 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
1781 << getQualifiedName(RR) << ", MVT::" << getEnumName(RVT) << ")"
1782 << ", Select(" << RootName << OpNo << "), InFlag);\n";
1783 OS << " Chain = " << RootName << "CR" << i
1784 << ".getValue(0);\n";
1785 OS << " InFlag = " << RootName << "CR" << i
1786 << ".getValue(1);\n";
1787 } else {
1788 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
1789 << ", CurDAG->getRegister(" << getQualifiedName(RR)
1790 << ", MVT::" << getEnumName(RVT) << ")"
1791 << ", Select(" << RootName << OpNo
1792 << "), InFlag).getValue(1);\n";
1793 }
Evan Cheng66a48bb2005-12-01 00:18:45 +00001794 }
1795 }
1796 }
1797 }
1798}
1799
Chris Lattner6bc7e512005-09-26 21:53:26 +00001800/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1801/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001802unsigned DAGISelEmitter::
1803CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1804 std::map<std::string,std::string> &VariableMap,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001805 std::ostream &OS, bool &HasChain, bool InFlag,
1806 bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001807 // This is something selected from the pattern we matched.
1808 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001809 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001810 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001811 assert(!Val.empty() &&
1812 "Variable referenced but not defined and not caught earlier!");
1813 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1814 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001815 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001816 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001817
1818 unsigned ResNo = Ctr++;
1819 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1820 switch (N->getType()) {
1821 default: assert(0 && "Unknown type for constant node!");
1822 case MVT::i1: OS << " bool Tmp"; break;
1823 case MVT::i8: OS << " unsigned char Tmp"; break;
1824 case MVT::i16: OS << " unsigned short Tmp"; break;
1825 case MVT::i32: OS << " unsigned Tmp"; break;
1826 case MVT::i64: OS << " uint64_t Tmp"; break;
1827 }
1828 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1829 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1830 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
Chris Lattnerb120a642005-11-17 07:39:45 +00001831 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1832 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Chris Lattnerf6f94162005-09-28 16:58:06 +00001833 } else {
1834 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1835 }
1836 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1837 // value if used multiple times by this pattern result.
1838 Val = "Tmp"+utostr(ResNo);
1839 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001840 }
1841
1842 if (N->isLeaf()) {
Chris Lattner4c593092005-10-19 02:07:26 +00001843 // If this is an explicit register reference, handle it.
1844 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1845 unsigned ResNo = Ctr++;
1846 if (DI->getDef()->isSubClassOf("Register")) {
1847 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1848 << getQualifiedName(DI->getDef()) << ", MVT::"
1849 << getEnumName(N->getType())
1850 << ");\n";
1851 return ResNo;
1852 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001853 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1854 unsigned ResNo = Ctr++;
1855 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1856 << II->getValue() << ", MVT::"
1857 << getEnumName(N->getType())
1858 << ");\n";
1859 return ResNo;
Chris Lattner4c593092005-10-19 02:07:26 +00001860 }
1861
Chris Lattner72fe91c2005-09-24 00:40:24 +00001862 N->dump();
1863 assert(0 && "Unknown leaf type!");
1864 return ~0U;
1865 }
1866
1867 Record *Op = N->getOperator();
1868 if (Op->isSubClassOf("Instruction")) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001869 bool HasCtrlDep = Op->getValueAsBit("hasCtrlDep");
1870
Chris Lattner72fe91c2005-09-24 00:40:24 +00001871 // Emit all of the operands.
1872 std::vector<unsigned> Ops;
1873 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001874 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr,
1875 VariableMap, OS, HasChain, InFlag));
Chris Lattner72fe91c2005-09-24 00:40:24 +00001876
1877 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1878 unsigned ResNo = Ctr++;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001879
1880 const DAGInstruction &Inst = getInstruction(Op);
1881 unsigned NumResults = Inst.getNumResults();
Chris Lattner72fe91c2005-09-24 00:40:24 +00001882
Chris Lattner5024d932005-10-16 01:41:58 +00001883 if (!isRoot) {
1884 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1885 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1886 << getEnumName(N->getType());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001887 unsigned LastOp = 0;
1888 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1889 LastOp = Ops[i];
1890 OS << ", Tmp" << LastOp;
1891 }
1892 OS << ");\n";
1893 if (HasCtrlDep) {
1894 // Must have at least one result
1895 OS << " Chain = Tmp" << LastOp << ".getValue("
1896 << NumResults << ");\n";
1897 }
1898 } else if (HasCtrlDep) {
1899 if (NumResults > 0)
1900 OS << " SDOperand Result = ";
1901 else
1902 OS << " Chain = CodeGenMap[N] = ";
1903 OS << "CurDAG->getTargetNode("
1904 << II.Namespace << "::" << II.TheDef->getName();
1905 if (NumResults > 0)
1906 OS << ", MVT::" << getEnumName(N->getType()); // TODO: multiple results?
1907 OS << ", MVT::Other";
Chris Lattner5024d932005-10-16 01:41:58 +00001908 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1909 OS << ", Tmp" << Ops[i];
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001910 OS << ", Chain";
1911 if (InFlag)
1912 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00001913 OS << ");\n";
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001914 if (NumResults > 0) {
1915 OS << " CodeGenMap[N.getValue(0)] = Result;\n";
1916 OS << " CodeGenMap[N.getValue(" << NumResults
1917 << ")] = Result.getValue(" << NumResults << ");\n";
1918 OS << " Chain = CodeGenMap[N].getValue(" << NumResults << ");\n";
1919 }
1920 if (NumResults == 0)
1921 OS << " return Chain;\n";
1922 else
1923 OS << " return (N.ResNo) ? Chain : CodeGenMap[N];\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001924 } else {
1925 // If this instruction is the root, and if there is only one use of it,
1926 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1927 OS << " if (N.Val->hasOneUse()) {\n";
Chris Lattner5d28ffd2005-11-30 23:08:45 +00001928 OS << " return CurDAG->SelectNodeTo(N.Val, "
Chris Lattner5024d932005-10-16 01:41:58 +00001929 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1930 << getEnumName(N->getType());
1931 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1932 OS << ", Tmp" << Ops[i];
Evan Cheng66a48bb2005-12-01 00:18:45 +00001933 if (InFlag)
1934 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00001935 OS << ");\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001936 OS << " } else {\n";
1937 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001938 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1939 << getEnumName(N->getType());
Chris Lattner5024d932005-10-16 01:41:58 +00001940 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1941 OS << ", Tmp" << Ops[i];
Evan Cheng66a48bb2005-12-01 00:18:45 +00001942 if (InFlag)
1943 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00001944 OS << ");\n";
1945 OS << " }\n";
1946 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001947 return ResNo;
1948 } else if (Op->isSubClassOf("SDNodeXForm")) {
1949 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001950 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr,
1951 VariableMap, OS, HasChain, InFlag);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001952
1953 unsigned ResNo = Ctr++;
1954 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1955 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001956 if (isRoot) {
1957 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1958 OS << " return Tmp" << ResNo << ";\n";
1959 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001960 return ResNo;
1961 } else {
1962 N->dump();
1963 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001964 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001965 }
1966}
1967
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001968/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1969/// type information from it.
1970static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001971 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001972 if (!N->isLeaf())
1973 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1974 RemoveAllTypes(N->getChild(i));
1975}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001976
Chris Lattner7e82f132005-10-15 21:34:21 +00001977/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1978/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1979/// 'Pat' may be missing types. If we find an unresolved type to add a check
1980/// for, this returns true otherwise false if Pat has all types.
1981static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001982 DAGISelEmitter &ISE,
Chris Lattner7e82f132005-10-15 21:34:21 +00001983 const std::string &Prefix, unsigned PatternNo,
1984 std::ostream &OS) {
1985 // Did we find one?
1986 if (!Pat->hasTypeSet()) {
1987 // Move a type over from 'other' to 'pat'.
1988 Pat->setType(Other->getType());
1989 OS << " if (" << Prefix << ".getValueType() != MVT::"
1990 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1991 return true;
1992 } else if (Pat->isLeaf()) {
1993 return false;
1994 }
1995
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001996 unsigned OpNo = (unsigned) nodeHasChain(Pat, ISE);
1997 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
Chris Lattner7e82f132005-10-15 21:34:21 +00001998 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001999 ISE, Prefix + utostr(OpNo), PatternNo, OS))
Chris Lattner7e82f132005-10-15 21:34:21 +00002000 return true;
2001 return false;
2002}
2003
Chris Lattner0614b622005-11-02 06:49:14 +00002004Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2005 Record *N = Records.getDef(Name);
2006 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
2007 return N;
2008}
2009
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002010/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2011/// stream to match the pattern, and generate the code for the match if it
2012/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002013void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2014 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002015 static unsigned PatternCount = 0;
2016 unsigned PatternNo = PatternCount++;
2017 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002018 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002019 OS << "\n // Emits: ";
2020 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002021 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00002022 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
2023 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002024
Chris Lattner8fc35682005-09-23 23:16:51 +00002025 // Emit the matcher, capturing named arguments in VariableMap.
2026 std::map<std::string,std::string> VariableMap;
2027 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002028
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002029 // TP - Get *SOME* tree pattern, we don't care which.
2030 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002031
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002032 // At this point, we know that we structurally match the pattern, but the
2033 // types of the nodes may not match. Figure out the fewest number of type
2034 // comparisons we need to emit. For example, if there is only one integer
2035 // type supported by a target, there should be no type comparisons at all for
2036 // integer patterns!
2037 //
2038 // To figure out the fewest number of type checks needed, clone the pattern,
2039 // remove the types, then perform type inference on the pattern as a whole.
2040 // If there are unresolved types, emit an explicit check for those types,
2041 // apply the type to the tree, then rerun type inference. Iterate until all
2042 // types are resolved.
2043 //
2044 TreePatternNode *Pat = Pattern.first->clone();
2045 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002046
2047 do {
2048 // Resolve/propagate as many types as possible.
2049 try {
2050 bool MadeChange = true;
2051 while (MadeChange)
2052 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2053 } catch (...) {
2054 assert(0 && "Error: could not find consistent types for something we"
2055 " already decided was ok!");
2056 abort();
2057 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002058
Chris Lattner7e82f132005-10-15 21:34:21 +00002059 // Insert a check for an unresolved type and add it to the tree. If we find
2060 // an unresolved type to add a check for, this returns true and we iterate,
2061 // otherwise we are done.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002062 } while (InsertOneTypeCheck(Pat, Pattern.first, *this, "N", PatternNo, OS));
2063
2064 bool HasChain = false;
2065 EmitLeadChainForPattern(Pattern.second, "N", OS, HasChain);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002066
2067 bool InFlag = false;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002068 EmitCopyToRegsForPattern(Pattern.first, "N", OS, HasChain, InFlag);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002069
Chris Lattner5024d932005-10-16 01:41:58 +00002070 unsigned TmpNo = 0;
Evan Cheng66a48bb2005-12-01 00:18:45 +00002071 CodeGenPatternResult(Pattern.second,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002072 TmpNo, VariableMap, OS, HasChain, InFlag, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002073 delete Pat;
2074
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002075 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002076}
2077
Chris Lattner37481472005-09-26 21:59:35 +00002078
2079namespace {
2080 /// CompareByRecordName - An ordering predicate that implements less-than by
2081 /// comparing the names records.
2082 struct CompareByRecordName {
2083 bool operator()(const Record *LHS, const Record *RHS) const {
2084 // Sort by name first.
2085 if (LHS->getName() < RHS->getName()) return true;
2086 // If both names are equal, sort by pointer.
2087 return LHS->getName() == RHS->getName() && LHS < RHS;
2088 }
2089 };
2090}
2091
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002092void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002093 std::string InstNS = Target.inst_begin()->second.Namespace;
2094 if (!InstNS.empty()) InstNS += "::";
2095
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002096 // Emit boilerplate.
2097 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002098 << "SDOperand SelectCode(SDOperand N) {\n"
2099 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002100 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2101 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002102 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00002103 << " if (!N.Val->hasOneUse()) {\n"
2104 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2105 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2106 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002107 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002108 << " default: break;\n"
2109 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002110 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002111 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002112 << " case ISD::AssertZext: {\n"
2113 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2114 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2115 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002116 << " }\n"
2117 << " case ISD::TokenFactor:\n"
2118 << " if (N.getNumOperands() == 2) {\n"
2119 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2120 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2121 << " return CodeGenMap[N] =\n"
2122 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2123 << " } else {\n"
2124 << " std::vector<SDOperand> Ops;\n"
2125 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2126 << " Ops.push_back(Select(N.getOperand(i)));\n"
2127 << " return CodeGenMap[N] = \n"
2128 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2129 << " }\n"
2130 << " case ISD::CopyFromReg: {\n"
2131 << " SDOperand Chain = Select(N.getOperand(0));\n"
2132 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2133 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
2134 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
2135 << " N.Val->getValueType(0));\n"
2136 << " return New.getValue(N.ResNo);\n"
2137 << " }\n"
2138 << " case ISD::CopyToReg: {\n"
2139 << " SDOperand Chain = Select(N.getOperand(0));\n"
2140 << " SDOperand Reg = N.getOperand(1);\n"
2141 << " SDOperand Val = Select(N.getOperand(2));\n"
2142 << " return CodeGenMap[N] = \n"
2143 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
2144 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002145 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002146
Chris Lattner81303322005-09-23 19:36:15 +00002147 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00002148 std::map<Record*, std::vector<PatternToMatch*>,
2149 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00002150 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
Chris Lattner0614b622005-11-02 06:49:14 +00002151 if (!PatternsToMatch[i].first->isLeaf()) {
2152 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
2153 .push_back(&PatternsToMatch[i]);
2154 } else {
2155 if (IntInit *II =
2156 dynamic_cast<IntInit*>(PatternsToMatch[i].first->getLeafValue())) {
2157 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2158 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00002159 std::cerr << "Unrecognized opcode '";
2160 PatternsToMatch[i].first->dump();
2161 std::cerr << "' on tree pattern '";
2162 std::cerr << PatternsToMatch[i].second->getOperator()->getName();
2163 std::cerr << "'!\n";
2164 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00002165 }
2166 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002167
Chris Lattner3f7e9142005-09-23 20:52:47 +00002168 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00002169 for (std::map<Record*, std::vector<PatternToMatch*>,
2170 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2171 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002172 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2173 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2174
2175 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002176
2177 // We want to emit all of the matching code now. However, we want to emit
2178 // the matches in order of minimal cost. Sort the patterns so the least
2179 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002180 std::stable_sort(Patterns.begin(), Patterns.end(),
2181 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00002182
Chris Lattner3f7e9142005-09-23 20:52:47 +00002183 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2184 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002185 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00002186 }
2187
2188
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002189 OS << " } // end of big switch.\n\n"
2190 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002191 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002192 << " std::cerr << '\\n';\n"
2193 << " abort();\n"
2194 << "}\n";
2195}
2196
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002197void DAGISelEmitter::run(std::ostream &OS) {
2198 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2199 " target", OS);
2200
Chris Lattner1f39e292005-09-14 00:09:24 +00002201 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2202 << "// *** instruction selector class. These functions are really "
2203 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002204
Chris Lattner296dfe32005-09-24 00:50:51 +00002205 OS << "// Instance var to keep track of multiply used nodes that have \n"
2206 << "// already been selected.\n"
2207 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2208
Chris Lattnerca559d02005-09-08 21:03:01 +00002209 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002210 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002211 ParsePatternFragments(OS);
2212 ParseInstructions();
2213 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002214
Chris Lattnere97603f2005-09-28 19:27:25 +00002215 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002216 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002217 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002218
Chris Lattnere46e17b2005-09-29 19:28:10 +00002219
2220 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2221 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2222 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
2223 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
2224 std::cerr << "\n";
2225 });
2226
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002227 // At this point, we have full information about the 'Patterns' we need to
2228 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002229 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002230 EmitInstructionSelector(OS);
2231
2232 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2233 E = PatternFragments.end(); I != E; ++I)
2234 delete I->second;
2235 PatternFragments.clear();
2236
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002237 Instructions.clear();
2238}