blob: bb0f81c58b3f6646fa0b90530666f991924ad3b2 [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 {
87 assert(NumResults == 1 && "We only work with single result nodes so far!");
88
89 if (OpNo < NumResults)
90 return N; // FIXME: need value #
91 else
92 return N->getChild(OpNo-NumResults);
93}
94
95/// ApplyTypeConstraint - Given a node in a pattern, apply this type
96/// constraint to the nodes operands. This returns true if it makes a
97/// change, false otherwise. If a type contradiction is found, throw an
98/// exception.
99bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
100 const SDNodeInfo &NodeInfo,
101 TreePattern &TP) const {
102 unsigned NumResults = NodeInfo.getNumResults();
103 assert(NumResults == 1 && "We only work with single result nodes so far!");
104
105 // Check that the number of operands is sane.
106 if (NodeInfo.getNumOperands() >= 0) {
107 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
108 TP.error(N->getOperator()->getName() + " node requires exactly " +
109 itostr(NodeInfo.getNumOperands()) + " operands!");
110 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000111
112 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000113
114 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
115
116 switch (ConstraintType) {
117 default: assert(0 && "Unknown constraint type!");
118 case SDTCisVT:
119 // Operand must be a particular type.
120 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000121 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000122 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000123 std::vector<MVT::ValueType> IntVTs =
124 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000125
126 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000127 if (IntVTs.size() == 1)
128 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000129 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000130 }
131 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000132 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000133 std::vector<MVT::ValueType> FPVTs =
134 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000135
136 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000137 if (FPVTs.size() == 1)
138 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000139 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000140 }
Chris Lattner32707602005-09-08 23:22:48 +0000141 case SDTCisSameAs: {
142 TreePatternNode *OtherNode =
143 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000144 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
145 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000146 }
147 case SDTCisVTSmallerThanOp: {
148 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
149 // have an integer type that is smaller than the VT.
150 if (!NodeToApply->isLeaf() ||
151 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
152 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
153 ->isSubClassOf("ValueType"))
154 TP.error(N->getOperator()->getName() + " expects a VT operand!");
155 MVT::ValueType VT =
156 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
157 if (!MVT::isInteger(VT))
158 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
159
160 TreePatternNode *OtherNode =
161 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000162
163 // It must be integer.
164 bool MadeChange = false;
165 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
166
167 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000168 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
169 return false;
170 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000171 case SDTCisOpSmallerThanOp: {
172 // TODO
173 return false;
174 }
Chris Lattner32707602005-09-08 23:22:48 +0000175 }
176 return false;
177}
178
179
Chris Lattner33c92e92005-09-08 21:27:15 +0000180//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000181// SDNodeInfo implementation
182//
183SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
184 EnumName = R->getValueAsString("Opcode");
185 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000186 Record *TypeProfile = R->getValueAsDef("TypeProfile");
187 NumResults = TypeProfile->getValueAsInt("NumResults");
188 NumOperands = TypeProfile->getValueAsInt("NumOperands");
189
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000190 // Parse the properties.
191 Properties = 0;
192 ListInit *LI = R->getValueAsListInit("Properties");
193 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
194 DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
195 assert(DI && "Properties list must be list of defs!");
196 if (DI->getDef()->getName() == "SDNPCommutative") {
197 Properties |= 1 << SDNPCommutative;
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000198 } else if (DI->getDef()->getName() == "SDNPAssociative") {
199 Properties |= 1 << SDNPAssociative;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000200 } else {
201 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
202 << "' on node '" << R->getName() << "'!\n";
203 exit(1);
204 }
205 }
206
207
Chris Lattner33c92e92005-09-08 21:27:15 +0000208 // Parse the type constraints.
209 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
210 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
211 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
212 "Constraints list should contain constraint definitions!");
213 Record *Constraint =
214 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
215 TypeConstraints.push_back(Constraint);
216 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000217}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000218
219//===----------------------------------------------------------------------===//
220// TreePatternNode implementation
221//
222
223TreePatternNode::~TreePatternNode() {
224#if 0 // FIXME: implement refcounted tree nodes!
225 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
226 delete getChild(i);
227#endif
228}
229
Chris Lattner32707602005-09-08 23:22:48 +0000230/// UpdateNodeType - Set the node type of N to VT if VT contains
231/// information. If N already contains a conflicting type, then throw an
232/// exception. This returns true if any information was updated.
233///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000234bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
235 if (VT == MVT::isUnknown || getExtType() == VT) return false;
236 if (getExtType() == MVT::isUnknown) {
Chris Lattner32707602005-09-08 23:22:48 +0000237 setType(VT);
238 return true;
239 }
240
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000241 // If we are told this is to be an int or FP type, and it already is, ignore
242 // the advice.
243 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
244 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
245 return false;
246
247 // If we know this is an int or fp type, and we are told it is a specific one,
248 // take the advice.
249 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
250 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
251 setType(VT);
252 return true;
253 }
254
Chris Lattner32707602005-09-08 23:22:48 +0000255 TP.error("Type inference contradiction found in node " +
256 getOperator()->getName() + "!");
257 return true; // unreachable
258}
259
260
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000261void TreePatternNode::print(std::ostream &OS) const {
262 if (isLeaf()) {
263 OS << *getLeafValue();
264 } else {
265 OS << "(" << getOperator()->getName();
266 }
267
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000268 switch (getExtType()) {
269 case MVT::Other: OS << ":Other"; break;
270 case MVT::isInt: OS << ":isInt"; break;
271 case MVT::isFP : OS << ":isFP"; break;
272 case MVT::isUnknown: ; /*OS << ":?";*/ break;
273 default: OS << ":" << getType(); break;
274 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000275
276 if (!isLeaf()) {
277 if (getNumChildren() != 0) {
278 OS << " ";
279 getChild(0)->print(OS);
280 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
281 OS << ", ";
282 getChild(i)->print(OS);
283 }
284 }
285 OS << ")";
286 }
287
288 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000289 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000290 if (TransformFn)
291 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000292 if (!getName().empty())
293 OS << ":$" << getName();
294
295}
296void TreePatternNode::dump() const {
297 print(std::cerr);
298}
299
Chris Lattnere46e17b2005-09-29 19:28:10 +0000300/// isIsomorphicTo - Return true if this node is recursively isomorphic to
301/// the specified node. For this comparison, all of the state of the node
302/// is considered, except for the assigned name. Nodes with differing names
303/// that are otherwise identical are considered isomorphic.
304bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
305 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000306 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000307 getPredicateFn() != N->getPredicateFn() ||
308 getTransformFn() != N->getTransformFn())
309 return false;
310
311 if (isLeaf()) {
312 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
313 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
314 return DI->getDef() == NDI->getDef();
315 return getLeafValue() == N->getLeafValue();
316 }
317
318 if (N->getOperator() != getOperator() ||
319 N->getNumChildren() != getNumChildren()) return false;
320 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
321 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
322 return false;
323 return true;
324}
325
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000326/// clone - Make a copy of this tree and all of its children.
327///
328TreePatternNode *TreePatternNode::clone() const {
329 TreePatternNode *New;
330 if (isLeaf()) {
331 New = new TreePatternNode(getLeafValue());
332 } else {
333 std::vector<TreePatternNode*> CChildren;
334 CChildren.reserve(Children.size());
335 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
336 CChildren.push_back(getChild(i)->clone());
337 New = new TreePatternNode(getOperator(), CChildren);
338 }
339 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000340 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000341 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000342 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000343 return New;
344}
345
Chris Lattner32707602005-09-08 23:22:48 +0000346/// SubstituteFormalArguments - Replace the formal arguments in this tree
347/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000348void TreePatternNode::
349SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
350 if (isLeaf()) return;
351
352 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
353 TreePatternNode *Child = getChild(i);
354 if (Child->isLeaf()) {
355 Init *Val = Child->getLeafValue();
356 if (dynamic_cast<DefInit*>(Val) &&
357 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
358 // We found a use of a formal argument, replace it with its value.
359 Child = ArgMap[Child->getName()];
360 assert(Child && "Couldn't find formal argument!");
361 setChild(i, Child);
362 }
363 } else {
364 getChild(i)->SubstituteFormalArguments(ArgMap);
365 }
366 }
367}
368
369
370/// InlinePatternFragments - If this pattern refers to any pattern
371/// fragments, inline them into place, giving us a pattern without any
372/// PatFrag references.
373TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
374 if (isLeaf()) return this; // nothing to do.
375 Record *Op = getOperator();
376
377 if (!Op->isSubClassOf("PatFrag")) {
378 // Just recursively inline children nodes.
379 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
380 setChild(i, getChild(i)->InlinePatternFragments(TP));
381 return this;
382 }
383
384 // Otherwise, we found a reference to a fragment. First, look up its
385 // TreePattern record.
386 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
387
388 // Verify that we are passing the right number of operands.
389 if (Frag->getNumArgs() != Children.size())
390 TP.error("'" + Op->getName() + "' fragment requires " +
391 utostr(Frag->getNumArgs()) + " operands!");
392
Chris Lattner37937092005-09-09 01:15:01 +0000393 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000394
395 // Resolve formal arguments to their actual value.
396 if (Frag->getNumArgs()) {
397 // Compute the map of formal to actual arguments.
398 std::map<std::string, TreePatternNode*> ArgMap;
399 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
400 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
401
402 FragTree->SubstituteFormalArguments(ArgMap);
403 }
404
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000405 FragTree->setName(getName());
406
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000407 // Get a new copy of this fragment to stitch into here.
408 //delete this; // FIXME: implement refcounting!
409 return FragTree;
410}
411
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000412/// getIntrinsicType - Check to see if the specified record has an intrinsic
413/// type which should be applied to it. This infer the type of register
414/// references from the register file information, for example.
415///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000416static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
417 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000418 // Check to see if this is a register or a register class...
419 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000420 if (NotRegisters) return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000421 return getValueType(R->getValueAsDef("RegType"));
422 } else if (R->isSubClassOf("PatFrag")) {
423 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000424 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000425 } else if (R->isSubClassOf("Register")) {
426 assert(0 && "Explicit registers not handled here yet!\n");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000427 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000428 } else if (R->isSubClassOf("ValueType")) {
429 // Using a VTSDNode.
430 return MVT::Other;
431 } else if (R->getName() == "node") {
432 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000433 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000434 }
435
436 TP.error("Unknown node flavor used in pattern: " + R->getName());
437 return MVT::Other;
438}
439
Chris Lattner32707602005-09-08 23:22:48 +0000440/// ApplyTypeConstraints - Apply all of the type constraints relevent to
441/// this node and its children in the tree. This returns true if it makes a
442/// change, false otherwise. If a type contradiction is found, throw an
443/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000444bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
445 if (isLeaf()) {
446 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
447 // If it's a regclass or something else known, include the type.
448 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
449 TP);
450 return false;
451 }
Chris Lattner32707602005-09-08 23:22:48 +0000452
453 // special handling for set, which isn't really an SDNode.
454 if (getOperator()->getName() == "set") {
455 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000456 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
457 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000458
459 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000460 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
461 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000462 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
463 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000464 } else if (getOperator()->isSubClassOf("SDNode")) {
465 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
466
467 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
468 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000469 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000470 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000471 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000472 const DAGInstruction &Inst =
473 TP.getDAGISelEmitter().getInstruction(getOperator());
474
Chris Lattnera28aec12005-09-15 22:23:50 +0000475 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
476 // Apply the result type to the node
477 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
478
479 if (getNumChildren() != Inst.getNumOperands())
480 TP.error("Instruction '" + getOperator()->getName() + " expects " +
481 utostr(Inst.getNumOperands()) + " operands, not " +
482 utostr(getNumChildren()) + " operands!");
483 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
484 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000485 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000486 }
487 return MadeChange;
488 } else {
489 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
490
491 // Node transforms always take one operand, and take and return the same
492 // type.
493 if (getNumChildren() != 1)
494 TP.error("Node transform '" + getOperator()->getName() +
495 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000496 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
497 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000498 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000499 }
Chris Lattner32707602005-09-08 23:22:48 +0000500}
501
Chris Lattnere97603f2005-09-28 19:27:25 +0000502/// canPatternMatch - If it is impossible for this pattern to match on this
503/// target, fill in Reason and return false. Otherwise, return true. This is
504/// used as a santity check for .td files (to prevent people from writing stuff
505/// that can never possibly work), and to prevent the pattern permuter from
506/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000507bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000508 if (isLeaf()) return true;
509
510 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
511 if (!getChild(i)->canPatternMatch(Reason, ISE))
512 return false;
513
514 // If this node is a commutative operator, check that the LHS isn't an
515 // immediate.
516 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
517 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
518 // Scan all of the operands of the node and make sure that only the last one
519 // is a constant node.
520 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
521 if (!getChild(i)->isLeaf() &&
522 getChild(i)->getOperator()->getName() == "imm") {
523 Reason = "Immediate value must be on the RHS of commutative operators!";
524 return false;
525 }
526 }
527
528 return true;
529}
Chris Lattner32707602005-09-08 23:22:48 +0000530
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000531//===----------------------------------------------------------------------===//
532// TreePattern implementation
533//
534
Chris Lattnera28aec12005-09-15 22:23:50 +0000535TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000536 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000537 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
538 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000539}
540
Chris Lattnera28aec12005-09-15 22:23:50 +0000541TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
542 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
543 Trees.push_back(ParseTreePattern(Pat));
544}
545
546TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
547 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
548 Trees.push_back(Pat);
549}
550
551
552
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000553void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000554 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000555 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000556}
557
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000558TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
559 Record *Operator = Dag->getNodeType();
560
561 if (Operator->isSubClassOf("ValueType")) {
562 // If the operator is a ValueType, then this must be "type cast" of a leaf
563 // node.
564 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000565 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000566
567 Init *Arg = Dag->getArg(0);
568 TreePatternNode *New;
569 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000570 Record *R = DI->getDef();
571 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
572 Dag->setArg(0, new DagInit(R,
573 std::vector<std::pair<Init*, std::string> >()));
574 TreePatternNode *TPN = ParseTreePattern(Dag);
575 TPN->setName(Dag->getArgName(0));
576 return TPN;
577 }
578
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000579 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000580 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
581 New = ParseTreePattern(DI);
582 } else {
583 Arg->dump();
584 error("Unknown leaf value for tree pattern!");
585 return 0;
586 }
587
Chris Lattner32707602005-09-08 23:22:48 +0000588 // Apply the type cast.
589 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000590 return New;
591 }
592
593 // Verify that this is something that makes sense for an operator.
594 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000595 !Operator->isSubClassOf("Instruction") &&
596 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000597 Operator->getName() != "set")
598 error("Unrecognized node '" + Operator->getName() + "'!");
599
600 std::vector<TreePatternNode*> Children;
601
602 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
603 Init *Arg = Dag->getArg(i);
604 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
605 Children.push_back(ParseTreePattern(DI));
606 Children.back()->setName(Dag->getArgName(i));
607 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
608 Record *R = DefI->getDef();
609 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
610 // TreePatternNode if its own.
611 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
612 Dag->setArg(i, new DagInit(R,
613 std::vector<std::pair<Init*, std::string> >()));
614 --i; // Revisit this node...
615 } else {
616 TreePatternNode *Node = new TreePatternNode(DefI);
617 Node->setName(Dag->getArgName(i));
618 Children.push_back(Node);
619
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000620 // Input argument?
621 if (R->getName() == "node") {
622 if (Dag->getArgName(i).empty())
623 error("'node' argument requires a name to match with operand list");
624 Args.push_back(Dag->getArgName(i));
625 }
626 }
627 } else {
628 Arg->dump();
629 error("Unknown leaf value for tree pattern!");
630 }
631 }
632
633 return new TreePatternNode(Operator, Children);
634}
635
Chris Lattner32707602005-09-08 23:22:48 +0000636/// InferAllTypes - Infer/propagate as many types throughout the expression
637/// patterns as possible. Return true if all types are infered, false
638/// otherwise. Throw an exception if a type contradiction is found.
639bool TreePattern::InferAllTypes() {
640 bool MadeChange = true;
641 while (MadeChange) {
642 MadeChange = false;
643 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000644 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000645 }
646
647 bool HasUnresolvedTypes = false;
648 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
649 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
650 return !HasUnresolvedTypes;
651}
652
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000653void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000654 OS << getRecord()->getName();
655 if (!Args.empty()) {
656 OS << "(" << Args[0];
657 for (unsigned i = 1, e = Args.size(); i != e; ++i)
658 OS << ", " << Args[i];
659 OS << ")";
660 }
661 OS << ": ";
662
663 if (Trees.size() > 1)
664 OS << "[\n";
665 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
666 OS << "\t";
667 Trees[i]->print(OS);
668 OS << "\n";
669 }
670
671 if (Trees.size() > 1)
672 OS << "]\n";
673}
674
675void TreePattern::dump() const { print(std::cerr); }
676
677
678
679//===----------------------------------------------------------------------===//
680// DAGISelEmitter implementation
681//
682
Chris Lattnerca559d02005-09-08 21:03:01 +0000683// Parse all of the SDNode definitions for the target, populating SDNodes.
684void DAGISelEmitter::ParseNodeInfo() {
685 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
686 while (!Nodes.empty()) {
687 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
688 Nodes.pop_back();
689 }
690}
691
Chris Lattner24eeeb82005-09-13 21:51:00 +0000692/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
693/// map, and emit them to the file as functions.
694void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
695 OS << "\n// Node transformations.\n";
696 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
697 while (!Xforms.empty()) {
698 Record *XFormNode = Xforms.back();
699 Record *SDNode = XFormNode->getValueAsDef("Opcode");
700 std::string Code = XFormNode->getValueAsCode("XFormFunction");
701 SDNodeXForms.insert(std::make_pair(XFormNode,
702 std::make_pair(SDNode, Code)));
703
Chris Lattner1048b7a2005-09-13 22:03:37 +0000704 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000705 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
706 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
707
Chris Lattner1048b7a2005-09-13 22:03:37 +0000708 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000709 << "(SDNode *" << C2 << ") {\n";
710 if (ClassName != "SDNode")
711 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
712 OS << Code << "\n}\n";
713 }
714
715 Xforms.pop_back();
716 }
717}
718
719
720
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000721/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
722/// file, building up the PatternFragments map. After we've collected them all,
723/// inline fragments together as necessary, so that there are no references left
724/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000725///
726/// This also emits all of the predicate functions to the output file.
727///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000728void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000729 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
730
731 // First step, parse all of the fragments and emit predicate functions.
732 OS << "\n// Predicate functions.\n";
733 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000734 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
735 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000736 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000737
738 // Validate the argument list, converting it to map, to discard duplicates.
739 std::vector<std::string> &Args = P->getArgList();
740 std::set<std::string> OperandsMap(Args.begin(), Args.end());
741
742 if (OperandsMap.count(""))
743 P->error("Cannot have unnamed 'node' values in pattern fragment!");
744
745 // Parse the operands list.
746 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
747 if (OpsList->getNodeType()->getName() != "ops")
748 P->error("Operands list should start with '(ops ... '!");
749
750 // Copy over the arguments.
751 Args.clear();
752 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
753 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
754 static_cast<DefInit*>(OpsList->getArg(j))->
755 getDef()->getName() != "node")
756 P->error("Operands list should all be 'node' values.");
757 if (OpsList->getArgName(j).empty())
758 P->error("Operands list should have names for each operand!");
759 if (!OperandsMap.count(OpsList->getArgName(j)))
760 P->error("'" + OpsList->getArgName(j) +
761 "' does not occur in pattern or was multiply specified!");
762 OperandsMap.erase(OpsList->getArgName(j));
763 Args.push_back(OpsList->getArgName(j));
764 }
765
766 if (!OperandsMap.empty())
767 P->error("Operands list does not contain an entry for operand '" +
768 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000769
770 // If there is a code init for this fragment, emit the predicate code and
771 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000772 std::string Code = Fragments[i]->getValueAsCode("Predicate");
773 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000774 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000775 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000776 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000777 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
778
Chris Lattner1048b7a2005-09-13 22:03:37 +0000779 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000780 << "(SDNode *" << C2 << ") {\n";
781 if (ClassName != "SDNode")
782 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000783 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000784 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000785 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000786
787 // If there is a node transformation corresponding to this, keep track of
788 // it.
789 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
790 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000791 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000792 }
793
794 OS << "\n\n";
795
796 // Now that we've parsed all of the tree fragments, do a closure on them so
797 // that there are not references to PatFrags left inside of them.
798 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
799 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000800 TreePattern *ThePat = I->second;
801 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000802
Chris Lattner32707602005-09-08 23:22:48 +0000803 // Infer as many types as possible. Don't worry about it if we don't infer
804 // all of them, some may depend on the inputs of the pattern.
805 try {
806 ThePat->InferAllTypes();
807 } catch (...) {
808 // If this pattern fragment is not supported by this target (no types can
809 // satisfy its constraints), just ignore it. If the bogus pattern is
810 // actually used by instructions, the type consistency error will be
811 // reported there.
812 }
813
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000814 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000815 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000816 }
817}
818
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000819/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000820/// instruction input. Return true if this is a real use.
821static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000822 std::map<std::string, TreePatternNode*> &InstInputs) {
823 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000824 if (Pat->getName().empty()) {
825 if (Pat->isLeaf()) {
826 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
827 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
828 I->error("Input " + DI->getDef()->getName() + " must be named!");
829
830 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000831 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000832 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000833
834 Record *Rec;
835 if (Pat->isLeaf()) {
836 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
837 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
838 Rec = DI->getDef();
839 } else {
840 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
841 Rec = Pat->getOperator();
842 }
843
844 TreePatternNode *&Slot = InstInputs[Pat->getName()];
845 if (!Slot) {
846 Slot = Pat;
847 } else {
848 Record *SlotRec;
849 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000850 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000851 } else {
852 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
853 SlotRec = Slot->getOperator();
854 }
855
856 // Ensure that the inputs agree if we've already seen this input.
857 if (Rec != SlotRec)
858 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000859 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000860 I->error("All $" + Pat->getName() + " inputs must agree with each other");
861 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000862 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000863}
864
865/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
866/// part of "I", the instruction), computing the set of inputs and outputs of
867/// the pattern. Report errors if we see anything naughty.
868void DAGISelEmitter::
869FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
870 std::map<std::string, TreePatternNode*> &InstInputs,
871 std::map<std::string, Record*> &InstResults) {
872 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000873 bool isUse = HandleUse(I, Pat, InstInputs);
874 if (!isUse && Pat->getTransformFn())
875 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000876 return;
877 } else if (Pat->getOperator()->getName() != "set") {
878 // If this is not a set, verify that the children nodes are not void typed,
879 // and recurse.
880 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000881 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000882 I->error("Cannot have void nodes inside of patterns!");
883 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
884 }
885
886 // If this is a non-leaf node with no children, treat it basically as if
887 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000888 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000889 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000890 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000891
Chris Lattnerf1311842005-09-14 23:05:13 +0000892 if (!isUse && Pat->getTransformFn())
893 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000894 return;
895 }
896
897 // Otherwise, this is a set, validate and collect instruction results.
898 if (Pat->getNumChildren() == 0)
899 I->error("set requires operands!");
900 else if (Pat->getNumChildren() & 1)
901 I->error("set requires an even number of operands");
902
Chris Lattnerf1311842005-09-14 23:05:13 +0000903 if (Pat->getTransformFn())
904 I->error("Cannot specify a transform function on a set node!");
905
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000906 // Check the set destinations.
907 unsigned NumValues = Pat->getNumChildren()/2;
908 for (unsigned i = 0; i != NumValues; ++i) {
909 TreePatternNode *Dest = Pat->getChild(i);
910 if (!Dest->isLeaf())
911 I->error("set destination should be a virtual register!");
912
913 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
914 if (!Val)
915 I->error("set destination should be a virtual register!");
916
917 if (!Val->getDef()->isSubClassOf("RegisterClass"))
918 I->error("set destination should be a virtual register!");
919 if (Dest->getName().empty())
920 I->error("set destination must have a name!");
921 if (InstResults.count(Dest->getName()))
922 I->error("cannot set '" + Dest->getName() +"' multiple times");
923 InstResults[Dest->getName()] = Val->getDef();
924
925 // Verify and collect info from the computation.
926 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
927 InstInputs, InstResults);
928 }
929}
930
931
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000932/// ParseInstructions - Parse all of the instructions, inlining and resolving
933/// any fragments involved. This populates the Instructions list with fully
934/// resolved instructions.
935void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000936 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
937
938 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
939 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
940 continue; // no pattern yet, ignore it.
941
942 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
943 if (LI->getSize() == 0) continue; // no pattern.
944
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000945 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000946 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000947 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000948 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000949
Chris Lattner95f6b762005-09-08 23:26:30 +0000950 // Infer as many types as possible. If we cannot infer all of them, we can
951 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000952 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +0000953 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000954
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000955 // InstInputs - Keep track of all of the inputs of the instruction, along
956 // with the record they are declared as.
957 std::map<std::string, TreePatternNode*> InstInputs;
958
959 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000960 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000961 std::map<std::string, Record*> InstResults;
962
Chris Lattner1f39e292005-09-14 00:09:24 +0000963 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000964 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000965 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
966 TreePatternNode *Pat = I->getTree(j);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000967 if (Pat->getExtType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000968 I->dump();
969 I->error("Top-level forms in instruction pattern should have"
970 " void types");
971 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000972
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000973 // Find inputs and outputs, and verify the structure of the uses/defs.
974 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000975 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000976
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000977 // Now that we have inputs and outputs of the pattern, inspect the operands
978 // list for the instruction. This determines the order that operands are
979 // added to the machine instruction the node corresponds to.
980 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000981
982 // Parse the operands list from the (ops) list, validating it.
983 std::vector<std::string> &Args = I->getArgList();
984 assert(Args.empty() && "Args list should still be empty here!");
985 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
986
987 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +0000988 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +0000989 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000990 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000991 I->error("'" + InstResults.begin()->first +
992 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +0000993 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +0000994
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000995 // Check that it exists in InstResults.
996 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000997 if (R == 0)
998 I->error("Operand $" + OpName + " should be a set destination: all "
999 "outputs must occur before inputs in operand list!");
1000
1001 if (CGI.OperandList[i].Rec != R)
1002 I->error("Operand $" + OpName + " class mismatch!");
1003
Chris Lattnerae6d8282005-09-15 21:51:12 +00001004 // Remember the return type.
1005 ResultTypes.push_back(CGI.OperandList[i].Ty);
1006
Chris Lattner39e8af92005-09-14 18:19:25 +00001007 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001008 InstResults.erase(OpName);
1009 }
1010
Chris Lattner0b592252005-09-14 21:59:34 +00001011 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1012 // the copy while we're checking the inputs.
1013 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001014
1015 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +00001016 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001017 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1018 const std::string &OpName = CGI.OperandList[i].Name;
1019 if (OpName.empty())
1020 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1021
Chris Lattner0b592252005-09-14 21:59:34 +00001022 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001023 I->error("Operand $" + OpName +
1024 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001025 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001026 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001027 if (CGI.OperandList[i].Ty != InVal->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001028 I->error("Operand $" + OpName +
1029 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +00001030 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +00001031
Chris Lattner2175c182005-09-14 23:01:59 +00001032 // Construct the result for the dest-pattern operand list.
1033 TreePatternNode *OpNode = InVal->clone();
1034
1035 // No predicate is useful on the result.
1036 OpNode->setPredicateFn("");
1037
1038 // Promote the xform function to be an explicit node if set.
1039 if (Record *Xform = OpNode->getTransformFn()) {
1040 OpNode->setTransformFn(0);
1041 std::vector<TreePatternNode*> Children;
1042 Children.push_back(OpNode);
1043 OpNode = new TreePatternNode(Xform, Children);
1044 }
1045
1046 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001047 }
1048
Chris Lattner0b592252005-09-14 21:59:34 +00001049 if (!InstInputsCheck.empty())
1050 I->error("Input operand $" + InstInputsCheck.begin()->first +
1051 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001052
1053 TreePatternNode *ResultPattern =
1054 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001055
1056 // Create and insert the instruction.
1057 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1058 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1059
1060 // Use a temporary tree pattern to infer all types and make sure that the
1061 // constructed result is correct. This depends on the instruction already
1062 // being inserted into the Instructions map.
1063 TreePattern Temp(I->getRecord(), ResultPattern, *this);
1064 Temp.InferAllTypes();
1065
1066 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1067 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001068
Chris Lattner32707602005-09-08 23:22:48 +00001069 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001070 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001071
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001072 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001073 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1074 E = Instructions.end(); II != E; ++II) {
1075 TreePattern *I = II->second.getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001076
1077 if (I->getNumTrees() != 1) {
1078 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1079 continue;
1080 }
1081 TreePatternNode *Pattern = I->getTree(0);
1082 if (Pattern->getOperator()->getName() != "set")
1083 continue; // Not a set (store or something?)
1084
1085 if (Pattern->getNumChildren() != 2)
1086 continue; // Not a set of a single value (not handled so far)
1087
1088 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001089
1090 std::string Reason;
1091 if (!SrcPattern->canPatternMatch(Reason, *this))
1092 I->error("Instruction can never match: " + Reason);
1093
Chris Lattnerae5b3502005-09-15 21:57:35 +00001094 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001095 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001096 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001097}
1098
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001099void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001100 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001101
Chris Lattnerabbb6052005-09-15 21:42:00 +00001102 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001103 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1104 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001105
Chris Lattnerabbb6052005-09-15 21:42:00 +00001106 // Inline pattern fragments into it.
1107 Pattern->InlinePatternFragments();
1108
1109 // Infer as many types as possible. If we cannot infer all of them, we can
1110 // never do anything with this pattern: report it to the user.
1111 if (!Pattern->InferAllTypes())
1112 Pattern->error("Could not infer all types in pattern!");
1113
1114 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1115 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001116
1117 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +00001118 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001119
1120 // Inline pattern fragments into it.
1121 Result->InlinePatternFragments();
1122
1123 // Infer as many types as possible. If we cannot infer all of them, we can
1124 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001125 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001126 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001127
1128 if (Result->getNumTrees() != 1)
1129 Result->error("Cannot handle instructions producing instructions "
1130 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001131
1132 std::string Reason;
1133 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1134 Pattern->error("Pattern can never match: " + Reason);
1135
Chris Lattnerabbb6052005-09-15 21:42:00 +00001136 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1137 Result->getOnlyTree()));
1138 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001139}
1140
Chris Lattnere46e17b2005-09-29 19:28:10 +00001141/// CombineChildVariants - Given a bunch of permutations of each child of the
1142/// 'operator' node, put them together in all possible ways.
1143static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001144 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001145 std::vector<TreePatternNode*> &OutVariants,
1146 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001147 // Make sure that each operand has at least one variant to choose from.
1148 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1149 if (ChildVariants[i].empty())
1150 return;
1151
Chris Lattnere46e17b2005-09-29 19:28:10 +00001152 // The end result is an all-pairs construction of the resultant pattern.
1153 std::vector<unsigned> Idxs;
1154 Idxs.resize(ChildVariants.size());
1155 bool NotDone = true;
1156 while (NotDone) {
1157 // Create the variant and add it to the output list.
1158 std::vector<TreePatternNode*> NewChildren;
1159 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1160 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1161 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1162
1163 // Copy over properties.
1164 R->setName(Orig->getName());
1165 R->setPredicateFn(Orig->getPredicateFn());
1166 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001167 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001168
1169 // If this pattern cannot every match, do not include it as a variant.
1170 std::string ErrString;
1171 if (!R->canPatternMatch(ErrString, ISE)) {
1172 delete R;
1173 } else {
1174 bool AlreadyExists = false;
1175
1176 // Scan to see if this pattern has already been emitted. We can get
1177 // duplication due to things like commuting:
1178 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1179 // which are the same pattern. Ignore the dups.
1180 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1181 if (R->isIsomorphicTo(OutVariants[i])) {
1182 AlreadyExists = true;
1183 break;
1184 }
1185
1186 if (AlreadyExists)
1187 delete R;
1188 else
1189 OutVariants.push_back(R);
1190 }
1191
1192 // Increment indices to the next permutation.
1193 NotDone = false;
1194 // Look for something we can increment without causing a wrap-around.
1195 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1196 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1197 NotDone = true; // Found something to increment.
1198 break;
1199 }
1200 Idxs[IdxsIdx] = 0;
1201 }
1202 }
1203}
1204
Chris Lattneraf302912005-09-29 22:36:54 +00001205/// CombineChildVariants - A helper function for binary operators.
1206///
1207static void CombineChildVariants(TreePatternNode *Orig,
1208 const std::vector<TreePatternNode*> &LHS,
1209 const std::vector<TreePatternNode*> &RHS,
1210 std::vector<TreePatternNode*> &OutVariants,
1211 DAGISelEmitter &ISE) {
1212 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1213 ChildVariants.push_back(LHS);
1214 ChildVariants.push_back(RHS);
1215 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1216}
1217
1218
1219static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1220 std::vector<TreePatternNode *> &Children) {
1221 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1222 Record *Operator = N->getOperator();
1223
1224 // Only permit raw nodes.
1225 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1226 N->getTransformFn()) {
1227 Children.push_back(N);
1228 return;
1229 }
1230
1231 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1232 Children.push_back(N->getChild(0));
1233 else
1234 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1235
1236 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1237 Children.push_back(N->getChild(1));
1238 else
1239 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1240}
1241
Chris Lattnere46e17b2005-09-29 19:28:10 +00001242/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1243/// the (potentially recursive) pattern by using algebraic laws.
1244///
1245static void GenerateVariantsOf(TreePatternNode *N,
1246 std::vector<TreePatternNode*> &OutVariants,
1247 DAGISelEmitter &ISE) {
1248 // We cannot permute leaves.
1249 if (N->isLeaf()) {
1250 OutVariants.push_back(N);
1251 return;
1252 }
1253
1254 // Look up interesting info about the node.
1255 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1256
1257 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001258 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1259 // Reassociate by pulling together all of the linked operators
1260 std::vector<TreePatternNode*> MaximalChildren;
1261 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1262
1263 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1264 // permutations.
1265 if (MaximalChildren.size() == 3) {
1266 // Find the variants of all of our maximal children.
1267 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1268 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1269 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1270 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1271
1272 // There are only two ways we can permute the tree:
1273 // (A op B) op C and A op (B op C)
1274 // Within these forms, we can also permute A/B/C.
1275
1276 // Generate legal pair permutations of A/B/C.
1277 std::vector<TreePatternNode*> ABVariants;
1278 std::vector<TreePatternNode*> BAVariants;
1279 std::vector<TreePatternNode*> ACVariants;
1280 std::vector<TreePatternNode*> CAVariants;
1281 std::vector<TreePatternNode*> BCVariants;
1282 std::vector<TreePatternNode*> CBVariants;
1283 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1284 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1285 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1286 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1287 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1288 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1289
1290 // Combine those into the result: (x op x) op x
1291 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1292 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1293 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1294 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1295 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1296 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1297
1298 // Combine those into the result: x op (x op x)
1299 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1300 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1301 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1302 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1303 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1304 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1305 return;
1306 }
1307 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001308
1309 // Compute permutations of all children.
1310 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1311 ChildVariants.resize(N->getNumChildren());
1312 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1313 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1314
1315 // Build all permutations based on how the children were formed.
1316 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1317
1318 // If this node is commutative, consider the commuted order.
1319 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1320 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001321 // Consider the commuted order.
1322 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1323 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001324 }
1325}
1326
1327
Chris Lattnere97603f2005-09-28 19:27:25 +00001328// GenerateVariants - Generate variants. For example, commutative patterns can
1329// match multiple ways. Add them to PatternsToMatch as well.
1330void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001331
1332 DEBUG(std::cerr << "Generating instruction variants.\n");
1333
1334 // Loop over all of the patterns we've collected, checking to see if we can
1335 // generate variants of the instruction, through the exploitation of
1336 // identities. This permits the target to provide agressive matching without
1337 // the .td file having to contain tons of variants of instructions.
1338 //
1339 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1340 // intentionally do not reconsider these. Any variants of added patterns have
1341 // already been added.
1342 //
1343 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1344 std::vector<TreePatternNode*> Variants;
1345 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1346
1347 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001348 Variants.erase(Variants.begin()); // Remove the original pattern.
1349
1350 if (Variants.empty()) // No variants for this pattern.
1351 continue;
1352
1353 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1354 PatternsToMatch[i].first->dump();
1355 std::cerr << "\n");
1356
1357 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1358 TreePatternNode *Variant = Variants[v];
1359
1360 DEBUG(std::cerr << " VAR#" << v << ": ";
1361 Variant->dump();
1362 std::cerr << "\n");
1363
1364 // Scan to see if an instruction or explicit pattern already matches this.
1365 bool AlreadyExists = false;
1366 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1367 // Check to see if this variant already exists.
1368 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1369 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1370 AlreadyExists = true;
1371 break;
1372 }
1373 }
1374 // If we already have it, ignore the variant.
1375 if (AlreadyExists) continue;
1376
1377 // Otherwise, add it to the list of patterns we have.
1378 PatternsToMatch.push_back(std::make_pair(Variant,
1379 PatternsToMatch[i].second));
1380 }
1381
1382 DEBUG(std::cerr << "\n");
1383 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001384}
1385
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001386
Chris Lattner05814af2005-09-28 17:57:56 +00001387/// getPatternSize - Return the 'size' of this pattern. We want to match large
1388/// patterns before small ones. This is used to determine the size of a
1389/// pattern.
1390static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001391 assert(isExtIntegerVT(P->getExtType()) ||
1392 isExtFloatingPointVT(P->getExtType()) &&
Chris Lattner05814af2005-09-28 17:57:56 +00001393 "Not a valid pattern node to size!");
1394 unsigned Size = 1; // The node itself.
1395
1396 // Count children in the count if they are also nodes.
1397 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1398 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001399 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001400 Size += getPatternSize(Child);
1401 }
1402
1403 return Size;
1404}
1405
1406/// getResultPatternCost - Compute the number of instructions for this pattern.
1407/// This is a temporary hack. We should really include the instruction
1408/// latencies in this calculation.
1409static unsigned getResultPatternCost(TreePatternNode *P) {
1410 if (P->isLeaf()) return 0;
1411
1412 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1413 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1414 Cost += getResultPatternCost(P->getChild(i));
1415 return Cost;
1416}
1417
1418// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1419// In particular, we want to match maximal patterns first and lowest cost within
1420// a particular complexity first.
1421struct PatternSortingPredicate {
1422 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1423 DAGISelEmitter::PatternToMatch *RHS) {
1424 unsigned LHSSize = getPatternSize(LHS->first);
1425 unsigned RHSSize = getPatternSize(RHS->first);
1426 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1427 if (LHSSize < RHSSize) return false;
1428
1429 // If the patterns have equal complexity, compare generated instruction cost
1430 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1431 }
1432};
1433
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001434/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1435/// if the match fails. At this point, we already know that the opcode for N
1436/// matches, and the SDNode for the result has the RootName specified name.
1437void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001438 const std::string &RootName,
1439 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001440 unsigned PatternNo, std::ostream &OS) {
1441 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001442
1443 // If this node has a name associated with it, capture it in VarMap. If
1444 // we already saw this in the pattern, emit code to verify dagness.
1445 if (!N->getName().empty()) {
1446 std::string &VarMapEntry = VarMap[N->getName()];
1447 if (VarMapEntry.empty()) {
1448 VarMapEntry = RootName;
1449 } else {
1450 // If we get here, this is a second reference to a specific name. Since
1451 // we already have checked that the first reference is valid, we don't
1452 // have to recursively match it, just check that it's the same as the
1453 // previously named thing.
1454 OS << " if (" << VarMapEntry << " != " << RootName
1455 << ") goto P" << PatternNo << "Fail;\n";
1456 return;
1457 }
1458 }
1459
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001460 // Emit code to load the child nodes and match their contents recursively.
1461 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001462 OS << " SDOperand " << RootName << i <<" = " << RootName
1463 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001464 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001465
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001466 if (!Child->isLeaf()) {
1467 // If it's not a leaf, recursively match.
1468 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001469 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001470 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001471 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001472 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001473 // If this child has a name associated with it, capture it in VarMap. If
1474 // we already saw this in the pattern, emit code to verify dagness.
1475 if (!Child->getName().empty()) {
1476 std::string &VarMapEntry = VarMap[Child->getName()];
1477 if (VarMapEntry.empty()) {
1478 VarMapEntry = RootName + utostr(i);
1479 } else {
1480 // If we get here, this is a second reference to a specific name. Since
1481 // we already have checked that the first reference is valid, we don't
1482 // have to recursively match it, just check that it's the same as the
1483 // previously named thing.
1484 OS << " if (" << VarMapEntry << " != " << RootName << i
1485 << ") goto P" << PatternNo << "Fail;\n";
1486 continue;
1487 }
1488 }
1489
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001490 // Handle leaves of various types.
1491 Init *LeafVal = Child->getLeafValue();
1492 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1493 if (LeafRec->isSubClassOf("RegisterClass")) {
1494 // Handle register references. Nothing to do here.
1495 } else if (LeafRec->isSubClassOf("ValueType")) {
1496 // Make sure this is the specified value type.
1497 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1498 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1499 << "Fail;\n";
1500 } else {
1501 Child->dump();
1502 assert(0 && "Unknown leaf type!");
1503 }
1504 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001505 }
1506
1507 // If there is a node predicate for this, emit the call.
1508 if (!N->getPredicateFn().empty())
1509 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001510 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001511}
1512
Chris Lattner6bc7e512005-09-26 21:53:26 +00001513/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1514/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001515unsigned DAGISelEmitter::
1516CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1517 std::map<std::string,std::string> &VariableMap,
Chris Lattner6bc7e512005-09-26 21:53:26 +00001518 std::ostream &OS) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001519 // This is something selected from the pattern we matched.
1520 if (!N->getName().empty()) {
Chris Lattner6bc7e512005-09-26 21:53:26 +00001521 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001522 assert(!Val.empty() &&
1523 "Variable referenced but not defined and not caught earlier!");
1524 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1525 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001526 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001527 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001528
1529 unsigned ResNo = Ctr++;
1530 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1531 switch (N->getType()) {
1532 default: assert(0 && "Unknown type for constant node!");
1533 case MVT::i1: OS << " bool Tmp"; break;
1534 case MVT::i8: OS << " unsigned char Tmp"; break;
1535 case MVT::i16: OS << " unsigned short Tmp"; break;
1536 case MVT::i32: OS << " unsigned Tmp"; break;
1537 case MVT::i64: OS << " uint64_t Tmp"; break;
1538 }
1539 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1540 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1541 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1542 } else {
1543 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1544 }
1545 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1546 // value if used multiple times by this pattern result.
1547 Val = "Tmp"+utostr(ResNo);
1548 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001549 }
1550
1551 if (N->isLeaf()) {
1552 N->dump();
1553 assert(0 && "Unknown leaf type!");
1554 return ~0U;
1555 }
1556
1557 Record *Op = N->getOperator();
1558 if (Op->isSubClassOf("Instruction")) {
1559 // Emit all of the operands.
1560 std::vector<unsigned> Ops;
1561 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1562 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1563
1564 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1565 unsigned ResNo = Ctr++;
1566
1567 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1568 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1569 << getEnumName(N->getType());
1570 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1571 OS << ", Tmp" << Ops[i];
1572 OS << ");\n";
1573 return ResNo;
1574 } else if (Op->isSubClassOf("SDNodeXForm")) {
1575 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1576 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1577
1578 unsigned ResNo = Ctr++;
1579 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1580 << "(Tmp" << OpVal << ".Val);\n";
1581 return ResNo;
1582 } else {
1583 N->dump();
1584 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001585 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001586 }
1587}
1588
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001589/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1590/// type information from it.
1591static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001592 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001593 if (!N->isLeaf())
1594 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1595 RemoveAllTypes(N->getChild(i));
1596}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001597
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001598/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1599/// stream to match the pattern, and generate the code for the match if it
1600/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001601void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1602 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001603 static unsigned PatternCount = 0;
1604 unsigned PatternNo = PatternCount++;
1605 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001606 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001607 OS << "\n // Emits: ";
1608 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001609 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001610 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1611 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001612
Chris Lattner8fc35682005-09-23 23:16:51 +00001613 // Emit the matcher, capturing named arguments in VariableMap.
1614 std::map<std::string,std::string> VariableMap;
1615 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001616
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001617 // TP - Get *SOME* tree pattern, we don't care which.
1618 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001619
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001620 // At this point, we know that we structurally match the pattern, but the
1621 // types of the nodes may not match. Figure out the fewest number of type
1622 // comparisons we need to emit. For example, if there is only one integer
1623 // type supported by a target, there should be no type comparisons at all for
1624 // integer patterns!
1625 //
1626 // To figure out the fewest number of type checks needed, clone the pattern,
1627 // remove the types, then perform type inference on the pattern as a whole.
1628 // If there are unresolved types, emit an explicit check for those types,
1629 // apply the type to the tree, then rerun type inference. Iterate until all
1630 // types are resolved.
1631 //
1632 TreePatternNode *Pat = Pattern.first->clone();
1633 RemoveAllTypes(Pat);
1634 bool MadeChange = true;
1635 try {
1636 while (MadeChange)
1637 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1638 } catch (...) {
1639 assert(0 && "Error: could not find consistent types for something we"
1640 " already decided was ok!");
1641 abort();
1642 }
1643
1644 if (!Pat->ContainsUnresolvedType()) {
1645 unsigned TmpNo = 0;
1646 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
1647
1648 // Add the result to the map if it has multiple uses.
1649 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
1650 OS << " return Tmp" << Res << ";\n";
1651 }
1652
1653 delete Pat;
1654
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001655 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001656}
1657
Chris Lattner37481472005-09-26 21:59:35 +00001658
1659namespace {
1660 /// CompareByRecordName - An ordering predicate that implements less-than by
1661 /// comparing the names records.
1662 struct CompareByRecordName {
1663 bool operator()(const Record *LHS, const Record *RHS) const {
1664 // Sort by name first.
1665 if (LHS->getName() < RHS->getName()) return true;
1666 // If both names are equal, sort by pointer.
1667 return LHS->getName() == RHS->getName() && LHS < RHS;
1668 }
1669 };
1670}
1671
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001672void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1673 // Emit boilerplate.
1674 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001675 << "SDOperand SelectCode(SDOperand N) {\n"
1676 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1677 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1678 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001679 << " if (!N.Val->hasOneUse()) {\n"
1680 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1681 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1682 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001683 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001684 << " default: break;\n"
1685 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001686 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001687 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001688 << " case ISD::AssertZext: {\n"
1689 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1690 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1691 << " return Tmp0;\n"
1692 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001693
Chris Lattner81303322005-09-23 19:36:15 +00001694 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001695 std::map<Record*, std::vector<PatternToMatch*>,
1696 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001697 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1698 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1699 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001700
Chris Lattner3f7e9142005-09-23 20:52:47 +00001701 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001702 for (std::map<Record*, std::vector<PatternToMatch*>,
1703 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1704 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001705 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1706 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1707
1708 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001709
1710 // We want to emit all of the matching code now. However, we want to emit
1711 // the matches in order of minimal cost. Sort the patterns so the least
1712 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001713 std::stable_sort(Patterns.begin(), Patterns.end(),
1714 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001715
Chris Lattner3f7e9142005-09-23 20:52:47 +00001716 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1717 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001718 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001719 }
1720
1721
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001722 OS << " } // end of big switch.\n\n"
1723 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001724 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001725 << " std::cerr << '\\n';\n"
1726 << " abort();\n"
1727 << "}\n";
1728}
1729
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001730void DAGISelEmitter::run(std::ostream &OS) {
1731 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1732 " target", OS);
1733
Chris Lattner1f39e292005-09-14 00:09:24 +00001734 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1735 << "// *** instruction selector class. These functions are really "
1736 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001737
Chris Lattner296dfe32005-09-24 00:50:51 +00001738 OS << "// Instance var to keep track of multiply used nodes that have \n"
1739 << "// already been selected.\n"
1740 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1741
Chris Lattnerca559d02005-09-08 21:03:01 +00001742 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001743 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001744 ParsePatternFragments(OS);
1745 ParseInstructions();
1746 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001747
Chris Lattnere97603f2005-09-28 19:27:25 +00001748 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001749 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001750 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001751
Chris Lattnere46e17b2005-09-29 19:28:10 +00001752
1753 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1754 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1755 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1756 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1757 std::cerr << "\n";
1758 });
1759
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001760 // At this point, we have full information about the 'Patterns' we need to
1761 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001762 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001763 EmitInstructionSelector(OS);
1764
1765 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1766 E = PatternFragments.end(); I != E; ++I)
1767 delete I->second;
1768 PatternFragments.clear();
1769
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001770 Instructions.clear();
1771}