blob: 06150d088753c4276f6554c0102bf71b4ae098f8 [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"
18#include <set>
19using namespace llvm;
20
Chris Lattnerca559d02005-09-08 21:03:01 +000021//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000022// SDTypeConstraint implementation
23//
24
25SDTypeConstraint::SDTypeConstraint(Record *R) {
26 OperandNo = R->getValueAsInt("OperandNum");
27
28 if (R->isSubClassOf("SDTCisVT")) {
29 ConstraintType = SDTCisVT;
30 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
31 } else if (R->isSubClassOf("SDTCisInt")) {
32 ConstraintType = SDTCisInt;
33 } else if (R->isSubClassOf("SDTCisFP")) {
34 ConstraintType = SDTCisFP;
35 } else if (R->isSubClassOf("SDTCisSameAs")) {
36 ConstraintType = SDTCisSameAs;
37 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
38 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
39 ConstraintType = SDTCisVTSmallerThanOp;
40 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
41 R->getValueAsInt("OtherOperandNum");
42 } else {
43 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
44 exit(1);
45 }
46}
47
Chris Lattner32707602005-09-08 23:22:48 +000048/// getOperandNum - Return the node corresponding to operand #OpNo in tree
49/// N, which has NumResults results.
50TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
51 TreePatternNode *N,
52 unsigned NumResults) const {
53 assert(NumResults == 1 && "We only work with single result nodes so far!");
54
55 if (OpNo < NumResults)
56 return N; // FIXME: need value #
57 else
58 return N->getChild(OpNo-NumResults);
59}
60
61/// ApplyTypeConstraint - Given a node in a pattern, apply this type
62/// constraint to the nodes operands. This returns true if it makes a
63/// change, false otherwise. If a type contradiction is found, throw an
64/// exception.
65bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
66 const SDNodeInfo &NodeInfo,
67 TreePattern &TP) const {
68 unsigned NumResults = NodeInfo.getNumResults();
69 assert(NumResults == 1 && "We only work with single result nodes so far!");
70
71 // Check that the number of operands is sane.
72 if (NodeInfo.getNumOperands() >= 0) {
73 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
74 TP.error(N->getOperator()->getName() + " node requires exactly " +
75 itostr(NodeInfo.getNumOperands()) + " operands!");
76 }
77
78 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
79
80 switch (ConstraintType) {
81 default: assert(0 && "Unknown constraint type!");
82 case SDTCisVT:
83 // Operand must be a particular type.
84 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
85 case SDTCisInt:
86 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
87 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
88
89 // FIXME: can tell from the target if there is only one Int type supported.
90 return false;
91 case SDTCisFP:
92 if (NodeToApply->hasTypeSet() &&
93 !MVT::isFloatingPoint(NodeToApply->getType()))
94 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
95 // FIXME: can tell from the target if there is only one FP type supported.
96 return false;
97 case SDTCisSameAs: {
98 TreePatternNode *OtherNode =
99 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
100 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
101 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
102 }
103 case SDTCisVTSmallerThanOp: {
104 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
105 // have an integer type that is smaller than the VT.
106 if (!NodeToApply->isLeaf() ||
107 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
108 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
109 ->isSubClassOf("ValueType"))
110 TP.error(N->getOperator()->getName() + " expects a VT operand!");
111 MVT::ValueType VT =
112 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
113 if (!MVT::isInteger(VT))
114 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
115
116 TreePatternNode *OtherNode =
117 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
118 if (OtherNode->hasTypeSet() &&
119 (!MVT::isInteger(OtherNode->getType()) ||
120 OtherNode->getType() <= VT))
121 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
122 return false;
123 }
124 }
125 return false;
126}
127
128
Chris Lattner33c92e92005-09-08 21:27:15 +0000129//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000130// SDNodeInfo implementation
131//
132SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
133 EnumName = R->getValueAsString("Opcode");
134 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000135 Record *TypeProfile = R->getValueAsDef("TypeProfile");
136 NumResults = TypeProfile->getValueAsInt("NumResults");
137 NumOperands = TypeProfile->getValueAsInt("NumOperands");
138
139 // Parse the type constraints.
140 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
141 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
142 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
143 "Constraints list should contain constraint definitions!");
144 Record *Constraint =
145 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
146 TypeConstraints.push_back(Constraint);
147 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000148}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000149
150//===----------------------------------------------------------------------===//
151// TreePatternNode implementation
152//
153
154TreePatternNode::~TreePatternNode() {
155#if 0 // FIXME: implement refcounted tree nodes!
156 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
157 delete getChild(i);
158#endif
159}
160
Chris Lattner32707602005-09-08 23:22:48 +0000161/// UpdateNodeType - Set the node type of N to VT if VT contains
162/// information. If N already contains a conflicting type, then throw an
163/// exception. This returns true if any information was updated.
164///
165bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
166 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
167 if (getType() == MVT::LAST_VALUETYPE) {
168 setType(VT);
169 return true;
170 }
171
172 TP.error("Type inference contradiction found in node " +
173 getOperator()->getName() + "!");
174 return true; // unreachable
175}
176
177
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000178void TreePatternNode::print(std::ostream &OS) const {
179 if (isLeaf()) {
180 OS << *getLeafValue();
181 } else {
182 OS << "(" << getOperator()->getName();
183 }
184
185 if (getType() == MVT::Other)
186 OS << ":Other";
187 else if (getType() == MVT::LAST_VALUETYPE)
188 ;//OS << ":?";
189 else
190 OS << ":" << getType();
191
192 if (!isLeaf()) {
193 if (getNumChildren() != 0) {
194 OS << " ";
195 getChild(0)->print(OS);
196 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
197 OS << ", ";
198 getChild(i)->print(OS);
199 }
200 }
201 OS << ")";
202 }
203
204 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000205 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000206 if (TransformFn)
207 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000208 if (!getName().empty())
209 OS << ":$" << getName();
210
211}
212void TreePatternNode::dump() const {
213 print(std::cerr);
214}
215
216/// clone - Make a copy of this tree and all of its children.
217///
218TreePatternNode *TreePatternNode::clone() const {
219 TreePatternNode *New;
220 if (isLeaf()) {
221 New = new TreePatternNode(getLeafValue());
222 } else {
223 std::vector<TreePatternNode*> CChildren;
224 CChildren.reserve(Children.size());
225 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
226 CChildren.push_back(getChild(i)->clone());
227 New = new TreePatternNode(getOperator(), CChildren);
228 }
229 New->setName(getName());
230 New->setType(getType());
231 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000232 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000233 return New;
234}
235
Chris Lattner32707602005-09-08 23:22:48 +0000236/// SubstituteFormalArguments - Replace the formal arguments in this tree
237/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000238void TreePatternNode::
239SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
240 if (isLeaf()) return;
241
242 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
243 TreePatternNode *Child = getChild(i);
244 if (Child->isLeaf()) {
245 Init *Val = Child->getLeafValue();
246 if (dynamic_cast<DefInit*>(Val) &&
247 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
248 // We found a use of a formal argument, replace it with its value.
249 Child = ArgMap[Child->getName()];
250 assert(Child && "Couldn't find formal argument!");
251 setChild(i, Child);
252 }
253 } else {
254 getChild(i)->SubstituteFormalArguments(ArgMap);
255 }
256 }
257}
258
259
260/// InlinePatternFragments - If this pattern refers to any pattern
261/// fragments, inline them into place, giving us a pattern without any
262/// PatFrag references.
263TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
264 if (isLeaf()) return this; // nothing to do.
265 Record *Op = getOperator();
266
267 if (!Op->isSubClassOf("PatFrag")) {
268 // Just recursively inline children nodes.
269 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
270 setChild(i, getChild(i)->InlinePatternFragments(TP));
271 return this;
272 }
273
274 // Otherwise, we found a reference to a fragment. First, look up its
275 // TreePattern record.
276 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
277
278 // Verify that we are passing the right number of operands.
279 if (Frag->getNumArgs() != Children.size())
280 TP.error("'" + Op->getName() + "' fragment requires " +
281 utostr(Frag->getNumArgs()) + " operands!");
282
Chris Lattner37937092005-09-09 01:15:01 +0000283 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000284
285 // Resolve formal arguments to their actual value.
286 if (Frag->getNumArgs()) {
287 // Compute the map of formal to actual arguments.
288 std::map<std::string, TreePatternNode*> ArgMap;
289 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
290 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
291
292 FragTree->SubstituteFormalArguments(ArgMap);
293 }
294
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000295 FragTree->setName(getName());
296
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000297 // Get a new copy of this fragment to stitch into here.
298 //delete this; // FIXME: implement refcounting!
299 return FragTree;
300}
301
Chris Lattner32707602005-09-08 23:22:48 +0000302/// ApplyTypeConstraints - Apply all of the type constraints relevent to
303/// this node and its children in the tree. This returns true if it makes a
304/// change, false otherwise. If a type contradiction is found, throw an
305/// exception.
306bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
307 if (isLeaf()) return false;
308
309 // special handling for set, which isn't really an SDNode.
310 if (getOperator()->getName() == "set") {
311 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
312 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
313 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
314
315 // Types of operands must match.
316 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
317 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
318 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
319 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000320 } else if (getOperator()->isSubClassOf("SDNode")) {
321 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
322
323 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
324 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
325 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
326 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000327 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000328 const DAGInstruction &Inst =
329 TP.getDAGISelEmitter().getInstruction(getOperator());
330
Chris Lattnera28aec12005-09-15 22:23:50 +0000331 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
332 // Apply the result type to the node
333 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
334
335 if (getNumChildren() != Inst.getNumOperands())
336 TP.error("Instruction '" + getOperator()->getName() + " expects " +
337 utostr(Inst.getNumOperands()) + " operands, not " +
338 utostr(getNumChildren()) + " operands!");
339 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
340 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
341 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
342 }
343 return MadeChange;
344 } else {
345 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
346
347 // Node transforms always take one operand, and take and return the same
348 // type.
349 if (getNumChildren() != 1)
350 TP.error("Node transform '" + getOperator()->getName() +
351 "' requires one operand!");
352 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
353 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
354 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000355 }
Chris Lattner32707602005-09-08 23:22:48 +0000356}
357
358
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000359//===----------------------------------------------------------------------===//
360// TreePattern implementation
361//
362
Chris Lattnera28aec12005-09-15 22:23:50 +0000363TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000364 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000365 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
366 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000367}
368
Chris Lattnera28aec12005-09-15 22:23:50 +0000369TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
370 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
371 Trees.push_back(ParseTreePattern(Pat));
372}
373
374TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
375 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
376 Trees.push_back(Pat);
377}
378
379
380
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000381void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000382 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000383 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000384}
385
386/// getIntrinsicType - Check to see if the specified record has an intrinsic
387/// type which should be applied to it. This infer the type of register
388/// references from the register file information, for example.
389///
390MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
391 // Check to see if this is a register or a register class...
392 if (R->isSubClassOf("RegisterClass"))
393 return getValueType(R->getValueAsDef("RegType"));
394 else if (R->isSubClassOf("PatFrag")) {
Chris Lattner37937092005-09-09 01:15:01 +0000395 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000396 return MVT::LAST_VALUETYPE;
397 } else if (R->isSubClassOf("Register")) {
398 assert(0 && "Explicit registers not handled here yet!\n");
399 return MVT::LAST_VALUETYPE;
400 } else if (R->isSubClassOf("ValueType")) {
401 // Using a VTSDNode.
402 return MVT::Other;
403 } else if (R->getName() == "node") {
404 // Placeholder.
405 return MVT::LAST_VALUETYPE;
406 }
407
Chris Lattner72fe91c2005-09-24 00:40:24 +0000408 error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000409 return MVT::Other;
410}
411
412TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
413 Record *Operator = Dag->getNodeType();
414
415 if (Operator->isSubClassOf("ValueType")) {
416 // If the operator is a ValueType, then this must be "type cast" of a leaf
417 // node.
418 if (Dag->getNumArgs() != 1)
419 error("Type cast only valid for a leaf node!");
420
421 Init *Arg = Dag->getArg(0);
422 TreePatternNode *New;
423 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000424 Record *R = DI->getDef();
425 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
426 Dag->setArg(0, new DagInit(R,
427 std::vector<std::pair<Init*, std::string> >()));
428 TreePatternNode *TPN = ParseTreePattern(Dag);
429 TPN->setName(Dag->getArgName(0));
430 return TPN;
431 }
432
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000433 New = new TreePatternNode(DI);
434 // If it's a regclass or something else known, set the type.
435 New->setType(getIntrinsicType(DI->getDef()));
436 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
437 New = ParseTreePattern(DI);
438 } else {
439 Arg->dump();
440 error("Unknown leaf value for tree pattern!");
441 return 0;
442 }
443
Chris Lattner32707602005-09-08 23:22:48 +0000444 // Apply the type cast.
445 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000446 return New;
447 }
448
449 // Verify that this is something that makes sense for an operator.
450 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000451 !Operator->isSubClassOf("Instruction") &&
452 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000453 Operator->getName() != "set")
454 error("Unrecognized node '" + Operator->getName() + "'!");
455
456 std::vector<TreePatternNode*> Children;
457
458 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
459 Init *Arg = Dag->getArg(i);
460 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
461 Children.push_back(ParseTreePattern(DI));
462 Children.back()->setName(Dag->getArgName(i));
463 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
464 Record *R = DefI->getDef();
465 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
466 // TreePatternNode if its own.
467 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
468 Dag->setArg(i, new DagInit(R,
469 std::vector<std::pair<Init*, std::string> >()));
470 --i; // Revisit this node...
471 } else {
472 TreePatternNode *Node = new TreePatternNode(DefI);
473 Node->setName(Dag->getArgName(i));
474 Children.push_back(Node);
475
476 // If it's a regclass or something else known, set the type.
477 Node->setType(getIntrinsicType(R));
478
479 // Input argument?
480 if (R->getName() == "node") {
481 if (Dag->getArgName(i).empty())
482 error("'node' argument requires a name to match with operand list");
483 Args.push_back(Dag->getArgName(i));
484 }
485 }
486 } else {
487 Arg->dump();
488 error("Unknown leaf value for tree pattern!");
489 }
490 }
491
492 return new TreePatternNode(Operator, Children);
493}
494
Chris Lattner32707602005-09-08 23:22:48 +0000495/// InferAllTypes - Infer/propagate as many types throughout the expression
496/// patterns as possible. Return true if all types are infered, false
497/// otherwise. Throw an exception if a type contradiction is found.
498bool TreePattern::InferAllTypes() {
499 bool MadeChange = true;
500 while (MadeChange) {
501 MadeChange = false;
502 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
503 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
504 }
505
506 bool HasUnresolvedTypes = false;
507 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
508 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
509 return !HasUnresolvedTypes;
510}
511
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000512void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000513 OS << getRecord()->getName();
514 if (!Args.empty()) {
515 OS << "(" << Args[0];
516 for (unsigned i = 1, e = Args.size(); i != e; ++i)
517 OS << ", " << Args[i];
518 OS << ")";
519 }
520 OS << ": ";
521
522 if (Trees.size() > 1)
523 OS << "[\n";
524 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
525 OS << "\t";
526 Trees[i]->print(OS);
527 OS << "\n";
528 }
529
530 if (Trees.size() > 1)
531 OS << "]\n";
532}
533
534void TreePattern::dump() const { print(std::cerr); }
535
536
537
538//===----------------------------------------------------------------------===//
539// DAGISelEmitter implementation
540//
541
Chris Lattnerca559d02005-09-08 21:03:01 +0000542// Parse all of the SDNode definitions for the target, populating SDNodes.
543void DAGISelEmitter::ParseNodeInfo() {
544 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
545 while (!Nodes.empty()) {
546 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
547 Nodes.pop_back();
548 }
549}
550
Chris Lattner24eeeb82005-09-13 21:51:00 +0000551/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
552/// map, and emit them to the file as functions.
553void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
554 OS << "\n// Node transformations.\n";
555 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
556 while (!Xforms.empty()) {
557 Record *XFormNode = Xforms.back();
558 Record *SDNode = XFormNode->getValueAsDef("Opcode");
559 std::string Code = XFormNode->getValueAsCode("XFormFunction");
560 SDNodeXForms.insert(std::make_pair(XFormNode,
561 std::make_pair(SDNode, Code)));
562
Chris Lattner1048b7a2005-09-13 22:03:37 +0000563 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000564 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
565 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
566
Chris Lattner1048b7a2005-09-13 22:03:37 +0000567 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000568 << "(SDNode *" << C2 << ") {\n";
569 if (ClassName != "SDNode")
570 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
571 OS << Code << "\n}\n";
572 }
573
574 Xforms.pop_back();
575 }
576}
577
578
579
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000580/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
581/// file, building up the PatternFragments map. After we've collected them all,
582/// inline fragments together as necessary, so that there are no references left
583/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000584///
585/// This also emits all of the predicate functions to the output file.
586///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000587void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000588 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
589
590 // First step, parse all of the fragments and emit predicate functions.
591 OS << "\n// Predicate functions.\n";
592 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000593 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
594 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000595 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000596
597 // Validate the argument list, converting it to map, to discard duplicates.
598 std::vector<std::string> &Args = P->getArgList();
599 std::set<std::string> OperandsMap(Args.begin(), Args.end());
600
601 if (OperandsMap.count(""))
602 P->error("Cannot have unnamed 'node' values in pattern fragment!");
603
604 // Parse the operands list.
605 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
606 if (OpsList->getNodeType()->getName() != "ops")
607 P->error("Operands list should start with '(ops ... '!");
608
609 // Copy over the arguments.
610 Args.clear();
611 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
612 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
613 static_cast<DefInit*>(OpsList->getArg(j))->
614 getDef()->getName() != "node")
615 P->error("Operands list should all be 'node' values.");
616 if (OpsList->getArgName(j).empty())
617 P->error("Operands list should have names for each operand!");
618 if (!OperandsMap.count(OpsList->getArgName(j)))
619 P->error("'" + OpsList->getArgName(j) +
620 "' does not occur in pattern or was multiply specified!");
621 OperandsMap.erase(OpsList->getArgName(j));
622 Args.push_back(OpsList->getArgName(j));
623 }
624
625 if (!OperandsMap.empty())
626 P->error("Operands list does not contain an entry for operand '" +
627 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000628
629 // If there is a code init for this fragment, emit the predicate code and
630 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000631 std::string Code = Fragments[i]->getValueAsCode("Predicate");
632 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000633 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000634 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000635 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000636 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
637
Chris Lattner1048b7a2005-09-13 22:03:37 +0000638 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000639 << "(SDNode *" << C2 << ") {\n";
640 if (ClassName != "SDNode")
641 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000642 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000643 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000644 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000645
646 // If there is a node transformation corresponding to this, keep track of
647 // it.
648 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
649 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000650 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000651 }
652
653 OS << "\n\n";
654
655 // Now that we've parsed all of the tree fragments, do a closure on them so
656 // that there are not references to PatFrags left inside of them.
657 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
658 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000659 TreePattern *ThePat = I->second;
660 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000661
Chris Lattner32707602005-09-08 23:22:48 +0000662 // Infer as many types as possible. Don't worry about it if we don't infer
663 // all of them, some may depend on the inputs of the pattern.
664 try {
665 ThePat->InferAllTypes();
666 } catch (...) {
667 // If this pattern fragment is not supported by this target (no types can
668 // satisfy its constraints), just ignore it. If the bogus pattern is
669 // actually used by instructions, the type consistency error will be
670 // reported there.
671 }
672
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000673 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000674 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000675 }
676}
677
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000678/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000679/// instruction input. Return true if this is a real use.
680static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000681 std::map<std::string, TreePatternNode*> &InstInputs) {
682 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000683 if (Pat->getName().empty()) {
684 if (Pat->isLeaf()) {
685 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
686 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
687 I->error("Input " + DI->getDef()->getName() + " must be named!");
688
689 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000690 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000691 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000692
693 Record *Rec;
694 if (Pat->isLeaf()) {
695 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
696 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
697 Rec = DI->getDef();
698 } else {
699 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
700 Rec = Pat->getOperator();
701 }
702
703 TreePatternNode *&Slot = InstInputs[Pat->getName()];
704 if (!Slot) {
705 Slot = Pat;
706 } else {
707 Record *SlotRec;
708 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000709 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000710 } else {
711 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
712 SlotRec = Slot->getOperator();
713 }
714
715 // Ensure that the inputs agree if we've already seen this input.
716 if (Rec != SlotRec)
717 I->error("All $" + Pat->getName() + " inputs must agree with each other");
718 if (Slot->getType() != Pat->getType())
719 I->error("All $" + Pat->getName() + " inputs must agree with each other");
720 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000721 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000722}
723
724/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
725/// part of "I", the instruction), computing the set of inputs and outputs of
726/// the pattern. Report errors if we see anything naughty.
727void DAGISelEmitter::
728FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
729 std::map<std::string, TreePatternNode*> &InstInputs,
730 std::map<std::string, Record*> &InstResults) {
731 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000732 bool isUse = HandleUse(I, Pat, InstInputs);
733 if (!isUse && Pat->getTransformFn())
734 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000735 return;
736 } else if (Pat->getOperator()->getName() != "set") {
737 // If this is not a set, verify that the children nodes are not void typed,
738 // and recurse.
739 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
740 if (Pat->getChild(i)->getType() == MVT::isVoid)
741 I->error("Cannot have void nodes inside of patterns!");
742 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
743 }
744
745 // If this is a non-leaf node with no children, treat it basically as if
746 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000747 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000748 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000749 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000750
Chris Lattnerf1311842005-09-14 23:05:13 +0000751 if (!isUse && Pat->getTransformFn())
752 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000753 return;
754 }
755
756 // Otherwise, this is a set, validate and collect instruction results.
757 if (Pat->getNumChildren() == 0)
758 I->error("set requires operands!");
759 else if (Pat->getNumChildren() & 1)
760 I->error("set requires an even number of operands");
761
Chris Lattnerf1311842005-09-14 23:05:13 +0000762 if (Pat->getTransformFn())
763 I->error("Cannot specify a transform function on a set node!");
764
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000765 // Check the set destinations.
766 unsigned NumValues = Pat->getNumChildren()/2;
767 for (unsigned i = 0; i != NumValues; ++i) {
768 TreePatternNode *Dest = Pat->getChild(i);
769 if (!Dest->isLeaf())
770 I->error("set destination should be a virtual register!");
771
772 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
773 if (!Val)
774 I->error("set destination should be a virtual register!");
775
776 if (!Val->getDef()->isSubClassOf("RegisterClass"))
777 I->error("set destination should be a virtual register!");
778 if (Dest->getName().empty())
779 I->error("set destination must have a name!");
780 if (InstResults.count(Dest->getName()))
781 I->error("cannot set '" + Dest->getName() +"' multiple times");
782 InstResults[Dest->getName()] = Val->getDef();
783
784 // Verify and collect info from the computation.
785 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
786 InstInputs, InstResults);
787 }
788}
789
790
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000791/// ParseInstructions - Parse all of the instructions, inlining and resolving
792/// any fragments involved. This populates the Instructions list with fully
793/// resolved instructions.
794void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000795 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
796
797 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
798 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
799 continue; // no pattern yet, ignore it.
800
801 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
802 if (LI->getSize() == 0) continue; // no pattern.
803
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000804 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000805 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000806 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000807 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000808
Chris Lattner95f6b762005-09-08 23:26:30 +0000809 // Infer as many types as possible. If we cannot infer all of them, we can
810 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000811 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +0000812 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000813
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000814 // InstInputs - Keep track of all of the inputs of the instruction, along
815 // with the record they are declared as.
816 std::map<std::string, TreePatternNode*> InstInputs;
817
818 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000819 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000820 std::map<std::string, Record*> InstResults;
821
Chris Lattner1f39e292005-09-14 00:09:24 +0000822 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000823 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000824 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
825 TreePatternNode *Pat = I->getTree(j);
826 if (Pat->getType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000827 I->dump();
828 I->error("Top-level forms in instruction pattern should have"
829 " void types");
830 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000831
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000832 // Find inputs and outputs, and verify the structure of the uses/defs.
833 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000834 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000835
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000836 // Now that we have inputs and outputs of the pattern, inspect the operands
837 // list for the instruction. This determines the order that operands are
838 // added to the machine instruction the node corresponds to.
839 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000840
841 // Parse the operands list from the (ops) list, validating it.
842 std::vector<std::string> &Args = I->getArgList();
843 assert(Args.empty() && "Args list should still be empty here!");
844 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
845
846 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +0000847 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +0000848 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000849 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000850 I->error("'" + InstResults.begin()->first +
851 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +0000852 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +0000853
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000854 // Check that it exists in InstResults.
855 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000856 if (R == 0)
857 I->error("Operand $" + OpName + " should be a set destination: all "
858 "outputs must occur before inputs in operand list!");
859
860 if (CGI.OperandList[i].Rec != R)
861 I->error("Operand $" + OpName + " class mismatch!");
862
Chris Lattnerae6d8282005-09-15 21:51:12 +0000863 // Remember the return type.
864 ResultTypes.push_back(CGI.OperandList[i].Ty);
865
Chris Lattner39e8af92005-09-14 18:19:25 +0000866 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000867 InstResults.erase(OpName);
868 }
869
Chris Lattner0b592252005-09-14 21:59:34 +0000870 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
871 // the copy while we're checking the inputs.
872 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +0000873
874 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +0000875 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000876 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
877 const std::string &OpName = CGI.OperandList[i].Name;
878 if (OpName.empty())
879 I->error("Operand #" + utostr(i) + " in operands list has no name!");
880
Chris Lattner0b592252005-09-14 21:59:34 +0000881 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000882 I->error("Operand $" + OpName +
883 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +0000884 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +0000885 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000886 if (CGI.OperandList[i].Ty != InVal->getType())
887 I->error("Operand $" + OpName +
888 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +0000889 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +0000890
Chris Lattner2175c182005-09-14 23:01:59 +0000891 // Construct the result for the dest-pattern operand list.
892 TreePatternNode *OpNode = InVal->clone();
893
894 // No predicate is useful on the result.
895 OpNode->setPredicateFn("");
896
897 // Promote the xform function to be an explicit node if set.
898 if (Record *Xform = OpNode->getTransformFn()) {
899 OpNode->setTransformFn(0);
900 std::vector<TreePatternNode*> Children;
901 Children.push_back(OpNode);
902 OpNode = new TreePatternNode(Xform, Children);
903 }
904
905 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +0000906 }
907
Chris Lattner0b592252005-09-14 21:59:34 +0000908 if (!InstInputsCheck.empty())
909 I->error("Input operand $" + InstInputsCheck.begin()->first +
910 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +0000911
912 TreePatternNode *ResultPattern =
913 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +0000914
915 // Create and insert the instruction.
916 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
917 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
918
919 // Use a temporary tree pattern to infer all types and make sure that the
920 // constructed result is correct. This depends on the instruction already
921 // being inserted into the Instructions map.
922 TreePattern Temp(I->getRecord(), ResultPattern, *this);
923 Temp.InferAllTypes();
924
925 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
926 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +0000927
Chris Lattner32707602005-09-08 23:22:48 +0000928 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000929 }
Chris Lattner1f39e292005-09-14 00:09:24 +0000930
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000931 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +0000932 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
933 E = Instructions.end(); II != E; ++II) {
934 TreePattern *I = II->second.getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +0000935
936 if (I->getNumTrees() != 1) {
937 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
938 continue;
939 }
940 TreePatternNode *Pattern = I->getTree(0);
941 if (Pattern->getOperator()->getName() != "set")
942 continue; // Not a set (store or something?)
943
944 if (Pattern->getNumChildren() != 2)
945 continue; // Not a set of a single value (not handled so far)
946
947 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000948 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +0000949 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +0000950 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000951}
952
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000953void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +0000954 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000955
Chris Lattnerabbb6052005-09-15 21:42:00 +0000956 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000957 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
958 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000959
Chris Lattnerabbb6052005-09-15 21:42:00 +0000960 // Inline pattern fragments into it.
961 Pattern->InlinePatternFragments();
962
963 // Infer as many types as possible. If we cannot infer all of them, we can
964 // never do anything with this pattern: report it to the user.
965 if (!Pattern->InferAllTypes())
966 Pattern->error("Could not infer all types in pattern!");
967
968 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
969 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000970
971 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000972 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000973
974 // Inline pattern fragments into it.
975 Result->InlinePatternFragments();
976
977 // Infer as many types as possible. If we cannot infer all of them, we can
978 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000979 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +0000980 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +0000981
982 if (Result->getNumTrees() != 1)
983 Result->error("Cannot handle instructions producing instructions "
984 "with temporaries yet!");
985 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
986 Result->getOnlyTree()));
987 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000988
989 DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
990 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
991 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
992 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
993 std::cerr << "\n";
994 });
995}
996
Chris Lattnerd1ff35a2005-09-23 21:33:23 +0000997/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
998/// if the match fails. At this point, we already know that the opcode for N
999/// matches, and the SDNode for the result has the RootName specified name.
1000void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001001 const std::string &RootName,
1002 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001003 unsigned PatternNo, std::ostream &OS) {
1004 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001005
1006 // If this node has a name associated with it, capture it in VarMap. If
1007 // we already saw this in the pattern, emit code to verify dagness.
1008 if (!N->getName().empty()) {
1009 std::string &VarMapEntry = VarMap[N->getName()];
1010 if (VarMapEntry.empty()) {
1011 VarMapEntry = RootName;
1012 } else {
1013 // If we get here, this is a second reference to a specific name. Since
1014 // we already have checked that the first reference is valid, we don't
1015 // have to recursively match it, just check that it's the same as the
1016 // previously named thing.
1017 OS << " if (" << VarMapEntry << " != " << RootName
1018 << ") goto P" << PatternNo << "Fail;\n";
1019 return;
1020 }
1021 }
1022
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001023 // Emit code to load the child nodes and match their contents recursively.
1024 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001025 OS << " SDOperand " << RootName << i <<" = " << RootName
1026 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001027 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001028
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001029 if (!Child->isLeaf()) {
1030 // If it's not a leaf, recursively match.
1031 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001032 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001033 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001034 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001035 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001036 // If this child has a name associated with it, capture it in VarMap. If
1037 // we already saw this in the pattern, emit code to verify dagness.
1038 if (!Child->getName().empty()) {
1039 std::string &VarMapEntry = VarMap[Child->getName()];
1040 if (VarMapEntry.empty()) {
1041 VarMapEntry = RootName + utostr(i);
1042 } else {
1043 // If we get here, this is a second reference to a specific name. Since
1044 // we already have checked that the first reference is valid, we don't
1045 // have to recursively match it, just check that it's the same as the
1046 // previously named thing.
1047 OS << " if (" << VarMapEntry << " != " << RootName << i
1048 << ") goto P" << PatternNo << "Fail;\n";
1049 continue;
1050 }
1051 }
1052
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001053 // Handle leaves of various types.
1054 Init *LeafVal = Child->getLeafValue();
1055 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1056 if (LeafRec->isSubClassOf("RegisterClass")) {
1057 // Handle register references. Nothing to do here.
1058 } else if (LeafRec->isSubClassOf("ValueType")) {
1059 // Make sure this is the specified value type.
1060 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1061 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1062 << "Fail;\n";
1063 } else {
1064 Child->dump();
1065 assert(0 && "Unknown leaf type!");
1066 }
1067 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001068 }
1069
1070 // If there is a node predicate for this, emit the call.
1071 if (!N->getPredicateFn().empty())
1072 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001073 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001074}
1075
Chris Lattner72fe91c2005-09-24 00:40:24 +00001076
1077unsigned DAGISelEmitter::
1078CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1079 std::map<std::string,std::string> &VariableMap,
1080 std::ostream &OS){
1081 // This is something selected from the pattern we matched.
1082 if (!N->getName().empty()) {
1083 const std::string &Val = VariableMap[N->getName()];
1084 assert(!Val.empty() &&
1085 "Variable referenced but not defined and not caught earlier!");
1086 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1087 // Already selected this operand, just return the tmpval.
1088 // FIXME: DO THIS.
1089 } else {
1090 unsigned ResNo = Ctr++;
1091 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1092 // FIXME: Add Tmp<ResNo> to VariableMap.
1093 return ResNo;
1094 }
1095 }
1096
1097 if (N->isLeaf()) {
1098 N->dump();
1099 assert(0 && "Unknown leaf type!");
1100 return ~0U;
1101 }
1102
1103 Record *Op = N->getOperator();
1104 if (Op->isSubClassOf("Instruction")) {
1105 // Emit all of the operands.
1106 std::vector<unsigned> Ops;
1107 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1108 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1109
1110 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1111 unsigned ResNo = Ctr++;
1112
1113 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1114 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1115 << getEnumName(N->getType());
1116 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1117 OS << ", Tmp" << Ops[i];
1118 OS << ");\n";
1119 return ResNo;
1120 } else if (Op->isSubClassOf("SDNodeXForm")) {
1121 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1122 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1123
1124 unsigned ResNo = Ctr++;
1125 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1126 << "(Tmp" << OpVal << ".Val);\n";
1127 return ResNo;
1128 } else {
1129 N->dump();
1130 assert(0 && "Unknown node in result pattern!");
1131 }
1132}
1133
1134
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001135/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1136/// stream to match the pattern, and generate the code for the match if it
1137/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001138void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1139 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001140 static unsigned PatternCount = 0;
1141 unsigned PatternNo = PatternCount++;
1142 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001143 Pattern.first->print(OS);
1144 OS << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001145
Chris Lattner8fc35682005-09-23 23:16:51 +00001146 // Emit the matcher, capturing named arguments in VariableMap.
1147 std::map<std::string,std::string> VariableMap;
1148 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001149
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001150 OS << " // Emit: ";
1151 Pattern.second->print(OS);
1152 OS << "\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001153
Chris Lattner72fe91c2005-09-24 00:40:24 +00001154 unsigned TmpNo = 0;
1155 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
1156 OS << " return Tmp" << Res << ";\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001157 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001158}
1159
1160/// getPatternSize - Return the 'size' of this pattern. We want to match large
1161/// patterns before small ones. This is used to determine the size of a
1162/// pattern.
1163static unsigned getPatternSize(TreePatternNode *P) {
1164 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1165 "Not a valid pattern node to size!");
1166 unsigned Size = 1; // The node itself.
1167
1168 // Count children in the count if they are also nodes.
1169 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1170 TreePatternNode *Child = P->getChild(i);
1171 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1172 Size += getPatternSize(Child);
1173 }
1174
1175 return Size;
1176}
1177
1178// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1179// In particular, we want to match maximal patterns first and lowest cost within
1180// a particular complexity first.
1181struct PatternSortingPredicate {
1182 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1183 DAGISelEmitter::PatternToMatch *RHS) {
1184 unsigned LHSSize = getPatternSize(LHS->first);
1185 unsigned RHSSize = getPatternSize(RHS->first);
1186 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1187 if (LHSSize < RHSSize) return false;
1188
1189 // If they are equal, compare cost.
1190 // FIXME: Compute cost!
1191 return false;
1192 }
1193};
1194
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001195void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1196 // Emit boilerplate.
1197 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001198 << "SDOperand SelectCode(SDOperand N) {\n"
1199 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1200 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1201 << " return N; // Already selected.\n\n"
1202 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001203 << " default: break;\n"
1204 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001205 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001206 << " case ISD::AssertSext:\n"
1207 << " case ISD::AssertZext:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001208 << " return Select(N.getOperand(0));\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001209
Chris Lattner81303322005-09-23 19:36:15 +00001210 // Group the patterns by their top-level opcodes.
1211 std::map<Record*, std::vector<PatternToMatch*> > PatternsByOpcode;
1212 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1213 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1214 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001215
Chris Lattner3f7e9142005-09-23 20:52:47 +00001216 // Loop over all of the case statements.
Chris Lattner81303322005-09-23 19:36:15 +00001217 for (std::map<Record*, std::vector<PatternToMatch*> >::iterator
1218 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E;
1219 ++PBOI) {
1220 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1221 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1222
1223 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001224
1225 // We want to emit all of the matching code now. However, we want to emit
1226 // the matches in order of minimal cost. Sort the patterns so the least
1227 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001228 std::stable_sort(Patterns.begin(), Patterns.end(),
1229 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001230
Chris Lattner3f7e9142005-09-23 20:52:47 +00001231 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1232 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001233 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001234 }
1235
1236
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001237 OS << " } // end of big switch.\n\n"
1238 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001239 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001240 << " std::cerr << '\\n';\n"
1241 << " abort();\n"
1242 << "}\n";
1243}
1244
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001245void DAGISelEmitter::run(std::ostream &OS) {
1246 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1247 " target", OS);
1248
Chris Lattner1f39e292005-09-14 00:09:24 +00001249 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1250 << "// *** instruction selector class. These functions are really "
1251 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001252
Chris Lattnerca559d02005-09-08 21:03:01 +00001253 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001254 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001255 ParsePatternFragments(OS);
1256 ParseInstructions();
1257 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001258
1259 // FIXME: Generate variants. For example, commutative patterns can match
1260 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001261
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001262 // At this point, we have full information about the 'Patterns' we need to
1263 // parse, both implicitly from instructions as well as from explicit pattern
1264 // definitions.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001265
1266 EmitInstructionSelector(OS);
1267
1268 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1269 E = PatternFragments.end(); I != E; ++I)
1270 delete I->second;
1271 PatternFragments.clear();
1272
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001273 Instructions.clear();
1274}