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 // Helpers for working with extended types.
25 /// FilterVTs - Filter a list of VT's according to a predicate.
28 static std::vector<MVT::ValueType>
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
33 Result.push_back(InVTs[i]);
37 /// isExtIntegerVT - Return true if the specified extended value type is
38 /// integer, or isInt.
39 static bool isExtIntegerVT(unsigned char VT) {
40 return VT == MVT::isInt ||
41 (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
44 /// isExtFloatingPointVT - Return true if the specified extended value type is
45 /// floating point, or isFP.
46 static bool isExtFloatingPointVT(unsigned char VT) {
47 return VT == MVT::isFP ||
48 (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
51 //===----------------------------------------------------------------------===//
52 // SDTypeConstraint implementation
55 SDTypeConstraint::SDTypeConstraint(Record *R) {
56 OperandNo = R->getValueAsInt("OperandNum");
58 if (R->isSubClassOf("SDTCisVT")) {
59 ConstraintType = SDTCisVT;
60 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61 } else if (R->isSubClassOf("SDTCisInt")) {
62 ConstraintType = SDTCisInt;
63 } else if (R->isSubClassOf("SDTCisFP")) {
64 ConstraintType = SDTCisFP;
65 } else if (R->isSubClassOf("SDTCisSameAs")) {
66 ConstraintType = SDTCisSameAs;
67 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
68 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
69 ConstraintType = SDTCisVTSmallerThanOp;
70 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
71 R->getValueAsInt("OtherOperandNum");
72 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
73 ConstraintType = SDTCisOpSmallerThanOp;
74 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
75 R->getValueAsInt("BigOperandNum");
77 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
82 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
83 /// N, which has NumResults results.
84 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
86 unsigned NumResults) const {
87 assert(NumResults == 1 && "We only work with single result nodes so far!");
89 if (OpNo < NumResults)
90 return N; // FIXME: need value #
92 return N->getChild(OpNo-NumResults);
95 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
96 /// constraint to the nodes operands. This returns true if it makes a
97 /// change, false otherwise. If a type contradiction is found, throw an
99 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
100 const SDNodeInfo &NodeInfo,
101 TreePattern &TP) const {
102 unsigned NumResults = NodeInfo.getNumResults();
103 assert(NumResults == 1 && "We only work with single result nodes so far!");
105 // Check that the number of operands is sane.
106 if (NodeInfo.getNumOperands() >= 0) {
107 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
108 TP.error(N->getOperator()->getName() + " node requires exactly " +
109 itostr(NodeInfo.getNumOperands()) + " operands!");
112 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
114 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
116 switch (ConstraintType) {
117 default: assert(0 && "Unknown constraint type!");
119 // Operand must be a particular type.
120 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
122 // If there is only one integer type supported, this must be it.
123 std::vector<MVT::ValueType> IntVTs =
124 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
126 // If we found exactly one supported integer type, apply it.
127 if (IntVTs.size() == 1)
128 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
129 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
132 // If there is only one FP type supported, this must be it.
133 std::vector<MVT::ValueType> FPVTs =
134 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
136 // If we found exactly one supported FP type, apply it.
137 if (FPVTs.size() == 1)
138 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
139 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
142 TreePatternNode *OtherNode =
143 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
144 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
145 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
147 case SDTCisVTSmallerThanOp: {
148 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
149 // have an integer type that is smaller than the VT.
150 if (!NodeToApply->isLeaf() ||
151 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
152 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
153 ->isSubClassOf("ValueType"))
154 TP.error(N->getOperator()->getName() + " expects a VT operand!");
156 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
157 if (!MVT::isInteger(VT))
158 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
160 TreePatternNode *OtherNode =
161 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
163 // It must be integer.
164 bool MadeChange = false;
165 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
167 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
168 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
171 case SDTCisOpSmallerThanOp: {
172 TreePatternNode *BigOperand =
173 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
175 // Both operands must be integer or FP, but we don't care which.
176 bool MadeChange = false;
178 if (isExtIntegerVT(NodeToApply->getExtType()))
179 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
180 else if (isExtFloatingPointVT(NodeToApply->getExtType()))
181 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
182 if (isExtIntegerVT(BigOperand->getExtType()))
183 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
184 else if (isExtFloatingPointVT(BigOperand->getExtType()))
185 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
187 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
189 if (isExtIntegerVT(NodeToApply->getExtType())) {
190 VTs = FilterVTs(VTs, MVT::isInteger);
191 } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
192 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
197 switch (VTs.size()) {
198 default: // Too many VT's to pick from.
199 case 0: break; // No info yet.
201 // Only one VT of this flavor. Cannot ever satisify the constraints.
202 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
204 // If we have exactly two possible types, the little operand must be the
205 // small one, the big operand should be the big one. Common with
206 // float/double for example.
207 assert(VTs[0] < VTs[1] && "Should be sorted!");
208 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
209 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
219 //===----------------------------------------------------------------------===//
220 // SDNodeInfo implementation
222 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
223 EnumName = R->getValueAsString("Opcode");
224 SDClassName = R->getValueAsString("SDClass");
225 Record *TypeProfile = R->getValueAsDef("TypeProfile");
226 NumResults = TypeProfile->getValueAsInt("NumResults");
227 NumOperands = TypeProfile->getValueAsInt("NumOperands");
229 // Parse the properties.
231 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
232 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
233 if (PropList[i]->getName() == "SDNPCommutative") {
234 Properties |= 1 << SDNPCommutative;
235 } else if (PropList[i]->getName() == "SDNPAssociative") {
236 Properties |= 1 << SDNPAssociative;
238 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
239 << "' on node '" << R->getName() << "'!\n";
245 // Parse the type constraints.
246 std::vector<Record*> ConstraintList =
247 TypeProfile->getValueAsListOfDefs("Constraints");
248 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
251 //===----------------------------------------------------------------------===//
252 // TreePatternNode implementation
255 TreePatternNode::~TreePatternNode() {
256 #if 0 // FIXME: implement refcounted tree nodes!
257 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
262 /// UpdateNodeType - Set the node type of N to VT if VT contains
263 /// information. If N already contains a conflicting type, then throw an
264 /// exception. This returns true if any information was updated.
266 bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
267 if (VT == MVT::isUnknown || getExtType() == VT) return false;
268 if (getExtType() == MVT::isUnknown) {
273 // If we are told this is to be an int or FP type, and it already is, ignore
275 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
276 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
279 // If we know this is an int or fp type, and we are told it is a specific one,
281 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
282 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
289 TP.error("Type inference contradiction found in node!");
291 TP.error("Type inference contradiction found in node " +
292 getOperator()->getName() + "!");
294 return true; // unreachable
298 void TreePatternNode::print(std::ostream &OS) const {
300 OS << *getLeafValue();
302 OS << "(" << getOperator()->getName();
305 switch (getExtType()) {
306 case MVT::Other: OS << ":Other"; break;
307 case MVT::isInt: OS << ":isInt"; break;
308 case MVT::isFP : OS << ":isFP"; break;
309 case MVT::isUnknown: ; /*OS << ":?";*/ break;
310 default: OS << ":" << getType(); break;
314 if (getNumChildren() != 0) {
316 getChild(0)->print(OS);
317 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
319 getChild(i)->print(OS);
325 if (!PredicateFn.empty())
326 OS << "<<P:" << PredicateFn << ">>";
328 OS << "<<X:" << TransformFn->getName() << ">>";
329 if (!getName().empty())
330 OS << ":$" << getName();
333 void TreePatternNode::dump() const {
337 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
338 /// the specified node. For this comparison, all of the state of the node
339 /// is considered, except for the assigned name. Nodes with differing names
340 /// that are otherwise identical are considered isomorphic.
341 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
342 if (N == this) return true;
343 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
344 getPredicateFn() != N->getPredicateFn() ||
345 getTransformFn() != N->getTransformFn())
349 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
350 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
351 return DI->getDef() == NDI->getDef();
352 return getLeafValue() == N->getLeafValue();
355 if (N->getOperator() != getOperator() ||
356 N->getNumChildren() != getNumChildren()) return false;
357 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
358 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
363 /// clone - Make a copy of this tree and all of its children.
365 TreePatternNode *TreePatternNode::clone() const {
366 TreePatternNode *New;
368 New = new TreePatternNode(getLeafValue());
370 std::vector<TreePatternNode*> CChildren;
371 CChildren.reserve(Children.size());
372 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
373 CChildren.push_back(getChild(i)->clone());
374 New = new TreePatternNode(getOperator(), CChildren);
376 New->setName(getName());
377 New->setType(getExtType());
378 New->setPredicateFn(getPredicateFn());
379 New->setTransformFn(getTransformFn());
383 /// SubstituteFormalArguments - Replace the formal arguments in this tree
384 /// with actual values specified by ArgMap.
385 void TreePatternNode::
386 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
387 if (isLeaf()) return;
389 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
390 TreePatternNode *Child = getChild(i);
391 if (Child->isLeaf()) {
392 Init *Val = Child->getLeafValue();
393 if (dynamic_cast<DefInit*>(Val) &&
394 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
395 // We found a use of a formal argument, replace it with its value.
396 Child = ArgMap[Child->getName()];
397 assert(Child && "Couldn't find formal argument!");
401 getChild(i)->SubstituteFormalArguments(ArgMap);
407 /// InlinePatternFragments - If this pattern refers to any pattern
408 /// fragments, inline them into place, giving us a pattern without any
409 /// PatFrag references.
410 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
411 if (isLeaf()) return this; // nothing to do.
412 Record *Op = getOperator();
414 if (!Op->isSubClassOf("PatFrag")) {
415 // Just recursively inline children nodes.
416 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
417 setChild(i, getChild(i)->InlinePatternFragments(TP));
421 // Otherwise, we found a reference to a fragment. First, look up its
422 // TreePattern record.
423 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
425 // Verify that we are passing the right number of operands.
426 if (Frag->getNumArgs() != Children.size())
427 TP.error("'" + Op->getName() + "' fragment requires " +
428 utostr(Frag->getNumArgs()) + " operands!");
430 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
432 // Resolve formal arguments to their actual value.
433 if (Frag->getNumArgs()) {
434 // Compute the map of formal to actual arguments.
435 std::map<std::string, TreePatternNode*> ArgMap;
436 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
437 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
439 FragTree->SubstituteFormalArguments(ArgMap);
442 FragTree->setName(getName());
444 // Get a new copy of this fragment to stitch into here.
445 //delete this; // FIXME: implement refcounting!
449 /// getIntrinsicType - Check to see if the specified record has an intrinsic
450 /// type which should be applied to it. This infer the type of register
451 /// references from the register file information, for example.
453 static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
455 // Check to see if this is a register or a register class...
456 if (R->isSubClassOf("RegisterClass")) {
457 if (NotRegisters) return MVT::isUnknown;
458 return getValueType(R->getValueAsDef("RegType"));
459 } else if (R->isSubClassOf("PatFrag")) {
460 // Pattern fragment types will be resolved when they are inlined.
461 return MVT::isUnknown;
462 } else if (R->isSubClassOf("Register")) {
463 //const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
464 // TODO: if a register appears in exactly one regclass, we could use that
466 return MVT::isUnknown;
467 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
468 // Using a VTSDNode or CondCodeSDNode.
470 } else if (R->getName() == "node") {
472 return MVT::isUnknown;
475 TP.error("Unknown node flavor used in pattern: " + R->getName());
479 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
480 /// this node and its children in the tree. This returns true if it makes a
481 /// change, false otherwise. If a type contradiction is found, throw an
483 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
485 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
486 // If it's a regclass or something else known, include the type.
487 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
489 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
490 // Int inits are always integers. :)
491 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
494 unsigned Size = MVT::getSizeInBits(getType());
495 // Make sure that the value is representable for this type.
497 int Val = (II->getValue() << (32-Size)) >> (32-Size);
498 if (Val != II->getValue())
499 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
500 "' is out of range for type 'MVT::" +
501 getEnumName(getType()) + "'!");
510 // special handling for set, which isn't really an SDNode.
511 if (getOperator()->getName() == "set") {
512 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
513 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
514 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
516 // Types of operands must match.
517 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
518 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
519 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
521 } else if (getOperator()->isSubClassOf("SDNode")) {
522 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
524 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
525 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
526 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
528 } else if (getOperator()->isSubClassOf("Instruction")) {
529 const DAGInstruction &Inst =
530 TP.getDAGISelEmitter().getInstruction(getOperator());
532 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
533 // Apply the result type to the node
534 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
536 if (getNumChildren() != Inst.getNumOperands())
537 TP.error("Instruction '" + getOperator()->getName() + " expects " +
538 utostr(Inst.getNumOperands()) + " operands, not " +
539 utostr(getNumChildren()) + " operands!");
540 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
541 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
542 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
546 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
548 // Node transforms always take one operand, and take and return the same
550 if (getNumChildren() != 1)
551 TP.error("Node transform '" + getOperator()->getName() +
552 "' requires one operand!");
553 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
554 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
559 /// canPatternMatch - If it is impossible for this pattern to match on this
560 /// target, fill in Reason and return false. Otherwise, return true. This is
561 /// used as a santity check for .td files (to prevent people from writing stuff
562 /// that can never possibly work), and to prevent the pattern permuter from
563 /// generating stuff that is useless.
564 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
565 if (isLeaf()) return true;
567 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
568 if (!getChild(i)->canPatternMatch(Reason, ISE))
571 // If this node is a commutative operator, check that the LHS isn't an
573 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
574 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
575 // Scan all of the operands of the node and make sure that only the last one
576 // is a constant node.
577 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
578 if (!getChild(i)->isLeaf() &&
579 getChild(i)->getOperator()->getName() == "imm") {
580 Reason = "Immediate value must be on the RHS of commutative operators!";
588 //===----------------------------------------------------------------------===//
589 // TreePattern implementation
592 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
593 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
594 isInputPattern = isInput;
595 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
596 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
599 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
600 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
601 isInputPattern = isInput;
602 Trees.push_back(ParseTreePattern(Pat));
605 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
606 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
607 isInputPattern = isInput;
608 Trees.push_back(Pat);
613 void TreePattern::error(const std::string &Msg) const {
615 throw "In " + TheRecord->getName() + ": " + Msg;
618 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
619 Record *Operator = Dag->getNodeType();
621 if (Operator->isSubClassOf("ValueType")) {
622 // If the operator is a ValueType, then this must be "type cast" of a leaf
624 if (Dag->getNumArgs() != 1)
625 error("Type cast only takes one operand!");
627 Init *Arg = Dag->getArg(0);
628 TreePatternNode *New;
629 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
630 Record *R = DI->getDef();
631 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
632 Dag->setArg(0, new DagInit(R,
633 std::vector<std::pair<Init*, std::string> >()));
634 return ParseTreePattern(Dag);
637 New = new TreePatternNode(DI);
638 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
639 New = ParseTreePattern(DI);
640 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
641 New = new TreePatternNode(II);
642 if (!Dag->getArgName(0).empty())
643 error("Constant int argument should not have a name!");
646 error("Unknown leaf value for tree pattern!");
650 // Apply the type cast.
651 New->UpdateNodeType(getValueType(Operator), *this);
652 New->setName(Dag->getArgName(0));
656 // Verify that this is something that makes sense for an operator.
657 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
658 !Operator->isSubClassOf("Instruction") &&
659 !Operator->isSubClassOf("SDNodeXForm") &&
660 Operator->getName() != "set")
661 error("Unrecognized node '" + Operator->getName() + "'!");
663 // Check to see if this is something that is illegal in an input pattern.
664 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
665 Operator->isSubClassOf("SDNodeXForm")))
666 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
668 std::vector<TreePatternNode*> Children;
670 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
671 Init *Arg = Dag->getArg(i);
672 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
673 Children.push_back(ParseTreePattern(DI));
674 if (Children.back()->getName().empty())
675 Children.back()->setName(Dag->getArgName(i));
676 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
677 Record *R = DefI->getDef();
678 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
679 // TreePatternNode if its own.
680 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
681 Dag->setArg(i, new DagInit(R,
682 std::vector<std::pair<Init*, std::string> >()));
683 --i; // Revisit this node...
685 TreePatternNode *Node = new TreePatternNode(DefI);
686 Node->setName(Dag->getArgName(i));
687 Children.push_back(Node);
690 if (R->getName() == "node") {
691 if (Dag->getArgName(i).empty())
692 error("'node' argument requires a name to match with operand list");
693 Args.push_back(Dag->getArgName(i));
696 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
697 TreePatternNode *Node = new TreePatternNode(II);
698 if (!Dag->getArgName(i).empty())
699 error("Constant int argument should not have a name!");
700 Children.push_back(Node);
705 error("Unknown leaf value for tree pattern!");
709 return new TreePatternNode(Operator, Children);
712 /// InferAllTypes - Infer/propagate as many types throughout the expression
713 /// patterns as possible. Return true if all types are infered, false
714 /// otherwise. Throw an exception if a type contradiction is found.
715 bool TreePattern::InferAllTypes() {
716 bool MadeChange = true;
719 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
720 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
723 bool HasUnresolvedTypes = false;
724 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
725 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
726 return !HasUnresolvedTypes;
729 void TreePattern::print(std::ostream &OS) const {
730 OS << getRecord()->getName();
732 OS << "(" << Args[0];
733 for (unsigned i = 1, e = Args.size(); i != e; ++i)
734 OS << ", " << Args[i];
739 if (Trees.size() > 1)
741 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
747 if (Trees.size() > 1)
751 void TreePattern::dump() const { print(std::cerr); }
755 //===----------------------------------------------------------------------===//
756 // DAGISelEmitter implementation
759 // Parse all of the SDNode definitions for the target, populating SDNodes.
760 void DAGISelEmitter::ParseNodeInfo() {
761 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
762 while (!Nodes.empty()) {
763 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
768 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
769 /// map, and emit them to the file as functions.
770 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
771 OS << "\n// Node transformations.\n";
772 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
773 while (!Xforms.empty()) {
774 Record *XFormNode = Xforms.back();
775 Record *SDNode = XFormNode->getValueAsDef("Opcode");
776 std::string Code = XFormNode->getValueAsCode("XFormFunction");
777 SDNodeXForms.insert(std::make_pair(XFormNode,
778 std::make_pair(SDNode, Code)));
781 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
782 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
784 OS << "inline SDOperand Transform_" << XFormNode->getName()
785 << "(SDNode *" << C2 << ") {\n";
786 if (ClassName != "SDNode")
787 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
788 OS << Code << "\n}\n";
797 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
798 /// file, building up the PatternFragments map. After we've collected them all,
799 /// inline fragments together as necessary, so that there are no references left
800 /// inside a pattern fragment to a pattern fragment.
802 /// This also emits all of the predicate functions to the output file.
804 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
805 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
807 // First step, parse all of the fragments and emit predicate functions.
808 OS << "\n// Predicate functions.\n";
809 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
810 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
811 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
812 PatternFragments[Fragments[i]] = P;
814 // Validate the argument list, converting it to map, to discard duplicates.
815 std::vector<std::string> &Args = P->getArgList();
816 std::set<std::string> OperandsMap(Args.begin(), Args.end());
818 if (OperandsMap.count(""))
819 P->error("Cannot have unnamed 'node' values in pattern fragment!");
821 // Parse the operands list.
822 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
823 if (OpsList->getNodeType()->getName() != "ops")
824 P->error("Operands list should start with '(ops ... '!");
826 // Copy over the arguments.
828 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
829 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
830 static_cast<DefInit*>(OpsList->getArg(j))->
831 getDef()->getName() != "node")
832 P->error("Operands list should all be 'node' values.");
833 if (OpsList->getArgName(j).empty())
834 P->error("Operands list should have names for each operand!");
835 if (!OperandsMap.count(OpsList->getArgName(j)))
836 P->error("'" + OpsList->getArgName(j) +
837 "' does not occur in pattern or was multiply specified!");
838 OperandsMap.erase(OpsList->getArgName(j));
839 Args.push_back(OpsList->getArgName(j));
842 if (!OperandsMap.empty())
843 P->error("Operands list does not contain an entry for operand '" +
844 *OperandsMap.begin() + "'!");
846 // If there is a code init for this fragment, emit the predicate code and
847 // keep track of the fact that this fragment uses it.
848 std::string Code = Fragments[i]->getValueAsCode("Predicate");
850 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
851 std::string ClassName =
852 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
853 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
855 OS << "inline bool Predicate_" << Fragments[i]->getName()
856 << "(SDNode *" << C2 << ") {\n";
857 if (ClassName != "SDNode")
858 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
859 OS << Code << "\n}\n";
860 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
863 // If there is a node transformation corresponding to this, keep track of
865 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
866 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
867 P->getOnlyTree()->setTransformFn(Transform);
872 // Now that we've parsed all of the tree fragments, do a closure on them so
873 // that there are not references to PatFrags left inside of them.
874 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
875 E = PatternFragments.end(); I != E; ++I) {
876 TreePattern *ThePat = I->second;
877 ThePat->InlinePatternFragments();
879 // Infer as many types as possible. Don't worry about it if we don't infer
880 // all of them, some may depend on the inputs of the pattern.
882 ThePat->InferAllTypes();
884 // If this pattern fragment is not supported by this target (no types can
885 // satisfy its constraints), just ignore it. If the bogus pattern is
886 // actually used by instructions, the type consistency error will be
890 // If debugging, print out the pattern fragment result.
891 DEBUG(ThePat->dump());
895 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
896 /// instruction input. Return true if this is a real use.
897 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
898 std::map<std::string, TreePatternNode*> &InstInputs) {
899 // No name -> not interesting.
900 if (Pat->getName().empty()) {
902 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
903 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
904 I->error("Input " + DI->getDef()->getName() + " must be named!");
912 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
913 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
916 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
917 Rec = Pat->getOperator();
920 TreePatternNode *&Slot = InstInputs[Pat->getName()];
925 if (Slot->isLeaf()) {
926 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
928 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
929 SlotRec = Slot->getOperator();
932 // Ensure that the inputs agree if we've already seen this input.
934 I->error("All $" + Pat->getName() + " inputs must agree with each other");
935 if (Slot->getExtType() != Pat->getExtType())
936 I->error("All $" + Pat->getName() + " inputs must agree with each other");
941 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
942 /// part of "I", the instruction), computing the set of inputs and outputs of
943 /// the pattern. Report errors if we see anything naughty.
944 void DAGISelEmitter::
945 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
946 std::map<std::string, TreePatternNode*> &InstInputs,
947 std::map<std::string, Record*> &InstResults) {
949 bool isUse = HandleUse(I, Pat, InstInputs);
950 if (!isUse && Pat->getTransformFn())
951 I->error("Cannot specify a transform function for a non-input value!");
953 } else if (Pat->getOperator()->getName() != "set") {
954 // If this is not a set, verify that the children nodes are not void typed,
956 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
957 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
958 I->error("Cannot have void nodes inside of patterns!");
959 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
962 // If this is a non-leaf node with no children, treat it basically as if
963 // it were a leaf. This handles nodes like (imm).
965 if (Pat->getNumChildren() == 0)
966 isUse = HandleUse(I, Pat, InstInputs);
968 if (!isUse && Pat->getTransformFn())
969 I->error("Cannot specify a transform function for a non-input value!");
973 // Otherwise, this is a set, validate and collect instruction results.
974 if (Pat->getNumChildren() == 0)
975 I->error("set requires operands!");
976 else if (Pat->getNumChildren() & 1)
977 I->error("set requires an even number of operands");
979 if (Pat->getTransformFn())
980 I->error("Cannot specify a transform function on a set node!");
982 // Check the set destinations.
983 unsigned NumValues = Pat->getNumChildren()/2;
984 for (unsigned i = 0; i != NumValues; ++i) {
985 TreePatternNode *Dest = Pat->getChild(i);
987 I->error("set destination should be a virtual register!");
989 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
991 I->error("set destination should be a virtual register!");
993 if (!Val->getDef()->isSubClassOf("RegisterClass"))
994 I->error("set destination should be a virtual register!");
995 if (Dest->getName().empty())
996 I->error("set destination must have a name!");
997 if (InstResults.count(Dest->getName()))
998 I->error("cannot set '" + Dest->getName() +"' multiple times");
999 InstResults[Dest->getName()] = Val->getDef();
1001 // Verify and collect info from the computation.
1002 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1003 InstInputs, InstResults);
1008 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1009 /// any fragments involved. This populates the Instructions list with fully
1010 /// resolved instructions.
1011 void DAGISelEmitter::ParseInstructions() {
1012 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1014 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1017 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1018 LI = Instrs[i]->getValueAsListInit("Pattern");
1020 // If there is no pattern, only collect minimal information about the
1021 // instruction for its operand list. We have to assume that there is one
1022 // result, as we have no detailed info.
1023 if (!LI || LI->getSize() == 0) {
1024 std::vector<MVT::ValueType> ResultTypes;
1025 std::vector<MVT::ValueType> OperandTypes;
1027 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1029 // Doesn't even define a result?
1030 if (InstInfo.OperandList.size() == 0)
1033 // Assume the first operand is the result.
1034 ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1036 // The rest are inputs.
1037 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1038 OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1040 // Create and insert the instruction.
1041 Instructions.insert(std::make_pair(Instrs[i],
1042 DAGInstruction(0, ResultTypes, OperandTypes)));
1043 continue; // no pattern.
1046 // Parse the instruction.
1047 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1048 // Inline pattern fragments into it.
1049 I->InlinePatternFragments();
1051 // Infer as many types as possible. If we cannot infer all of them, we can
1052 // never do anything with this instruction pattern: report it to the user.
1053 if (!I->InferAllTypes())
1054 I->error("Could not infer all types in pattern!");
1056 // InstInputs - Keep track of all of the inputs of the instruction, along
1057 // with the record they are declared as.
1058 std::map<std::string, TreePatternNode*> InstInputs;
1060 // InstResults - Keep track of all the virtual registers that are 'set'
1061 // in the instruction, including what reg class they are.
1062 std::map<std::string, Record*> InstResults;
1064 // Verify that the top-level forms in the instruction are of void type, and
1065 // fill in the InstResults map.
1066 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1067 TreePatternNode *Pat = I->getTree(j);
1068 if (Pat->getExtType() != MVT::isVoid) {
1070 I->error("Top-level forms in instruction pattern should have"
1074 // Find inputs and outputs, and verify the structure of the uses/defs.
1075 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
1078 // Now that we have inputs and outputs of the pattern, inspect the operands
1079 // list for the instruction. This determines the order that operands are
1080 // added to the machine instruction the node corresponds to.
1081 unsigned NumResults = InstResults.size();
1083 // Parse the operands list from the (ops) list, validating it.
1084 std::vector<std::string> &Args = I->getArgList();
1085 assert(Args.empty() && "Args list should still be empty here!");
1086 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1088 // Check that all of the results occur first in the list.
1089 std::vector<MVT::ValueType> ResultTypes;
1090 for (unsigned i = 0; i != NumResults; ++i) {
1091 if (i == CGI.OperandList.size())
1092 I->error("'" + InstResults.begin()->first +
1093 "' set but does not appear in operand list!");
1094 const std::string &OpName = CGI.OperandList[i].Name;
1096 // Check that it exists in InstResults.
1097 Record *R = InstResults[OpName];
1099 I->error("Operand $" + OpName + " should be a set destination: all "
1100 "outputs must occur before inputs in operand list!");
1102 if (CGI.OperandList[i].Rec != R)
1103 I->error("Operand $" + OpName + " class mismatch!");
1105 // Remember the return type.
1106 ResultTypes.push_back(CGI.OperandList[i].Ty);
1108 // Okay, this one checks out.
1109 InstResults.erase(OpName);
1112 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1113 // the copy while we're checking the inputs.
1114 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1116 std::vector<TreePatternNode*> ResultNodeOperands;
1117 std::vector<MVT::ValueType> OperandTypes;
1118 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1119 const std::string &OpName = CGI.OperandList[i].Name;
1121 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1123 if (!InstInputsCheck.count(OpName))
1124 I->error("Operand $" + OpName +
1125 " does not appear in the instruction pattern");
1126 TreePatternNode *InVal = InstInputsCheck[OpName];
1127 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1128 if (CGI.OperandList[i].Ty != InVal->getExtType())
1129 I->error("Operand $" + OpName +
1130 "'s type disagrees between the operand and pattern");
1131 OperandTypes.push_back(InVal->getType());
1133 // Construct the result for the dest-pattern operand list.
1134 TreePatternNode *OpNode = InVal->clone();
1136 // No predicate is useful on the result.
1137 OpNode->setPredicateFn("");
1139 // Promote the xform function to be an explicit node if set.
1140 if (Record *Xform = OpNode->getTransformFn()) {
1141 OpNode->setTransformFn(0);
1142 std::vector<TreePatternNode*> Children;
1143 Children.push_back(OpNode);
1144 OpNode = new TreePatternNode(Xform, Children);
1147 ResultNodeOperands.push_back(OpNode);
1150 if (!InstInputsCheck.empty())
1151 I->error("Input operand $" + InstInputsCheck.begin()->first +
1152 " occurs in pattern but not in operands list!");
1154 TreePatternNode *ResultPattern =
1155 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1157 // Create and insert the instruction.
1158 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1159 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1161 // Use a temporary tree pattern to infer all types and make sure that the
1162 // constructed result is correct. This depends on the instruction already
1163 // being inserted into the Instructions map.
1164 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1165 Temp.InferAllTypes();
1167 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1168 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1173 // If we can, convert the instructions to be patterns that are matched!
1174 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1175 E = Instructions.end(); II != E; ++II) {
1176 TreePattern *I = II->second.getPattern();
1177 if (I == 0) continue; // No pattern.
1179 if (I->getNumTrees() != 1) {
1180 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1183 TreePatternNode *Pattern = I->getTree(0);
1184 if (Pattern->getOperator()->getName() != "set")
1185 continue; // Not a set (store or something?)
1187 if (Pattern->getNumChildren() != 2)
1188 continue; // Not a set of a single value (not handled so far)
1190 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
1193 if (!SrcPattern->canPatternMatch(Reason, *this))
1194 I->error("Instruction can never match: " + Reason);
1196 TreePatternNode *DstPattern = II->second.getResultPattern();
1197 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1201 void DAGISelEmitter::ParsePatterns() {
1202 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1204 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1205 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1206 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1208 // Inline pattern fragments into it.
1209 Pattern->InlinePatternFragments();
1211 // Infer as many types as possible. If we cannot infer all of them, we can
1212 // never do anything with this pattern: report it to the user.
1213 if (!Pattern->InferAllTypes())
1214 Pattern->error("Could not infer all types in pattern!");
1216 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1217 if (LI->getSize() == 0) continue; // no pattern.
1219 // Parse the instruction.
1220 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1222 // Inline pattern fragments into it.
1223 Result->InlinePatternFragments();
1225 // Infer as many types as possible. If we cannot infer all of them, we can
1226 // never do anything with this pattern: report it to the user.
1227 if (!Result->InferAllTypes())
1228 Result->error("Could not infer all types in pattern result!");
1230 if (Result->getNumTrees() != 1)
1231 Result->error("Cannot handle instructions producing instructions "
1232 "with temporaries yet!");
1235 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1236 Pattern->error("Pattern can never match: " + Reason);
1238 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1239 Result->getOnlyTree()));
1243 /// CombineChildVariants - Given a bunch of permutations of each child of the
1244 /// 'operator' node, put them together in all possible ways.
1245 static void CombineChildVariants(TreePatternNode *Orig,
1246 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1247 std::vector<TreePatternNode*> &OutVariants,
1248 DAGISelEmitter &ISE) {
1249 // Make sure that each operand has at least one variant to choose from.
1250 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1251 if (ChildVariants[i].empty())
1254 // The end result is an all-pairs construction of the resultant pattern.
1255 std::vector<unsigned> Idxs;
1256 Idxs.resize(ChildVariants.size());
1257 bool NotDone = true;
1259 // Create the variant and add it to the output list.
1260 std::vector<TreePatternNode*> NewChildren;
1261 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1262 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1263 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1265 // Copy over properties.
1266 R->setName(Orig->getName());
1267 R->setPredicateFn(Orig->getPredicateFn());
1268 R->setTransformFn(Orig->getTransformFn());
1269 R->setType(Orig->getExtType());
1271 // If this pattern cannot every match, do not include it as a variant.
1272 std::string ErrString;
1273 if (!R->canPatternMatch(ErrString, ISE)) {
1276 bool AlreadyExists = false;
1278 // Scan to see if this pattern has already been emitted. We can get
1279 // duplication due to things like commuting:
1280 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1281 // which are the same pattern. Ignore the dups.
1282 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1283 if (R->isIsomorphicTo(OutVariants[i])) {
1284 AlreadyExists = true;
1291 OutVariants.push_back(R);
1294 // Increment indices to the next permutation.
1296 // Look for something we can increment without causing a wrap-around.
1297 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1298 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1299 NotDone = true; // Found something to increment.
1307 /// CombineChildVariants - A helper function for binary operators.
1309 static void CombineChildVariants(TreePatternNode *Orig,
1310 const std::vector<TreePatternNode*> &LHS,
1311 const std::vector<TreePatternNode*> &RHS,
1312 std::vector<TreePatternNode*> &OutVariants,
1313 DAGISelEmitter &ISE) {
1314 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1315 ChildVariants.push_back(LHS);
1316 ChildVariants.push_back(RHS);
1317 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1321 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1322 std::vector<TreePatternNode *> &Children) {
1323 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1324 Record *Operator = N->getOperator();
1326 // Only permit raw nodes.
1327 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1328 N->getTransformFn()) {
1329 Children.push_back(N);
1333 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1334 Children.push_back(N->getChild(0));
1336 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1338 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1339 Children.push_back(N->getChild(1));
1341 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1344 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1345 /// the (potentially recursive) pattern by using algebraic laws.
1347 static void GenerateVariantsOf(TreePatternNode *N,
1348 std::vector<TreePatternNode*> &OutVariants,
1349 DAGISelEmitter &ISE) {
1350 // We cannot permute leaves.
1352 OutVariants.push_back(N);
1356 // Look up interesting info about the node.
1357 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1359 // If this node is associative, reassociate.
1360 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1361 // Reassociate by pulling together all of the linked operators
1362 std::vector<TreePatternNode*> MaximalChildren;
1363 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1365 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1367 if (MaximalChildren.size() == 3) {
1368 // Find the variants of all of our maximal children.
1369 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1370 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1371 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1372 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1374 // There are only two ways we can permute the tree:
1375 // (A op B) op C and A op (B op C)
1376 // Within these forms, we can also permute A/B/C.
1378 // Generate legal pair permutations of A/B/C.
1379 std::vector<TreePatternNode*> ABVariants;
1380 std::vector<TreePatternNode*> BAVariants;
1381 std::vector<TreePatternNode*> ACVariants;
1382 std::vector<TreePatternNode*> CAVariants;
1383 std::vector<TreePatternNode*> BCVariants;
1384 std::vector<TreePatternNode*> CBVariants;
1385 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1386 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1387 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1388 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1389 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1390 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1392 // Combine those into the result: (x op x) op x
1393 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1394 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1395 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1396 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1397 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1398 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1400 // Combine those into the result: x op (x op x)
1401 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1402 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1403 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1404 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1405 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1406 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1411 // Compute permutations of all children.
1412 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1413 ChildVariants.resize(N->getNumChildren());
1414 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1415 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1417 // Build all permutations based on how the children were formed.
1418 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1420 // If this node is commutative, consider the commuted order.
1421 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1422 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1423 // Consider the commuted order.
1424 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1430 // GenerateVariants - Generate variants. For example, commutative patterns can
1431 // match multiple ways. Add them to PatternsToMatch as well.
1432 void DAGISelEmitter::GenerateVariants() {
1434 DEBUG(std::cerr << "Generating instruction variants.\n");
1436 // Loop over all of the patterns we've collected, checking to see if we can
1437 // generate variants of the instruction, through the exploitation of
1438 // identities. This permits the target to provide agressive matching without
1439 // the .td file having to contain tons of variants of instructions.
1441 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1442 // intentionally do not reconsider these. Any variants of added patterns have
1443 // already been added.
1445 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1446 std::vector<TreePatternNode*> Variants;
1447 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1449 assert(!Variants.empty() && "Must create at least original variant!");
1450 Variants.erase(Variants.begin()); // Remove the original pattern.
1452 if (Variants.empty()) // No variants for this pattern.
1455 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1456 PatternsToMatch[i].first->dump();
1459 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1460 TreePatternNode *Variant = Variants[v];
1462 DEBUG(std::cerr << " VAR#" << v << ": ";
1466 // Scan to see if an instruction or explicit pattern already matches this.
1467 bool AlreadyExists = false;
1468 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1469 // Check to see if this variant already exists.
1470 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1471 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1472 AlreadyExists = true;
1476 // If we already have it, ignore the variant.
1477 if (AlreadyExists) continue;
1479 // Otherwise, add it to the list of patterns we have.
1480 PatternsToMatch.push_back(std::make_pair(Variant,
1481 PatternsToMatch[i].second));
1484 DEBUG(std::cerr << "\n");
1489 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1490 /// patterns before small ones. This is used to determine the size of a
1492 static unsigned getPatternSize(TreePatternNode *P) {
1493 assert(isExtIntegerVT(P->getExtType()) ||
1494 isExtFloatingPointVT(P->getExtType()) &&
1495 "Not a valid pattern node to size!");
1496 unsigned Size = 1; // The node itself.
1498 // Count children in the count if they are also nodes.
1499 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1500 TreePatternNode *Child = P->getChild(i);
1501 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1502 Size += getPatternSize(Child);
1503 else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1504 ++Size; // Matches a ConstantSDNode.
1511 /// getResultPatternCost - Compute the number of instructions for this pattern.
1512 /// This is a temporary hack. We should really include the instruction
1513 /// latencies in this calculation.
1514 static unsigned getResultPatternCost(TreePatternNode *P) {
1515 if (P->isLeaf()) return 0;
1517 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1518 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1519 Cost += getResultPatternCost(P->getChild(i));
1523 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1524 // In particular, we want to match maximal patterns first and lowest cost within
1525 // a particular complexity first.
1526 struct PatternSortingPredicate {
1527 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1528 DAGISelEmitter::PatternToMatch *RHS) {
1529 unsigned LHSSize = getPatternSize(LHS->first);
1530 unsigned RHSSize = getPatternSize(RHS->first);
1531 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1532 if (LHSSize < RHSSize) return false;
1534 // If the patterns have equal complexity, compare generated instruction cost
1535 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1539 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1540 /// if the match fails. At this point, we already know that the opcode for N
1541 /// matches, and the SDNode for the result has the RootName specified name.
1542 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1543 const std::string &RootName,
1544 std::map<std::string,std::string> &VarMap,
1545 unsigned PatternNo, std::ostream &OS) {
1547 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1548 OS << " if (cast<ConstantSDNode>(" << RootName
1549 << ")->getSignExtended() != " << II->getValue() << ")\n"
1550 << " goto P" << PatternNo << "Fail;\n";
1553 assert(0 && "Cannot match this as a leaf value!");
1557 // If this node has a name associated with it, capture it in VarMap. If
1558 // we already saw this in the pattern, emit code to verify dagness.
1559 if (!N->getName().empty()) {
1560 std::string &VarMapEntry = VarMap[N->getName()];
1561 if (VarMapEntry.empty()) {
1562 VarMapEntry = RootName;
1564 // If we get here, this is a second reference to a specific name. Since
1565 // we already have checked that the first reference is valid, we don't
1566 // have to recursively match it, just check that it's the same as the
1567 // previously named thing.
1568 OS << " if (" << VarMapEntry << " != " << RootName
1569 << ") goto P" << PatternNo << "Fail;\n";
1574 // Emit code to load the child nodes and match their contents recursively.
1575 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1576 OS << " SDOperand " << RootName << i <<" = " << RootName
1577 << ".getOperand(" << i << ");\n";
1578 TreePatternNode *Child = N->getChild(i);
1580 if (!Child->isLeaf()) {
1581 // If it's not a leaf, recursively match.
1582 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1583 OS << " if (" << RootName << i << ".getOpcode() != "
1584 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1585 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1587 // If this child has a name associated with it, capture it in VarMap. If
1588 // we already saw this in the pattern, emit code to verify dagness.
1589 if (!Child->getName().empty()) {
1590 std::string &VarMapEntry = VarMap[Child->getName()];
1591 if (VarMapEntry.empty()) {
1592 VarMapEntry = RootName + utostr(i);
1594 // If we get here, this is a second reference to a specific name. Since
1595 // we already have checked that the first reference is valid, we don't
1596 // have to recursively match it, just check that it's the same as the
1597 // previously named thing.
1598 OS << " if (" << VarMapEntry << " != " << RootName << i
1599 << ") goto P" << PatternNo << "Fail;\n";
1604 // Handle leaves of various types.
1605 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1606 Record *LeafRec = DI->getDef();
1607 if (LeafRec->isSubClassOf("RegisterClass")) {
1608 // Handle register references. Nothing to do here.
1609 } else if (LeafRec->isSubClassOf("ValueType")) {
1610 // Make sure this is the specified value type.
1611 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1612 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1614 } else if (LeafRec->isSubClassOf("CondCode")) {
1615 // Make sure this is the specified cond code.
1616 OS << " if (cast<CondCodeSDNode>(" << RootName << i
1617 << ")->get() != " << "ISD::" << LeafRec->getName()
1618 << ") goto P" << PatternNo << "Fail;\n";
1621 assert(0 && "Unknown leaf type!");
1623 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1624 OS << " if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1625 << " cast<ConstantSDNode>(" << RootName << i
1626 << ")->getSignExtended() != " << II->getValue() << ")\n"
1627 << " goto P" << PatternNo << "Fail;\n";
1630 assert(0 && "Unknown leaf type!");
1635 // If there is a node predicate for this, emit the call.
1636 if (!N->getPredicateFn().empty())
1637 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1638 << ".Val)) goto P" << PatternNo << "Fail;\n";
1641 /// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1642 /// matched, we actually have to build a DAG!
1643 unsigned DAGISelEmitter::
1644 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1645 std::map<std::string,std::string> &VariableMap,
1646 std::ostream &OS, bool isRoot) {
1647 // This is something selected from the pattern we matched.
1648 if (!N->getName().empty()) {
1649 assert(!isRoot && "Root of pattern cannot be a leaf!");
1650 std::string &Val = VariableMap[N->getName()];
1651 assert(!Val.empty() &&
1652 "Variable referenced but not defined and not caught earlier!");
1653 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1654 // Already selected this operand, just return the tmpval.
1655 return atoi(Val.c_str()+3);
1658 unsigned ResNo = Ctr++;
1659 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1660 switch (N->getType()) {
1661 default: assert(0 && "Unknown type for constant node!");
1662 case MVT::i1: OS << " bool Tmp"; break;
1663 case MVT::i8: OS << " unsigned char Tmp"; break;
1664 case MVT::i16: OS << " unsigned short Tmp"; break;
1665 case MVT::i32: OS << " unsigned Tmp"; break;
1666 case MVT::i64: OS << " uint64_t Tmp"; break;
1668 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1669 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1670 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1671 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1672 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
1674 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1676 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1677 // value if used multiple times by this pattern result.
1678 Val = "Tmp"+utostr(ResNo);
1683 // If this is an explicit register reference, handle it.
1684 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1685 unsigned ResNo = Ctr++;
1686 if (DI->getDef()->isSubClassOf("Register")) {
1687 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1688 << getQualifiedName(DI->getDef()) << ", MVT::"
1689 << getEnumName(N->getType())
1693 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1694 unsigned ResNo = Ctr++;
1695 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1696 << II->getValue() << ", MVT::"
1697 << getEnumName(N->getType())
1703 assert(0 && "Unknown leaf type!");
1707 Record *Op = N->getOperator();
1708 if (Op->isSubClassOf("Instruction")) {
1709 // Emit all of the operands.
1710 std::vector<unsigned> Ops;
1711 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1712 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1714 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1715 unsigned ResNo = Ctr++;
1718 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1719 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1720 << getEnumName(N->getType());
1721 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1722 OS << ", Tmp" << Ops[i];
1725 // If this instruction is the root, and if there is only one use of it,
1726 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1727 OS << " if (N.Val->hasOneUse()) {\n";
1728 OS << " CurDAG->SelectNodeTo(N.Val, "
1729 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1730 << getEnumName(N->getType());
1731 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1732 OS << ", Tmp" << Ops[i];
1734 OS << " return N;\n";
1735 OS << " } else {\n";
1736 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1737 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1738 << getEnumName(N->getType());
1739 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1740 OS << ", Tmp" << Ops[i];
1745 } else if (Op->isSubClassOf("SDNodeXForm")) {
1746 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1747 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1749 unsigned ResNo = Ctr++;
1750 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1751 << "(Tmp" << OpVal << ".Val);\n";
1753 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1754 OS << " return Tmp" << ResNo << ";\n";
1759 assert(0 && "Unknown node in result pattern!");
1764 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1765 /// type information from it.
1766 static void RemoveAllTypes(TreePatternNode *N) {
1767 N->setType(MVT::isUnknown);
1769 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1770 RemoveAllTypes(N->getChild(i));
1773 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1774 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1775 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1776 /// for, this returns true otherwise false if Pat has all types.
1777 static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1778 const std::string &Prefix, unsigned PatternNo,
1781 if (!Pat->hasTypeSet()) {
1782 // Move a type over from 'other' to 'pat'.
1783 Pat->setType(Other->getType());
1784 OS << " if (" << Prefix << ".getValueType() != MVT::"
1785 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1787 } else if (Pat->isLeaf()) {
1791 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1792 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1793 Prefix + utostr(i), PatternNo, OS))
1798 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1799 Record *N = Records.getDef(Name);
1800 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1804 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1805 /// stream to match the pattern, and generate the code for the match if it
1807 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1809 static unsigned PatternCount = 0;
1810 unsigned PatternNo = PatternCount++;
1811 OS << " { // Pattern #" << PatternNo << ": ";
1812 Pattern.first->print(OS);
1813 OS << "\n // Emits: ";
1814 Pattern.second->print(OS);
1816 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1817 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
1819 // Emit the matcher, capturing named arguments in VariableMap.
1820 std::map<std::string,std::string> VariableMap;
1821 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1823 // TP - Get *SOME* tree pattern, we don't care which.
1824 TreePattern &TP = *PatternFragments.begin()->second;
1826 // At this point, we know that we structurally match the pattern, but the
1827 // types of the nodes may not match. Figure out the fewest number of type
1828 // comparisons we need to emit. For example, if there is only one integer
1829 // type supported by a target, there should be no type comparisons at all for
1830 // integer patterns!
1832 // To figure out the fewest number of type checks needed, clone the pattern,
1833 // remove the types, then perform type inference on the pattern as a whole.
1834 // If there are unresolved types, emit an explicit check for those types,
1835 // apply the type to the tree, then rerun type inference. Iterate until all
1836 // types are resolved.
1838 TreePatternNode *Pat = Pattern.first->clone();
1839 RemoveAllTypes(Pat);
1842 // Resolve/propagate as many types as possible.
1844 bool MadeChange = true;
1846 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1848 assert(0 && "Error: could not find consistent types for something we"
1849 " already decided was ok!");
1853 // Insert a check for an unresolved type and add it to the tree. If we find
1854 // an unresolved type to add a check for, this returns true and we iterate,
1855 // otherwise we are done.
1856 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
1859 CodeGenPatternResult(Pattern.second, TmpNo,
1860 VariableMap, OS, true /*the root*/);
1863 OS << " }\n P" << PatternNo << "Fail:\n";
1868 /// CompareByRecordName - An ordering predicate that implements less-than by
1869 /// comparing the names records.
1870 struct CompareByRecordName {
1871 bool operator()(const Record *LHS, const Record *RHS) const {
1872 // Sort by name first.
1873 if (LHS->getName() < RHS->getName()) return true;
1874 // If both names are equal, sort by pointer.
1875 return LHS->getName() == RHS->getName() && LHS < RHS;
1880 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1881 std::string InstNS = Target.inst_begin()->second.Namespace;
1882 if (!InstNS.empty()) InstNS += "::";
1884 // Emit boilerplate.
1885 OS << "// The main instruction selector code.\n"
1886 << "SDOperand SelectCode(SDOperand N) {\n"
1887 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1888 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1889 << "INSTRUCTION_LIST_END))\n"
1890 << " return N; // Already selected.\n\n"
1891 << " if (!N.Val->hasOneUse()) {\n"
1892 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1893 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1895 << " switch (N.getOpcode()) {\n"
1896 << " default: break;\n"
1897 << " case ISD::EntryToken: // These leaves remain the same.\n"
1899 << " case ISD::AssertSext:\n"
1900 << " case ISD::AssertZext: {\n"
1901 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1902 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1903 << " return Tmp0;\n"
1905 << " case ISD::TokenFactor:\n"
1906 << " if (N.getNumOperands() == 2) {\n"
1907 << " SDOperand Op0 = Select(N.getOperand(0));\n"
1908 << " SDOperand Op1 = Select(N.getOperand(1));\n"
1909 << " return CodeGenMap[N] =\n"
1910 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
1912 << " std::vector<SDOperand> Ops;\n"
1913 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1914 << " Ops.push_back(Select(N.getOperand(i)));\n"
1915 << " return CodeGenMap[N] = \n"
1916 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
1918 << " case ISD::CopyFromReg: {\n"
1919 << " SDOperand Chain = Select(N.getOperand(0));\n"
1920 << " if (Chain == N.getOperand(0)) return N; // No change\n"
1921 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
1922 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
1923 << " N.Val->getValueType(0));\n"
1924 << " return New.getValue(N.ResNo);\n"
1926 << " case ISD::CopyToReg: {\n"
1927 << " SDOperand Chain = Select(N.getOperand(0));\n"
1928 << " SDOperand Reg = N.getOperand(1);\n"
1929 << " SDOperand Val = Select(N.getOperand(2));\n"
1930 << " return CodeGenMap[N] = \n"
1931 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
1932 << " Chain, Reg, Val);\n"
1935 // Group the patterns by their top-level opcodes.
1936 std::map<Record*, std::vector<PatternToMatch*>,
1937 CompareByRecordName> PatternsByOpcode;
1938 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1939 if (!PatternsToMatch[i].first->isLeaf()) {
1940 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1941 .push_back(&PatternsToMatch[i]);
1944 dynamic_cast<IntInit*>(PatternsToMatch[i].first->getLeafValue())) {
1945 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
1947 assert(0 && "Unknown leaf value");
1951 // Loop over all of the case statements.
1952 for (std::map<Record*, std::vector<PatternToMatch*>,
1953 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1954 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1955 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1956 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1958 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
1960 // We want to emit all of the matching code now. However, we want to emit
1961 // the matches in order of minimal cost. Sort the patterns so the least
1962 // cost one is at the start.
1963 std::stable_sort(Patterns.begin(), Patterns.end(),
1964 PatternSortingPredicate());
1966 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1967 EmitCodeForPattern(*Patterns[i], OS);
1968 OS << " break;\n\n";
1972 OS << " } // end of big switch.\n\n"
1973 << " std::cerr << \"Cannot yet select: \";\n"
1974 << " N.Val->dump();\n"
1975 << " std::cerr << '\\n';\n"
1980 void DAGISelEmitter::run(std::ostream &OS) {
1981 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1984 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1985 << "// *** instruction selector class. These functions are really "
1988 OS << "// Instance var to keep track of multiply used nodes that have \n"
1989 << "// already been selected.\n"
1990 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1993 ParseNodeTransforms(OS);
1994 ParsePatternFragments(OS);
1995 ParseInstructions();
1998 // Generate variants. For example, commutative patterns can match
1999 // multiple ways. Add them to PatternsToMatch as well.
2003 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2004 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2005 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
2006 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
2010 // At this point, we have full information about the 'Patterns' we need to
2011 // parse, both implicitly from instructions as well as from explicit pattern
2012 // definitions. Emit the resultant instruction selector.
2013 EmitInstructionSelector(OS);
2015 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2016 E = PatternFragments.end(); I != E; ++I)
2018 PatternFragments.clear();
2020 Instructions.clear();