blob: 69757e9700df48c3904fb42c49d396170931e3b4 [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
Chris Lattnere0583b12005-10-14 05:08:37 +000066template<typename T>
67static std::vector<MVT::ValueType>
68FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
69 std::vector<MVT::ValueType> Result;
70 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
71 if (Filter(InVTs[i]))
72 Result.push_back(InVTs[i]);
73 return Result;
74}
75
Chris Lattner32707602005-09-08 23:22:48 +000076/// ApplyTypeConstraint - Given a node in a pattern, apply this type
77/// constraint to the nodes operands. This returns true if it makes a
78/// change, false otherwise. If a type contradiction is found, throw an
79/// exception.
80bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
81 const SDNodeInfo &NodeInfo,
82 TreePattern &TP) const {
83 unsigned NumResults = NodeInfo.getNumResults();
84 assert(NumResults == 1 && "We only work with single result nodes so far!");
85
86 // Check that the number of operands is sane.
87 if (NodeInfo.getNumOperands() >= 0) {
88 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
89 TP.error(N->getOperator()->getName() + " node requires exactly " +
90 itostr(NodeInfo.getNumOperands()) + " operands!");
91 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +000092
93 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +000094
95 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
96
97 switch (ConstraintType) {
98 default: assert(0 && "Unknown constraint type!");
99 case SDTCisVT:
100 // Operand must be a particular type.
101 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000102 case SDTCisInt: {
Chris Lattner32707602005-09-08 23:22:48 +0000103 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
104 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
105
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000106 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000107 std::vector<MVT::ValueType> IntVTs =
108 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000109
110 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000111 if (IntVTs.size() == 1)
112 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner32707602005-09-08 23:22:48 +0000113 return false;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000114 }
115 case SDTCisFP: {
Chris Lattner32707602005-09-08 23:22:48 +0000116 if (NodeToApply->hasTypeSet() &&
117 !MVT::isFloatingPoint(NodeToApply->getType()))
118 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000119
120 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000121 std::vector<MVT::ValueType> FPVTs =
122 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000123
124 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000125 if (FPVTs.size() == 1)
126 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner32707602005-09-08 23:22:48 +0000127 return false;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000128 }
Chris Lattner32707602005-09-08 23:22:48 +0000129 case SDTCisSameAs: {
130 TreePatternNode *OtherNode =
131 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
132 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
133 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
134 }
135 case SDTCisVTSmallerThanOp: {
136 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
137 // have an integer type that is smaller than the VT.
138 if (!NodeToApply->isLeaf() ||
139 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
140 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
141 ->isSubClassOf("ValueType"))
142 TP.error(N->getOperator()->getName() + " expects a VT operand!");
143 MVT::ValueType VT =
144 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
145 if (!MVT::isInteger(VT))
146 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
147
148 TreePatternNode *OtherNode =
149 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
150 if (OtherNode->hasTypeSet() &&
151 (!MVT::isInteger(OtherNode->getType()) ||
152 OtherNode->getType() <= VT))
153 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
154 return false;
155 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000156 case SDTCisOpSmallerThanOp: {
157 // TODO
158 return false;
159 }
Chris Lattner32707602005-09-08 23:22:48 +0000160 }
161 return false;
162}
163
164
Chris Lattner33c92e92005-09-08 21:27:15 +0000165//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000166// SDNodeInfo implementation
167//
168SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
169 EnumName = R->getValueAsString("Opcode");
170 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000171 Record *TypeProfile = R->getValueAsDef("TypeProfile");
172 NumResults = TypeProfile->getValueAsInt("NumResults");
173 NumOperands = TypeProfile->getValueAsInt("NumOperands");
174
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000175 // Parse the properties.
176 Properties = 0;
177 ListInit *LI = R->getValueAsListInit("Properties");
178 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
179 DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
180 assert(DI && "Properties list must be list of defs!");
181 if (DI->getDef()->getName() == "SDNPCommutative") {
182 Properties |= 1 << SDNPCommutative;
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000183 } else if (DI->getDef()->getName() == "SDNPAssociative") {
184 Properties |= 1 << SDNPAssociative;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000185 } else {
186 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
187 << "' on node '" << R->getName() << "'!\n";
188 exit(1);
189 }
190 }
191
192
Chris Lattner33c92e92005-09-08 21:27:15 +0000193 // Parse the type constraints.
194 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
195 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
196 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
197 "Constraints list should contain constraint definitions!");
198 Record *Constraint =
199 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
200 TypeConstraints.push_back(Constraint);
201 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000202}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000203
204//===----------------------------------------------------------------------===//
205// TreePatternNode implementation
206//
207
208TreePatternNode::~TreePatternNode() {
209#if 0 // FIXME: implement refcounted tree nodes!
210 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
211 delete getChild(i);
212#endif
213}
214
Chris Lattner32707602005-09-08 23:22:48 +0000215/// UpdateNodeType - Set the node type of N to VT if VT contains
216/// information. If N already contains a conflicting type, then throw an
217/// exception. This returns true if any information was updated.
218///
219bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
220 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
221 if (getType() == MVT::LAST_VALUETYPE) {
222 setType(VT);
223 return true;
224 }
225
226 TP.error("Type inference contradiction found in node " +
227 getOperator()->getName() + "!");
228 return true; // unreachable
229}
230
231
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000232void TreePatternNode::print(std::ostream &OS) const {
233 if (isLeaf()) {
234 OS << *getLeafValue();
235 } else {
236 OS << "(" << getOperator()->getName();
237 }
238
239 if (getType() == MVT::Other)
240 OS << ":Other";
241 else if (getType() == MVT::LAST_VALUETYPE)
242 ;//OS << ":?";
243 else
244 OS << ":" << getType();
245
246 if (!isLeaf()) {
247 if (getNumChildren() != 0) {
248 OS << " ";
249 getChild(0)->print(OS);
250 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
251 OS << ", ";
252 getChild(i)->print(OS);
253 }
254 }
255 OS << ")";
256 }
257
258 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000259 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000260 if (TransformFn)
261 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000262 if (!getName().empty())
263 OS << ":$" << getName();
264
265}
266void TreePatternNode::dump() const {
267 print(std::cerr);
268}
269
Chris Lattnere46e17b2005-09-29 19:28:10 +0000270/// isIsomorphicTo - Return true if this node is recursively isomorphic to
271/// the specified node. For this comparison, all of the state of the node
272/// is considered, except for the assigned name. Nodes with differing names
273/// that are otherwise identical are considered isomorphic.
274bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
275 if (N == this) return true;
276 if (N->isLeaf() != isLeaf() || getType() != N->getType() ||
277 getPredicateFn() != N->getPredicateFn() ||
278 getTransformFn() != N->getTransformFn())
279 return false;
280
281 if (isLeaf()) {
282 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
283 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
284 return DI->getDef() == NDI->getDef();
285 return getLeafValue() == N->getLeafValue();
286 }
287
288 if (N->getOperator() != getOperator() ||
289 N->getNumChildren() != getNumChildren()) return false;
290 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
291 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
292 return false;
293 return true;
294}
295
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000296/// clone - Make a copy of this tree and all of its children.
297///
298TreePatternNode *TreePatternNode::clone() const {
299 TreePatternNode *New;
300 if (isLeaf()) {
301 New = new TreePatternNode(getLeafValue());
302 } else {
303 std::vector<TreePatternNode*> CChildren;
304 CChildren.reserve(Children.size());
305 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
306 CChildren.push_back(getChild(i)->clone());
307 New = new TreePatternNode(getOperator(), CChildren);
308 }
309 New->setName(getName());
310 New->setType(getType());
311 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000312 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000313 return New;
314}
315
Chris Lattner32707602005-09-08 23:22:48 +0000316/// SubstituteFormalArguments - Replace the formal arguments in this tree
317/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000318void TreePatternNode::
319SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
320 if (isLeaf()) return;
321
322 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
323 TreePatternNode *Child = getChild(i);
324 if (Child->isLeaf()) {
325 Init *Val = Child->getLeafValue();
326 if (dynamic_cast<DefInit*>(Val) &&
327 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
328 // We found a use of a formal argument, replace it with its value.
329 Child = ArgMap[Child->getName()];
330 assert(Child && "Couldn't find formal argument!");
331 setChild(i, Child);
332 }
333 } else {
334 getChild(i)->SubstituteFormalArguments(ArgMap);
335 }
336 }
337}
338
339
340/// InlinePatternFragments - If this pattern refers to any pattern
341/// fragments, inline them into place, giving us a pattern without any
342/// PatFrag references.
343TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
344 if (isLeaf()) return this; // nothing to do.
345 Record *Op = getOperator();
346
347 if (!Op->isSubClassOf("PatFrag")) {
348 // Just recursively inline children nodes.
349 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
350 setChild(i, getChild(i)->InlinePatternFragments(TP));
351 return this;
352 }
353
354 // Otherwise, we found a reference to a fragment. First, look up its
355 // TreePattern record.
356 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
357
358 // Verify that we are passing the right number of operands.
359 if (Frag->getNumArgs() != Children.size())
360 TP.error("'" + Op->getName() + "' fragment requires " +
361 utostr(Frag->getNumArgs()) + " operands!");
362
Chris Lattner37937092005-09-09 01:15:01 +0000363 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000364
365 // Resolve formal arguments to their actual value.
366 if (Frag->getNumArgs()) {
367 // Compute the map of formal to actual arguments.
368 std::map<std::string, TreePatternNode*> ArgMap;
369 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
370 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
371
372 FragTree->SubstituteFormalArguments(ArgMap);
373 }
374
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000375 FragTree->setName(getName());
376
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000377 // Get a new copy of this fragment to stitch into here.
378 //delete this; // FIXME: implement refcounting!
379 return FragTree;
380}
381
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000382/// getIntrinsicType - Check to see if the specified record has an intrinsic
383/// type which should be applied to it. This infer the type of register
384/// references from the register file information, for example.
385///
386static MVT::ValueType getIntrinsicType(Record *R, bool NotRegisters, TreePattern &TP) {
387 // Check to see if this is a register or a register class...
388 if (R->isSubClassOf("RegisterClass")) {
389 if (NotRegisters) return MVT::LAST_VALUETYPE;
390 return getValueType(R->getValueAsDef("RegType"));
391 } else if (R->isSubClassOf("PatFrag")) {
392 // Pattern fragment types will be resolved when they are inlined.
393 return MVT::LAST_VALUETYPE;
394 } else if (R->isSubClassOf("Register")) {
395 assert(0 && "Explicit registers not handled here yet!\n");
396 return MVT::LAST_VALUETYPE;
397 } else if (R->isSubClassOf("ValueType")) {
398 // Using a VTSDNode.
399 return MVT::Other;
400 } else if (R->getName() == "node") {
401 // Placeholder.
402 return MVT::LAST_VALUETYPE;
403 }
404
405 TP.error("Unknown node flavor used in pattern: " + R->getName());
406 return MVT::Other;
407}
408
Chris Lattner32707602005-09-08 23:22:48 +0000409/// ApplyTypeConstraints - Apply all of the type constraints relevent to
410/// this node and its children in the tree. This returns true if it makes a
411/// change, false otherwise. If a type contradiction is found, throw an
412/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000413bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
414 if (isLeaf()) {
415 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
416 // If it's a regclass or something else known, include the type.
417 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
418 TP);
419 return false;
420 }
Chris Lattner32707602005-09-08 23:22:48 +0000421
422 // special handling for set, which isn't really an SDNode.
423 if (getOperator()->getName() == "set") {
424 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000425 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
426 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000427
428 // Types of operands must match.
429 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
430 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
431 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
432 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000433 } else if (getOperator()->isSubClassOf("SDNode")) {
434 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
435
436 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
437 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000438 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000439 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000440 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000441 const DAGInstruction &Inst =
442 TP.getDAGISelEmitter().getInstruction(getOperator());
443
Chris Lattnera28aec12005-09-15 22:23:50 +0000444 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
445 // Apply the result type to the node
446 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
447
448 if (getNumChildren() != Inst.getNumOperands())
449 TP.error("Instruction '" + getOperator()->getName() + " expects " +
450 utostr(Inst.getNumOperands()) + " operands, not " +
451 utostr(getNumChildren()) + " operands!");
452 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
453 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000454 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000455 }
456 return MadeChange;
457 } else {
458 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
459
460 // Node transforms always take one operand, and take and return the same
461 // type.
462 if (getNumChildren() != 1)
463 TP.error("Node transform '" + getOperator()->getName() +
464 "' requires one operand!");
465 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
466 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
467 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000468 }
Chris Lattner32707602005-09-08 23:22:48 +0000469}
470
Chris Lattnere97603f2005-09-28 19:27:25 +0000471/// canPatternMatch - If it is impossible for this pattern to match on this
472/// target, fill in Reason and return false. Otherwise, return true. This is
473/// used as a santity check for .td files (to prevent people from writing stuff
474/// that can never possibly work), and to prevent the pattern permuter from
475/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000476bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000477 if (isLeaf()) return true;
478
479 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
480 if (!getChild(i)->canPatternMatch(Reason, ISE))
481 return false;
482
483 // If this node is a commutative operator, check that the LHS isn't an
484 // immediate.
485 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
486 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
487 // Scan all of the operands of the node and make sure that only the last one
488 // is a constant node.
489 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
490 if (!getChild(i)->isLeaf() &&
491 getChild(i)->getOperator()->getName() == "imm") {
492 Reason = "Immediate value must be on the RHS of commutative operators!";
493 return false;
494 }
495 }
496
497 return true;
498}
Chris Lattner32707602005-09-08 23:22:48 +0000499
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000500//===----------------------------------------------------------------------===//
501// TreePattern implementation
502//
503
Chris Lattnera28aec12005-09-15 22:23:50 +0000504TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000505 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000506 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
507 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000508}
509
Chris Lattnera28aec12005-09-15 22:23:50 +0000510TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
511 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
512 Trees.push_back(ParseTreePattern(Pat));
513}
514
515TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
516 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
517 Trees.push_back(Pat);
518}
519
520
521
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000522void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000523 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000524 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000525}
526
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000527TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
528 Record *Operator = Dag->getNodeType();
529
530 if (Operator->isSubClassOf("ValueType")) {
531 // If the operator is a ValueType, then this must be "type cast" of a leaf
532 // node.
533 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000534 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000535
536 Init *Arg = Dag->getArg(0);
537 TreePatternNode *New;
538 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000539 Record *R = DI->getDef();
540 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
541 Dag->setArg(0, new DagInit(R,
542 std::vector<std::pair<Init*, std::string> >()));
543 TreePatternNode *TPN = ParseTreePattern(Dag);
544 TPN->setName(Dag->getArgName(0));
545 return TPN;
546 }
547
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000548 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000549 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
550 New = ParseTreePattern(DI);
551 } else {
552 Arg->dump();
553 error("Unknown leaf value for tree pattern!");
554 return 0;
555 }
556
Chris Lattner32707602005-09-08 23:22:48 +0000557 // Apply the type cast.
558 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000559 return New;
560 }
561
562 // Verify that this is something that makes sense for an operator.
563 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000564 !Operator->isSubClassOf("Instruction") &&
565 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000566 Operator->getName() != "set")
567 error("Unrecognized node '" + Operator->getName() + "'!");
568
569 std::vector<TreePatternNode*> Children;
570
571 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
572 Init *Arg = Dag->getArg(i);
573 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
574 Children.push_back(ParseTreePattern(DI));
575 Children.back()->setName(Dag->getArgName(i));
576 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
577 Record *R = DefI->getDef();
578 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
579 // TreePatternNode if its own.
580 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
581 Dag->setArg(i, new DagInit(R,
582 std::vector<std::pair<Init*, std::string> >()));
583 --i; // Revisit this node...
584 } else {
585 TreePatternNode *Node = new TreePatternNode(DefI);
586 Node->setName(Dag->getArgName(i));
587 Children.push_back(Node);
588
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000589 // Input argument?
590 if (R->getName() == "node") {
591 if (Dag->getArgName(i).empty())
592 error("'node' argument requires a name to match with operand list");
593 Args.push_back(Dag->getArgName(i));
594 }
595 }
596 } else {
597 Arg->dump();
598 error("Unknown leaf value for tree pattern!");
599 }
600 }
601
602 return new TreePatternNode(Operator, Children);
603}
604
Chris Lattner32707602005-09-08 23:22:48 +0000605/// InferAllTypes - Infer/propagate as many types throughout the expression
606/// patterns as possible. Return true if all types are infered, false
607/// otherwise. Throw an exception if a type contradiction is found.
608bool TreePattern::InferAllTypes() {
609 bool MadeChange = true;
610 while (MadeChange) {
611 MadeChange = false;
612 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000613 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000614 }
615
616 bool HasUnresolvedTypes = false;
617 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
618 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
619 return !HasUnresolvedTypes;
620}
621
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000622void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000623 OS << getRecord()->getName();
624 if (!Args.empty()) {
625 OS << "(" << Args[0];
626 for (unsigned i = 1, e = Args.size(); i != e; ++i)
627 OS << ", " << Args[i];
628 OS << ")";
629 }
630 OS << ": ";
631
632 if (Trees.size() > 1)
633 OS << "[\n";
634 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
635 OS << "\t";
636 Trees[i]->print(OS);
637 OS << "\n";
638 }
639
640 if (Trees.size() > 1)
641 OS << "]\n";
642}
643
644void TreePattern::dump() const { print(std::cerr); }
645
646
647
648//===----------------------------------------------------------------------===//
649// DAGISelEmitter implementation
650//
651
Chris Lattnerca559d02005-09-08 21:03:01 +0000652// Parse all of the SDNode definitions for the target, populating SDNodes.
653void DAGISelEmitter::ParseNodeInfo() {
654 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
655 while (!Nodes.empty()) {
656 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
657 Nodes.pop_back();
658 }
659}
660
Chris Lattner24eeeb82005-09-13 21:51:00 +0000661/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
662/// map, and emit them to the file as functions.
663void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
664 OS << "\n// Node transformations.\n";
665 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
666 while (!Xforms.empty()) {
667 Record *XFormNode = Xforms.back();
668 Record *SDNode = XFormNode->getValueAsDef("Opcode");
669 std::string Code = XFormNode->getValueAsCode("XFormFunction");
670 SDNodeXForms.insert(std::make_pair(XFormNode,
671 std::make_pair(SDNode, Code)));
672
Chris Lattner1048b7a2005-09-13 22:03:37 +0000673 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000674 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
675 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
676
Chris Lattner1048b7a2005-09-13 22:03:37 +0000677 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000678 << "(SDNode *" << C2 << ") {\n";
679 if (ClassName != "SDNode")
680 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
681 OS << Code << "\n}\n";
682 }
683
684 Xforms.pop_back();
685 }
686}
687
688
689
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000690/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
691/// file, building up the PatternFragments map. After we've collected them all,
692/// inline fragments together as necessary, so that there are no references left
693/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000694///
695/// This also emits all of the predicate functions to the output file.
696///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000697void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000698 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
699
700 // First step, parse all of the fragments and emit predicate functions.
701 OS << "\n// Predicate functions.\n";
702 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000703 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
704 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000705 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000706
707 // Validate the argument list, converting it to map, to discard duplicates.
708 std::vector<std::string> &Args = P->getArgList();
709 std::set<std::string> OperandsMap(Args.begin(), Args.end());
710
711 if (OperandsMap.count(""))
712 P->error("Cannot have unnamed 'node' values in pattern fragment!");
713
714 // Parse the operands list.
715 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
716 if (OpsList->getNodeType()->getName() != "ops")
717 P->error("Operands list should start with '(ops ... '!");
718
719 // Copy over the arguments.
720 Args.clear();
721 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
722 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
723 static_cast<DefInit*>(OpsList->getArg(j))->
724 getDef()->getName() != "node")
725 P->error("Operands list should all be 'node' values.");
726 if (OpsList->getArgName(j).empty())
727 P->error("Operands list should have names for each operand!");
728 if (!OperandsMap.count(OpsList->getArgName(j)))
729 P->error("'" + OpsList->getArgName(j) +
730 "' does not occur in pattern or was multiply specified!");
731 OperandsMap.erase(OpsList->getArgName(j));
732 Args.push_back(OpsList->getArgName(j));
733 }
734
735 if (!OperandsMap.empty())
736 P->error("Operands list does not contain an entry for operand '" +
737 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000738
739 // If there is a code init for this fragment, emit the predicate code and
740 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000741 std::string Code = Fragments[i]->getValueAsCode("Predicate");
742 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000743 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000744 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000745 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
747
Chris Lattner1048b7a2005-09-13 22:03:37 +0000748 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000749 << "(SDNode *" << C2 << ") {\n";
750 if (ClassName != "SDNode")
751 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000752 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000753 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000754 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000755
756 // If there is a node transformation corresponding to this, keep track of
757 // it.
758 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
759 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000760 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000761 }
762
763 OS << "\n\n";
764
765 // Now that we've parsed all of the tree fragments, do a closure on them so
766 // that there are not references to PatFrags left inside of them.
767 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
768 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000769 TreePattern *ThePat = I->second;
770 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000771
Chris Lattner32707602005-09-08 23:22:48 +0000772 // Infer as many types as possible. Don't worry about it if we don't infer
773 // all of them, some may depend on the inputs of the pattern.
774 try {
775 ThePat->InferAllTypes();
776 } catch (...) {
777 // If this pattern fragment is not supported by this target (no types can
778 // satisfy its constraints), just ignore it. If the bogus pattern is
779 // actually used by instructions, the type consistency error will be
780 // reported there.
781 }
782
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000783 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000784 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000785 }
786}
787
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000788/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000789/// instruction input. Return true if this is a real use.
790static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000791 std::map<std::string, TreePatternNode*> &InstInputs) {
792 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000793 if (Pat->getName().empty()) {
794 if (Pat->isLeaf()) {
795 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
796 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
797 I->error("Input " + DI->getDef()->getName() + " must be named!");
798
799 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000800 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000801 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000802
803 Record *Rec;
804 if (Pat->isLeaf()) {
805 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
806 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
807 Rec = DI->getDef();
808 } else {
809 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
810 Rec = Pat->getOperator();
811 }
812
813 TreePatternNode *&Slot = InstInputs[Pat->getName()];
814 if (!Slot) {
815 Slot = Pat;
816 } else {
817 Record *SlotRec;
818 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000819 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000820 } else {
821 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
822 SlotRec = Slot->getOperator();
823 }
824
825 // Ensure that the inputs agree if we've already seen this input.
826 if (Rec != SlotRec)
827 I->error("All $" + Pat->getName() + " inputs must agree with each other");
828 if (Slot->getType() != Pat->getType())
829 I->error("All $" + Pat->getName() + " inputs must agree with each other");
830 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000831 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000832}
833
834/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
835/// part of "I", the instruction), computing the set of inputs and outputs of
836/// the pattern. Report errors if we see anything naughty.
837void DAGISelEmitter::
838FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
839 std::map<std::string, TreePatternNode*> &InstInputs,
840 std::map<std::string, Record*> &InstResults) {
841 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000842 bool isUse = HandleUse(I, Pat, InstInputs);
843 if (!isUse && Pat->getTransformFn())
844 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000845 return;
846 } else if (Pat->getOperator()->getName() != "set") {
847 // If this is not a set, verify that the children nodes are not void typed,
848 // and recurse.
849 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
850 if (Pat->getChild(i)->getType() == MVT::isVoid)
851 I->error("Cannot have void nodes inside of patterns!");
852 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
853 }
854
855 // If this is a non-leaf node with no children, treat it basically as if
856 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000857 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000858 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000859 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000860
Chris Lattnerf1311842005-09-14 23:05:13 +0000861 if (!isUse && Pat->getTransformFn())
862 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000863 return;
864 }
865
866 // Otherwise, this is a set, validate and collect instruction results.
867 if (Pat->getNumChildren() == 0)
868 I->error("set requires operands!");
869 else if (Pat->getNumChildren() & 1)
870 I->error("set requires an even number of operands");
871
Chris Lattnerf1311842005-09-14 23:05:13 +0000872 if (Pat->getTransformFn())
873 I->error("Cannot specify a transform function on a set node!");
874
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000875 // Check the set destinations.
876 unsigned NumValues = Pat->getNumChildren()/2;
877 for (unsigned i = 0; i != NumValues; ++i) {
878 TreePatternNode *Dest = Pat->getChild(i);
879 if (!Dest->isLeaf())
880 I->error("set destination should be a virtual register!");
881
882 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
883 if (!Val)
884 I->error("set destination should be a virtual register!");
885
886 if (!Val->getDef()->isSubClassOf("RegisterClass"))
887 I->error("set destination should be a virtual register!");
888 if (Dest->getName().empty())
889 I->error("set destination must have a name!");
890 if (InstResults.count(Dest->getName()))
891 I->error("cannot set '" + Dest->getName() +"' multiple times");
892 InstResults[Dest->getName()] = Val->getDef();
893
894 // Verify and collect info from the computation.
895 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
896 InstInputs, InstResults);
897 }
898}
899
900
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000901/// ParseInstructions - Parse all of the instructions, inlining and resolving
902/// any fragments involved. This populates the Instructions list with fully
903/// resolved instructions.
904void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000905 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
906
907 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
908 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
909 continue; // no pattern yet, ignore it.
910
911 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
912 if (LI->getSize() == 0) continue; // no pattern.
913
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000914 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000915 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000916 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000917 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000918
Chris Lattner95f6b762005-09-08 23:26:30 +0000919 // Infer as many types as possible. If we cannot infer all of them, we can
920 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000921 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +0000922 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000923
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000924 // InstInputs - Keep track of all of the inputs of the instruction, along
925 // with the record they are declared as.
926 std::map<std::string, TreePatternNode*> InstInputs;
927
928 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000929 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000930 std::map<std::string, Record*> InstResults;
931
Chris Lattner1f39e292005-09-14 00:09:24 +0000932 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000933 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000934 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
935 TreePatternNode *Pat = I->getTree(j);
936 if (Pat->getType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000937 I->dump();
938 I->error("Top-level forms in instruction pattern should have"
939 " void types");
940 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000941
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000942 // Find inputs and outputs, and verify the structure of the uses/defs.
943 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000944 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000945
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000946 // Now that we have inputs and outputs of the pattern, inspect the operands
947 // list for the instruction. This determines the order that operands are
948 // added to the machine instruction the node corresponds to.
949 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000950
951 // Parse the operands list from the (ops) list, validating it.
952 std::vector<std::string> &Args = I->getArgList();
953 assert(Args.empty() && "Args list should still be empty here!");
954 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
955
956 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +0000957 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +0000958 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000959 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000960 I->error("'" + InstResults.begin()->first +
961 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +0000962 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +0000963
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000964 // Check that it exists in InstResults.
965 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000966 if (R == 0)
967 I->error("Operand $" + OpName + " should be a set destination: all "
968 "outputs must occur before inputs in operand list!");
969
970 if (CGI.OperandList[i].Rec != R)
971 I->error("Operand $" + OpName + " class mismatch!");
972
Chris Lattnerae6d8282005-09-15 21:51:12 +0000973 // Remember the return type.
974 ResultTypes.push_back(CGI.OperandList[i].Ty);
975
Chris Lattner39e8af92005-09-14 18:19:25 +0000976 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000977 InstResults.erase(OpName);
978 }
979
Chris Lattner0b592252005-09-14 21:59:34 +0000980 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
981 // the copy while we're checking the inputs.
982 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +0000983
984 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +0000985 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000986 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
987 const std::string &OpName = CGI.OperandList[i].Name;
988 if (OpName.empty())
989 I->error("Operand #" + utostr(i) + " in operands list has no name!");
990
Chris Lattner0b592252005-09-14 21:59:34 +0000991 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000992 I->error("Operand $" + OpName +
993 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +0000994 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +0000995 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000996 if (CGI.OperandList[i].Ty != InVal->getType())
997 I->error("Operand $" + OpName +
998 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +0000999 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +00001000
Chris Lattner2175c182005-09-14 23:01:59 +00001001 // Construct the result for the dest-pattern operand list.
1002 TreePatternNode *OpNode = InVal->clone();
1003
1004 // No predicate is useful on the result.
1005 OpNode->setPredicateFn("");
1006
1007 // Promote the xform function to be an explicit node if set.
1008 if (Record *Xform = OpNode->getTransformFn()) {
1009 OpNode->setTransformFn(0);
1010 std::vector<TreePatternNode*> Children;
1011 Children.push_back(OpNode);
1012 OpNode = new TreePatternNode(Xform, Children);
1013 }
1014
1015 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001016 }
1017
Chris Lattner0b592252005-09-14 21:59:34 +00001018 if (!InstInputsCheck.empty())
1019 I->error("Input operand $" + InstInputsCheck.begin()->first +
1020 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001021
1022 TreePatternNode *ResultPattern =
1023 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001024
1025 // Create and insert the instruction.
1026 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1027 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1028
1029 // Use a temporary tree pattern to infer all types and make sure that the
1030 // constructed result is correct. This depends on the instruction already
1031 // being inserted into the Instructions map.
1032 TreePattern Temp(I->getRecord(), ResultPattern, *this);
1033 Temp.InferAllTypes();
1034
1035 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1036 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001037
Chris Lattner32707602005-09-08 23:22:48 +00001038 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001039 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001040
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001041 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001042 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1043 E = Instructions.end(); II != E; ++II) {
1044 TreePattern *I = II->second.getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001045
1046 if (I->getNumTrees() != 1) {
1047 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1048 continue;
1049 }
1050 TreePatternNode *Pattern = I->getTree(0);
1051 if (Pattern->getOperator()->getName() != "set")
1052 continue; // Not a set (store or something?)
1053
1054 if (Pattern->getNumChildren() != 2)
1055 continue; // Not a set of a single value (not handled so far)
1056
1057 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001058
1059 std::string Reason;
1060 if (!SrcPattern->canPatternMatch(Reason, *this))
1061 I->error("Instruction can never match: " + Reason);
1062
Chris Lattnerae5b3502005-09-15 21:57:35 +00001063 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001064 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001065 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001066}
1067
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001068void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001069 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001070
Chris Lattnerabbb6052005-09-15 21:42:00 +00001071 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001072 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1073 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001074
Chris Lattnerabbb6052005-09-15 21:42:00 +00001075 // Inline pattern fragments into it.
1076 Pattern->InlinePatternFragments();
1077
1078 // Infer as many types as possible. If we cannot infer all of them, we can
1079 // never do anything with this pattern: report it to the user.
1080 if (!Pattern->InferAllTypes())
1081 Pattern->error("Could not infer all types in pattern!");
1082
1083 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1084 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001085
1086 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +00001087 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001088
1089 // Inline pattern fragments into it.
1090 Result->InlinePatternFragments();
1091
1092 // Infer as many types as possible. If we cannot infer all of them, we can
1093 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001094 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001095 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001096
1097 if (Result->getNumTrees() != 1)
1098 Result->error("Cannot handle instructions producing instructions "
1099 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001100
1101 std::string Reason;
1102 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1103 Pattern->error("Pattern can never match: " + Reason);
1104
Chris Lattnerabbb6052005-09-15 21:42:00 +00001105 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1106 Result->getOnlyTree()));
1107 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001108}
1109
Chris Lattnere46e17b2005-09-29 19:28:10 +00001110/// CombineChildVariants - Given a bunch of permutations of each child of the
1111/// 'operator' node, put them together in all possible ways.
1112static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001113 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001114 std::vector<TreePatternNode*> &OutVariants,
1115 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001116 // Make sure that each operand has at least one variant to choose from.
1117 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1118 if (ChildVariants[i].empty())
1119 return;
1120
Chris Lattnere46e17b2005-09-29 19:28:10 +00001121 // The end result is an all-pairs construction of the resultant pattern.
1122 std::vector<unsigned> Idxs;
1123 Idxs.resize(ChildVariants.size());
1124 bool NotDone = true;
1125 while (NotDone) {
1126 // Create the variant and add it to the output list.
1127 std::vector<TreePatternNode*> NewChildren;
1128 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1129 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1130 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1131
1132 // Copy over properties.
1133 R->setName(Orig->getName());
1134 R->setPredicateFn(Orig->getPredicateFn());
1135 R->setTransformFn(Orig->getTransformFn());
1136 R->setType(Orig->getType());
1137
1138 // If this pattern cannot every match, do not include it as a variant.
1139 std::string ErrString;
1140 if (!R->canPatternMatch(ErrString, ISE)) {
1141 delete R;
1142 } else {
1143 bool AlreadyExists = false;
1144
1145 // Scan to see if this pattern has already been emitted. We can get
1146 // duplication due to things like commuting:
1147 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1148 // which are the same pattern. Ignore the dups.
1149 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1150 if (R->isIsomorphicTo(OutVariants[i])) {
1151 AlreadyExists = true;
1152 break;
1153 }
1154
1155 if (AlreadyExists)
1156 delete R;
1157 else
1158 OutVariants.push_back(R);
1159 }
1160
1161 // Increment indices to the next permutation.
1162 NotDone = false;
1163 // Look for something we can increment without causing a wrap-around.
1164 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1165 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1166 NotDone = true; // Found something to increment.
1167 break;
1168 }
1169 Idxs[IdxsIdx] = 0;
1170 }
1171 }
1172}
1173
Chris Lattneraf302912005-09-29 22:36:54 +00001174/// CombineChildVariants - A helper function for binary operators.
1175///
1176static void CombineChildVariants(TreePatternNode *Orig,
1177 const std::vector<TreePatternNode*> &LHS,
1178 const std::vector<TreePatternNode*> &RHS,
1179 std::vector<TreePatternNode*> &OutVariants,
1180 DAGISelEmitter &ISE) {
1181 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1182 ChildVariants.push_back(LHS);
1183 ChildVariants.push_back(RHS);
1184 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1185}
1186
1187
1188static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1189 std::vector<TreePatternNode *> &Children) {
1190 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1191 Record *Operator = N->getOperator();
1192
1193 // Only permit raw nodes.
1194 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1195 N->getTransformFn()) {
1196 Children.push_back(N);
1197 return;
1198 }
1199
1200 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1201 Children.push_back(N->getChild(0));
1202 else
1203 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1204
1205 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1206 Children.push_back(N->getChild(1));
1207 else
1208 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1209}
1210
Chris Lattnere46e17b2005-09-29 19:28:10 +00001211/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1212/// the (potentially recursive) pattern by using algebraic laws.
1213///
1214static void GenerateVariantsOf(TreePatternNode *N,
1215 std::vector<TreePatternNode*> &OutVariants,
1216 DAGISelEmitter &ISE) {
1217 // We cannot permute leaves.
1218 if (N->isLeaf()) {
1219 OutVariants.push_back(N);
1220 return;
1221 }
1222
1223 // Look up interesting info about the node.
1224 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1225
1226 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001227 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1228 // Reassociate by pulling together all of the linked operators
1229 std::vector<TreePatternNode*> MaximalChildren;
1230 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1231
1232 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1233 // permutations.
1234 if (MaximalChildren.size() == 3) {
1235 // Find the variants of all of our maximal children.
1236 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1237 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1238 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1239 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1240
1241 // There are only two ways we can permute the tree:
1242 // (A op B) op C and A op (B op C)
1243 // Within these forms, we can also permute A/B/C.
1244
1245 // Generate legal pair permutations of A/B/C.
1246 std::vector<TreePatternNode*> ABVariants;
1247 std::vector<TreePatternNode*> BAVariants;
1248 std::vector<TreePatternNode*> ACVariants;
1249 std::vector<TreePatternNode*> CAVariants;
1250 std::vector<TreePatternNode*> BCVariants;
1251 std::vector<TreePatternNode*> CBVariants;
1252 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1253 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1254 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1255 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1256 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1257 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1258
1259 // Combine those into the result: (x op x) op x
1260 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1261 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1262 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1263 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1264 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1265 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1266
1267 // Combine those into the result: x op (x op x)
1268 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1269 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1270 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1271 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1272 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1273 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1274 return;
1275 }
1276 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001277
1278 // Compute permutations of all children.
1279 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1280 ChildVariants.resize(N->getNumChildren());
1281 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1282 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1283
1284 // Build all permutations based on how the children were formed.
1285 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1286
1287 // If this node is commutative, consider the commuted order.
1288 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1289 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001290 // Consider the commuted order.
1291 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1292 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001293 }
1294}
1295
1296
Chris Lattnere97603f2005-09-28 19:27:25 +00001297// GenerateVariants - Generate variants. For example, commutative patterns can
1298// match multiple ways. Add them to PatternsToMatch as well.
1299void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001300
1301 DEBUG(std::cerr << "Generating instruction variants.\n");
1302
1303 // Loop over all of the patterns we've collected, checking to see if we can
1304 // generate variants of the instruction, through the exploitation of
1305 // identities. This permits the target to provide agressive matching without
1306 // the .td file having to contain tons of variants of instructions.
1307 //
1308 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1309 // intentionally do not reconsider these. Any variants of added patterns have
1310 // already been added.
1311 //
1312 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1313 std::vector<TreePatternNode*> Variants;
1314 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1315
1316 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001317 Variants.erase(Variants.begin()); // Remove the original pattern.
1318
1319 if (Variants.empty()) // No variants for this pattern.
1320 continue;
1321
1322 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1323 PatternsToMatch[i].first->dump();
1324 std::cerr << "\n");
1325
1326 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1327 TreePatternNode *Variant = Variants[v];
1328
1329 DEBUG(std::cerr << " VAR#" << v << ": ";
1330 Variant->dump();
1331 std::cerr << "\n");
1332
1333 // Scan to see if an instruction or explicit pattern already matches this.
1334 bool AlreadyExists = false;
1335 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1336 // Check to see if this variant already exists.
1337 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1338 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1339 AlreadyExists = true;
1340 break;
1341 }
1342 }
1343 // If we already have it, ignore the variant.
1344 if (AlreadyExists) continue;
1345
1346 // Otherwise, add it to the list of patterns we have.
1347 PatternsToMatch.push_back(std::make_pair(Variant,
1348 PatternsToMatch[i].second));
1349 }
1350
1351 DEBUG(std::cerr << "\n");
1352 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001353}
1354
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001355
Chris Lattner05814af2005-09-28 17:57:56 +00001356/// getPatternSize - Return the 'size' of this pattern. We want to match large
1357/// patterns before small ones. This is used to determine the size of a
1358/// pattern.
1359static unsigned getPatternSize(TreePatternNode *P) {
1360 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1361 "Not a valid pattern node to size!");
1362 unsigned Size = 1; // The node itself.
1363
1364 // Count children in the count if they are also nodes.
1365 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1366 TreePatternNode *Child = P->getChild(i);
1367 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1368 Size += getPatternSize(Child);
1369 }
1370
1371 return Size;
1372}
1373
1374/// getResultPatternCost - Compute the number of instructions for this pattern.
1375/// This is a temporary hack. We should really include the instruction
1376/// latencies in this calculation.
1377static unsigned getResultPatternCost(TreePatternNode *P) {
1378 if (P->isLeaf()) return 0;
1379
1380 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1381 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1382 Cost += getResultPatternCost(P->getChild(i));
1383 return Cost;
1384}
1385
1386// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1387// In particular, we want to match maximal patterns first and lowest cost within
1388// a particular complexity first.
1389struct PatternSortingPredicate {
1390 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1391 DAGISelEmitter::PatternToMatch *RHS) {
1392 unsigned LHSSize = getPatternSize(LHS->first);
1393 unsigned RHSSize = getPatternSize(RHS->first);
1394 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1395 if (LHSSize < RHSSize) return false;
1396
1397 // If the patterns have equal complexity, compare generated instruction cost
1398 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1399 }
1400};
1401
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001402/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1403/// if the match fails. At this point, we already know that the opcode for N
1404/// matches, and the SDNode for the result has the RootName specified name.
1405void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001406 const std::string &RootName,
1407 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001408 unsigned PatternNo, std::ostream &OS) {
1409 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001410
1411 // If this node has a name associated with it, capture it in VarMap. If
1412 // we already saw this in the pattern, emit code to verify dagness.
1413 if (!N->getName().empty()) {
1414 std::string &VarMapEntry = VarMap[N->getName()];
1415 if (VarMapEntry.empty()) {
1416 VarMapEntry = RootName;
1417 } else {
1418 // If we get here, this is a second reference to a specific name. Since
1419 // we already have checked that the first reference is valid, we don't
1420 // have to recursively match it, just check that it's the same as the
1421 // previously named thing.
1422 OS << " if (" << VarMapEntry << " != " << RootName
1423 << ") goto P" << PatternNo << "Fail;\n";
1424 return;
1425 }
1426 }
1427
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001428 // Emit code to load the child nodes and match their contents recursively.
1429 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001430 OS << " SDOperand " << RootName << i <<" = " << RootName
1431 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001432 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001433
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001434 if (!Child->isLeaf()) {
1435 // If it's not a leaf, recursively match.
1436 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001437 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001438 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001439 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001440 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001441 // If this child has a name associated with it, capture it in VarMap. If
1442 // we already saw this in the pattern, emit code to verify dagness.
1443 if (!Child->getName().empty()) {
1444 std::string &VarMapEntry = VarMap[Child->getName()];
1445 if (VarMapEntry.empty()) {
1446 VarMapEntry = RootName + utostr(i);
1447 } else {
1448 // If we get here, this is a second reference to a specific name. Since
1449 // we already have checked that the first reference is valid, we don't
1450 // have to recursively match it, just check that it's the same as the
1451 // previously named thing.
1452 OS << " if (" << VarMapEntry << " != " << RootName << i
1453 << ") goto P" << PatternNo << "Fail;\n";
1454 continue;
1455 }
1456 }
1457
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001458 // Handle leaves of various types.
1459 Init *LeafVal = Child->getLeafValue();
1460 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1461 if (LeafRec->isSubClassOf("RegisterClass")) {
1462 // Handle register references. Nothing to do here.
1463 } else if (LeafRec->isSubClassOf("ValueType")) {
1464 // Make sure this is the specified value type.
1465 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1466 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1467 << "Fail;\n";
1468 } else {
1469 Child->dump();
1470 assert(0 && "Unknown leaf type!");
1471 }
1472 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001473 }
1474
1475 // If there is a node predicate for this, emit the call.
1476 if (!N->getPredicateFn().empty())
1477 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001478 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001479}
1480
Chris Lattner6bc7e512005-09-26 21:53:26 +00001481/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1482/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001483unsigned DAGISelEmitter::
1484CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1485 std::map<std::string,std::string> &VariableMap,
Chris Lattner6bc7e512005-09-26 21:53:26 +00001486 std::ostream &OS) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001487 // This is something selected from the pattern we matched.
1488 if (!N->getName().empty()) {
Chris Lattner6bc7e512005-09-26 21:53:26 +00001489 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001490 assert(!Val.empty() &&
1491 "Variable referenced but not defined and not caught earlier!");
1492 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1493 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001494 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001495 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001496
1497 unsigned ResNo = Ctr++;
1498 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1499 switch (N->getType()) {
1500 default: assert(0 && "Unknown type for constant node!");
1501 case MVT::i1: OS << " bool Tmp"; break;
1502 case MVT::i8: OS << " unsigned char Tmp"; break;
1503 case MVT::i16: OS << " unsigned short Tmp"; break;
1504 case MVT::i32: OS << " unsigned Tmp"; break;
1505 case MVT::i64: OS << " uint64_t Tmp"; break;
1506 }
1507 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1508 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1509 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1510 } else {
1511 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1512 }
1513 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1514 // value if used multiple times by this pattern result.
1515 Val = "Tmp"+utostr(ResNo);
1516 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001517 }
1518
1519 if (N->isLeaf()) {
1520 N->dump();
1521 assert(0 && "Unknown leaf type!");
1522 return ~0U;
1523 }
1524
1525 Record *Op = N->getOperator();
1526 if (Op->isSubClassOf("Instruction")) {
1527 // Emit all of the operands.
1528 std::vector<unsigned> Ops;
1529 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1530 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1531
1532 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1533 unsigned ResNo = Ctr++;
1534
1535 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1536 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1537 << getEnumName(N->getType());
1538 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1539 OS << ", Tmp" << Ops[i];
1540 OS << ");\n";
1541 return ResNo;
1542 } else if (Op->isSubClassOf("SDNodeXForm")) {
1543 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1544 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1545
1546 unsigned ResNo = Ctr++;
1547 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1548 << "(Tmp" << OpVal << ".Val);\n";
1549 return ResNo;
1550 } else {
1551 N->dump();
1552 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001553 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001554 }
1555}
1556
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001557/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1558/// type information from it.
1559static void RemoveAllTypes(TreePatternNode *N) {
1560 N->setType(MVT::LAST_VALUETYPE);
1561 if (!N->isLeaf())
1562 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1563 RemoveAllTypes(N->getChild(i));
1564}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001565
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001566/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1567/// stream to match the pattern, and generate the code for the match if it
1568/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001569void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1570 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001571 static unsigned PatternCount = 0;
1572 unsigned PatternNo = PatternCount++;
1573 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001574 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001575 OS << "\n // Emits: ";
1576 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001577 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001578 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1579 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001580
Chris Lattner8fc35682005-09-23 23:16:51 +00001581 // Emit the matcher, capturing named arguments in VariableMap.
1582 std::map<std::string,std::string> VariableMap;
1583 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001584
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001585 // TP - Get *SOME* tree pattern, we don't care which.
1586 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001587
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001588 // At this point, we know that we structurally match the pattern, but the
1589 // types of the nodes may not match. Figure out the fewest number of type
1590 // comparisons we need to emit. For example, if there is only one integer
1591 // type supported by a target, there should be no type comparisons at all for
1592 // integer patterns!
1593 //
1594 // To figure out the fewest number of type checks needed, clone the pattern,
1595 // remove the types, then perform type inference on the pattern as a whole.
1596 // If there are unresolved types, emit an explicit check for those types,
1597 // apply the type to the tree, then rerun type inference. Iterate until all
1598 // types are resolved.
1599 //
1600 TreePatternNode *Pat = Pattern.first->clone();
1601 RemoveAllTypes(Pat);
1602 bool MadeChange = true;
1603 try {
1604 while (MadeChange)
1605 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1606 } catch (...) {
1607 assert(0 && "Error: could not find consistent types for something we"
1608 " already decided was ok!");
1609 abort();
1610 }
1611
1612 if (!Pat->ContainsUnresolvedType()) {
1613 unsigned TmpNo = 0;
1614 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
1615
1616 // Add the result to the map if it has multiple uses.
1617 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
1618 OS << " return Tmp" << Res << ";\n";
1619 }
1620
1621 delete Pat;
1622
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001623 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001624}
1625
Chris Lattner37481472005-09-26 21:59:35 +00001626
1627namespace {
1628 /// CompareByRecordName - An ordering predicate that implements less-than by
1629 /// comparing the names records.
1630 struct CompareByRecordName {
1631 bool operator()(const Record *LHS, const Record *RHS) const {
1632 // Sort by name first.
1633 if (LHS->getName() < RHS->getName()) return true;
1634 // If both names are equal, sort by pointer.
1635 return LHS->getName() == RHS->getName() && LHS < RHS;
1636 }
1637 };
1638}
1639
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001640void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1641 // Emit boilerplate.
1642 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001643 << "SDOperand SelectCode(SDOperand N) {\n"
1644 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1645 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1646 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001647 << " if (!N.Val->hasOneUse()) {\n"
1648 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1649 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1650 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001651 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001652 << " default: break;\n"
1653 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001654 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001655 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001656 << " case ISD::AssertZext: {\n"
1657 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1658 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1659 << " return Tmp0;\n"
1660 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001661
Chris Lattner81303322005-09-23 19:36:15 +00001662 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001663 std::map<Record*, std::vector<PatternToMatch*>,
1664 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001665 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1666 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1667 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001668
Chris Lattner3f7e9142005-09-23 20:52:47 +00001669 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001670 for (std::map<Record*, std::vector<PatternToMatch*>,
1671 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1672 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001673 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1674 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1675
1676 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001677
1678 // We want to emit all of the matching code now. However, we want to emit
1679 // the matches in order of minimal cost. Sort the patterns so the least
1680 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001681 std::stable_sort(Patterns.begin(), Patterns.end(),
1682 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001683
Chris Lattner3f7e9142005-09-23 20:52:47 +00001684 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1685 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001686 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001687 }
1688
1689
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001690 OS << " } // end of big switch.\n\n"
1691 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001692 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001693 << " std::cerr << '\\n';\n"
1694 << " abort();\n"
1695 << "}\n";
1696}
1697
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001698void DAGISelEmitter::run(std::ostream &OS) {
1699 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1700 " target", OS);
1701
Chris Lattner1f39e292005-09-14 00:09:24 +00001702 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1703 << "// *** instruction selector class. These functions are really "
1704 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001705
Chris Lattner296dfe32005-09-24 00:50:51 +00001706 OS << "// Instance var to keep track of multiply used nodes that have \n"
1707 << "// already been selected.\n"
1708 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1709
Chris Lattnerca559d02005-09-08 21:03:01 +00001710 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001711 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001712 ParsePatternFragments(OS);
1713 ParseInstructions();
1714 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001715
Chris Lattnere97603f2005-09-28 19:27:25 +00001716 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001717 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001718 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001719
Chris Lattnere46e17b2005-09-29 19:28:10 +00001720
1721 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1722 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1723 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1724 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1725 std::cerr << "\n";
1726 });
1727
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001728 // At this point, we have full information about the 'Patterns' we need to
1729 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001730 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001731 EmitInstructionSelector(OS);
1732
1733 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1734 E = PatternFragments.end(); I != E; ++I)
1735 delete I->second;
1736 PatternFragments.clear();
1737
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001738 Instructions.clear();
1739}