blob: 8cbed47e0848803b01da4d7816f4c3bb17f9863a [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 Lattner33c92e92005-09-08 21:27:15 +000023// SDTypeConstraint implementation
24//
25
26SDTypeConstraint::SDTypeConstraint(Record *R) {
27 OperandNo = R->getValueAsInt("OperandNum");
28
29 if (R->isSubClassOf("SDTCisVT")) {
30 ConstraintType = SDTCisVT;
31 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
32 } else if (R->isSubClassOf("SDTCisInt")) {
33 ConstraintType = SDTCisInt;
34 } else if (R->isSubClassOf("SDTCisFP")) {
35 ConstraintType = SDTCisFP;
36 } else if (R->isSubClassOf("SDTCisSameAs")) {
37 ConstraintType = SDTCisSameAs;
38 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
39 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
40 ConstraintType = SDTCisVTSmallerThanOp;
41 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
42 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +000043 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
44 ConstraintType = SDTCisOpSmallerThanOp;
45 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
46 R->getValueAsInt("BigOperandNum");
Chris Lattner33c92e92005-09-08 21:27:15 +000047 } else {
48 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
49 exit(1);
50 }
51}
52
Chris Lattner32707602005-09-08 23:22:48 +000053/// getOperandNum - Return the node corresponding to operand #OpNo in tree
54/// N, which has NumResults results.
55TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
56 TreePatternNode *N,
57 unsigned NumResults) const {
58 assert(NumResults == 1 && "We only work with single result nodes so far!");
59
60 if (OpNo < NumResults)
61 return N; // FIXME: need value #
62 else
63 return N->getChild(OpNo-NumResults);
64}
65
66/// ApplyTypeConstraint - Given a node in a pattern, apply this type
67/// constraint to the nodes operands. This returns true if it makes a
68/// change, false otherwise. If a type contradiction is found, throw an
69/// exception.
70bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
71 const SDNodeInfo &NodeInfo,
72 TreePattern &TP) const {
73 unsigned NumResults = NodeInfo.getNumResults();
74 assert(NumResults == 1 && "We only work with single result nodes so far!");
75
76 // Check that the number of operands is sane.
77 if (NodeInfo.getNumOperands() >= 0) {
78 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
79 TP.error(N->getOperator()->getName() + " node requires exactly " +
80 itostr(NodeInfo.getNumOperands()) + " operands!");
81 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +000082
83 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +000084
85 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
86
87 switch (ConstraintType) {
88 default: assert(0 && "Unknown constraint type!");
89 case SDTCisVT:
90 // Operand must be a particular type.
91 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +000092 case SDTCisInt: {
Chris Lattner32707602005-09-08 23:22:48 +000093 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
94 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
95
Chris Lattner0ee7cff2005-10-14 04:11:13 +000096 // If there is only one integer type supported, this must be it.
97 const std::vector<MVT::ValueType> &VTs = CGT.getLegalValueTypes();
98 MVT::ValueType VT = MVT::LAST_VALUETYPE;
99 for (unsigned i = 0, e = VTs.size(); i != e; ++i)
100 if (MVT::isInteger(VTs[i])) {
101 if (VT == MVT::LAST_VALUETYPE)
102 VT = VTs[i]; // First integer type we've found.
103 else {
104 VT = MVT::LAST_VALUETYPE;
105 break;
106 }
107 }
108
109 // If we found exactly one supported integer type, apply it.
110 if (VT != MVT::LAST_VALUETYPE)
111 return NodeToApply->UpdateNodeType(VT, TP);
Chris Lattner32707602005-09-08 23:22:48 +0000112 return false;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000113 }
114 case SDTCisFP: {
Chris Lattner32707602005-09-08 23:22:48 +0000115 if (NodeToApply->hasTypeSet() &&
116 !MVT::isFloatingPoint(NodeToApply->getType()))
117 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000118
119 // If there is only one FP type supported, this must be it.
120 const std::vector<MVT::ValueType> &VTs = CGT.getLegalValueTypes();
121 MVT::ValueType VT = MVT::LAST_VALUETYPE;
122 for (unsigned i = 0, e = VTs.size(); i != e; ++i)
123 if (MVT::isFloatingPoint(VTs[i])) {
124 if (VT == MVT::LAST_VALUETYPE)
125 VT = VTs[i]; // First integer type we've found.
126 else {
127 VT = MVT::LAST_VALUETYPE;
128 break;
129 }
130 }
131
132 // If we found exactly one supported FP type, apply it.
133 if (VT != MVT::LAST_VALUETYPE)
134 return NodeToApply->UpdateNodeType(VT, TP);
Chris Lattner32707602005-09-08 23:22:48 +0000135 return false;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000136 }
Chris Lattner32707602005-09-08 23:22:48 +0000137 case SDTCisSameAs: {
138 TreePatternNode *OtherNode =
139 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
140 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
141 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
142 }
143 case SDTCisVTSmallerThanOp: {
144 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
145 // have an integer type that is smaller than the VT.
146 if (!NodeToApply->isLeaf() ||
147 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
148 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
149 ->isSubClassOf("ValueType"))
150 TP.error(N->getOperator()->getName() + " expects a VT operand!");
151 MVT::ValueType VT =
152 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
153 if (!MVT::isInteger(VT))
154 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
155
156 TreePatternNode *OtherNode =
157 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
158 if (OtherNode->hasTypeSet() &&
159 (!MVT::isInteger(OtherNode->getType()) ||
160 OtherNode->getType() <= VT))
161 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
162 return false;
163 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000164 case SDTCisOpSmallerThanOp: {
165 // TODO
166 return false;
167 }
Chris Lattner32707602005-09-08 23:22:48 +0000168 }
169 return false;
170}
171
172
Chris Lattner33c92e92005-09-08 21:27:15 +0000173//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000174// SDNodeInfo implementation
175//
176SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
177 EnumName = R->getValueAsString("Opcode");
178 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000179 Record *TypeProfile = R->getValueAsDef("TypeProfile");
180 NumResults = TypeProfile->getValueAsInt("NumResults");
181 NumOperands = TypeProfile->getValueAsInt("NumOperands");
182
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000183 // Parse the properties.
184 Properties = 0;
185 ListInit *LI = R->getValueAsListInit("Properties");
186 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
187 DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
188 assert(DI && "Properties list must be list of defs!");
189 if (DI->getDef()->getName() == "SDNPCommutative") {
190 Properties |= 1 << SDNPCommutative;
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000191 } else if (DI->getDef()->getName() == "SDNPAssociative") {
192 Properties |= 1 << SDNPAssociative;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000193 } else {
194 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
195 << "' on node '" << R->getName() << "'!\n";
196 exit(1);
197 }
198 }
199
200
Chris Lattner33c92e92005-09-08 21:27:15 +0000201 // Parse the type constraints.
202 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
203 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
204 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
205 "Constraints list should contain constraint definitions!");
206 Record *Constraint =
207 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
208 TypeConstraints.push_back(Constraint);
209 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000210}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000211
212//===----------------------------------------------------------------------===//
213// TreePatternNode implementation
214//
215
216TreePatternNode::~TreePatternNode() {
217#if 0 // FIXME: implement refcounted tree nodes!
218 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
219 delete getChild(i);
220#endif
221}
222
Chris Lattner32707602005-09-08 23:22:48 +0000223/// UpdateNodeType - Set the node type of N to VT if VT contains
224/// information. If N already contains a conflicting type, then throw an
225/// exception. This returns true if any information was updated.
226///
227bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
228 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
229 if (getType() == MVT::LAST_VALUETYPE) {
230 setType(VT);
231 return true;
232 }
233
234 TP.error("Type inference contradiction found in node " +
235 getOperator()->getName() + "!");
236 return true; // unreachable
237}
238
239
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000240void TreePatternNode::print(std::ostream &OS) const {
241 if (isLeaf()) {
242 OS << *getLeafValue();
243 } else {
244 OS << "(" << getOperator()->getName();
245 }
246
247 if (getType() == MVT::Other)
248 OS << ":Other";
249 else if (getType() == MVT::LAST_VALUETYPE)
250 ;//OS << ":?";
251 else
252 OS << ":" << getType();
253
254 if (!isLeaf()) {
255 if (getNumChildren() != 0) {
256 OS << " ";
257 getChild(0)->print(OS);
258 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
259 OS << ", ";
260 getChild(i)->print(OS);
261 }
262 }
263 OS << ")";
264 }
265
266 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000267 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000268 if (TransformFn)
269 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000270 if (!getName().empty())
271 OS << ":$" << getName();
272
273}
274void TreePatternNode::dump() const {
275 print(std::cerr);
276}
277
Chris Lattnere46e17b2005-09-29 19:28:10 +0000278/// isIsomorphicTo - Return true if this node is recursively isomorphic to
279/// the specified node. For this comparison, all of the state of the node
280/// is considered, except for the assigned name. Nodes with differing names
281/// that are otherwise identical are considered isomorphic.
282bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
283 if (N == this) return true;
284 if (N->isLeaf() != isLeaf() || getType() != N->getType() ||
285 getPredicateFn() != N->getPredicateFn() ||
286 getTransformFn() != N->getTransformFn())
287 return false;
288
289 if (isLeaf()) {
290 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
291 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
292 return DI->getDef() == NDI->getDef();
293 return getLeafValue() == N->getLeafValue();
294 }
295
296 if (N->getOperator() != getOperator() ||
297 N->getNumChildren() != getNumChildren()) return false;
298 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
299 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
300 return false;
301 return true;
302}
303
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000304/// clone - Make a copy of this tree and all of its children.
305///
306TreePatternNode *TreePatternNode::clone() const {
307 TreePatternNode *New;
308 if (isLeaf()) {
309 New = new TreePatternNode(getLeafValue());
310 } else {
311 std::vector<TreePatternNode*> CChildren;
312 CChildren.reserve(Children.size());
313 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
314 CChildren.push_back(getChild(i)->clone());
315 New = new TreePatternNode(getOperator(), CChildren);
316 }
317 New->setName(getName());
318 New->setType(getType());
319 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000320 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000321 return New;
322}
323
Chris Lattner32707602005-09-08 23:22:48 +0000324/// SubstituteFormalArguments - Replace the formal arguments in this tree
325/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000326void TreePatternNode::
327SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
328 if (isLeaf()) return;
329
330 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
331 TreePatternNode *Child = getChild(i);
332 if (Child->isLeaf()) {
333 Init *Val = Child->getLeafValue();
334 if (dynamic_cast<DefInit*>(Val) &&
335 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
336 // We found a use of a formal argument, replace it with its value.
337 Child = ArgMap[Child->getName()];
338 assert(Child && "Couldn't find formal argument!");
339 setChild(i, Child);
340 }
341 } else {
342 getChild(i)->SubstituteFormalArguments(ArgMap);
343 }
344 }
345}
346
347
348/// InlinePatternFragments - If this pattern refers to any pattern
349/// fragments, inline them into place, giving us a pattern without any
350/// PatFrag references.
351TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
352 if (isLeaf()) return this; // nothing to do.
353 Record *Op = getOperator();
354
355 if (!Op->isSubClassOf("PatFrag")) {
356 // Just recursively inline children nodes.
357 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
358 setChild(i, getChild(i)->InlinePatternFragments(TP));
359 return this;
360 }
361
362 // Otherwise, we found a reference to a fragment. First, look up its
363 // TreePattern record.
364 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
365
366 // Verify that we are passing the right number of operands.
367 if (Frag->getNumArgs() != Children.size())
368 TP.error("'" + Op->getName() + "' fragment requires " +
369 utostr(Frag->getNumArgs()) + " operands!");
370
Chris Lattner37937092005-09-09 01:15:01 +0000371 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000372
373 // Resolve formal arguments to their actual value.
374 if (Frag->getNumArgs()) {
375 // Compute the map of formal to actual arguments.
376 std::map<std::string, TreePatternNode*> ArgMap;
377 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
378 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
379
380 FragTree->SubstituteFormalArguments(ArgMap);
381 }
382
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000383 FragTree->setName(getName());
384
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000385 // Get a new copy of this fragment to stitch into here.
386 //delete this; // FIXME: implement refcounting!
387 return FragTree;
388}
389
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000390/// getIntrinsicType - Check to see if the specified record has an intrinsic
391/// type which should be applied to it. This infer the type of register
392/// references from the register file information, for example.
393///
394static MVT::ValueType getIntrinsicType(Record *R, bool NotRegisters, TreePattern &TP) {
395 // Check to see if this is a register or a register class...
396 if (R->isSubClassOf("RegisterClass")) {
397 if (NotRegisters) return MVT::LAST_VALUETYPE;
398 return getValueType(R->getValueAsDef("RegType"));
399 } else if (R->isSubClassOf("PatFrag")) {
400 // Pattern fragment types will be resolved when they are inlined.
401 return MVT::LAST_VALUETYPE;
402 } else if (R->isSubClassOf("Register")) {
403 assert(0 && "Explicit registers not handled here yet!\n");
404 return MVT::LAST_VALUETYPE;
405 } else if (R->isSubClassOf("ValueType")) {
406 // Using a VTSDNode.
407 return MVT::Other;
408 } else if (R->getName() == "node") {
409 // Placeholder.
410 return MVT::LAST_VALUETYPE;
411 }
412
413 TP.error("Unknown node flavor used in pattern: " + R->getName());
414 return MVT::Other;
415}
416
Chris Lattner32707602005-09-08 23:22:48 +0000417/// ApplyTypeConstraints - Apply all of the type constraints relevent to
418/// this node and its children in the tree. This returns true if it makes a
419/// change, false otherwise. If a type contradiction is found, throw an
420/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000421bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
422 if (isLeaf()) {
423 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
424 // If it's a regclass or something else known, include the type.
425 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
426 TP);
427 return false;
428 }
Chris Lattner32707602005-09-08 23:22:48 +0000429
430 // special handling for set, which isn't really an SDNode.
431 if (getOperator()->getName() == "set") {
432 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000433 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
434 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000435
436 // Types of operands must match.
437 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
438 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
439 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
440 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000441 } else if (getOperator()->isSubClassOf("SDNode")) {
442 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
443
444 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
445 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000446 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000447 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000448 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000449 const DAGInstruction &Inst =
450 TP.getDAGISelEmitter().getInstruction(getOperator());
451
Chris Lattnera28aec12005-09-15 22:23:50 +0000452 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
453 // Apply the result type to the node
454 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
455
456 if (getNumChildren() != Inst.getNumOperands())
457 TP.error("Instruction '" + getOperator()->getName() + " expects " +
458 utostr(Inst.getNumOperands()) + " operands, not " +
459 utostr(getNumChildren()) + " operands!");
460 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
461 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000462 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000463 }
464 return MadeChange;
465 } else {
466 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
467
468 // Node transforms always take one operand, and take and return the same
469 // type.
470 if (getNumChildren() != 1)
471 TP.error("Node transform '" + getOperator()->getName() +
472 "' requires one operand!");
473 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
474 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
475 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000476 }
Chris Lattner32707602005-09-08 23:22:48 +0000477}
478
Chris Lattnere97603f2005-09-28 19:27:25 +0000479/// canPatternMatch - If it is impossible for this pattern to match on this
480/// target, fill in Reason and return false. Otherwise, return true. This is
481/// used as a santity check for .td files (to prevent people from writing stuff
482/// that can never possibly work), and to prevent the pattern permuter from
483/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000484bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000485 if (isLeaf()) return true;
486
487 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
488 if (!getChild(i)->canPatternMatch(Reason, ISE))
489 return false;
490
491 // If this node is a commutative operator, check that the LHS isn't an
492 // immediate.
493 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
494 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
495 // Scan all of the operands of the node and make sure that only the last one
496 // is a constant node.
497 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
498 if (!getChild(i)->isLeaf() &&
499 getChild(i)->getOperator()->getName() == "imm") {
500 Reason = "Immediate value must be on the RHS of commutative operators!";
501 return false;
502 }
503 }
504
505 return true;
506}
Chris Lattner32707602005-09-08 23:22:48 +0000507
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000508//===----------------------------------------------------------------------===//
509// TreePattern implementation
510//
511
Chris Lattnera28aec12005-09-15 22:23:50 +0000512TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000513 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000514 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
515 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000516}
517
Chris Lattnera28aec12005-09-15 22:23:50 +0000518TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
519 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
520 Trees.push_back(ParseTreePattern(Pat));
521}
522
523TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
524 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
525 Trees.push_back(Pat);
526}
527
528
529
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000530void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000531 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000532 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000533}
534
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000535TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
536 Record *Operator = Dag->getNodeType();
537
538 if (Operator->isSubClassOf("ValueType")) {
539 // If the operator is a ValueType, then this must be "type cast" of a leaf
540 // node.
541 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000542 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000543
544 Init *Arg = Dag->getArg(0);
545 TreePatternNode *New;
546 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000547 Record *R = DI->getDef();
548 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
549 Dag->setArg(0, new DagInit(R,
550 std::vector<std::pair<Init*, std::string> >()));
551 TreePatternNode *TPN = ParseTreePattern(Dag);
552 TPN->setName(Dag->getArgName(0));
553 return TPN;
554 }
555
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000556 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000557 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
558 New = ParseTreePattern(DI);
559 } else {
560 Arg->dump();
561 error("Unknown leaf value for tree pattern!");
562 return 0;
563 }
564
Chris Lattner32707602005-09-08 23:22:48 +0000565 // Apply the type cast.
566 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000567 return New;
568 }
569
570 // Verify that this is something that makes sense for an operator.
571 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000572 !Operator->isSubClassOf("Instruction") &&
573 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000574 Operator->getName() != "set")
575 error("Unrecognized node '" + Operator->getName() + "'!");
576
577 std::vector<TreePatternNode*> Children;
578
579 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
580 Init *Arg = Dag->getArg(i);
581 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
582 Children.push_back(ParseTreePattern(DI));
583 Children.back()->setName(Dag->getArgName(i));
584 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
585 Record *R = DefI->getDef();
586 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
587 // TreePatternNode if its own.
588 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
589 Dag->setArg(i, new DagInit(R,
590 std::vector<std::pair<Init*, std::string> >()));
591 --i; // Revisit this node...
592 } else {
593 TreePatternNode *Node = new TreePatternNode(DefI);
594 Node->setName(Dag->getArgName(i));
595 Children.push_back(Node);
596
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000597 // Input argument?
598 if (R->getName() == "node") {
599 if (Dag->getArgName(i).empty())
600 error("'node' argument requires a name to match with operand list");
601 Args.push_back(Dag->getArgName(i));
602 }
603 }
604 } else {
605 Arg->dump();
606 error("Unknown leaf value for tree pattern!");
607 }
608 }
609
610 return new TreePatternNode(Operator, Children);
611}
612
Chris Lattner32707602005-09-08 23:22:48 +0000613/// InferAllTypes - Infer/propagate as many types throughout the expression
614/// patterns as possible. Return true if all types are infered, false
615/// otherwise. Throw an exception if a type contradiction is found.
616bool TreePattern::InferAllTypes() {
617 bool MadeChange = true;
618 while (MadeChange) {
619 MadeChange = false;
620 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000621 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000622 }
623
624 bool HasUnresolvedTypes = false;
625 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
626 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
627 return !HasUnresolvedTypes;
628}
629
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000630void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000631 OS << getRecord()->getName();
632 if (!Args.empty()) {
633 OS << "(" << Args[0];
634 for (unsigned i = 1, e = Args.size(); i != e; ++i)
635 OS << ", " << Args[i];
636 OS << ")";
637 }
638 OS << ": ";
639
640 if (Trees.size() > 1)
641 OS << "[\n";
642 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
643 OS << "\t";
644 Trees[i]->print(OS);
645 OS << "\n";
646 }
647
648 if (Trees.size() > 1)
649 OS << "]\n";
650}
651
652void TreePattern::dump() const { print(std::cerr); }
653
654
655
656//===----------------------------------------------------------------------===//
657// DAGISelEmitter implementation
658//
659
Chris Lattnerca559d02005-09-08 21:03:01 +0000660// Parse all of the SDNode definitions for the target, populating SDNodes.
661void DAGISelEmitter::ParseNodeInfo() {
662 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
663 while (!Nodes.empty()) {
664 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
665 Nodes.pop_back();
666 }
667}
668
Chris Lattner24eeeb82005-09-13 21:51:00 +0000669/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
670/// map, and emit them to the file as functions.
671void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
672 OS << "\n// Node transformations.\n";
673 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
674 while (!Xforms.empty()) {
675 Record *XFormNode = Xforms.back();
676 Record *SDNode = XFormNode->getValueAsDef("Opcode");
677 std::string Code = XFormNode->getValueAsCode("XFormFunction");
678 SDNodeXForms.insert(std::make_pair(XFormNode,
679 std::make_pair(SDNode, Code)));
680
Chris Lattner1048b7a2005-09-13 22:03:37 +0000681 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000682 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
683 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
684
Chris Lattner1048b7a2005-09-13 22:03:37 +0000685 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000686 << "(SDNode *" << C2 << ") {\n";
687 if (ClassName != "SDNode")
688 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
689 OS << Code << "\n}\n";
690 }
691
692 Xforms.pop_back();
693 }
694}
695
696
697
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000698/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
699/// file, building up the PatternFragments map. After we've collected them all,
700/// inline fragments together as necessary, so that there are no references left
701/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000702///
703/// This also emits all of the predicate functions to the output file.
704///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000705void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000706 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
707
708 // First step, parse all of the fragments and emit predicate functions.
709 OS << "\n// Predicate functions.\n";
710 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000711 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
712 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000713 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000714
715 // Validate the argument list, converting it to map, to discard duplicates.
716 std::vector<std::string> &Args = P->getArgList();
717 std::set<std::string> OperandsMap(Args.begin(), Args.end());
718
719 if (OperandsMap.count(""))
720 P->error("Cannot have unnamed 'node' values in pattern fragment!");
721
722 // Parse the operands list.
723 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
724 if (OpsList->getNodeType()->getName() != "ops")
725 P->error("Operands list should start with '(ops ... '!");
726
727 // Copy over the arguments.
728 Args.clear();
729 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
730 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
731 static_cast<DefInit*>(OpsList->getArg(j))->
732 getDef()->getName() != "node")
733 P->error("Operands list should all be 'node' values.");
734 if (OpsList->getArgName(j).empty())
735 P->error("Operands list should have names for each operand!");
736 if (!OperandsMap.count(OpsList->getArgName(j)))
737 P->error("'" + OpsList->getArgName(j) +
738 "' does not occur in pattern or was multiply specified!");
739 OperandsMap.erase(OpsList->getArgName(j));
740 Args.push_back(OpsList->getArgName(j));
741 }
742
743 if (!OperandsMap.empty())
744 P->error("Operands list does not contain an entry for operand '" +
745 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746
747 // If there is a code init for this fragment, emit the predicate code and
748 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000749 std::string Code = Fragments[i]->getValueAsCode("Predicate");
750 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000751 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000752 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000753 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000754 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
755
Chris Lattner1048b7a2005-09-13 22:03:37 +0000756 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000757 << "(SDNode *" << C2 << ") {\n";
758 if (ClassName != "SDNode")
759 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000760 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000761 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000762 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000763
764 // If there is a node transformation corresponding to this, keep track of
765 // it.
766 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
767 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000768 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000769 }
770
771 OS << "\n\n";
772
773 // Now that we've parsed all of the tree fragments, do a closure on them so
774 // that there are not references to PatFrags left inside of them.
775 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
776 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000777 TreePattern *ThePat = I->second;
778 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000779
Chris Lattner32707602005-09-08 23:22:48 +0000780 // Infer as many types as possible. Don't worry about it if we don't infer
781 // all of them, some may depend on the inputs of the pattern.
782 try {
783 ThePat->InferAllTypes();
784 } catch (...) {
785 // If this pattern fragment is not supported by this target (no types can
786 // satisfy its constraints), just ignore it. If the bogus pattern is
787 // actually used by instructions, the type consistency error will be
788 // reported there.
789 }
790
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000791 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000792 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000793 }
794}
795
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000796/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000797/// instruction input. Return true if this is a real use.
798static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000799 std::map<std::string, TreePatternNode*> &InstInputs) {
800 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000801 if (Pat->getName().empty()) {
802 if (Pat->isLeaf()) {
803 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
804 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
805 I->error("Input " + DI->getDef()->getName() + " must be named!");
806
807 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000808 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000809 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000810
811 Record *Rec;
812 if (Pat->isLeaf()) {
813 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
814 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
815 Rec = DI->getDef();
816 } else {
817 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
818 Rec = Pat->getOperator();
819 }
820
821 TreePatternNode *&Slot = InstInputs[Pat->getName()];
822 if (!Slot) {
823 Slot = Pat;
824 } else {
825 Record *SlotRec;
826 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000827 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000828 } else {
829 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
830 SlotRec = Slot->getOperator();
831 }
832
833 // Ensure that the inputs agree if we've already seen this input.
834 if (Rec != SlotRec)
835 I->error("All $" + Pat->getName() + " inputs must agree with each other");
836 if (Slot->getType() != Pat->getType())
837 I->error("All $" + Pat->getName() + " inputs must agree with each other");
838 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000839 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000840}
841
842/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
843/// part of "I", the instruction), computing the set of inputs and outputs of
844/// the pattern. Report errors if we see anything naughty.
845void DAGISelEmitter::
846FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
847 std::map<std::string, TreePatternNode*> &InstInputs,
848 std::map<std::string, Record*> &InstResults) {
849 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000850 bool isUse = HandleUse(I, Pat, InstInputs);
851 if (!isUse && Pat->getTransformFn())
852 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000853 return;
854 } else if (Pat->getOperator()->getName() != "set") {
855 // If this is not a set, verify that the children nodes are not void typed,
856 // and recurse.
857 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
858 if (Pat->getChild(i)->getType() == MVT::isVoid)
859 I->error("Cannot have void nodes inside of patterns!");
860 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
861 }
862
863 // If this is a non-leaf node with no children, treat it basically as if
864 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000865 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000866 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000867 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000868
Chris Lattnerf1311842005-09-14 23:05:13 +0000869 if (!isUse && Pat->getTransformFn())
870 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000871 return;
872 }
873
874 // Otherwise, this is a set, validate and collect instruction results.
875 if (Pat->getNumChildren() == 0)
876 I->error("set requires operands!");
877 else if (Pat->getNumChildren() & 1)
878 I->error("set requires an even number of operands");
879
Chris Lattnerf1311842005-09-14 23:05:13 +0000880 if (Pat->getTransformFn())
881 I->error("Cannot specify a transform function on a set node!");
882
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000883 // Check the set destinations.
884 unsigned NumValues = Pat->getNumChildren()/2;
885 for (unsigned i = 0; i != NumValues; ++i) {
886 TreePatternNode *Dest = Pat->getChild(i);
887 if (!Dest->isLeaf())
888 I->error("set destination should be a virtual register!");
889
890 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
891 if (!Val)
892 I->error("set destination should be a virtual register!");
893
894 if (!Val->getDef()->isSubClassOf("RegisterClass"))
895 I->error("set destination should be a virtual register!");
896 if (Dest->getName().empty())
897 I->error("set destination must have a name!");
898 if (InstResults.count(Dest->getName()))
899 I->error("cannot set '" + Dest->getName() +"' multiple times");
900 InstResults[Dest->getName()] = Val->getDef();
901
902 // Verify and collect info from the computation.
903 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
904 InstInputs, InstResults);
905 }
906}
907
908
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000909/// ParseInstructions - Parse all of the instructions, inlining and resolving
910/// any fragments involved. This populates the Instructions list with fully
911/// resolved instructions.
912void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000913 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
914
915 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
916 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
917 continue; // no pattern yet, ignore it.
918
919 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
920 if (LI->getSize() == 0) continue; // no pattern.
921
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000922 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000923 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000924 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000925 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000926
Chris Lattner95f6b762005-09-08 23:26:30 +0000927 // Infer as many types as possible. If we cannot infer all of them, we can
928 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000929 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +0000930 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000931
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000932 // InstInputs - Keep track of all of the inputs of the instruction, along
933 // with the record they are declared as.
934 std::map<std::string, TreePatternNode*> InstInputs;
935
936 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000937 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000938 std::map<std::string, Record*> InstResults;
939
Chris Lattner1f39e292005-09-14 00:09:24 +0000940 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000941 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000942 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
943 TreePatternNode *Pat = I->getTree(j);
944 if (Pat->getType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000945 I->dump();
946 I->error("Top-level forms in instruction pattern should have"
947 " void types");
948 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000949
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000950 // Find inputs and outputs, and verify the structure of the uses/defs.
951 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000952 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000953
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000954 // Now that we have inputs and outputs of the pattern, inspect the operands
955 // list for the instruction. This determines the order that operands are
956 // added to the machine instruction the node corresponds to.
957 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000958
959 // Parse the operands list from the (ops) list, validating it.
960 std::vector<std::string> &Args = I->getArgList();
961 assert(Args.empty() && "Args list should still be empty here!");
962 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
963
964 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +0000965 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +0000966 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000967 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000968 I->error("'" + InstResults.begin()->first +
969 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +0000970 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +0000971
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000972 // Check that it exists in InstResults.
973 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000974 if (R == 0)
975 I->error("Operand $" + OpName + " should be a set destination: all "
976 "outputs must occur before inputs in operand list!");
977
978 if (CGI.OperandList[i].Rec != R)
979 I->error("Operand $" + OpName + " class mismatch!");
980
Chris Lattnerae6d8282005-09-15 21:51:12 +0000981 // Remember the return type.
982 ResultTypes.push_back(CGI.OperandList[i].Ty);
983
Chris Lattner39e8af92005-09-14 18:19:25 +0000984 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000985 InstResults.erase(OpName);
986 }
987
Chris Lattner0b592252005-09-14 21:59:34 +0000988 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
989 // the copy while we're checking the inputs.
990 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +0000991
992 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +0000993 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000994 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
995 const std::string &OpName = CGI.OperandList[i].Name;
996 if (OpName.empty())
997 I->error("Operand #" + utostr(i) + " in operands list has no name!");
998
Chris Lattner0b592252005-09-14 21:59:34 +0000999 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001000 I->error("Operand $" + OpName +
1001 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001002 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001003 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001004 if (CGI.OperandList[i].Ty != InVal->getType())
1005 I->error("Operand $" + OpName +
1006 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +00001007 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +00001008
Chris Lattner2175c182005-09-14 23:01:59 +00001009 // Construct the result for the dest-pattern operand list.
1010 TreePatternNode *OpNode = InVal->clone();
1011
1012 // No predicate is useful on the result.
1013 OpNode->setPredicateFn("");
1014
1015 // Promote the xform function to be an explicit node if set.
1016 if (Record *Xform = OpNode->getTransformFn()) {
1017 OpNode->setTransformFn(0);
1018 std::vector<TreePatternNode*> Children;
1019 Children.push_back(OpNode);
1020 OpNode = new TreePatternNode(Xform, Children);
1021 }
1022
1023 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001024 }
1025
Chris Lattner0b592252005-09-14 21:59:34 +00001026 if (!InstInputsCheck.empty())
1027 I->error("Input operand $" + InstInputsCheck.begin()->first +
1028 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001029
1030 TreePatternNode *ResultPattern =
1031 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001032
1033 // Create and insert the instruction.
1034 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1035 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1036
1037 // Use a temporary tree pattern to infer all types and make sure that the
1038 // constructed result is correct. This depends on the instruction already
1039 // being inserted into the Instructions map.
1040 TreePattern Temp(I->getRecord(), ResultPattern, *this);
1041 Temp.InferAllTypes();
1042
1043 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1044 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001045
Chris Lattner32707602005-09-08 23:22:48 +00001046 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001047 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001048
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001049 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001050 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1051 E = Instructions.end(); II != E; ++II) {
1052 TreePattern *I = II->second.getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001053
1054 if (I->getNumTrees() != 1) {
1055 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1056 continue;
1057 }
1058 TreePatternNode *Pattern = I->getTree(0);
1059 if (Pattern->getOperator()->getName() != "set")
1060 continue; // Not a set (store or something?)
1061
1062 if (Pattern->getNumChildren() != 2)
1063 continue; // Not a set of a single value (not handled so far)
1064
1065 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001066
1067 std::string Reason;
1068 if (!SrcPattern->canPatternMatch(Reason, *this))
1069 I->error("Instruction can never match: " + Reason);
1070
Chris Lattnerae5b3502005-09-15 21:57:35 +00001071 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001072 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001073 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001074}
1075
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001076void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001077 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001078
Chris Lattnerabbb6052005-09-15 21:42:00 +00001079 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001080 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1081 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001082
Chris Lattnerabbb6052005-09-15 21:42:00 +00001083 // Inline pattern fragments into it.
1084 Pattern->InlinePatternFragments();
1085
1086 // Infer as many types as possible. If we cannot infer all of them, we can
1087 // never do anything with this pattern: report it to the user.
1088 if (!Pattern->InferAllTypes())
1089 Pattern->error("Could not infer all types in pattern!");
1090
1091 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1092 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001093
1094 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +00001095 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001096
1097 // Inline pattern fragments into it.
1098 Result->InlinePatternFragments();
1099
1100 // Infer as many types as possible. If we cannot infer all of them, we can
1101 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001102 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001103 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001104
1105 if (Result->getNumTrees() != 1)
1106 Result->error("Cannot handle instructions producing instructions "
1107 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001108
1109 std::string Reason;
1110 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1111 Pattern->error("Pattern can never match: " + Reason);
1112
Chris Lattnerabbb6052005-09-15 21:42:00 +00001113 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1114 Result->getOnlyTree()));
1115 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001116}
1117
Chris Lattnere46e17b2005-09-29 19:28:10 +00001118/// CombineChildVariants - Given a bunch of permutations of each child of the
1119/// 'operator' node, put them together in all possible ways.
1120static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001121 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001122 std::vector<TreePatternNode*> &OutVariants,
1123 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001124 // Make sure that each operand has at least one variant to choose from.
1125 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1126 if (ChildVariants[i].empty())
1127 return;
1128
Chris Lattnere46e17b2005-09-29 19:28:10 +00001129 // The end result is an all-pairs construction of the resultant pattern.
1130 std::vector<unsigned> Idxs;
1131 Idxs.resize(ChildVariants.size());
1132 bool NotDone = true;
1133 while (NotDone) {
1134 // Create the variant and add it to the output list.
1135 std::vector<TreePatternNode*> NewChildren;
1136 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1137 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1138 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1139
1140 // Copy over properties.
1141 R->setName(Orig->getName());
1142 R->setPredicateFn(Orig->getPredicateFn());
1143 R->setTransformFn(Orig->getTransformFn());
1144 R->setType(Orig->getType());
1145
1146 // If this pattern cannot every match, do not include it as a variant.
1147 std::string ErrString;
1148 if (!R->canPatternMatch(ErrString, ISE)) {
1149 delete R;
1150 } else {
1151 bool AlreadyExists = false;
1152
1153 // Scan to see if this pattern has already been emitted. We can get
1154 // duplication due to things like commuting:
1155 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1156 // which are the same pattern. Ignore the dups.
1157 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1158 if (R->isIsomorphicTo(OutVariants[i])) {
1159 AlreadyExists = true;
1160 break;
1161 }
1162
1163 if (AlreadyExists)
1164 delete R;
1165 else
1166 OutVariants.push_back(R);
1167 }
1168
1169 // Increment indices to the next permutation.
1170 NotDone = false;
1171 // Look for something we can increment without causing a wrap-around.
1172 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1173 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1174 NotDone = true; // Found something to increment.
1175 break;
1176 }
1177 Idxs[IdxsIdx] = 0;
1178 }
1179 }
1180}
1181
Chris Lattneraf302912005-09-29 22:36:54 +00001182/// CombineChildVariants - A helper function for binary operators.
1183///
1184static void CombineChildVariants(TreePatternNode *Orig,
1185 const std::vector<TreePatternNode*> &LHS,
1186 const std::vector<TreePatternNode*> &RHS,
1187 std::vector<TreePatternNode*> &OutVariants,
1188 DAGISelEmitter &ISE) {
1189 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1190 ChildVariants.push_back(LHS);
1191 ChildVariants.push_back(RHS);
1192 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1193}
1194
1195
1196static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1197 std::vector<TreePatternNode *> &Children) {
1198 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1199 Record *Operator = N->getOperator();
1200
1201 // Only permit raw nodes.
1202 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1203 N->getTransformFn()) {
1204 Children.push_back(N);
1205 return;
1206 }
1207
1208 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1209 Children.push_back(N->getChild(0));
1210 else
1211 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1212
1213 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1214 Children.push_back(N->getChild(1));
1215 else
1216 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1217}
1218
Chris Lattnere46e17b2005-09-29 19:28:10 +00001219/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1220/// the (potentially recursive) pattern by using algebraic laws.
1221///
1222static void GenerateVariantsOf(TreePatternNode *N,
1223 std::vector<TreePatternNode*> &OutVariants,
1224 DAGISelEmitter &ISE) {
1225 // We cannot permute leaves.
1226 if (N->isLeaf()) {
1227 OutVariants.push_back(N);
1228 return;
1229 }
1230
1231 // Look up interesting info about the node.
1232 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1233
1234 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001235 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1236 // Reassociate by pulling together all of the linked operators
1237 std::vector<TreePatternNode*> MaximalChildren;
1238 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1239
1240 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1241 // permutations.
1242 if (MaximalChildren.size() == 3) {
1243 // Find the variants of all of our maximal children.
1244 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1245 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1246 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1247 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1248
1249 // There are only two ways we can permute the tree:
1250 // (A op B) op C and A op (B op C)
1251 // Within these forms, we can also permute A/B/C.
1252
1253 // Generate legal pair permutations of A/B/C.
1254 std::vector<TreePatternNode*> ABVariants;
1255 std::vector<TreePatternNode*> BAVariants;
1256 std::vector<TreePatternNode*> ACVariants;
1257 std::vector<TreePatternNode*> CAVariants;
1258 std::vector<TreePatternNode*> BCVariants;
1259 std::vector<TreePatternNode*> CBVariants;
1260 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1261 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1262 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1263 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1264 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1265 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1266
1267 // Combine those into the result: (x op x) op x
1268 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1269 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1270 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1271 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1272 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1273 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1274
1275 // Combine those into the result: x op (x op x)
1276 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1277 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1278 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1279 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1280 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1281 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1282 return;
1283 }
1284 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001285
1286 // Compute permutations of all children.
1287 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1288 ChildVariants.resize(N->getNumChildren());
1289 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1290 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1291
1292 // Build all permutations based on how the children were formed.
1293 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1294
1295 // If this node is commutative, consider the commuted order.
1296 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1297 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001298 // Consider the commuted order.
1299 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1300 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001301 }
1302}
1303
1304
Chris Lattnere97603f2005-09-28 19:27:25 +00001305// GenerateVariants - Generate variants. For example, commutative patterns can
1306// match multiple ways. Add them to PatternsToMatch as well.
1307void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001308
1309 DEBUG(std::cerr << "Generating instruction variants.\n");
1310
1311 // Loop over all of the patterns we've collected, checking to see if we can
1312 // generate variants of the instruction, through the exploitation of
1313 // identities. This permits the target to provide agressive matching without
1314 // the .td file having to contain tons of variants of instructions.
1315 //
1316 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1317 // intentionally do not reconsider these. Any variants of added patterns have
1318 // already been added.
1319 //
1320 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1321 std::vector<TreePatternNode*> Variants;
1322 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1323
1324 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001325 Variants.erase(Variants.begin()); // Remove the original pattern.
1326
1327 if (Variants.empty()) // No variants for this pattern.
1328 continue;
1329
1330 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1331 PatternsToMatch[i].first->dump();
1332 std::cerr << "\n");
1333
1334 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1335 TreePatternNode *Variant = Variants[v];
1336
1337 DEBUG(std::cerr << " VAR#" << v << ": ";
1338 Variant->dump();
1339 std::cerr << "\n");
1340
1341 // Scan to see if an instruction or explicit pattern already matches this.
1342 bool AlreadyExists = false;
1343 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1344 // Check to see if this variant already exists.
1345 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1346 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1347 AlreadyExists = true;
1348 break;
1349 }
1350 }
1351 // If we already have it, ignore the variant.
1352 if (AlreadyExists) continue;
1353
1354 // Otherwise, add it to the list of patterns we have.
1355 PatternsToMatch.push_back(std::make_pair(Variant,
1356 PatternsToMatch[i].second));
1357 }
1358
1359 DEBUG(std::cerr << "\n");
1360 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001361}
1362
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001363
Chris Lattner05814af2005-09-28 17:57:56 +00001364/// getPatternSize - Return the 'size' of this pattern. We want to match large
1365/// patterns before small ones. This is used to determine the size of a
1366/// pattern.
1367static unsigned getPatternSize(TreePatternNode *P) {
1368 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1369 "Not a valid pattern node to size!");
1370 unsigned Size = 1; // The node itself.
1371
1372 // Count children in the count if they are also nodes.
1373 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1374 TreePatternNode *Child = P->getChild(i);
1375 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1376 Size += getPatternSize(Child);
1377 }
1378
1379 return Size;
1380}
1381
1382/// getResultPatternCost - Compute the number of instructions for this pattern.
1383/// This is a temporary hack. We should really include the instruction
1384/// latencies in this calculation.
1385static unsigned getResultPatternCost(TreePatternNode *P) {
1386 if (P->isLeaf()) return 0;
1387
1388 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1389 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1390 Cost += getResultPatternCost(P->getChild(i));
1391 return Cost;
1392}
1393
1394// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1395// In particular, we want to match maximal patterns first and lowest cost within
1396// a particular complexity first.
1397struct PatternSortingPredicate {
1398 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1399 DAGISelEmitter::PatternToMatch *RHS) {
1400 unsigned LHSSize = getPatternSize(LHS->first);
1401 unsigned RHSSize = getPatternSize(RHS->first);
1402 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1403 if (LHSSize < RHSSize) return false;
1404
1405 // If the patterns have equal complexity, compare generated instruction cost
1406 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1407 }
1408};
1409
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001410/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1411/// if the match fails. At this point, we already know that the opcode for N
1412/// matches, and the SDNode for the result has the RootName specified name.
1413void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001414 const std::string &RootName,
1415 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001416 unsigned PatternNo, std::ostream &OS) {
1417 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001418
1419 // If this node has a name associated with it, capture it in VarMap. If
1420 // we already saw this in the pattern, emit code to verify dagness.
1421 if (!N->getName().empty()) {
1422 std::string &VarMapEntry = VarMap[N->getName()];
1423 if (VarMapEntry.empty()) {
1424 VarMapEntry = RootName;
1425 } else {
1426 // If we get here, this is a second reference to a specific name. Since
1427 // we already have checked that the first reference is valid, we don't
1428 // have to recursively match it, just check that it's the same as the
1429 // previously named thing.
1430 OS << " if (" << VarMapEntry << " != " << RootName
1431 << ") goto P" << PatternNo << "Fail;\n";
1432 return;
1433 }
1434 }
1435
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001436 // Emit code to load the child nodes and match their contents recursively.
1437 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001438 OS << " SDOperand " << RootName << i <<" = " << RootName
1439 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001440 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001441
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001442 if (!Child->isLeaf()) {
1443 // If it's not a leaf, recursively match.
1444 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001445 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001446 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001447 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001448 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001449 // If this child has a name associated with it, capture it in VarMap. If
1450 // we already saw this in the pattern, emit code to verify dagness.
1451 if (!Child->getName().empty()) {
1452 std::string &VarMapEntry = VarMap[Child->getName()];
1453 if (VarMapEntry.empty()) {
1454 VarMapEntry = RootName + utostr(i);
1455 } else {
1456 // If we get here, this is a second reference to a specific name. Since
1457 // we already have checked that the first reference is valid, we don't
1458 // have to recursively match it, just check that it's the same as the
1459 // previously named thing.
1460 OS << " if (" << VarMapEntry << " != " << RootName << i
1461 << ") goto P" << PatternNo << "Fail;\n";
1462 continue;
1463 }
1464 }
1465
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001466 // Handle leaves of various types.
1467 Init *LeafVal = Child->getLeafValue();
1468 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1469 if (LeafRec->isSubClassOf("RegisterClass")) {
1470 // Handle register references. Nothing to do here.
1471 } else if (LeafRec->isSubClassOf("ValueType")) {
1472 // Make sure this is the specified value type.
1473 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1474 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1475 << "Fail;\n";
1476 } else {
1477 Child->dump();
1478 assert(0 && "Unknown leaf type!");
1479 }
1480 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001481 }
1482
1483 // If there is a node predicate for this, emit the call.
1484 if (!N->getPredicateFn().empty())
1485 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001486 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001487}
1488
Chris Lattner6bc7e512005-09-26 21:53:26 +00001489/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1490/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001491unsigned DAGISelEmitter::
1492CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1493 std::map<std::string,std::string> &VariableMap,
Chris Lattner6bc7e512005-09-26 21:53:26 +00001494 std::ostream &OS) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001495 // This is something selected from the pattern we matched.
1496 if (!N->getName().empty()) {
Chris Lattner6bc7e512005-09-26 21:53:26 +00001497 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001498 assert(!Val.empty() &&
1499 "Variable referenced but not defined and not caught earlier!");
1500 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1501 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001502 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001503 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001504
1505 unsigned ResNo = Ctr++;
1506 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1507 switch (N->getType()) {
1508 default: assert(0 && "Unknown type for constant node!");
1509 case MVT::i1: OS << " bool Tmp"; break;
1510 case MVT::i8: OS << " unsigned char Tmp"; break;
1511 case MVT::i16: OS << " unsigned short Tmp"; break;
1512 case MVT::i32: OS << " unsigned Tmp"; break;
1513 case MVT::i64: OS << " uint64_t Tmp"; break;
1514 }
1515 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1516 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1517 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1518 } else {
1519 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1520 }
1521 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1522 // value if used multiple times by this pattern result.
1523 Val = "Tmp"+utostr(ResNo);
1524 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001525 }
1526
1527 if (N->isLeaf()) {
1528 N->dump();
1529 assert(0 && "Unknown leaf type!");
1530 return ~0U;
1531 }
1532
1533 Record *Op = N->getOperator();
1534 if (Op->isSubClassOf("Instruction")) {
1535 // Emit all of the operands.
1536 std::vector<unsigned> Ops;
1537 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1538 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1539
1540 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1541 unsigned ResNo = Ctr++;
1542
1543 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1544 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1545 << getEnumName(N->getType());
1546 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1547 OS << ", Tmp" << Ops[i];
1548 OS << ");\n";
1549 return ResNo;
1550 } else if (Op->isSubClassOf("SDNodeXForm")) {
1551 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1552 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1553
1554 unsigned ResNo = Ctr++;
1555 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1556 << "(Tmp" << OpVal << ".Val);\n";
1557 return ResNo;
1558 } else {
1559 N->dump();
1560 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001561 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001562 }
1563}
1564
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001565/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1566/// type information from it.
1567static void RemoveAllTypes(TreePatternNode *N) {
1568 N->setType(MVT::LAST_VALUETYPE);
1569 if (!N->isLeaf())
1570 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1571 RemoveAllTypes(N->getChild(i));
1572}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001573
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001574/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1575/// stream to match the pattern, and generate the code for the match if it
1576/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001577void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1578 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001579 static unsigned PatternCount = 0;
1580 unsigned PatternNo = PatternCount++;
1581 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001582 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001583 OS << "\n // Emits: ";
1584 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001585 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001586 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1587 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001588
Chris Lattner8fc35682005-09-23 23:16:51 +00001589 // Emit the matcher, capturing named arguments in VariableMap.
1590 std::map<std::string,std::string> VariableMap;
1591 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001592
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001593 // TP - Get *SOME* tree pattern, we don't care which.
1594 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001595
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001596 // At this point, we know that we structurally match the pattern, but the
1597 // types of the nodes may not match. Figure out the fewest number of type
1598 // comparisons we need to emit. For example, if there is only one integer
1599 // type supported by a target, there should be no type comparisons at all for
1600 // integer patterns!
1601 //
1602 // To figure out the fewest number of type checks needed, clone the pattern,
1603 // remove the types, then perform type inference on the pattern as a whole.
1604 // If there are unresolved types, emit an explicit check for those types,
1605 // apply the type to the tree, then rerun type inference. Iterate until all
1606 // types are resolved.
1607 //
1608 TreePatternNode *Pat = Pattern.first->clone();
1609 RemoveAllTypes(Pat);
1610 bool MadeChange = true;
1611 try {
1612 while (MadeChange)
1613 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1614 } catch (...) {
1615 assert(0 && "Error: could not find consistent types for something we"
1616 " already decided was ok!");
1617 abort();
1618 }
1619
1620 if (!Pat->ContainsUnresolvedType()) {
1621 unsigned TmpNo = 0;
1622 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
1623
1624 // Add the result to the map if it has multiple uses.
1625 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
1626 OS << " return Tmp" << Res << ";\n";
1627 }
1628
1629 delete Pat;
1630
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001631 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001632}
1633
Chris Lattner37481472005-09-26 21:59:35 +00001634
1635namespace {
1636 /// CompareByRecordName - An ordering predicate that implements less-than by
1637 /// comparing the names records.
1638 struct CompareByRecordName {
1639 bool operator()(const Record *LHS, const Record *RHS) const {
1640 // Sort by name first.
1641 if (LHS->getName() < RHS->getName()) return true;
1642 // If both names are equal, sort by pointer.
1643 return LHS->getName() == RHS->getName() && LHS < RHS;
1644 }
1645 };
1646}
1647
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001648void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1649 // Emit boilerplate.
1650 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001651 << "SDOperand SelectCode(SDOperand N) {\n"
1652 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1653 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1654 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001655 << " if (!N.Val->hasOneUse()) {\n"
1656 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1657 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1658 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001659 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001660 << " default: break;\n"
1661 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001662 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001663 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001664 << " case ISD::AssertZext: {\n"
1665 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1666 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1667 << " return Tmp0;\n"
1668 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001669
Chris Lattner81303322005-09-23 19:36:15 +00001670 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001671 std::map<Record*, std::vector<PatternToMatch*>,
1672 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001673 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1674 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1675 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001676
Chris Lattner3f7e9142005-09-23 20:52:47 +00001677 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001678 for (std::map<Record*, std::vector<PatternToMatch*>,
1679 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1680 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001681 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1682 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1683
1684 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001685
1686 // We want to emit all of the matching code now. However, we want to emit
1687 // the matches in order of minimal cost. Sort the patterns so the least
1688 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001689 std::stable_sort(Patterns.begin(), Patterns.end(),
1690 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001691
Chris Lattner3f7e9142005-09-23 20:52:47 +00001692 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1693 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001694 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001695 }
1696
1697
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001698 OS << " } // end of big switch.\n\n"
1699 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001700 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001701 << " std::cerr << '\\n';\n"
1702 << " abort();\n"
1703 << "}\n";
1704}
1705
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001706void DAGISelEmitter::run(std::ostream &OS) {
1707 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1708 " target", OS);
1709
Chris Lattner1f39e292005-09-14 00:09:24 +00001710 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1711 << "// *** instruction selector class. These functions are really "
1712 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001713
Chris Lattner296dfe32005-09-24 00:50:51 +00001714 OS << "// Instance var to keep track of multiply used nodes that have \n"
1715 << "// already been selected.\n"
1716 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1717
Chris Lattnerca559d02005-09-08 21:03:01 +00001718 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001719 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001720 ParsePatternFragments(OS);
1721 ParseInstructions();
1722 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001723
Chris Lattnere97603f2005-09-28 19:27:25 +00001724 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001725 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001726 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001727
Chris Lattnere46e17b2005-09-29 19:28:10 +00001728
1729 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1730 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1731 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1732 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1733 std::cerr << "\n";
1734 });
1735
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001736 // At this point, we have full information about the 'Patterns' we need to
1737 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001738 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001739 EmitInstructionSelector(OS);
1740
1741 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1742 E = PatternFragments.end(); I != E; ++I)
1743 delete I->second;
1744 PatternFragments.clear();
1745
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001746 Instructions.clear();
1747}