1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
22 //===----------------------------------------------------------------------===//
23 // SDTypeConstraint implementation
26 SDTypeConstraint::SDTypeConstraint(Record *R) {
27 OperandNo = R->getValueAsInt("OperandNum");
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");
44 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
49 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
50 /// N, which has NumResults results.
51 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
53 unsigned NumResults) const {
54 assert(NumResults == 1 && "We only work with single result nodes so far!");
56 if (OpNo < NumResults)
57 return N; // FIXME: need value #
59 return N->getChild(OpNo-NumResults);
62 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
63 /// constraint to the nodes operands. This returns true if it makes a
64 /// change, false otherwise. If a type contradiction is found, throw an
66 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
67 const SDNodeInfo &NodeInfo,
68 TreePattern &TP) const {
69 unsigned NumResults = NodeInfo.getNumResults();
70 assert(NumResults == 1 && "We only work with single result nodes so far!");
72 // Check that the number of operands is sane.
73 if (NodeInfo.getNumOperands() >= 0) {
74 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
75 TP.error(N->getOperator()->getName() + " node requires exactly " +
76 itostr(NodeInfo.getNumOperands()) + " operands!");
79 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
81 switch (ConstraintType) {
82 default: assert(0 && "Unknown constraint type!");
84 // Operand must be a particular type.
85 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
87 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
88 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
90 // FIXME: can tell from the target if there is only one Int type supported.
93 if (NodeToApply->hasTypeSet() &&
94 !MVT::isFloatingPoint(NodeToApply->getType()))
95 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
96 // FIXME: can tell from the target if there is only one FP type supported.
99 TreePatternNode *OtherNode =
100 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
101 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
102 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
104 case SDTCisVTSmallerThanOp: {
105 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
106 // have an integer type that is smaller than the VT.
107 if (!NodeToApply->isLeaf() ||
108 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
109 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
110 ->isSubClassOf("ValueType"))
111 TP.error(N->getOperator()->getName() + " expects a VT operand!");
113 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
114 if (!MVT::isInteger(VT))
115 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
117 TreePatternNode *OtherNode =
118 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
119 if (OtherNode->hasTypeSet() &&
120 (!MVT::isInteger(OtherNode->getType()) ||
121 OtherNode->getType() <= VT))
122 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
130 //===----------------------------------------------------------------------===//
131 // SDNodeInfo implementation
133 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
134 EnumName = R->getValueAsString("Opcode");
135 SDClassName = R->getValueAsString("SDClass");
136 Record *TypeProfile = R->getValueAsDef("TypeProfile");
137 NumResults = TypeProfile->getValueAsInt("NumResults");
138 NumOperands = TypeProfile->getValueAsInt("NumOperands");
140 // Parse the properties.
142 ListInit *LI = R->getValueAsListInit("Properties");
143 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
144 DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
145 assert(DI && "Properties list must be list of defs!");
146 if (DI->getDef()->getName() == "SDNPCommutative") {
147 Properties |= 1 << SDNPCommutative;
148 } else if (DI->getDef()->getName() == "SDNPAssociative") {
149 Properties |= 1 << SDNPAssociative;
151 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
152 << "' on node '" << R->getName() << "'!\n";
158 // Parse the type constraints.
159 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
160 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
161 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
162 "Constraints list should contain constraint definitions!");
164 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
165 TypeConstraints.push_back(Constraint);
169 //===----------------------------------------------------------------------===//
170 // TreePatternNode implementation
173 TreePatternNode::~TreePatternNode() {
174 #if 0 // FIXME: implement refcounted tree nodes!
175 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
180 /// UpdateNodeType - Set the node type of N to VT if VT contains
181 /// information. If N already contains a conflicting type, then throw an
182 /// exception. This returns true if any information was updated.
184 bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
185 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
186 if (getType() == MVT::LAST_VALUETYPE) {
191 TP.error("Type inference contradiction found in node " +
192 getOperator()->getName() + "!");
193 return true; // unreachable
197 void TreePatternNode::print(std::ostream &OS) const {
199 OS << *getLeafValue();
201 OS << "(" << getOperator()->getName();
204 if (getType() == MVT::Other)
206 else if (getType() == MVT::LAST_VALUETYPE)
209 OS << ":" << getType();
212 if (getNumChildren() != 0) {
214 getChild(0)->print(OS);
215 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
217 getChild(i)->print(OS);
223 if (!PredicateFn.empty())
224 OS << "<<P:" << PredicateFn << ">>";
226 OS << "<<X:" << TransformFn->getName() << ">>";
227 if (!getName().empty())
228 OS << ":$" << getName();
231 void TreePatternNode::dump() const {
235 /// clone - Make a copy of this tree and all of its children.
237 TreePatternNode *TreePatternNode::clone() const {
238 TreePatternNode *New;
240 New = new TreePatternNode(getLeafValue());
242 std::vector<TreePatternNode*> CChildren;
243 CChildren.reserve(Children.size());
244 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
245 CChildren.push_back(getChild(i)->clone());
246 New = new TreePatternNode(getOperator(), CChildren);
248 New->setName(getName());
249 New->setType(getType());
250 New->setPredicateFn(getPredicateFn());
251 New->setTransformFn(getTransformFn());
255 /// SubstituteFormalArguments - Replace the formal arguments in this tree
256 /// with actual values specified by ArgMap.
257 void TreePatternNode::
258 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
259 if (isLeaf()) return;
261 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
262 TreePatternNode *Child = getChild(i);
263 if (Child->isLeaf()) {
264 Init *Val = Child->getLeafValue();
265 if (dynamic_cast<DefInit*>(Val) &&
266 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
267 // We found a use of a formal argument, replace it with its value.
268 Child = ArgMap[Child->getName()];
269 assert(Child && "Couldn't find formal argument!");
273 getChild(i)->SubstituteFormalArguments(ArgMap);
279 /// InlinePatternFragments - If this pattern refers to any pattern
280 /// fragments, inline them into place, giving us a pattern without any
281 /// PatFrag references.
282 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
283 if (isLeaf()) return this; // nothing to do.
284 Record *Op = getOperator();
286 if (!Op->isSubClassOf("PatFrag")) {
287 // Just recursively inline children nodes.
288 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
289 setChild(i, getChild(i)->InlinePatternFragments(TP));
293 // Otherwise, we found a reference to a fragment. First, look up its
294 // TreePattern record.
295 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
297 // Verify that we are passing the right number of operands.
298 if (Frag->getNumArgs() != Children.size())
299 TP.error("'" + Op->getName() + "' fragment requires " +
300 utostr(Frag->getNumArgs()) + " operands!");
302 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
304 // Resolve formal arguments to their actual value.
305 if (Frag->getNumArgs()) {
306 // Compute the map of formal to actual arguments.
307 std::map<std::string, TreePatternNode*> ArgMap;
308 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
309 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
311 FragTree->SubstituteFormalArguments(ArgMap);
314 FragTree->setName(getName());
316 // Get a new copy of this fragment to stitch into here.
317 //delete this; // FIXME: implement refcounting!
321 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
322 /// this node and its children in the tree. This returns true if it makes a
323 /// change, false otherwise. If a type contradiction is found, throw an
325 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
326 if (isLeaf()) return false;
328 // special handling for set, which isn't really an SDNode.
329 if (getOperator()->getName() == "set") {
330 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
331 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
332 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
334 // Types of operands must match.
335 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
336 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
337 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
339 } else if (getOperator()->isSubClassOf("SDNode")) {
340 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
342 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
343 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
344 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
346 } else if (getOperator()->isSubClassOf("Instruction")) {
347 const DAGInstruction &Inst =
348 TP.getDAGISelEmitter().getInstruction(getOperator());
350 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
351 // Apply the result type to the node
352 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
354 if (getNumChildren() != Inst.getNumOperands())
355 TP.error("Instruction '" + getOperator()->getName() + " expects " +
356 utostr(Inst.getNumOperands()) + " operands, not " +
357 utostr(getNumChildren()) + " operands!");
358 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
359 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
360 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
364 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
366 // Node transforms always take one operand, and take and return the same
368 if (getNumChildren() != 1)
369 TP.error("Node transform '" + getOperator()->getName() +
370 "' requires one operand!");
371 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
372 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
377 /// canPatternMatch - If it is impossible for this pattern to match on this
378 /// target, fill in Reason and return false. Otherwise, return true. This is
379 /// used as a santity check for .td files (to prevent people from writing stuff
380 /// that can never possibly work), and to prevent the pattern permuter from
381 /// generating stuff that is useless.
382 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
383 if (isLeaf()) return true;
385 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
386 if (!getChild(i)->canPatternMatch(Reason, ISE))
389 // If this node is a commutative operator, check that the LHS isn't an
391 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
392 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
393 // Scan all of the operands of the node and make sure that only the last one
394 // is a constant node.
395 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
396 if (!getChild(i)->isLeaf() &&
397 getChild(i)->getOperator()->getName() == "imm") {
398 Reason = "Immediate value must be on the RHS of commutative operators!";
406 //===----------------------------------------------------------------------===//
407 // TreePattern implementation
410 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
411 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
412 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
413 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
416 TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
417 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
418 Trees.push_back(ParseTreePattern(Pat));
421 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
422 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
423 Trees.push_back(Pat);
428 void TreePattern::error(const std::string &Msg) const {
430 throw "In " + TheRecord->getName() + ": " + Msg;
433 /// getIntrinsicType - Check to see if the specified record has an intrinsic
434 /// type which should be applied to it. This infer the type of register
435 /// references from the register file information, for example.
437 MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
438 // Check to see if this is a register or a register class...
439 if (R->isSubClassOf("RegisterClass"))
440 return getValueType(R->getValueAsDef("RegType"));
441 else if (R->isSubClassOf("PatFrag")) {
442 // Pattern fragment types will be resolved when they are inlined.
443 return MVT::LAST_VALUETYPE;
444 } else if (R->isSubClassOf("Register")) {
445 assert(0 && "Explicit registers not handled here yet!\n");
446 return MVT::LAST_VALUETYPE;
447 } else if (R->isSubClassOf("ValueType")) {
450 } else if (R->getName() == "node") {
452 return MVT::LAST_VALUETYPE;
455 error("Unknown node flavor used in pattern: " + R->getName());
459 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
460 Record *Operator = Dag->getNodeType();
462 if (Operator->isSubClassOf("ValueType")) {
463 // If the operator is a ValueType, then this must be "type cast" of a leaf
465 if (Dag->getNumArgs() != 1)
466 error("Type cast only valid for a leaf node!");
468 Init *Arg = Dag->getArg(0);
469 TreePatternNode *New;
470 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
471 Record *R = DI->getDef();
472 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
473 Dag->setArg(0, new DagInit(R,
474 std::vector<std::pair<Init*, std::string> >()));
475 TreePatternNode *TPN = ParseTreePattern(Dag);
476 TPN->setName(Dag->getArgName(0));
480 New = new TreePatternNode(DI);
481 // If it's a regclass or something else known, set the type.
482 New->setType(getIntrinsicType(DI->getDef()));
483 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
484 New = ParseTreePattern(DI);
487 error("Unknown leaf value for tree pattern!");
491 // Apply the type cast.
492 New->UpdateNodeType(getValueType(Operator), *this);
496 // Verify that this is something that makes sense for an operator.
497 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
498 !Operator->isSubClassOf("Instruction") &&
499 !Operator->isSubClassOf("SDNodeXForm") &&
500 Operator->getName() != "set")
501 error("Unrecognized node '" + Operator->getName() + "'!");
503 std::vector<TreePatternNode*> Children;
505 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
506 Init *Arg = Dag->getArg(i);
507 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
508 Children.push_back(ParseTreePattern(DI));
509 Children.back()->setName(Dag->getArgName(i));
510 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
511 Record *R = DefI->getDef();
512 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
513 // TreePatternNode if its own.
514 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
515 Dag->setArg(i, new DagInit(R,
516 std::vector<std::pair<Init*, std::string> >()));
517 --i; // Revisit this node...
519 TreePatternNode *Node = new TreePatternNode(DefI);
520 Node->setName(Dag->getArgName(i));
521 Children.push_back(Node);
523 // If it's a regclass or something else known, set the type.
524 Node->setType(getIntrinsicType(R));
527 if (R->getName() == "node") {
528 if (Dag->getArgName(i).empty())
529 error("'node' argument requires a name to match with operand list");
530 Args.push_back(Dag->getArgName(i));
535 error("Unknown leaf value for tree pattern!");
539 return new TreePatternNode(Operator, Children);
542 /// InferAllTypes - Infer/propagate as many types throughout the expression
543 /// patterns as possible. Return true if all types are infered, false
544 /// otherwise. Throw an exception if a type contradiction is found.
545 bool TreePattern::InferAllTypes() {
546 bool MadeChange = true;
549 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
550 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
553 bool HasUnresolvedTypes = false;
554 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
555 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
556 return !HasUnresolvedTypes;
559 void TreePattern::print(std::ostream &OS) const {
560 OS << getRecord()->getName();
562 OS << "(" << Args[0];
563 for (unsigned i = 1, e = Args.size(); i != e; ++i)
564 OS << ", " << Args[i];
569 if (Trees.size() > 1)
571 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
577 if (Trees.size() > 1)
581 void TreePattern::dump() const { print(std::cerr); }
585 //===----------------------------------------------------------------------===//
586 // DAGISelEmitter implementation
589 // Parse all of the SDNode definitions for the target, populating SDNodes.
590 void DAGISelEmitter::ParseNodeInfo() {
591 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
592 while (!Nodes.empty()) {
593 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
598 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
599 /// map, and emit them to the file as functions.
600 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
601 OS << "\n// Node transformations.\n";
602 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
603 while (!Xforms.empty()) {
604 Record *XFormNode = Xforms.back();
605 Record *SDNode = XFormNode->getValueAsDef("Opcode");
606 std::string Code = XFormNode->getValueAsCode("XFormFunction");
607 SDNodeXForms.insert(std::make_pair(XFormNode,
608 std::make_pair(SDNode, Code)));
611 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
612 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
614 OS << "inline SDOperand Transform_" << XFormNode->getName()
615 << "(SDNode *" << C2 << ") {\n";
616 if (ClassName != "SDNode")
617 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
618 OS << Code << "\n}\n";
627 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
628 /// file, building up the PatternFragments map. After we've collected them all,
629 /// inline fragments together as necessary, so that there are no references left
630 /// inside a pattern fragment to a pattern fragment.
632 /// This also emits all of the predicate functions to the output file.
634 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
635 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
637 // First step, parse all of the fragments and emit predicate functions.
638 OS << "\n// Predicate functions.\n";
639 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
640 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
641 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
642 PatternFragments[Fragments[i]] = P;
644 // Validate the argument list, converting it to map, to discard duplicates.
645 std::vector<std::string> &Args = P->getArgList();
646 std::set<std::string> OperandsMap(Args.begin(), Args.end());
648 if (OperandsMap.count(""))
649 P->error("Cannot have unnamed 'node' values in pattern fragment!");
651 // Parse the operands list.
652 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
653 if (OpsList->getNodeType()->getName() != "ops")
654 P->error("Operands list should start with '(ops ... '!");
656 // Copy over the arguments.
658 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
659 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
660 static_cast<DefInit*>(OpsList->getArg(j))->
661 getDef()->getName() != "node")
662 P->error("Operands list should all be 'node' values.");
663 if (OpsList->getArgName(j).empty())
664 P->error("Operands list should have names for each operand!");
665 if (!OperandsMap.count(OpsList->getArgName(j)))
666 P->error("'" + OpsList->getArgName(j) +
667 "' does not occur in pattern or was multiply specified!");
668 OperandsMap.erase(OpsList->getArgName(j));
669 Args.push_back(OpsList->getArgName(j));
672 if (!OperandsMap.empty())
673 P->error("Operands list does not contain an entry for operand '" +
674 *OperandsMap.begin() + "'!");
676 // If there is a code init for this fragment, emit the predicate code and
677 // keep track of the fact that this fragment uses it.
678 std::string Code = Fragments[i]->getValueAsCode("Predicate");
680 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
681 std::string ClassName =
682 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
683 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
685 OS << "inline bool Predicate_" << Fragments[i]->getName()
686 << "(SDNode *" << C2 << ") {\n";
687 if (ClassName != "SDNode")
688 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
689 OS << Code << "\n}\n";
690 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
693 // If there is a node transformation corresponding to this, keep track of
695 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
696 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
697 P->getOnlyTree()->setTransformFn(Transform);
702 // Now that we've parsed all of the tree fragments, do a closure on them so
703 // that there are not references to PatFrags left inside of them.
704 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
705 E = PatternFragments.end(); I != E; ++I) {
706 TreePattern *ThePat = I->second;
707 ThePat->InlinePatternFragments();
709 // Infer as many types as possible. Don't worry about it if we don't infer
710 // all of them, some may depend on the inputs of the pattern.
712 ThePat->InferAllTypes();
714 // If this pattern fragment is not supported by this target (no types can
715 // satisfy its constraints), just ignore it. If the bogus pattern is
716 // actually used by instructions, the type consistency error will be
720 // If debugging, print out the pattern fragment result.
721 DEBUG(ThePat->dump());
725 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
726 /// instruction input. Return true if this is a real use.
727 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
728 std::map<std::string, TreePatternNode*> &InstInputs) {
729 // No name -> not interesting.
730 if (Pat->getName().empty()) {
732 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
733 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
734 I->error("Input " + DI->getDef()->getName() + " must be named!");
742 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
743 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
746 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
747 Rec = Pat->getOperator();
750 TreePatternNode *&Slot = InstInputs[Pat->getName()];
755 if (Slot->isLeaf()) {
756 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
758 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
759 SlotRec = Slot->getOperator();
762 // Ensure that the inputs agree if we've already seen this input.
764 I->error("All $" + Pat->getName() + " inputs must agree with each other");
765 if (Slot->getType() != Pat->getType())
766 I->error("All $" + Pat->getName() + " inputs must agree with each other");
771 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
772 /// part of "I", the instruction), computing the set of inputs and outputs of
773 /// the pattern. Report errors if we see anything naughty.
774 void DAGISelEmitter::
775 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
776 std::map<std::string, TreePatternNode*> &InstInputs,
777 std::map<std::string, Record*> &InstResults) {
779 bool isUse = HandleUse(I, Pat, InstInputs);
780 if (!isUse && Pat->getTransformFn())
781 I->error("Cannot specify a transform function for a non-input value!");
783 } else if (Pat->getOperator()->getName() != "set") {
784 // If this is not a set, verify that the children nodes are not void typed,
786 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
787 if (Pat->getChild(i)->getType() == MVT::isVoid)
788 I->error("Cannot have void nodes inside of patterns!");
789 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
792 // If this is a non-leaf node with no children, treat it basically as if
793 // it were a leaf. This handles nodes like (imm).
795 if (Pat->getNumChildren() == 0)
796 isUse = HandleUse(I, Pat, InstInputs);
798 if (!isUse && Pat->getTransformFn())
799 I->error("Cannot specify a transform function for a non-input value!");
803 // Otherwise, this is a set, validate and collect instruction results.
804 if (Pat->getNumChildren() == 0)
805 I->error("set requires operands!");
806 else if (Pat->getNumChildren() & 1)
807 I->error("set requires an even number of operands");
809 if (Pat->getTransformFn())
810 I->error("Cannot specify a transform function on a set node!");
812 // Check the set destinations.
813 unsigned NumValues = Pat->getNumChildren()/2;
814 for (unsigned i = 0; i != NumValues; ++i) {
815 TreePatternNode *Dest = Pat->getChild(i);
817 I->error("set destination should be a virtual register!");
819 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
821 I->error("set destination should be a virtual register!");
823 if (!Val->getDef()->isSubClassOf("RegisterClass"))
824 I->error("set destination should be a virtual register!");
825 if (Dest->getName().empty())
826 I->error("set destination must have a name!");
827 if (InstResults.count(Dest->getName()))
828 I->error("cannot set '" + Dest->getName() +"' multiple times");
829 InstResults[Dest->getName()] = Val->getDef();
831 // Verify and collect info from the computation.
832 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
833 InstInputs, InstResults);
838 /// ParseInstructions - Parse all of the instructions, inlining and resolving
839 /// any fragments involved. This populates the Instructions list with fully
840 /// resolved instructions.
841 void DAGISelEmitter::ParseInstructions() {
842 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
844 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
845 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
846 continue; // no pattern yet, ignore it.
848 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
849 if (LI->getSize() == 0) continue; // no pattern.
851 // Parse the instruction.
852 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
853 // Inline pattern fragments into it.
854 I->InlinePatternFragments();
856 // Infer as many types as possible. If we cannot infer all of them, we can
857 // never do anything with this instruction pattern: report it to the user.
858 if (!I->InferAllTypes())
859 I->error("Could not infer all types in pattern!");
861 // InstInputs - Keep track of all of the inputs of the instruction, along
862 // with the record they are declared as.
863 std::map<std::string, TreePatternNode*> InstInputs;
865 // InstResults - Keep track of all the virtual registers that are 'set'
866 // in the instruction, including what reg class they are.
867 std::map<std::string, Record*> InstResults;
869 // Verify that the top-level forms in the instruction are of void type, and
870 // fill in the InstResults map.
871 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
872 TreePatternNode *Pat = I->getTree(j);
873 if (Pat->getType() != MVT::isVoid) {
875 I->error("Top-level forms in instruction pattern should have"
879 // Find inputs and outputs, and verify the structure of the uses/defs.
880 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
883 // Now that we have inputs and outputs of the pattern, inspect the operands
884 // list for the instruction. This determines the order that operands are
885 // added to the machine instruction the node corresponds to.
886 unsigned NumResults = InstResults.size();
888 // Parse the operands list from the (ops) list, validating it.
889 std::vector<std::string> &Args = I->getArgList();
890 assert(Args.empty() && "Args list should still be empty here!");
891 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
893 // Check that all of the results occur first in the list.
894 std::vector<MVT::ValueType> ResultTypes;
895 for (unsigned i = 0; i != NumResults; ++i) {
896 if (i == CGI.OperandList.size())
897 I->error("'" + InstResults.begin()->first +
898 "' set but does not appear in operand list!");
899 const std::string &OpName = CGI.OperandList[i].Name;
901 // Check that it exists in InstResults.
902 Record *R = InstResults[OpName];
904 I->error("Operand $" + OpName + " should be a set destination: all "
905 "outputs must occur before inputs in operand list!");
907 if (CGI.OperandList[i].Rec != R)
908 I->error("Operand $" + OpName + " class mismatch!");
910 // Remember the return type.
911 ResultTypes.push_back(CGI.OperandList[i].Ty);
913 // Okay, this one checks out.
914 InstResults.erase(OpName);
917 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
918 // the copy while we're checking the inputs.
919 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
921 std::vector<TreePatternNode*> ResultNodeOperands;
922 std::vector<MVT::ValueType> OperandTypes;
923 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
924 const std::string &OpName = CGI.OperandList[i].Name;
926 I->error("Operand #" + utostr(i) + " in operands list has no name!");
928 if (!InstInputsCheck.count(OpName))
929 I->error("Operand $" + OpName +
930 " does not appear in the instruction pattern");
931 TreePatternNode *InVal = InstInputsCheck[OpName];
932 InstInputsCheck.erase(OpName); // It occurred, remove from map.
933 if (CGI.OperandList[i].Ty != InVal->getType())
934 I->error("Operand $" + OpName +
935 "'s type disagrees between the operand and pattern");
936 OperandTypes.push_back(InVal->getType());
938 // Construct the result for the dest-pattern operand list.
939 TreePatternNode *OpNode = InVal->clone();
941 // No predicate is useful on the result.
942 OpNode->setPredicateFn("");
944 // Promote the xform function to be an explicit node if set.
945 if (Record *Xform = OpNode->getTransformFn()) {
946 OpNode->setTransformFn(0);
947 std::vector<TreePatternNode*> Children;
948 Children.push_back(OpNode);
949 OpNode = new TreePatternNode(Xform, Children);
952 ResultNodeOperands.push_back(OpNode);
955 if (!InstInputsCheck.empty())
956 I->error("Input operand $" + InstInputsCheck.begin()->first +
957 " occurs in pattern but not in operands list!");
959 TreePatternNode *ResultPattern =
960 new TreePatternNode(I->getRecord(), ResultNodeOperands);
962 // Create and insert the instruction.
963 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
964 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
966 // Use a temporary tree pattern to infer all types and make sure that the
967 // constructed result is correct. This depends on the instruction already
968 // being inserted into the Instructions map.
969 TreePattern Temp(I->getRecord(), ResultPattern, *this);
970 Temp.InferAllTypes();
972 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
973 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
978 // If we can, convert the instructions to be patterns that are matched!
979 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
980 E = Instructions.end(); II != E; ++II) {
981 TreePattern *I = II->second.getPattern();
983 if (I->getNumTrees() != 1) {
984 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
987 TreePatternNode *Pattern = I->getTree(0);
988 if (Pattern->getOperator()->getName() != "set")
989 continue; // Not a set (store or something?)
991 if (Pattern->getNumChildren() != 2)
992 continue; // Not a set of a single value (not handled so far)
994 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
997 if (!SrcPattern->canPatternMatch(Reason, *this))
998 I->error("Instruction can never match: " + Reason);
1000 TreePatternNode *DstPattern = II->second.getResultPattern();
1001 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1005 void DAGISelEmitter::ParsePatterns() {
1006 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1008 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1009 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1010 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
1012 // Inline pattern fragments into it.
1013 Pattern->InlinePatternFragments();
1015 // Infer as many types as possible. If we cannot infer all of them, we can
1016 // never do anything with this pattern: report it to the user.
1017 if (!Pattern->InferAllTypes())
1018 Pattern->error("Could not infer all types in pattern!");
1020 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1021 if (LI->getSize() == 0) continue; // no pattern.
1023 // Parse the instruction.
1024 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
1026 // Inline pattern fragments into it.
1027 Result->InlinePatternFragments();
1029 // Infer as many types as possible. If we cannot infer all of them, we can
1030 // never do anything with this pattern: report it to the user.
1031 if (!Result->InferAllTypes())
1032 Result->error("Could not infer all types in pattern result!");
1034 if (Result->getNumTrees() != 1)
1035 Result->error("Cannot handle instructions producing instructions "
1036 "with temporaries yet!");
1039 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1040 Pattern->error("Pattern can never match: " + Reason);
1042 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1043 Result->getOnlyTree()));
1046 DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
1047 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1048 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1049 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1054 // GenerateVariants - Generate variants. For example, commutative patterns can
1055 // match multiple ways. Add them to PatternsToMatch as well.
1056 void DAGISelEmitter::GenerateVariants() {
1060 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1061 /// patterns before small ones. This is used to determine the size of a
1063 static unsigned getPatternSize(TreePatternNode *P) {
1064 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1065 "Not a valid pattern node to size!");
1066 unsigned Size = 1; // The node itself.
1068 // Count children in the count if they are also nodes.
1069 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1070 TreePatternNode *Child = P->getChild(i);
1071 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1072 Size += getPatternSize(Child);
1078 /// getResultPatternCost - Compute the number of instructions for this pattern.
1079 /// This is a temporary hack. We should really include the instruction
1080 /// latencies in this calculation.
1081 static unsigned getResultPatternCost(TreePatternNode *P) {
1082 if (P->isLeaf()) return 0;
1084 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1085 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1086 Cost += getResultPatternCost(P->getChild(i));
1090 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1091 // In particular, we want to match maximal patterns first and lowest cost within
1092 // a particular complexity first.
1093 struct PatternSortingPredicate {
1094 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1095 DAGISelEmitter::PatternToMatch *RHS) {
1096 unsigned LHSSize = getPatternSize(LHS->first);
1097 unsigned RHSSize = getPatternSize(RHS->first);
1098 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1099 if (LHSSize < RHSSize) return false;
1101 // If the patterns have equal complexity, compare generated instruction cost
1102 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1106 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1107 /// if the match fails. At this point, we already know that the opcode for N
1108 /// matches, and the SDNode for the result has the RootName specified name.
1109 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1110 const std::string &RootName,
1111 std::map<std::string,std::string> &VarMap,
1112 unsigned PatternNo, std::ostream &OS) {
1113 assert(!N->isLeaf() && "Cannot match against a leaf!");
1115 // If this node has a name associated with it, capture it in VarMap. If
1116 // we already saw this in the pattern, emit code to verify dagness.
1117 if (!N->getName().empty()) {
1118 std::string &VarMapEntry = VarMap[N->getName()];
1119 if (VarMapEntry.empty()) {
1120 VarMapEntry = RootName;
1122 // If we get here, this is a second reference to a specific name. Since
1123 // we already have checked that the first reference is valid, we don't
1124 // have to recursively match it, just check that it's the same as the
1125 // previously named thing.
1126 OS << " if (" << VarMapEntry << " != " << RootName
1127 << ") goto P" << PatternNo << "Fail;\n";
1132 // Emit code to load the child nodes and match their contents recursively.
1133 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1134 OS << " SDOperand " << RootName << i <<" = " << RootName
1135 << ".getOperand(" << i << ");\n";
1136 TreePatternNode *Child = N->getChild(i);
1138 if (!Child->isLeaf()) {
1139 // If it's not a leaf, recursively match.
1140 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1141 OS << " if (" << RootName << i << ".getOpcode() != "
1142 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1143 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1145 // If this child has a name associated with it, capture it in VarMap. If
1146 // we already saw this in the pattern, emit code to verify dagness.
1147 if (!Child->getName().empty()) {
1148 std::string &VarMapEntry = VarMap[Child->getName()];
1149 if (VarMapEntry.empty()) {
1150 VarMapEntry = RootName + utostr(i);
1152 // If we get here, this is a second reference to a specific name. Since
1153 // we already have checked that the first reference is valid, we don't
1154 // have to recursively match it, just check that it's the same as the
1155 // previously named thing.
1156 OS << " if (" << VarMapEntry << " != " << RootName << i
1157 << ") goto P" << PatternNo << "Fail;\n";
1162 // Handle leaves of various types.
1163 Init *LeafVal = Child->getLeafValue();
1164 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1165 if (LeafRec->isSubClassOf("RegisterClass")) {
1166 // Handle register references. Nothing to do here.
1167 } else if (LeafRec->isSubClassOf("ValueType")) {
1168 // Make sure this is the specified value type.
1169 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1170 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1174 assert(0 && "Unknown leaf type!");
1179 // If there is a node predicate for this, emit the call.
1180 if (!N->getPredicateFn().empty())
1181 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1182 << ".Val)) goto P" << PatternNo << "Fail;\n";
1185 /// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1186 /// matched, we actually have to build a DAG!
1187 unsigned DAGISelEmitter::
1188 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1189 std::map<std::string,std::string> &VariableMap,
1191 // This is something selected from the pattern we matched.
1192 if (!N->getName().empty()) {
1193 std::string &Val = VariableMap[N->getName()];
1194 assert(!Val.empty() &&
1195 "Variable referenced but not defined and not caught earlier!");
1196 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1197 // Already selected this operand, just return the tmpval.
1198 return atoi(Val.c_str()+3);
1201 unsigned ResNo = Ctr++;
1202 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1203 switch (N->getType()) {
1204 default: assert(0 && "Unknown type for constant node!");
1205 case MVT::i1: OS << " bool Tmp"; break;
1206 case MVT::i8: OS << " unsigned char Tmp"; break;
1207 case MVT::i16: OS << " unsigned short Tmp"; break;
1208 case MVT::i32: OS << " unsigned Tmp"; break;
1209 case MVT::i64: OS << " uint64_t Tmp"; break;
1211 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1212 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1213 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1215 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1217 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1218 // value if used multiple times by this pattern result.
1219 Val = "Tmp"+utostr(ResNo);
1225 assert(0 && "Unknown leaf type!");
1229 Record *Op = N->getOperator();
1230 if (Op->isSubClassOf("Instruction")) {
1231 // Emit all of the operands.
1232 std::vector<unsigned> Ops;
1233 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1234 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1236 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1237 unsigned ResNo = Ctr++;
1239 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1240 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1241 << getEnumName(N->getType());
1242 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1243 OS << ", Tmp" << Ops[i];
1246 } else if (Op->isSubClassOf("SDNodeXForm")) {
1247 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1248 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1250 unsigned ResNo = Ctr++;
1251 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1252 << "(Tmp" << OpVal << ".Val);\n";
1256 assert(0 && "Unknown node in result pattern!");
1262 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1263 /// stream to match the pattern, and generate the code for the match if it
1265 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1267 static unsigned PatternCount = 0;
1268 unsigned PatternNo = PatternCount++;
1269 OS << " { // Pattern #" << PatternNo << ": ";
1270 Pattern.first->print(OS);
1271 OS << "\n // Emits: ";
1272 Pattern.second->print(OS);
1274 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1275 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
1277 // Emit the matcher, capturing named arguments in VariableMap.
1278 std::map<std::string,std::string> VariableMap;
1279 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1282 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
1284 // Add the result to the map if it has multiple uses.
1285 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
1286 OS << " return Tmp" << Res << ";\n";
1287 OS << " }\n P" << PatternNo << "Fail:\n";
1292 /// CompareByRecordName - An ordering predicate that implements less-than by
1293 /// comparing the names records.
1294 struct CompareByRecordName {
1295 bool operator()(const Record *LHS, const Record *RHS) const {
1296 // Sort by name first.
1297 if (LHS->getName() < RHS->getName()) return true;
1298 // If both names are equal, sort by pointer.
1299 return LHS->getName() == RHS->getName() && LHS < RHS;
1304 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1305 // Emit boilerplate.
1306 OS << "// The main instruction selector code.\n"
1307 << "SDOperand SelectCode(SDOperand N) {\n"
1308 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1309 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1310 << " return N; // Already selected.\n\n"
1311 << " if (!N.Val->hasOneUse()) {\n"
1312 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1313 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1315 << " switch (N.getOpcode()) {\n"
1316 << " default: break;\n"
1317 << " case ISD::EntryToken: // These leaves remain the same.\n"
1319 << " case ISD::AssertSext:\n"
1320 << " case ISD::AssertZext: {\n"
1321 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1322 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1323 << " return Tmp0;\n"
1326 // Group the patterns by their top-level opcodes.
1327 std::map<Record*, std::vector<PatternToMatch*>,
1328 CompareByRecordName> PatternsByOpcode;
1329 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1330 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1331 .push_back(&PatternsToMatch[i]);
1333 // Loop over all of the case statements.
1334 for (std::map<Record*, std::vector<PatternToMatch*>,
1335 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1336 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1337 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1338 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1340 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
1342 // We want to emit all of the matching code now. However, we want to emit
1343 // the matches in order of minimal cost. Sort the patterns so the least
1344 // cost one is at the start.
1345 std::stable_sort(Patterns.begin(), Patterns.end(),
1346 PatternSortingPredicate());
1348 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1349 EmitCodeForPattern(*Patterns[i], OS);
1350 OS << " break;\n\n";
1354 OS << " } // end of big switch.\n\n"
1355 << " std::cerr << \"Cannot yet select: \";\n"
1356 << " N.Val->dump();\n"
1357 << " std::cerr << '\\n';\n"
1362 void DAGISelEmitter::run(std::ostream &OS) {
1363 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1366 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1367 << "// *** instruction selector class. These functions are really "
1370 OS << "// Instance var to keep track of multiply used nodes that have \n"
1371 << "// already been selected.\n"
1372 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1375 ParseNodeTransforms(OS);
1376 ParsePatternFragments(OS);
1377 ParseInstructions();
1380 // Generate variants. For example, commutative patterns can match
1381 // multiple ways. Add them to PatternsToMatch as well.
1384 // At this point, we have full information about the 'Patterns' we need to
1385 // parse, both implicitly from instructions as well as from explicit pattern
1386 // definitions. Emit the resultant instruction selector.
1387 EmitInstructionSelector(OS);
1389 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1390 E = PatternFragments.end(); I != E; ++I)
1392 PatternFragments.clear();
1394 Instructions.clear();