blob: cf5abc2de0eb9092ae3ca8a91719b549e496bc6b [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;
Evan Cheng0fc71982005-12-08 02:00:36 +0000480 } else if (R->isSubClassOf("ComplexPattern")) {
481 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
482 return T.getPointerType();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000483 } else if (R->getName() == "node") {
484 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000485 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000486 }
487
488 TP.error("Unknown node flavor used in pattern: " + R->getName());
489 return MVT::Other;
490}
491
Chris Lattner32707602005-09-08 23:22:48 +0000492/// ApplyTypeConstraints - Apply all of the type constraints relevent to
493/// this node and its children in the tree. This returns true if it makes a
494/// change, false otherwise. If a type contradiction is found, throw an
495/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000496bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
497 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000498 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000499 // If it's a regclass or something else known, include the type.
500 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
501 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000502 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
503 // Int inits are always integers. :)
504 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
505
506 if (hasTypeSet()) {
507 unsigned Size = MVT::getSizeInBits(getType());
508 // Make sure that the value is representable for this type.
509 if (Size < 32) {
510 int Val = (II->getValue() << (32-Size)) >> (32-Size);
511 if (Val != II->getValue())
512 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
513 "' is out of range for type 'MVT::" +
514 getEnumName(getType()) + "'!");
515 }
516 }
517
518 return MadeChange;
519 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000520 return false;
521 }
Chris Lattner32707602005-09-08 23:22:48 +0000522
523 // special handling for set, which isn't really an SDNode.
524 if (getOperator()->getName() == "set") {
525 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000526 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
527 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000528
529 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000530 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
531 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000532 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
533 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000534 } else if (getOperator()->isSubClassOf("SDNode")) {
535 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
536
537 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
538 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000539 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000540 // Branch, etc. do not produce results and top-level forms in instr pattern
541 // must have void types.
542 if (NI.getNumResults() == 0)
543 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000544 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000545 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000546 const DAGInstruction &Inst =
547 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000548 bool MadeChange = false;
549 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000550
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000551 assert(NumResults <= 1 &&
552 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000553 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000554 if (NumResults == 0) {
555 MadeChange = UpdateNodeType(MVT::isVoid, TP);
556 } else {
557 Record *ResultNode = Inst.getResult(0);
558 assert(ResultNode->isSubClassOf("RegisterClass") &&
559 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000560
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000561 const CodeGenRegisterClass &RC =
562 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000563
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000564 // Get the first ValueType in the RegClass, it's as good as any.
565 MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
566 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000567
568 if (getNumChildren() != Inst.getNumOperands())
569 TP.error("Instruction '" + getOperator()->getName() + " expects " +
570 utostr(Inst.getNumOperands()) + " operands, not " +
571 utostr(getNumChildren()) + " operands!");
572 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000573 Record *OperandNode = Inst.getOperand(i);
574 MVT::ValueType VT;
575 if (OperandNode->isSubClassOf("RegisterClass")) {
576 const CodeGenRegisterClass &RC =
577 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000578 VT = RC.getValueTypeNum(0);
Nate Begemanddb39542005-12-01 00:06:14 +0000579 } else if (OperandNode->isSubClassOf("Operand")) {
580 VT = getValueType(OperandNode->getValueAsDef("Type"));
581 } else {
582 assert(0 && "Unknown operand type!");
583 abort();
584 }
585
586 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000587 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000588 }
589 return MadeChange;
590 } else {
591 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
592
593 // Node transforms always take one operand, and take and return the same
594 // type.
595 if (getNumChildren() != 1)
596 TP.error("Node transform '" + getOperator()->getName() +
597 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000598 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
599 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000600 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000601 }
Chris Lattner32707602005-09-08 23:22:48 +0000602}
603
Chris Lattnere97603f2005-09-28 19:27:25 +0000604/// canPatternMatch - If it is impossible for this pattern to match on this
605/// target, fill in Reason and return false. Otherwise, return true. This is
606/// used as a santity check for .td files (to prevent people from writing stuff
607/// that can never possibly work), and to prevent the pattern permuter from
608/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000609bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000610 if (isLeaf()) return true;
611
612 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
613 if (!getChild(i)->canPatternMatch(Reason, ISE))
614 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000615
Chris Lattnere97603f2005-09-28 19:27:25 +0000616 // If this node is a commutative operator, check that the LHS isn't an
617 // immediate.
618 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
619 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
620 // Scan all of the operands of the node and make sure that only the last one
621 // is a constant node.
622 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
623 if (!getChild(i)->isLeaf() &&
624 getChild(i)->getOperator()->getName() == "imm") {
625 Reason = "Immediate value must be on the RHS of commutative operators!";
626 return false;
627 }
628 }
629
630 return true;
631}
Chris Lattner32707602005-09-08 23:22:48 +0000632
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000633//===----------------------------------------------------------------------===//
634// TreePattern implementation
635//
636
Chris Lattneredbd8712005-10-21 01:19:59 +0000637TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000638 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000639 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000640 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
641 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000642}
643
Chris Lattneredbd8712005-10-21 01:19:59 +0000644TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000645 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000646 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000647 Trees.push_back(ParseTreePattern(Pat));
648}
649
Chris Lattneredbd8712005-10-21 01:19:59 +0000650TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000651 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000652 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000653 Trees.push_back(Pat);
654}
655
656
657
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000658void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000659 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000660 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000661}
662
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000663TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
664 Record *Operator = Dag->getNodeType();
665
666 if (Operator->isSubClassOf("ValueType")) {
667 // If the operator is a ValueType, then this must be "type cast" of a leaf
668 // node.
669 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000670 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000671
672 Init *Arg = Dag->getArg(0);
673 TreePatternNode *New;
674 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000675 Record *R = DI->getDef();
676 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
677 Dag->setArg(0, new DagInit(R,
678 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000679 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000680 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000681 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000682 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
683 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000684 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
685 New = new TreePatternNode(II);
686 if (!Dag->getArgName(0).empty())
687 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000688 } else {
689 Arg->dump();
690 error("Unknown leaf value for tree pattern!");
691 return 0;
692 }
693
Chris Lattner32707602005-09-08 23:22:48 +0000694 // Apply the type cast.
695 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000696 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000697 return New;
698 }
699
700 // Verify that this is something that makes sense for an operator.
701 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000702 !Operator->isSubClassOf("Instruction") &&
703 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000704 Operator->getName() != "set")
705 error("Unrecognized node '" + Operator->getName() + "'!");
706
Chris Lattneredbd8712005-10-21 01:19:59 +0000707 // Check to see if this is something that is illegal in an input pattern.
708 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
709 Operator->isSubClassOf("SDNodeXForm")))
710 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
711
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000712 std::vector<TreePatternNode*> Children;
713
714 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
715 Init *Arg = Dag->getArg(i);
716 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
717 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000718 if (Children.back()->getName().empty())
719 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000720 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
721 Record *R = DefI->getDef();
722 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
723 // TreePatternNode if its own.
724 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
725 Dag->setArg(i, new DagInit(R,
726 std::vector<std::pair<Init*, std::string> >()));
727 --i; // Revisit this node...
728 } else {
729 TreePatternNode *Node = new TreePatternNode(DefI);
730 Node->setName(Dag->getArgName(i));
731 Children.push_back(Node);
732
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000733 // Input argument?
734 if (R->getName() == "node") {
735 if (Dag->getArgName(i).empty())
736 error("'node' argument requires a name to match with operand list");
737 Args.push_back(Dag->getArgName(i));
738 }
739 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000740 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
741 TreePatternNode *Node = new TreePatternNode(II);
742 if (!Dag->getArgName(i).empty())
743 error("Constant int argument should not have a name!");
744 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000745 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000746 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000747 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000748 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000749 error("Unknown leaf value for tree pattern!");
750 }
751 }
752
753 return new TreePatternNode(Operator, Children);
754}
755
Chris Lattner32707602005-09-08 23:22:48 +0000756/// InferAllTypes - Infer/propagate as many types throughout the expression
757/// patterns as possible. Return true if all types are infered, false
758/// otherwise. Throw an exception if a type contradiction is found.
759bool TreePattern::InferAllTypes() {
760 bool MadeChange = true;
761 while (MadeChange) {
762 MadeChange = false;
763 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000764 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000765 }
766
767 bool HasUnresolvedTypes = false;
768 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
769 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
770 return !HasUnresolvedTypes;
771}
772
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000773void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000774 OS << getRecord()->getName();
775 if (!Args.empty()) {
776 OS << "(" << Args[0];
777 for (unsigned i = 1, e = Args.size(); i != e; ++i)
778 OS << ", " << Args[i];
779 OS << ")";
780 }
781 OS << ": ";
782
783 if (Trees.size() > 1)
784 OS << "[\n";
785 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
786 OS << "\t";
787 Trees[i]->print(OS);
788 OS << "\n";
789 }
790
791 if (Trees.size() > 1)
792 OS << "]\n";
793}
794
795void TreePattern::dump() const { print(std::cerr); }
796
797
798
799//===----------------------------------------------------------------------===//
800// DAGISelEmitter implementation
801//
802
Chris Lattnerca559d02005-09-08 21:03:01 +0000803// Parse all of the SDNode definitions for the target, populating SDNodes.
804void DAGISelEmitter::ParseNodeInfo() {
805 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
806 while (!Nodes.empty()) {
807 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
808 Nodes.pop_back();
809 }
810}
811
Chris Lattner24eeeb82005-09-13 21:51:00 +0000812/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
813/// map, and emit them to the file as functions.
814void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
815 OS << "\n// Node transformations.\n";
816 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
817 while (!Xforms.empty()) {
818 Record *XFormNode = Xforms.back();
819 Record *SDNode = XFormNode->getValueAsDef("Opcode");
820 std::string Code = XFormNode->getValueAsCode("XFormFunction");
821 SDNodeXForms.insert(std::make_pair(XFormNode,
822 std::make_pair(SDNode, Code)));
823
Chris Lattner1048b7a2005-09-13 22:03:37 +0000824 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000825 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
826 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
827
Chris Lattner1048b7a2005-09-13 22:03:37 +0000828 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000829 << "(SDNode *" << C2 << ") {\n";
830 if (ClassName != "SDNode")
831 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
832 OS << Code << "\n}\n";
833 }
834
835 Xforms.pop_back();
836 }
837}
838
Evan Cheng0fc71982005-12-08 02:00:36 +0000839void DAGISelEmitter::ParseComplexPatterns() {
840 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
841 while (!AMs.empty()) {
842 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
843 AMs.pop_back();
844 }
845}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000846
847
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000848/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
849/// file, building up the PatternFragments map. After we've collected them all,
850/// inline fragments together as necessary, so that there are no references left
851/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000852///
853/// This also emits all of the predicate functions to the output file.
854///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000855void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000856 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
857
858 // First step, parse all of the fragments and emit predicate functions.
859 OS << "\n// Predicate functions.\n";
860 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000861 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000862 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000863 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000864
865 // Validate the argument list, converting it to map, to discard duplicates.
866 std::vector<std::string> &Args = P->getArgList();
867 std::set<std::string> OperandsMap(Args.begin(), Args.end());
868
869 if (OperandsMap.count(""))
870 P->error("Cannot have unnamed 'node' values in pattern fragment!");
871
872 // Parse the operands list.
873 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
874 if (OpsList->getNodeType()->getName() != "ops")
875 P->error("Operands list should start with '(ops ... '!");
876
877 // Copy over the arguments.
878 Args.clear();
879 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
880 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
881 static_cast<DefInit*>(OpsList->getArg(j))->
882 getDef()->getName() != "node")
883 P->error("Operands list should all be 'node' values.");
884 if (OpsList->getArgName(j).empty())
885 P->error("Operands list should have names for each operand!");
886 if (!OperandsMap.count(OpsList->getArgName(j)))
887 P->error("'" + OpsList->getArgName(j) +
888 "' does not occur in pattern or was multiply specified!");
889 OperandsMap.erase(OpsList->getArgName(j));
890 Args.push_back(OpsList->getArgName(j));
891 }
892
893 if (!OperandsMap.empty())
894 P->error("Operands list does not contain an entry for operand '" +
895 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000896
897 // If there is a code init for this fragment, emit the predicate code and
898 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000899 std::string Code = Fragments[i]->getValueAsCode("Predicate");
900 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000901 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000902 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000903 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000904 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
905
Chris Lattner1048b7a2005-09-13 22:03:37 +0000906 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000907 << "(SDNode *" << C2 << ") {\n";
908 if (ClassName != "SDNode")
909 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000910 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000911 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000912 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000913
914 // If there is a node transformation corresponding to this, keep track of
915 // it.
916 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
917 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000918 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000919 }
920
921 OS << "\n\n";
922
923 // Now that we've parsed all of the tree fragments, do a closure on them so
924 // that there are not references to PatFrags left inside of them.
925 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
926 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000927 TreePattern *ThePat = I->second;
928 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000929
Chris Lattner32707602005-09-08 23:22:48 +0000930 // Infer as many types as possible. Don't worry about it if we don't infer
931 // all of them, some may depend on the inputs of the pattern.
932 try {
933 ThePat->InferAllTypes();
934 } catch (...) {
935 // If this pattern fragment is not supported by this target (no types can
936 // satisfy its constraints), just ignore it. If the bogus pattern is
937 // actually used by instructions, the type consistency error will be
938 // reported there.
939 }
940
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000941 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000942 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000943 }
944}
945
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000946/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000947/// instruction input. Return true if this is a real use.
948static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000949 std::map<std::string, TreePatternNode*> &InstInputs) {
950 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000951 if (Pat->getName().empty()) {
952 if (Pat->isLeaf()) {
953 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
954 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
955 I->error("Input " + DI->getDef()->getName() + " must be named!");
956
957 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000958 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000959 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000960
961 Record *Rec;
962 if (Pat->isLeaf()) {
963 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
964 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
965 Rec = DI->getDef();
966 } else {
967 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
968 Rec = Pat->getOperator();
969 }
970
971 TreePatternNode *&Slot = InstInputs[Pat->getName()];
972 if (!Slot) {
973 Slot = Pat;
974 } else {
975 Record *SlotRec;
976 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000977 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000978 } else {
979 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
980 SlotRec = Slot->getOperator();
981 }
982
983 // Ensure that the inputs agree if we've already seen this input.
984 if (Rec != SlotRec)
985 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000986 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000987 I->error("All $" + Pat->getName() + " inputs must agree with each other");
988 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000989 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000990}
991
992/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
993/// part of "I", the instruction), computing the set of inputs and outputs of
994/// the pattern. Report errors if we see anything naughty.
995void DAGISelEmitter::
996FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
997 std::map<std::string, TreePatternNode*> &InstInputs,
998 std::map<std::string, Record*> &InstResults) {
999 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +00001000 bool isUse = HandleUse(I, Pat, InstInputs);
1001 if (!isUse && Pat->getTransformFn())
1002 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001003 return;
1004 } else if (Pat->getOperator()->getName() != "set") {
1005 // If this is not a set, verify that the children nodes are not void typed,
1006 // and recurse.
1007 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001008 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001009 I->error("Cannot have void nodes inside of patterns!");
1010 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
1011 }
1012
1013 // If this is a non-leaf node with no children, treat it basically as if
1014 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001015 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001016 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +00001017 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001018
Chris Lattnerf1311842005-09-14 23:05:13 +00001019 if (!isUse && Pat->getTransformFn())
1020 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001021 return;
1022 }
1023
1024 // Otherwise, this is a set, validate and collect instruction results.
1025 if (Pat->getNumChildren() == 0)
1026 I->error("set requires operands!");
1027 else if (Pat->getNumChildren() & 1)
1028 I->error("set requires an even number of operands");
1029
Chris Lattnerf1311842005-09-14 23:05:13 +00001030 if (Pat->getTransformFn())
1031 I->error("Cannot specify a transform function on a set node!");
1032
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001033 // Check the set destinations.
1034 unsigned NumValues = Pat->getNumChildren()/2;
1035 for (unsigned i = 0; i != NumValues; ++i) {
1036 TreePatternNode *Dest = Pat->getChild(i);
1037 if (!Dest->isLeaf())
1038 I->error("set destination should be a virtual register!");
1039
1040 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1041 if (!Val)
1042 I->error("set destination should be a virtual register!");
1043
1044 if (!Val->getDef()->isSubClassOf("RegisterClass"))
1045 I->error("set destination should be a virtual register!");
1046 if (Dest->getName().empty())
1047 I->error("set destination must have a name!");
1048 if (InstResults.count(Dest->getName()))
1049 I->error("cannot set '" + Dest->getName() +"' multiple times");
1050 InstResults[Dest->getName()] = Val->getDef();
1051
1052 // Verify and collect info from the computation.
1053 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1054 InstInputs, InstResults);
1055 }
1056}
1057
Evan Chengdd304dd2005-12-05 23:08:55 +00001058/// NodeHasChain - return true if TreePatternNode has the property
1059/// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1060/// a chain result.
1061static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1062{
1063 if (N->isLeaf()) return false;
1064 Record *Operator = N->getOperator();
1065 if (!Operator->isSubClassOf("SDNode")) return false;
1066
1067 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1068 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1069}
1070
1071static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1072{
1073 if (NodeHasChain(N, ISE))
1074 return true;
1075 else {
1076 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1077 TreePatternNode *Child = N->getChild(i);
1078 if (PatternHasCtrlDep(Child, ISE))
1079 return true;
1080 }
1081 }
1082
1083 return false;
1084}
1085
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001086
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001087/// ParseInstructions - Parse all of the instructions, inlining and resolving
1088/// any fragments involved. This populates the Instructions list with fully
1089/// resolved instructions.
1090void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001091 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1092
1093 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001094 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001095
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001096 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1097 LI = Instrs[i]->getValueAsListInit("Pattern");
1098
1099 // If there is no pattern, only collect minimal information about the
1100 // instruction for its operand list. We have to assume that there is one
1101 // result, as we have no detailed info.
1102 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001103 std::vector<Record*> Results;
1104 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001105
1106 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1107
1108 // Doesn't even define a result?
1109 if (InstInfo.OperandList.size() == 0)
1110 continue;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001111
1112 // FIXME: temporary hack...
1113 if (InstInfo.isReturn || InstInfo.isBranch || InstInfo.isCall ||
1114 InstInfo.isStore) {
1115 // These produce no results
1116 for (unsigned j = 0, e = InstInfo.OperandList.size(); j != e; ++j)
1117 Operands.push_back(InstInfo.OperandList[j].Rec);
1118 } else {
1119 // Assume the first operand is the result.
1120 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001121
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001122 // The rest are inputs.
1123 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1124 Operands.push_back(InstInfo.OperandList[j].Rec);
1125 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001126
1127 // Create and insert the instruction.
1128 Instructions.insert(std::make_pair(Instrs[i],
Nate Begemanddb39542005-12-01 00:06:14 +00001129 DAGInstruction(0, Results, Operands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001130 continue; // no pattern.
1131 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001132
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001133 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001134 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001135 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001136 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001137
Chris Lattner95f6b762005-09-08 23:26:30 +00001138 // Infer as many types as possible. If we cannot infer all of them, we can
1139 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001140 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001141 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001142
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001143 // InstInputs - Keep track of all of the inputs of the instruction, along
1144 // with the record they are declared as.
1145 std::map<std::string, TreePatternNode*> InstInputs;
1146
1147 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001148 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001149 std::map<std::string, Record*> InstResults;
1150
Chris Lattner1f39e292005-09-14 00:09:24 +00001151 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001152 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001153 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1154 TreePatternNode *Pat = I->getTree(j);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001155 if (Pat->getExtType() != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001156 I->error("Top-level forms in instruction pattern should have"
1157 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001158
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001159 // Find inputs and outputs, and verify the structure of the uses/defs.
1160 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001161 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001162
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001163 // Now that we have inputs and outputs of the pattern, inspect the operands
1164 // list for the instruction. This determines the order that operands are
1165 // added to the machine instruction the node corresponds to.
1166 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001167
1168 // Parse the operands list from the (ops) list, validating it.
1169 std::vector<std::string> &Args = I->getArgList();
1170 assert(Args.empty() && "Args list should still be empty here!");
1171 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1172
1173 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001174 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001175 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001176 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001177 I->error("'" + InstResults.begin()->first +
1178 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001179 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001180
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001181 // Check that it exists in InstResults.
1182 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001183 if (R == 0)
1184 I->error("Operand $" + OpName + " should be a set destination: all "
1185 "outputs must occur before inputs in operand list!");
1186
1187 if (CGI.OperandList[i].Rec != R)
1188 I->error("Operand $" + OpName + " class mismatch!");
1189
Chris Lattnerae6d8282005-09-15 21:51:12 +00001190 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001191 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001192
Chris Lattner39e8af92005-09-14 18:19:25 +00001193 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001194 InstResults.erase(OpName);
1195 }
1196
Chris Lattner0b592252005-09-14 21:59:34 +00001197 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1198 // the copy while we're checking the inputs.
1199 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001200
1201 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001202 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001203 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1204 const std::string &OpName = CGI.OperandList[i].Name;
1205 if (OpName.empty())
1206 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1207
Chris Lattner0b592252005-09-14 21:59:34 +00001208 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001209 I->error("Operand $" + OpName +
1210 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001211 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001212 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001213
1214 if (InVal->isLeaf() &&
1215 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1216 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001217 if (CGI.OperandList[i].Rec != InRec &&
1218 !InRec->isSubClassOf("ComplexPattern"))
Nate Begemanddb39542005-12-01 00:06:14 +00001219 I->error("Operand $" + OpName +
Evan Cheng0fc71982005-12-08 02:00:36 +00001220 "'s register class disagrees between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001221 }
1222 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001223
Chris Lattner2175c182005-09-14 23:01:59 +00001224 // Construct the result for the dest-pattern operand list.
1225 TreePatternNode *OpNode = InVal->clone();
1226
1227 // No predicate is useful on the result.
1228 OpNode->setPredicateFn("");
1229
1230 // Promote the xform function to be an explicit node if set.
1231 if (Record *Xform = OpNode->getTransformFn()) {
1232 OpNode->setTransformFn(0);
1233 std::vector<TreePatternNode*> Children;
1234 Children.push_back(OpNode);
1235 OpNode = new TreePatternNode(Xform, Children);
1236 }
1237
1238 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001239 }
1240
Chris Lattner0b592252005-09-14 21:59:34 +00001241 if (!InstInputsCheck.empty())
1242 I->error("Input operand $" + InstInputsCheck.begin()->first +
1243 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001244
1245 TreePatternNode *ResultPattern =
1246 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001247
1248 // Create and insert the instruction.
Nate Begemanddb39542005-12-01 00:06:14 +00001249 DAGInstruction TheInst(I, Results, Operands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001250 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1251
1252 // Use a temporary tree pattern to infer all types and make sure that the
1253 // constructed result is correct. This depends on the instruction already
1254 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001255 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001256 Temp.InferAllTypes();
1257
1258 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1259 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001260
Chris Lattner32707602005-09-08 23:22:48 +00001261 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001262 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001263
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001264 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001265 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1266 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001267 DAGInstruction &TheInst = II->second;
1268 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001269 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001270
Chris Lattner1f39e292005-09-14 00:09:24 +00001271 if (I->getNumTrees() != 1) {
1272 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1273 continue;
1274 }
1275 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001276 TreePatternNode *SrcPattern;
1277 if (TheInst.getNumResults() == 0) {
1278 SrcPattern = Pattern;
1279 } else {
1280 if (Pattern->getOperator()->getName() != "set")
1281 continue; // Not a set (store or something?)
Chris Lattner1f39e292005-09-14 00:09:24 +00001282
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001283 if (Pattern->getNumChildren() != 2)
1284 continue; // Not a set of a single value (not handled so far)
1285
1286 SrcPattern = Pattern->getChild(1)->clone();
1287 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001288
1289 std::string Reason;
1290 if (!SrcPattern->canPatternMatch(Reason, *this))
1291 I->error("Instruction can never match: " + Reason);
1292
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001293 TreePatternNode *DstPattern = TheInst.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001294 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Evan Chengdd304dd2005-12-05 23:08:55 +00001295
1296 if (PatternHasCtrlDep(Pattern, *this)) {
1297 Record *Instr = II->first;
1298 CodeGenInstruction &InstInfo = Target.getInstruction(Instr->getName());
1299 InstInfo.hasCtrlDep = true;
1300 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001301 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001302}
1303
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001304void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001305 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001306
Chris Lattnerabbb6052005-09-15 21:42:00 +00001307 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001308 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001309 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001310
Chris Lattnerabbb6052005-09-15 21:42:00 +00001311 // Inline pattern fragments into it.
1312 Pattern->InlinePatternFragments();
1313
1314 // Infer as many types as possible. If we cannot infer all of them, we can
1315 // never do anything with this pattern: report it to the user.
1316 if (!Pattern->InferAllTypes())
1317 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001318
1319 // Validate that the input pattern is correct.
1320 {
1321 std::map<std::string, TreePatternNode*> InstInputs;
1322 std::map<std::string, Record*> InstResults;
1323 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1324 InstInputs, InstResults);
1325 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001326
1327 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1328 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001329
1330 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001331 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001332
1333 // Inline pattern fragments into it.
1334 Result->InlinePatternFragments();
1335
1336 // Infer as many types as possible. If we cannot infer all of them, we can
1337 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001338 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001339 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001340
1341 if (Result->getNumTrees() != 1)
1342 Result->error("Cannot handle instructions producing instructions "
1343 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001344
1345 std::string Reason;
1346 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1347 Pattern->error("Pattern can never match: " + Reason);
1348
Chris Lattnerabbb6052005-09-15 21:42:00 +00001349 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1350 Result->getOnlyTree()));
1351 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001352}
1353
Chris Lattnere46e17b2005-09-29 19:28:10 +00001354/// CombineChildVariants - Given a bunch of permutations of each child of the
1355/// 'operator' node, put them together in all possible ways.
1356static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001357 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001358 std::vector<TreePatternNode*> &OutVariants,
1359 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001360 // Make sure that each operand has at least one variant to choose from.
1361 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1362 if (ChildVariants[i].empty())
1363 return;
1364
Chris Lattnere46e17b2005-09-29 19:28:10 +00001365 // The end result is an all-pairs construction of the resultant pattern.
1366 std::vector<unsigned> Idxs;
1367 Idxs.resize(ChildVariants.size());
1368 bool NotDone = true;
1369 while (NotDone) {
1370 // Create the variant and add it to the output list.
1371 std::vector<TreePatternNode*> NewChildren;
1372 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1373 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1374 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1375
1376 // Copy over properties.
1377 R->setName(Orig->getName());
1378 R->setPredicateFn(Orig->getPredicateFn());
1379 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001380 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001381
1382 // If this pattern cannot every match, do not include it as a variant.
1383 std::string ErrString;
1384 if (!R->canPatternMatch(ErrString, ISE)) {
1385 delete R;
1386 } else {
1387 bool AlreadyExists = false;
1388
1389 // Scan to see if this pattern has already been emitted. We can get
1390 // duplication due to things like commuting:
1391 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1392 // which are the same pattern. Ignore the dups.
1393 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1394 if (R->isIsomorphicTo(OutVariants[i])) {
1395 AlreadyExists = true;
1396 break;
1397 }
1398
1399 if (AlreadyExists)
1400 delete R;
1401 else
1402 OutVariants.push_back(R);
1403 }
1404
1405 // Increment indices to the next permutation.
1406 NotDone = false;
1407 // Look for something we can increment without causing a wrap-around.
1408 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1409 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1410 NotDone = true; // Found something to increment.
1411 break;
1412 }
1413 Idxs[IdxsIdx] = 0;
1414 }
1415 }
1416}
1417
Chris Lattneraf302912005-09-29 22:36:54 +00001418/// CombineChildVariants - A helper function for binary operators.
1419///
1420static void CombineChildVariants(TreePatternNode *Orig,
1421 const std::vector<TreePatternNode*> &LHS,
1422 const std::vector<TreePatternNode*> &RHS,
1423 std::vector<TreePatternNode*> &OutVariants,
1424 DAGISelEmitter &ISE) {
1425 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1426 ChildVariants.push_back(LHS);
1427 ChildVariants.push_back(RHS);
1428 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1429}
1430
1431
1432static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1433 std::vector<TreePatternNode *> &Children) {
1434 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1435 Record *Operator = N->getOperator();
1436
1437 // Only permit raw nodes.
1438 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1439 N->getTransformFn()) {
1440 Children.push_back(N);
1441 return;
1442 }
1443
1444 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1445 Children.push_back(N->getChild(0));
1446 else
1447 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1448
1449 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1450 Children.push_back(N->getChild(1));
1451 else
1452 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1453}
1454
Chris Lattnere46e17b2005-09-29 19:28:10 +00001455/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1456/// the (potentially recursive) pattern by using algebraic laws.
1457///
1458static void GenerateVariantsOf(TreePatternNode *N,
1459 std::vector<TreePatternNode*> &OutVariants,
1460 DAGISelEmitter &ISE) {
1461 // We cannot permute leaves.
1462 if (N->isLeaf()) {
1463 OutVariants.push_back(N);
1464 return;
1465 }
1466
1467 // Look up interesting info about the node.
1468 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1469
1470 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001471 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1472 // Reassociate by pulling together all of the linked operators
1473 std::vector<TreePatternNode*> MaximalChildren;
1474 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1475
1476 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1477 // permutations.
1478 if (MaximalChildren.size() == 3) {
1479 // Find the variants of all of our maximal children.
1480 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1481 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1482 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1483 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1484
1485 // There are only two ways we can permute the tree:
1486 // (A op B) op C and A op (B op C)
1487 // Within these forms, we can also permute A/B/C.
1488
1489 // Generate legal pair permutations of A/B/C.
1490 std::vector<TreePatternNode*> ABVariants;
1491 std::vector<TreePatternNode*> BAVariants;
1492 std::vector<TreePatternNode*> ACVariants;
1493 std::vector<TreePatternNode*> CAVariants;
1494 std::vector<TreePatternNode*> BCVariants;
1495 std::vector<TreePatternNode*> CBVariants;
1496 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1497 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1498 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1499 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1500 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1501 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1502
1503 // Combine those into the result: (x op x) op x
1504 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1505 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1506 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1507 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1508 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1509 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1510
1511 // Combine those into the result: x op (x op x)
1512 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1513 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1514 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1515 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1516 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1517 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1518 return;
1519 }
1520 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001521
1522 // Compute permutations of all children.
1523 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1524 ChildVariants.resize(N->getNumChildren());
1525 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1526 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1527
1528 // Build all permutations based on how the children were formed.
1529 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1530
1531 // If this node is commutative, consider the commuted order.
1532 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1533 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001534 // Consider the commuted order.
1535 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1536 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001537 }
1538}
1539
1540
Chris Lattnere97603f2005-09-28 19:27:25 +00001541// GenerateVariants - Generate variants. For example, commutative patterns can
1542// match multiple ways. Add them to PatternsToMatch as well.
1543void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001544
1545 DEBUG(std::cerr << "Generating instruction variants.\n");
1546
1547 // Loop over all of the patterns we've collected, checking to see if we can
1548 // generate variants of the instruction, through the exploitation of
1549 // identities. This permits the target to provide agressive matching without
1550 // the .td file having to contain tons of variants of instructions.
1551 //
1552 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1553 // intentionally do not reconsider these. Any variants of added patterns have
1554 // already been added.
1555 //
1556 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1557 std::vector<TreePatternNode*> Variants;
1558 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1559
1560 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001561 Variants.erase(Variants.begin()); // Remove the original pattern.
1562
1563 if (Variants.empty()) // No variants for this pattern.
1564 continue;
1565
1566 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1567 PatternsToMatch[i].first->dump();
1568 std::cerr << "\n");
1569
1570 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1571 TreePatternNode *Variant = Variants[v];
1572
1573 DEBUG(std::cerr << " VAR#" << v << ": ";
1574 Variant->dump();
1575 std::cerr << "\n");
1576
1577 // Scan to see if an instruction or explicit pattern already matches this.
1578 bool AlreadyExists = false;
1579 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1580 // Check to see if this variant already exists.
1581 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1582 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1583 AlreadyExists = true;
1584 break;
1585 }
1586 }
1587 // If we already have it, ignore the variant.
1588 if (AlreadyExists) continue;
1589
1590 // Otherwise, add it to the list of patterns we have.
1591 PatternsToMatch.push_back(std::make_pair(Variant,
1592 PatternsToMatch[i].second));
1593 }
1594
1595 DEBUG(std::cerr << "\n");
1596 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001597}
1598
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001599
Evan Cheng0fc71982005-12-08 02:00:36 +00001600// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1601// ComplexPattern.
1602static bool NodeIsComplexPattern(TreePatternNode *N)
1603{
1604 return (N->isLeaf() &&
1605 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1606 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1607 isSubClassOf("ComplexPattern"));
1608}
1609
1610// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1611// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1612static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1613 DAGISelEmitter &ISE)
1614{
1615 if (N->isLeaf() &&
1616 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1617 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1618 isSubClassOf("ComplexPattern")) {
1619 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1620 ->getDef());
1621 }
1622 return NULL;
1623}
1624
Chris Lattner05814af2005-09-28 17:57:56 +00001625/// getPatternSize - Return the 'size' of this pattern. We want to match large
1626/// patterns before small ones. This is used to determine the size of a
1627/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001628static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001629 assert(isExtIntegerVT(P->getExtType()) ||
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001630 isExtFloatingPointVT(P->getExtType()) ||
1631 P->getExtType() == MVT::isVoid && "Not a valid pattern node to size!");
Chris Lattner05814af2005-09-28 17:57:56 +00001632 unsigned Size = 1; // The node itself.
Evan Cheng0fc71982005-12-08 02:00:36 +00001633
1634 // FIXME: This is a hack to statically increase the priority of patterns
1635 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1636 // Later we can allow complexity / cost for each pattern to be (optionally)
1637 // specified. To get best possible pattern match we'll need to dynamically
1638 // calculate the complexity of all patterns a dag can potentially map to.
1639 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1640 if (AM)
1641 Size += AM->getNumOperands();
1642
Chris Lattner05814af2005-09-28 17:57:56 +00001643 // Count children in the count if they are also nodes.
1644 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1645 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001646 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001647 Size += getPatternSize(Child, ISE);
1648 else if (Child->isLeaf()) {
1649 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1650 ++Size; // Matches a ConstantSDNode.
1651 else if (NodeIsComplexPattern(Child))
1652 Size += getPatternSize(Child, ISE);
Chris Lattner2f041d42005-10-19 04:41:05 +00001653 }
Chris Lattner05814af2005-09-28 17:57:56 +00001654 }
1655
1656 return Size;
1657}
1658
1659/// getResultPatternCost - Compute the number of instructions for this pattern.
1660/// This is a temporary hack. We should really include the instruction
1661/// latencies in this calculation.
1662static unsigned getResultPatternCost(TreePatternNode *P) {
1663 if (P->isLeaf()) return 0;
1664
1665 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1666 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1667 Cost += getResultPatternCost(P->getChild(i));
1668 return Cost;
1669}
1670
1671// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1672// In particular, we want to match maximal patterns first and lowest cost within
1673// a particular complexity first.
1674struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001675 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1676 DAGISelEmitter &ISE;
1677
Chris Lattner05814af2005-09-28 17:57:56 +00001678 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1679 DAGISelEmitter::PatternToMatch *RHS) {
Evan Cheng0fc71982005-12-08 02:00:36 +00001680 unsigned LHSSize = getPatternSize(LHS->first, ISE);
1681 unsigned RHSSize = getPatternSize(RHS->first, ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001682 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1683 if (LHSSize < RHSSize) return false;
1684
1685 // If the patterns have equal complexity, compare generated instruction cost
1686 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1687 }
1688};
1689
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001690/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1691/// if the match fails. At this point, we already know that the opcode for N
1692/// matches, and the SDNode for the result has the RootName specified name.
1693void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001694 const std::string &RootName,
Evan Cheng66a48bb2005-12-01 00:18:45 +00001695 std::map<std::string,std::string> &VarMap,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001696 unsigned PatternNo,std::ostream &OS) {
Chris Lattner0614b622005-11-02 06:49:14 +00001697 if (N->isLeaf()) {
1698 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1699 OS << " if (cast<ConstantSDNode>(" << RootName
1700 << ")->getSignExtended() != " << II->getValue() << ")\n"
1701 << " goto P" << PatternNo << "Fail;\n";
1702 return;
Evan Cheng0fc71982005-12-08 02:00:36 +00001703 } else if (!NodeIsComplexPattern(N)) {
1704 assert(0 && "Cannot match this as a leaf value!");
1705 abort();
Chris Lattner0614b622005-11-02 06:49:14 +00001706 }
Chris Lattner0614b622005-11-02 06:49:14 +00001707 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001708
1709 // If this node has a name associated with it, capture it in VarMap. If
1710 // we already saw this in the pattern, emit code to verify dagness.
1711 if (!N->getName().empty()) {
1712 std::string &VarMapEntry = VarMap[N->getName()];
1713 if (VarMapEntry.empty()) {
1714 VarMapEntry = RootName;
1715 } else {
1716 // If we get here, this is a second reference to a specific name. Since
1717 // we already have checked that the first reference is valid, we don't
1718 // have to recursively match it, just check that it's the same as the
1719 // previously named thing.
1720 OS << " if (" << VarMapEntry << " != " << RootName
1721 << ") goto P" << PatternNo << "Fail;\n";
1722 return;
1723 }
1724 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001725
1726
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001727 // Emit code to load the child nodes and match their contents recursively.
Evan Chengdd304dd2005-12-05 23:08:55 +00001728 unsigned OpNo = (unsigned) NodeHasChain(N, *this);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001729 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1730 OS << " SDOperand " << RootName << OpNo <<" = " << RootName
1731 << ".getOperand(" << OpNo << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001732 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001733
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001734 if (!Child->isLeaf()) {
1735 // If it's not a leaf, recursively match.
1736 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001737 OS << " if (" << RootName << OpNo << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001738 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001739 EmitMatchForPattern(Child, RootName + utostr(OpNo), VarMap, PatternNo,
1740 OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001741 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001742 // If this child has a name associated with it, capture it in VarMap. If
1743 // we already saw this in the pattern, emit code to verify dagness.
1744 if (!Child->getName().empty()) {
1745 std::string &VarMapEntry = VarMap[Child->getName()];
1746 if (VarMapEntry.empty()) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001747 VarMapEntry = RootName + utostr(OpNo);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001748 } else {
1749 // If we get here, this is a second reference to a specific name. Since
1750 // we already have checked that the first reference is valid, we don't
1751 // have to recursively match it, just check that it's the same as the
1752 // previously named thing.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001753 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
Chris Lattner72fe91c2005-09-24 00:40:24 +00001754 << ") goto P" << PatternNo << "Fail;\n";
1755 continue;
1756 }
1757 }
1758
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001759 // Handle leaves of various types.
Chris Lattner2f041d42005-10-19 04:41:05 +00001760 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1761 Record *LeafRec = DI->getDef();
Evan Cheng66a48bb2005-12-01 00:18:45 +00001762 if (LeafRec->isSubClassOf("RegisterClass") ||
1763 LeafRec->isSubClassOf("Register")) {
Chris Lattner2f041d42005-10-19 04:41:05 +00001764 // Handle register references. Nothing to do here.
Evan Cheng0fc71982005-12-08 02:00:36 +00001765 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1766 // Handle complex pattern. Nothing to do here.
Chris Lattner2f041d42005-10-19 04:41:05 +00001767 } else if (LeafRec->isSubClassOf("ValueType")) {
1768 // Make sure this is the specified value type.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001769 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
Chris Lattner2f041d42005-10-19 04:41:05 +00001770 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1771 << "Fail;\n";
Chris Lattner1531f202005-10-26 16:59:37 +00001772 } else if (LeafRec->isSubClassOf("CondCode")) {
1773 // Make sure this is the specified cond code.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001774 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
Chris Lattnera7ad1982005-10-26 17:02:02 +00001775 << ")->get() != " << "ISD::" << LeafRec->getName()
Chris Lattner1531f202005-10-26 16:59:37 +00001776 << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner2f041d42005-10-19 04:41:05 +00001777 } else {
1778 Child->dump();
1779 assert(0 && "Unknown leaf type!");
1780 }
1781 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001782 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1783 << " cast<ConstantSDNode>(" << RootName << OpNo
Chris Lattner9d1a0232005-10-29 16:39:40 +00001784 << ")->getSignExtended() != " << II->getValue() << ")\n"
Chris Lattner2f041d42005-10-19 04:41:05 +00001785 << " goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001786 } else {
1787 Child->dump();
1788 assert(0 && "Unknown leaf type!");
1789 }
1790 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001791 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001792
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001793 // If there is a node predicate for this, emit the call.
1794 if (!N->getPredicateFn().empty())
1795 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001796 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001797}
1798
Nate Begeman6510b222005-12-01 04:51:06 +00001799/// getRegisterValueType - Look up and return the first ValueType of specified
1800/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001801static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001802 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1803 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001804 return MVT::Other;
1805}
1806
1807
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001808/// EmitLeadChainForPattern - Emit the flag operands for the DAG that will be
1809/// built in CodeGenPatternResult.
1810void DAGISelEmitter::EmitLeadChainForPattern(TreePatternNode *N,
1811 const std::string &RootName,
1812 std::ostream &OS,
1813 bool &HasChain) {
1814 if (!N->isLeaf()) {
Evan Chengdd304dd2005-12-05 23:08:55 +00001815 bool hc = NodeHasChain(N, *this);
1816 unsigned OpNo = (unsigned) hc;
1817 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1818 EmitLeadChainForPattern(N->getChild(i), RootName + utostr(OpNo),
1819 OS, HasChain);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001820
Evan Chengdd304dd2005-12-05 23:08:55 +00001821 if (!HasChain && hc) {
1822 OS << " SDOperand Chain = Select("
1823 << RootName << ".getOperand(0));\n";
1824 HasChain = true;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001825 }
1826 }
1827}
1828
Evan Cheng66a48bb2005-12-01 00:18:45 +00001829/// EmitCopyToRegsForPattern - Emit the flag operands for the DAG that will be
1830/// built in CodeGenPatternResult.
1831void DAGISelEmitter::EmitCopyToRegsForPattern(TreePatternNode *N,
1832 const std::string &RootName,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001833 std::ostream &OS,
1834 bool &HasChain, bool &InFlag) {
Evan Cheng66a48bb2005-12-01 00:18:45 +00001835 const CodeGenTarget &T = getTargetInfo();
Evan Chengdd304dd2005-12-05 23:08:55 +00001836 unsigned OpNo = (unsigned) NodeHasChain(N, *this);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001837 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng66a48bb2005-12-01 00:18:45 +00001838 TreePatternNode *Child = N->getChild(i);
1839 if (!Child->isLeaf()) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001840 EmitCopyToRegsForPattern(Child, RootName + utostr(OpNo), OS, HasChain,
1841 InFlag);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001842 } else {
1843 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1844 Record *RR = DI->getDef();
1845 if (RR->isSubClassOf("Register")) {
1846 MVT::ValueType RVT = getRegisterValueType(RR, T);
1847 if (!InFlag) {
Chris Lattner7292c5e2005-12-05 00:48:51 +00001848 OS << " SDOperand InFlag = SDOperand(0,0);\n";
Evan Cheng66a48bb2005-12-01 00:18:45 +00001849 InFlag = true;
1850 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001851 if (HasChain) {
1852 OS << " SDOperand " << RootName << "CR" << i << ";\n";
1853 OS << " " << RootName << "CR" << i
1854 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
1855 << getQualifiedName(RR) << ", MVT::" << getEnumName(RVT) << ")"
1856 << ", Select(" << RootName << OpNo << "), InFlag);\n";
1857 OS << " Chain = " << RootName << "CR" << i
1858 << ".getValue(0);\n";
1859 OS << " InFlag = " << RootName << "CR" << i
1860 << ".getValue(1);\n";
1861 } else {
1862 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
1863 << ", CurDAG->getRegister(" << getQualifiedName(RR)
1864 << ", MVT::" << getEnumName(RVT) << ")"
1865 << ", Select(" << RootName << OpNo
1866 << "), InFlag).getValue(1);\n";
1867 }
Evan Cheng66a48bb2005-12-01 00:18:45 +00001868 }
1869 }
1870 }
1871 }
1872}
1873
Chris Lattner6bc7e512005-09-26 21:53:26 +00001874/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1875/// matched, we actually have to build a DAG!
Evan Cheng0fc71982005-12-08 02:00:36 +00001876std::pair<unsigned, unsigned> DAGISelEmitter::
Chris Lattner72fe91c2005-09-24 00:40:24 +00001877CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1878 std::map<std::string,std::string> &VariableMap,
Evan Cheng0fc71982005-12-08 02:00:36 +00001879 unsigned PatternNo,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001880 std::ostream &OS, bool &HasChain, bool InFlag,
1881 bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001882 // This is something selected from the pattern we matched.
1883 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001884 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001885 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001886 assert(!Val.empty() &&
1887 "Variable referenced but not defined and not caught earlier!");
1888 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1889 // Already selected this operand, just return the tmpval.
Evan Cheng0fc71982005-12-08 02:00:36 +00001890 return std::make_pair(1, atoi(Val.c_str()+3));
Chris Lattner72fe91c2005-09-24 00:40:24 +00001891 }
Evan Cheng0fc71982005-12-08 02:00:36 +00001892
1893 const ComplexPattern *CP;
Chris Lattnerf6f94162005-09-28 16:58:06 +00001894 unsigned ResNo = Ctr++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001895 unsigned NumRes = 1;
Chris Lattnerf6f94162005-09-28 16:58:06 +00001896 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1897 switch (N->getType()) {
1898 default: assert(0 && "Unknown type for constant node!");
1899 case MVT::i1: OS << " bool Tmp"; break;
1900 case MVT::i8: OS << " unsigned char Tmp"; break;
1901 case MVT::i16: OS << " unsigned short Tmp"; break;
1902 case MVT::i32: OS << " unsigned Tmp"; break;
1903 case MVT::i64: OS << " uint64_t Tmp"; break;
1904 }
1905 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1906 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1907 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
Chris Lattnerb120a642005-11-17 07:39:45 +00001908 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1909 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Evan Cheng0fc71982005-12-08 02:00:36 +00001910 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, *this))) {
1911 std::string Fn = CP->getSelectFunc();
1912 NumRes = CP->getNumOperands();
1913 OS << " SDOperand ";
1914 for (unsigned i = 0; i < NumRes; i++) {
1915 if (i != 0) OS << ", ";
1916 OS << "Tmp" << i + ResNo;
1917 }
1918 OS << ";\n";
1919 OS << " if (!" << Fn << "(" << Val;
1920 for (unsigned i = 0; i < NumRes; i++)
1921 OS << " , Tmp" << i + ResNo;
1922 OS << ")) goto P" << PatternNo << "Fail;\n";
1923 Ctr = ResNo + NumRes;
Chris Lattnerf6f94162005-09-28 16:58:06 +00001924 } else {
1925 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1926 }
1927 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1928 // value if used multiple times by this pattern result.
1929 Val = "Tmp"+utostr(ResNo);
Evan Cheng0fc71982005-12-08 02:00:36 +00001930 return std::make_pair(NumRes, ResNo);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001931 }
1932
1933 if (N->isLeaf()) {
Chris Lattner4c593092005-10-19 02:07:26 +00001934 // If this is an explicit register reference, handle it.
1935 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1936 unsigned ResNo = Ctr++;
1937 if (DI->getDef()->isSubClassOf("Register")) {
1938 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1939 << getQualifiedName(DI->getDef()) << ", MVT::"
1940 << getEnumName(N->getType())
1941 << ");\n";
Evan Cheng0fc71982005-12-08 02:00:36 +00001942 return std::make_pair(1, ResNo);
Chris Lattner4c593092005-10-19 02:07:26 +00001943 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001944 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1945 unsigned ResNo = Ctr++;
1946 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1947 << II->getValue() << ", MVT::"
1948 << getEnumName(N->getType())
1949 << ");\n";
Evan Cheng0fc71982005-12-08 02:00:36 +00001950 return std::make_pair(1, ResNo);
Chris Lattner4c593092005-10-19 02:07:26 +00001951 }
1952
Chris Lattner72fe91c2005-09-24 00:40:24 +00001953 N->dump();
1954 assert(0 && "Unknown leaf type!");
Evan Cheng0fc71982005-12-08 02:00:36 +00001955 return std::make_pair(1, ~0U);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001956 }
1957
1958 Record *Op = N->getOperator();
1959 if (Op->isSubClassOf("Instruction")) {
1960 // Emit all of the operands.
1961 std::vector<unsigned> Ops;
Evan Cheng0fc71982005-12-08 02:00:36 +00001962 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1963 TreePatternNode *Child = N->getChild(i);
1964 std::pair<unsigned, unsigned> NOPair =
1965 CodeGenPatternResult(Child, Ctr,
1966 VariableMap, PatternNo, OS, HasChain, InFlag);
1967 for (unsigned j = 0; j < NOPair.first; j++)
1968 Ops.push_back(NOPair.second + j);
1969 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001970
1971 CodeGenInstruction &II = Target.getInstruction(Op->getName());
Evan Chengdd304dd2005-12-05 23:08:55 +00001972 bool HasCtrlDep = II.hasCtrlDep;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001973 unsigned ResNo = Ctr++;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001974
1975 const DAGInstruction &Inst = getInstruction(Op);
1976 unsigned NumResults = Inst.getNumResults();
Chris Lattner72fe91c2005-09-24 00:40:24 +00001977
Chris Lattner5024d932005-10-16 01:41:58 +00001978 if (!isRoot) {
1979 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1980 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1981 << getEnumName(N->getType());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001982 unsigned LastOp = 0;
1983 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1984 LastOp = Ops[i];
1985 OS << ", Tmp" << LastOp;
1986 }
1987 OS << ");\n";
1988 if (HasCtrlDep) {
1989 // Must have at least one result
1990 OS << " Chain = Tmp" << LastOp << ".getValue("
1991 << NumResults << ");\n";
1992 }
1993 } else if (HasCtrlDep) {
1994 if (NumResults > 0)
1995 OS << " SDOperand Result = ";
1996 else
1997 OS << " Chain = CodeGenMap[N] = ";
1998 OS << "CurDAG->getTargetNode("
1999 << II.Namespace << "::" << II.TheDef->getName();
2000 if (NumResults > 0)
2001 OS << ", MVT::" << getEnumName(N->getType()); // TODO: multiple results?
2002 OS << ", MVT::Other";
Chris Lattner5024d932005-10-16 01:41:58 +00002003 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2004 OS << ", Tmp" << Ops[i];
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002005 OS << ", Chain";
2006 if (InFlag)
2007 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00002008 OS << ");\n";
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002009 if (NumResults > 0) {
2010 OS << " CodeGenMap[N.getValue(0)] = Result;\n";
2011 OS << " CodeGenMap[N.getValue(" << NumResults
2012 << ")] = Result.getValue(" << NumResults << ");\n";
Evan Cheng0fc71982005-12-08 02:00:36 +00002013 OS << " Chain = Result.getValue(" << NumResults << ");\n";
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002014 }
2015 if (NumResults == 0)
2016 OS << " return Chain;\n";
2017 else
Evan Cheng0fc71982005-12-08 02:00:36 +00002018 OS << " return (N.ResNo) ? Chain : Result.getValue(0);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00002019 } else {
2020 // If this instruction is the root, and if there is only one use of it,
2021 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2022 OS << " if (N.Val->hasOneUse()) {\n";
Chris Lattner5d28ffd2005-11-30 23:08:45 +00002023 OS << " return CurDAG->SelectNodeTo(N.Val, "
Chris Lattner5024d932005-10-16 01:41:58 +00002024 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2025 << getEnumName(N->getType());
2026 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2027 OS << ", Tmp" << Ops[i];
Evan Cheng66a48bb2005-12-01 00:18:45 +00002028 if (InFlag)
2029 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00002030 OS << ");\n";
Chris Lattner5024d932005-10-16 01:41:58 +00002031 OS << " } else {\n";
2032 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002033 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2034 << getEnumName(N->getType());
Chris Lattner5024d932005-10-16 01:41:58 +00002035 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2036 OS << ", Tmp" << Ops[i];
Evan Cheng66a48bb2005-12-01 00:18:45 +00002037 if (InFlag)
2038 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00002039 OS << ");\n";
2040 OS << " }\n";
2041 }
Evan Cheng0fc71982005-12-08 02:00:36 +00002042 return std::make_pair(1, ResNo);
Chris Lattner72fe91c2005-09-24 00:40:24 +00002043 } else if (Op->isSubClassOf("SDNodeXForm")) {
2044 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002045 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr,
Evan Cheng0fc71982005-12-08 02:00:36 +00002046 VariableMap, PatternNo, OS, HasChain, InFlag)
2047 .second;
Chris Lattner72fe91c2005-09-24 00:40:24 +00002048
2049 unsigned ResNo = Ctr++;
2050 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
2051 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00002052 if (isRoot) {
2053 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2054 OS << " return Tmp" << ResNo << ";\n";
2055 }
Evan Cheng0fc71982005-12-08 02:00:36 +00002056 return std::make_pair(1, ResNo);
Chris Lattner72fe91c2005-09-24 00:40:24 +00002057 } else {
2058 N->dump();
2059 assert(0 && "Unknown node in result pattern!");
Evan Cheng0fc71982005-12-08 02:00:36 +00002060 return std::make_pair(1, ~0U);
Chris Lattner72fe91c2005-09-24 00:40:24 +00002061 }
2062}
2063
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002064/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2065/// type information from it.
2066static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00002067 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002068 if (!N->isLeaf())
2069 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2070 RemoveAllTypes(N->getChild(i));
2071}
Chris Lattner72fe91c2005-09-24 00:40:24 +00002072
Chris Lattner7e82f132005-10-15 21:34:21 +00002073/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2074/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2075/// 'Pat' may be missing types. If we find an unresolved type to add a check
2076/// for, this returns true otherwise false if Pat has all types.
2077static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002078 DAGISelEmitter &ISE,
Chris Lattner7e82f132005-10-15 21:34:21 +00002079 const std::string &Prefix, unsigned PatternNo,
2080 std::ostream &OS) {
2081 // Did we find one?
2082 if (!Pat->hasTypeSet()) {
2083 // Move a type over from 'other' to 'pat'.
2084 Pat->setType(Other->getType());
Evan Cheng0fc71982005-12-08 02:00:36 +00002085 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
Chris Lattner7e82f132005-10-15 21:34:21 +00002086 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2087 return true;
2088 } else if (Pat->isLeaf()) {
Evan Cheng0fc71982005-12-08 02:00:36 +00002089 if (NodeIsComplexPattern(Pat))
2090 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2091 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner7e82f132005-10-15 21:34:21 +00002092 return false;
2093 }
2094
Evan Chengdd304dd2005-12-05 23:08:55 +00002095 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002096 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
Chris Lattner7e82f132005-10-15 21:34:21 +00002097 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002098 ISE, Prefix + utostr(OpNo), PatternNo, OS))
Chris Lattner7e82f132005-10-15 21:34:21 +00002099 return true;
2100 return false;
2101}
2102
Chris Lattner0614b622005-11-02 06:49:14 +00002103Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2104 Record *N = Records.getDef(Name);
2105 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
2106 return N;
2107}
2108
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002109/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2110/// stream to match the pattern, and generate the code for the match if it
2111/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002112void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2113 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002114 static unsigned PatternCount = 0;
2115 unsigned PatternNo = PatternCount++;
2116 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002117 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002118 OS << "\n // Emits: ";
2119 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002120 OS << "\n";
Evan Cheng0fc71982005-12-08 02:00:36 +00002121 OS << " // Pattern complexity = " << getPatternSize(Pattern.first, *this)
Chris Lattner05814af2005-09-28 17:57:56 +00002122 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002123
Chris Lattner8fc35682005-09-23 23:16:51 +00002124 // Emit the matcher, capturing named arguments in VariableMap.
2125 std::map<std::string,std::string> VariableMap;
2126 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002127
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002128 // TP - Get *SOME* tree pattern, we don't care which.
2129 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002130
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002131 // At this point, we know that we structurally match the pattern, but the
2132 // types of the nodes may not match. Figure out the fewest number of type
2133 // comparisons we need to emit. For example, if there is only one integer
2134 // type supported by a target, there should be no type comparisons at all for
2135 // integer patterns!
2136 //
2137 // To figure out the fewest number of type checks needed, clone the pattern,
2138 // remove the types, then perform type inference on the pattern as a whole.
2139 // If there are unresolved types, emit an explicit check for those types,
2140 // apply the type to the tree, then rerun type inference. Iterate until all
2141 // types are resolved.
2142 //
2143 TreePatternNode *Pat = Pattern.first->clone();
2144 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002145
2146 do {
2147 // Resolve/propagate as many types as possible.
2148 try {
2149 bool MadeChange = true;
2150 while (MadeChange)
2151 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2152 } catch (...) {
2153 assert(0 && "Error: could not find consistent types for something we"
2154 " already decided was ok!");
2155 abort();
2156 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002157
Chris Lattner7e82f132005-10-15 21:34:21 +00002158 // Insert a check for an unresolved type and add it to the tree. If we find
2159 // an unresolved type to add a check for, this returns true and we iterate,
2160 // otherwise we are done.
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002161 } while (InsertOneTypeCheck(Pat, Pattern.first, *this, "N", PatternNo, OS));
2162
2163 bool HasChain = false;
Evan Chengdd304dd2005-12-05 23:08:55 +00002164 EmitLeadChainForPattern(Pattern.first, "N", OS, HasChain);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002165
2166 bool InFlag = false;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002167 EmitCopyToRegsForPattern(Pattern.first, "N", OS, HasChain, InFlag);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002168
Chris Lattner5024d932005-10-16 01:41:58 +00002169 unsigned TmpNo = 0;
Evan Cheng66a48bb2005-12-01 00:18:45 +00002170 CodeGenPatternResult(Pattern.second,
Evan Cheng0fc71982005-12-08 02:00:36 +00002171 TmpNo, VariableMap, PatternNo, OS, HasChain, InFlag, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002172 delete Pat;
2173
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002174 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002175}
2176
Chris Lattner37481472005-09-26 21:59:35 +00002177
2178namespace {
2179 /// CompareByRecordName - An ordering predicate that implements less-than by
2180 /// comparing the names records.
2181 struct CompareByRecordName {
2182 bool operator()(const Record *LHS, const Record *RHS) const {
2183 // Sort by name first.
2184 if (LHS->getName() < RHS->getName()) return true;
2185 // If both names are equal, sort by pointer.
2186 return LHS->getName() == RHS->getName() && LHS < RHS;
2187 }
2188 };
2189}
2190
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002191void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002192 std::string InstNS = Target.inst_begin()->second.Namespace;
2193 if (!InstNS.empty()) InstNS += "::";
2194
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002195 // Emit boilerplate.
2196 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002197 << "SDOperand SelectCode(SDOperand N) {\n"
2198 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002199 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2200 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002201 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00002202 << " if (!N.Val->hasOneUse()) {\n"
2203 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2204 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2205 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002206 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002207 << " default: break;\n"
2208 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002209 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002210 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002211 << " case ISD::AssertZext: {\n"
2212 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2213 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2214 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002215 << " }\n"
2216 << " case ISD::TokenFactor:\n"
2217 << " if (N.getNumOperands() == 2) {\n"
2218 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2219 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2220 << " return CodeGenMap[N] =\n"
2221 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2222 << " } else {\n"
2223 << " std::vector<SDOperand> Ops;\n"
2224 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2225 << " Ops.push_back(Select(N.getOperand(i)));\n"
2226 << " return CodeGenMap[N] = \n"
2227 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2228 << " }\n"
2229 << " case ISD::CopyFromReg: {\n"
2230 << " SDOperand Chain = Select(N.getOperand(0));\n"
2231 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2232 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
2233 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
2234 << " N.Val->getValueType(0));\n"
2235 << " return New.getValue(N.ResNo);\n"
2236 << " }\n"
2237 << " case ISD::CopyToReg: {\n"
2238 << " SDOperand Chain = Select(N.getOperand(0));\n"
2239 << " SDOperand Reg = N.getOperand(1);\n"
2240 << " SDOperand Val = Select(N.getOperand(2));\n"
2241 << " return CodeGenMap[N] = \n"
2242 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
2243 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002244 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002245
Chris Lattner81303322005-09-23 19:36:15 +00002246 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00002247 std::map<Record*, std::vector<PatternToMatch*>,
2248 CompareByRecordName> PatternsByOpcode;
Evan Cheng0fc71982005-12-08 02:00:36 +00002249 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2250 TreePatternNode *Node = PatternsToMatch[i].first;
2251 if (!Node->isLeaf()) {
2252 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
Chris Lattner0614b622005-11-02 06:49:14 +00002253 } else {
Evan Cheng0fc71982005-12-08 02:00:36 +00002254 const ComplexPattern *CP;
Chris Lattner0614b622005-11-02 06:49:14 +00002255 if (IntInit *II =
Evan Cheng0fc71982005-12-08 02:00:36 +00002256 dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner0614b622005-11-02 06:49:14 +00002257 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
Evan Cheng0fc71982005-12-08 02:00:36 +00002258 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2259 std::vector<Record*> OpNodes = CP->getMatchingNodes();
2260 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2261 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2262 &PatternsToMatch[i]);
2263 }
Chris Lattner0614b622005-11-02 06:49:14 +00002264 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00002265 std::cerr << "Unrecognized opcode '";
Evan Cheng0fc71982005-12-08 02:00:36 +00002266 Node->dump();
Evan Cheng76021f02005-11-29 18:44:58 +00002267 std::cerr << "' on tree pattern '";
2268 std::cerr << PatternsToMatch[i].second->getOperator()->getName();
2269 std::cerr << "'!\n";
2270 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00002271 }
2272 }
Evan Cheng0fc71982005-12-08 02:00:36 +00002273 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002274
Chris Lattner3f7e9142005-09-23 20:52:47 +00002275 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00002276 for (std::map<Record*, std::vector<PatternToMatch*>,
2277 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2278 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002279 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2280 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2281
2282 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002283
2284 // We want to emit all of the matching code now. However, we want to emit
2285 // the matches in order of minimal cost. Sort the patterns so the least
2286 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002287 std::stable_sort(Patterns.begin(), Patterns.end(),
Evan Cheng0fc71982005-12-08 02:00:36 +00002288 PatternSortingPredicate(*this));
Chris Lattner81303322005-09-23 19:36:15 +00002289
Chris Lattner3f7e9142005-09-23 20:52:47 +00002290 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2291 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002292 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00002293 }
2294
2295
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002296 OS << " } // end of big switch.\n\n"
2297 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002298 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002299 << " std::cerr << '\\n';\n"
2300 << " abort();\n"
2301 << "}\n";
2302}
2303
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002304void DAGISelEmitter::run(std::ostream &OS) {
2305 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2306 " target", OS);
2307
Chris Lattner1f39e292005-09-14 00:09:24 +00002308 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2309 << "// *** instruction selector class. These functions are really "
2310 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002311
Chris Lattner296dfe32005-09-24 00:50:51 +00002312 OS << "// Instance var to keep track of multiply used nodes that have \n"
2313 << "// already been selected.\n"
2314 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2315
Chris Lattnerca559d02005-09-08 21:03:01 +00002316 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002317 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00002318 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002319 ParsePatternFragments(OS);
2320 ParseInstructions();
2321 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002322
Chris Lattnere97603f2005-09-28 19:27:25 +00002323 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002324 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002325 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002326
Chris Lattnere46e17b2005-09-29 19:28:10 +00002327
2328 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2329 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2330 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
2331 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
2332 std::cerr << "\n";
2333 });
2334
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002335 // At this point, we have full information about the 'Patterns' we need to
2336 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002337 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002338 EmitInstructionSelector(OS);
2339
2340 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2341 E = PatternFragments.end(); I != E; ++I)
2342 delete I->second;
2343 PatternFragments.clear();
2344
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002345 Instructions.clear();
2346}