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]);
38 static std::vector<unsigned char>
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
67 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
71 /// isExtFloatingPointVT - Return true if the specified extended value type
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
74 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75 return EVTs[0] == MVT::isFP ||
76 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
79 //===----------------------------------------------------------------------===//
80 // SDTypeConstraint implementation
83 SDTypeConstraint::SDTypeConstraint(Record *R) {
84 OperandNo = R->getValueAsInt("OperandNum");
86 if (R->isSubClassOf("SDTCisVT")) {
87 ConstraintType = SDTCisVT;
88 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
89 } else if (R->isSubClassOf("SDTCisPtrTy")) {
90 ConstraintType = SDTCisPtrTy;
91 } else if (R->isSubClassOf("SDTCisInt")) {
92 ConstraintType = SDTCisInt;
93 } else if (R->isSubClassOf("SDTCisFP")) {
94 ConstraintType = SDTCisFP;
95 } else if (R->isSubClassOf("SDTCisSameAs")) {
96 ConstraintType = SDTCisSameAs;
97 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99 ConstraintType = SDTCisVTSmallerThanOp;
100 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
101 R->getValueAsInt("OtherOperandNum");
102 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103 ConstraintType = SDTCisOpSmallerThanOp;
104 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
105 R->getValueAsInt("BigOperandNum");
106 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107 ConstraintType = SDTCisIntVectorOfSameSize;
108 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109 R->getValueAsInt("OtherOpNum");
111 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
116 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
117 /// N, which has NumResults results.
118 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
120 unsigned NumResults) const {
121 assert(NumResults <= 1 &&
122 "We only work with nodes with zero or one result so far!");
124 if (OpNo >= (NumResults + N->getNumChildren())) {
125 std::cerr << "Invalid operand number " << OpNo << " ";
131 if (OpNo < NumResults)
132 return N; // FIXME: need value #
134 return N->getChild(OpNo-NumResults);
137 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
138 /// constraint to the nodes operands. This returns true if it makes a
139 /// change, false otherwise. If a type contradiction is found, throw an
141 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
142 const SDNodeInfo &NodeInfo,
143 TreePattern &TP) const {
144 unsigned NumResults = NodeInfo.getNumResults();
145 assert(NumResults <= 1 &&
146 "We only work with nodes with zero or one result so far!");
148 // Check that the number of operands is sane. Negative operands -> varargs.
149 if (NodeInfo.getNumOperands() >= 0) {
150 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
151 TP.error(N->getOperator()->getName() + " node requires exactly " +
152 itostr(NodeInfo.getNumOperands()) + " operands!");
155 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
157 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
159 switch (ConstraintType) {
160 default: assert(0 && "Unknown constraint type!");
162 // Operand must be a particular type.
163 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
165 // Operand must be same as target pointer type.
166 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
169 // If there is only one integer type supported, this must be it.
170 std::vector<MVT::ValueType> IntVTs =
171 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
173 // If we found exactly one supported integer type, apply it.
174 if (IntVTs.size() == 1)
175 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
176 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
179 // If there is only one FP type supported, this must be it.
180 std::vector<MVT::ValueType> FPVTs =
181 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
183 // If we found exactly one supported FP type, apply it.
184 if (FPVTs.size() == 1)
185 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
186 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
189 TreePatternNode *OtherNode =
190 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
191 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
192 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
194 case SDTCisVTSmallerThanOp: {
195 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
196 // have an integer type that is smaller than the VT.
197 if (!NodeToApply->isLeaf() ||
198 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
199 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
200 ->isSubClassOf("ValueType"))
201 TP.error(N->getOperator()->getName() + " expects a VT operand!");
203 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
204 if (!MVT::isInteger(VT))
205 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
207 TreePatternNode *OtherNode =
208 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
210 // It must be integer.
211 bool MadeChange = false;
212 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
214 // This code only handles nodes that have one type set. Assert here so
215 // that we can change this if we ever need to deal with multiple value
216 // types at this point.
217 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
218 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
219 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
222 case SDTCisOpSmallerThanOp: {
223 TreePatternNode *BigOperand =
224 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
226 // Both operands must be integer or FP, but we don't care which.
227 bool MadeChange = false;
229 // This code does not currently handle nodes which have multiple types,
230 // where some types are integer, and some are fp. Assert that this is not
232 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
233 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
234 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
235 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
236 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
237 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
238 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
239 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
240 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
241 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
242 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
243 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
244 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
246 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
248 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
249 VTs = FilterVTs(VTs, MVT::isInteger);
250 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
251 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
256 switch (VTs.size()) {
257 default: // Too many VT's to pick from.
258 case 0: break; // No info yet.
260 // Only one VT of this flavor. Cannot ever satisify the constraints.
261 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
263 // If we have exactly two possible types, the little operand must be the
264 // small one, the big operand should be the big one. Common with
265 // float/double for example.
266 assert(VTs[0] < VTs[1] && "Should be sorted!");
267 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
268 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
273 case SDTCisIntVectorOfSameSize: {
274 TreePatternNode *OtherOperand =
275 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
277 if (OtherOperand->hasTypeSet()) {
278 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
279 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
280 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
281 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
282 return NodeToApply->UpdateNodeType(IVT, TP);
291 //===----------------------------------------------------------------------===//
292 // SDNodeInfo implementation
294 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
295 EnumName = R->getValueAsString("Opcode");
296 SDClassName = R->getValueAsString("SDClass");
297 Record *TypeProfile = R->getValueAsDef("TypeProfile");
298 NumResults = TypeProfile->getValueAsInt("NumResults");
299 NumOperands = TypeProfile->getValueAsInt("NumOperands");
301 // Parse the properties.
303 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
304 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
305 if (PropList[i]->getName() == "SDNPCommutative") {
306 Properties |= 1 << SDNPCommutative;
307 } else if (PropList[i]->getName() == "SDNPAssociative") {
308 Properties |= 1 << SDNPAssociative;
309 } else if (PropList[i]->getName() == "SDNPHasChain") {
310 Properties |= 1 << SDNPHasChain;
311 } else if (PropList[i]->getName() == "SDNPOutFlag") {
312 Properties |= 1 << SDNPOutFlag;
313 } else if (PropList[i]->getName() == "SDNPInFlag") {
314 Properties |= 1 << SDNPInFlag;
315 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
316 Properties |= 1 << SDNPOptInFlag;
318 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
319 << "' on node '" << R->getName() << "'!\n";
325 // Parse the type constraints.
326 std::vector<Record*> ConstraintList =
327 TypeProfile->getValueAsListOfDefs("Constraints");
328 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
331 //===----------------------------------------------------------------------===//
332 // TreePatternNode implementation
335 TreePatternNode::~TreePatternNode() {
336 #if 0 // FIXME: implement refcounted tree nodes!
337 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
342 /// UpdateNodeType - Set the node type of N to VT if VT contains
343 /// information. If N already contains a conflicting type, then throw an
344 /// exception. This returns true if any information was updated.
346 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
348 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
350 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
352 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
357 if (getExtTypeNum(0) == MVT::iPTR) {
358 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
360 if (isExtIntegerInVTs(ExtVTs)) {
361 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
369 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
370 assert(hasTypeSet() && "should be handled above!");
371 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
372 if (getExtTypes() == FVTs)
377 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
378 //assert(hasTypeSet() && "should be handled above!");
379 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
380 if (getExtTypes() == FVTs)
387 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
388 assert(hasTypeSet() && "should be handled above!");
389 std::vector<unsigned char> FVTs =
390 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
391 if (getExtTypes() == FVTs)
397 // If we know this is an int or fp type, and we are told it is a specific one,
400 // Similarly, we should probably set the type here to the intersection of
401 // {isInt|isFP} and ExtVTs
402 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
403 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
407 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
415 TP.error("Type inference contradiction found in node!");
417 TP.error("Type inference contradiction found in node " +
418 getOperator()->getName() + "!");
420 return true; // unreachable
424 void TreePatternNode::print(std::ostream &OS) const {
426 OS << *getLeafValue();
428 OS << "(" << getOperator()->getName();
431 // FIXME: At some point we should handle printing all the value types for
432 // nodes that are multiply typed.
433 switch (getExtTypeNum(0)) {
434 case MVT::Other: OS << ":Other"; break;
435 case MVT::isInt: OS << ":isInt"; break;
436 case MVT::isFP : OS << ":isFP"; break;
437 case MVT::isUnknown: ; /*OS << ":?";*/ break;
438 case MVT::iPTR: OS << ":iPTR"; break;
440 std::string VTName = llvm::getName(getTypeNum(0));
441 // Strip off MVT:: prefix if present.
442 if (VTName.substr(0,5) == "MVT::")
443 VTName = VTName.substr(5);
450 if (getNumChildren() != 0) {
452 getChild(0)->print(OS);
453 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
455 getChild(i)->print(OS);
461 if (!PredicateFn.empty())
462 OS << "<<P:" << PredicateFn << ">>";
464 OS << "<<X:" << TransformFn->getName() << ">>";
465 if (!getName().empty())
466 OS << ":$" << getName();
469 void TreePatternNode::dump() const {
473 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
474 /// the specified node. For this comparison, all of the state of the node
475 /// is considered, except for the assigned name. Nodes with differing names
476 /// that are otherwise identical are considered isomorphic.
477 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
478 if (N == this) return true;
479 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
480 getPredicateFn() != N->getPredicateFn() ||
481 getTransformFn() != N->getTransformFn())
485 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
486 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
487 return DI->getDef() == NDI->getDef();
488 return getLeafValue() == N->getLeafValue();
491 if (N->getOperator() != getOperator() ||
492 N->getNumChildren() != getNumChildren()) return false;
493 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
494 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
499 /// clone - Make a copy of this tree and all of its children.
501 TreePatternNode *TreePatternNode::clone() const {
502 TreePatternNode *New;
504 New = new TreePatternNode(getLeafValue());
506 std::vector<TreePatternNode*> CChildren;
507 CChildren.reserve(Children.size());
508 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
509 CChildren.push_back(getChild(i)->clone());
510 New = new TreePatternNode(getOperator(), CChildren);
512 New->setName(getName());
513 New->setTypes(getExtTypes());
514 New->setPredicateFn(getPredicateFn());
515 New->setTransformFn(getTransformFn());
519 /// SubstituteFormalArguments - Replace the formal arguments in this tree
520 /// with actual values specified by ArgMap.
521 void TreePatternNode::
522 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
523 if (isLeaf()) return;
525 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
526 TreePatternNode *Child = getChild(i);
527 if (Child->isLeaf()) {
528 Init *Val = Child->getLeafValue();
529 if (dynamic_cast<DefInit*>(Val) &&
530 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
531 // We found a use of a formal argument, replace it with its value.
532 Child = ArgMap[Child->getName()];
533 assert(Child && "Couldn't find formal argument!");
537 getChild(i)->SubstituteFormalArguments(ArgMap);
543 /// InlinePatternFragments - If this pattern refers to any pattern
544 /// fragments, inline them into place, giving us a pattern without any
545 /// PatFrag references.
546 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
547 if (isLeaf()) return this; // nothing to do.
548 Record *Op = getOperator();
550 if (!Op->isSubClassOf("PatFrag")) {
551 // Just recursively inline children nodes.
552 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
553 setChild(i, getChild(i)->InlinePatternFragments(TP));
557 // Otherwise, we found a reference to a fragment. First, look up its
558 // TreePattern record.
559 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
561 // Verify that we are passing the right number of operands.
562 if (Frag->getNumArgs() != Children.size())
563 TP.error("'" + Op->getName() + "' fragment requires " +
564 utostr(Frag->getNumArgs()) + " operands!");
566 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
568 // Resolve formal arguments to their actual value.
569 if (Frag->getNumArgs()) {
570 // Compute the map of formal to actual arguments.
571 std::map<std::string, TreePatternNode*> ArgMap;
572 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
573 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
575 FragTree->SubstituteFormalArguments(ArgMap);
578 FragTree->setName(getName());
579 FragTree->UpdateNodeType(getExtTypes(), TP);
581 // Get a new copy of this fragment to stitch into here.
582 //delete this; // FIXME: implement refcounting!
586 /// getImplicitType - Check to see if the specified record has an implicit
587 /// type which should be applied to it. This infer the type of register
588 /// references from the register file information, for example.
590 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
592 // Some common return values
593 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
594 std::vector<unsigned char> Other(1, MVT::Other);
596 // Check to see if this is a register or a register class...
597 if (R->isSubClassOf("RegisterClass")) {
600 const CodeGenRegisterClass &RC =
601 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
602 return ConvertVTs(RC.getValueTypes());
603 } else if (R->isSubClassOf("PatFrag")) {
604 // Pattern fragment types will be resolved when they are inlined.
606 } else if (R->isSubClassOf("Register")) {
609 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
610 return T.getRegisterVTs(R);
611 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
612 // Using a VTSDNode or CondCodeSDNode.
614 } else if (R->isSubClassOf("ComplexPattern")) {
617 std::vector<unsigned char>
618 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
620 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
625 TP.error("Unknown node flavor used in pattern: " + R->getName());
629 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
630 /// this node and its children in the tree. This returns true if it makes a
631 /// change, false otherwise. If a type contradiction is found, throw an
633 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
634 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
636 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
637 // If it's a regclass or something else known, include the type.
638 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
639 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
640 // Int inits are always integers. :)
641 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
644 // At some point, it may make sense for this tree pattern to have
645 // multiple types. Assert here that it does not, so we revisit this
646 // code when appropriate.
647 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
648 MVT::ValueType VT = getTypeNum(0);
649 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
650 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
653 if (VT != MVT::iPTR) {
654 unsigned Size = MVT::getSizeInBits(VT);
655 // Make sure that the value is representable for this type.
657 int Val = (II->getValue() << (32-Size)) >> (32-Size);
658 if (Val != II->getValue())
659 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
660 "' is out of range for type '" +
661 getEnumName(getTypeNum(0)) + "'!");
671 // special handling for set, which isn't really an SDNode.
672 if (getOperator()->getName() == "set") {
673 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
674 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
675 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
677 // Types of operands must match.
678 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
679 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
680 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
682 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
683 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
684 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
686 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
687 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
688 bool MadeChange = false;
690 // Apply the result type to the node.
691 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
693 if (getNumChildren() != Int.ArgVTs.size())
694 TP.error("Intrinsic '" + Int.Name + "' expects " +
695 utostr(Int.ArgVTs.size()-1) + " operands, not " +
696 utostr(getNumChildren()-1) + " operands!");
698 // Apply type info to the intrinsic ID.
699 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
701 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
702 MVT::ValueType OpVT = Int.ArgVTs[i];
703 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
704 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
707 } else if (getOperator()->isSubClassOf("SDNode")) {
708 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
710 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
711 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
712 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
713 // Branch, etc. do not produce results and top-level forms in instr pattern
714 // must have void types.
715 if (NI.getNumResults() == 0)
716 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
718 // If this is a vector_shuffle operation, apply types to the build_vector
719 // operation. The types of the integers don't matter, but this ensures they
720 // won't get checked.
721 if (getOperator()->getName() == "vector_shuffle" &&
722 getChild(2)->getOperator()->getName() == "build_vector") {
723 TreePatternNode *BV = getChild(2);
724 const std::vector<MVT::ValueType> &LegalVTs
725 = ISE.getTargetInfo().getLegalValueTypes();
726 MVT::ValueType LegalIntVT = MVT::Other;
727 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
728 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
729 LegalIntVT = LegalVTs[i];
732 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
734 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
735 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
738 } else if (getOperator()->isSubClassOf("Instruction")) {
739 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
740 bool MadeChange = false;
741 unsigned NumResults = Inst.getNumResults();
743 assert(NumResults <= 1 &&
744 "Only supports zero or one result instrs!");
746 CodeGenInstruction &InstInfo =
747 ISE.getTargetInfo().getInstruction(getOperator()->getName());
748 // Apply the result type to the node
749 if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack...
750 MadeChange = UpdateNodeType(MVT::isVoid, TP);
752 Record *ResultNode = Inst.getResult(0);
753 assert(ResultNode->isSubClassOf("RegisterClass") &&
754 "Operands should be register classes!");
756 const CodeGenRegisterClass &RC =
757 ISE.getTargetInfo().getRegisterClass(ResultNode);
758 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
761 if (getNumChildren() != Inst.getNumOperands())
762 TP.error("Instruction '" + getOperator()->getName() + " expects " +
763 utostr(Inst.getNumOperands()) + " operands, not " +
764 utostr(getNumChildren()) + " operands!");
765 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
766 Record *OperandNode = Inst.getOperand(i);
768 if (OperandNode->isSubClassOf("RegisterClass")) {
769 const CodeGenRegisterClass &RC =
770 ISE.getTargetInfo().getRegisterClass(OperandNode);
771 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
773 } else if (OperandNode->isSubClassOf("Operand")) {
774 VT = getValueType(OperandNode->getValueAsDef("Type"));
775 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
777 assert(0 && "Unknown operand type!");
780 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
784 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
786 // Node transforms always take one operand.
787 if (getNumChildren() != 1)
788 TP.error("Node transform '" + getOperator()->getName() +
789 "' requires one operand!");
791 // If either the output or input of the xform does not have exact
792 // type info. We assume they must be the same. Otherwise, it is perfectly
793 // legal to transform from one type to a completely different type.
794 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
795 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
796 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
803 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
804 /// RHS of a commutative operation, not the on LHS.
805 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
806 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
808 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
814 /// canPatternMatch - If it is impossible for this pattern to match on this
815 /// target, fill in Reason and return false. Otherwise, return true. This is
816 /// used as a santity check for .td files (to prevent people from writing stuff
817 /// that can never possibly work), and to prevent the pattern permuter from
818 /// generating stuff that is useless.
819 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
820 if (isLeaf()) return true;
822 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
823 if (!getChild(i)->canPatternMatch(Reason, ISE))
826 // If this is an intrinsic, handle cases that would make it not match. For
827 // example, if an operand is required to be an immediate.
828 if (getOperator()->isSubClassOf("Intrinsic")) {
833 // If this node is a commutative operator, check that the LHS isn't an
835 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
836 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
837 // Scan all of the operands of the node and make sure that only the last one
838 // is a constant node, unless the RHS also is.
839 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
840 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
841 if (OnlyOnRHSOfCommutative(getChild(i))) {
842 Reason="Immediate value must be on the RHS of commutative operators!";
851 //===----------------------------------------------------------------------===//
852 // TreePattern implementation
855 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
856 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
857 isInputPattern = isInput;
858 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
859 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
862 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
863 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
864 isInputPattern = isInput;
865 Trees.push_back(ParseTreePattern(Pat));
868 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
869 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
870 isInputPattern = isInput;
871 Trees.push_back(Pat);
876 void TreePattern::error(const std::string &Msg) const {
878 throw "In " + TheRecord->getName() + ": " + Msg;
881 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
882 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
883 if (!OpDef) error("Pattern has unexpected operator type!");
884 Record *Operator = OpDef->getDef();
886 if (Operator->isSubClassOf("ValueType")) {
887 // If the operator is a ValueType, then this must be "type cast" of a leaf
889 if (Dag->getNumArgs() != 1)
890 error("Type cast only takes one operand!");
892 Init *Arg = Dag->getArg(0);
893 TreePatternNode *New;
894 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
895 Record *R = DI->getDef();
896 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
897 Dag->setArg(0, new DagInit(DI,
898 std::vector<std::pair<Init*, std::string> >()));
899 return ParseTreePattern(Dag);
901 New = new TreePatternNode(DI);
902 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
903 New = ParseTreePattern(DI);
904 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
905 New = new TreePatternNode(II);
906 if (!Dag->getArgName(0).empty())
907 error("Constant int argument should not have a name!");
908 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
909 // Turn this into an IntInit.
910 Init *II = BI->convertInitializerTo(new IntRecTy());
911 if (II == 0 || !dynamic_cast<IntInit*>(II))
912 error("Bits value must be constants!");
914 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
915 if (!Dag->getArgName(0).empty())
916 error("Constant int argument should not have a name!");
919 error("Unknown leaf value for tree pattern!");
923 // Apply the type cast.
924 New->UpdateNodeType(getValueType(Operator), *this);
925 New->setName(Dag->getArgName(0));
929 // Verify that this is something that makes sense for an operator.
930 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
931 !Operator->isSubClassOf("Instruction") &&
932 !Operator->isSubClassOf("SDNodeXForm") &&
933 !Operator->isSubClassOf("Intrinsic") &&
934 Operator->getName() != "set")
935 error("Unrecognized node '" + Operator->getName() + "'!");
937 // Check to see if this is something that is illegal in an input pattern.
938 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
939 Operator->isSubClassOf("SDNodeXForm")))
940 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
942 std::vector<TreePatternNode*> Children;
944 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
945 Init *Arg = Dag->getArg(i);
946 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
947 Children.push_back(ParseTreePattern(DI));
948 if (Children.back()->getName().empty())
949 Children.back()->setName(Dag->getArgName(i));
950 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
951 Record *R = DefI->getDef();
952 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
953 // TreePatternNode if its own.
954 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
955 Dag->setArg(i, new DagInit(DefI,
956 std::vector<std::pair<Init*, std::string> >()));
957 --i; // Revisit this node...
959 TreePatternNode *Node = new TreePatternNode(DefI);
960 Node->setName(Dag->getArgName(i));
961 Children.push_back(Node);
964 if (R->getName() == "node") {
965 if (Dag->getArgName(i).empty())
966 error("'node' argument requires a name to match with operand list");
967 Args.push_back(Dag->getArgName(i));
970 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
971 TreePatternNode *Node = new TreePatternNode(II);
972 if (!Dag->getArgName(i).empty())
973 error("Constant int argument should not have a name!");
974 Children.push_back(Node);
975 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
976 // Turn this into an IntInit.
977 Init *II = BI->convertInitializerTo(new IntRecTy());
978 if (II == 0 || !dynamic_cast<IntInit*>(II))
979 error("Bits value must be constants!");
981 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
982 if (!Dag->getArgName(i).empty())
983 error("Constant int argument should not have a name!");
984 Children.push_back(Node);
989 error("Unknown leaf value for tree pattern!");
993 // If the operator is an intrinsic, then this is just syntactic sugar for for
994 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
995 // convert the intrinsic name to a number.
996 if (Operator->isSubClassOf("Intrinsic")) {
997 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
998 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
1000 // If this intrinsic returns void, it must have side-effects and thus a
1002 if (Int.ArgVTs[0] == MVT::isVoid) {
1003 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
1004 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1005 // Has side-effects, requires chain.
1006 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
1008 // Otherwise, no chain.
1009 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1012 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1013 Children.insert(Children.begin(), IIDNode);
1016 return new TreePatternNode(Operator, Children);
1019 /// InferAllTypes - Infer/propagate as many types throughout the expression
1020 /// patterns as possible. Return true if all types are infered, false
1021 /// otherwise. Throw an exception if a type contradiction is found.
1022 bool TreePattern::InferAllTypes() {
1023 bool MadeChange = true;
1024 while (MadeChange) {
1026 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1027 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1030 bool HasUnresolvedTypes = false;
1031 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1032 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1033 return !HasUnresolvedTypes;
1036 void TreePattern::print(std::ostream &OS) const {
1037 OS << getRecord()->getName();
1038 if (!Args.empty()) {
1039 OS << "(" << Args[0];
1040 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1041 OS << ", " << Args[i];
1046 if (Trees.size() > 1)
1048 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1050 Trees[i]->print(OS);
1054 if (Trees.size() > 1)
1058 void TreePattern::dump() const { print(std::cerr); }
1062 //===----------------------------------------------------------------------===//
1063 // DAGISelEmitter implementation
1066 // Parse all of the SDNode definitions for the target, populating SDNodes.
1067 void DAGISelEmitter::ParseNodeInfo() {
1068 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1069 while (!Nodes.empty()) {
1070 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1074 // Get the buildin intrinsic nodes.
1075 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1076 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1077 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1080 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1081 /// map, and emit them to the file as functions.
1082 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1083 OS << "\n// Node transformations.\n";
1084 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1085 while (!Xforms.empty()) {
1086 Record *XFormNode = Xforms.back();
1087 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1088 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1089 SDNodeXForms.insert(std::make_pair(XFormNode,
1090 std::make_pair(SDNode, Code)));
1092 if (!Code.empty()) {
1093 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1094 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1096 OS << "inline SDOperand Transform_" << XFormNode->getName()
1097 << "(SDNode *" << C2 << ") {\n";
1098 if (ClassName != "SDNode")
1099 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1100 OS << Code << "\n}\n";
1107 void DAGISelEmitter::ParseComplexPatterns() {
1108 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1109 while (!AMs.empty()) {
1110 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1116 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1117 /// file, building up the PatternFragments map. After we've collected them all,
1118 /// inline fragments together as necessary, so that there are no references left
1119 /// inside a pattern fragment to a pattern fragment.
1121 /// This also emits all of the predicate functions to the output file.
1123 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1124 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1126 // First step, parse all of the fragments and emit predicate functions.
1127 OS << "\n// Predicate functions.\n";
1128 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1129 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1130 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1131 PatternFragments[Fragments[i]] = P;
1133 // Validate the argument list, converting it to map, to discard duplicates.
1134 std::vector<std::string> &Args = P->getArgList();
1135 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1137 if (OperandsMap.count(""))
1138 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1140 // Parse the operands list.
1141 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1142 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1143 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1144 P->error("Operands list should start with '(ops ... '!");
1146 // Copy over the arguments.
1148 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1149 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1150 static_cast<DefInit*>(OpsList->getArg(j))->
1151 getDef()->getName() != "node")
1152 P->error("Operands list should all be 'node' values.");
1153 if (OpsList->getArgName(j).empty())
1154 P->error("Operands list should have names for each operand!");
1155 if (!OperandsMap.count(OpsList->getArgName(j)))
1156 P->error("'" + OpsList->getArgName(j) +
1157 "' does not occur in pattern or was multiply specified!");
1158 OperandsMap.erase(OpsList->getArgName(j));
1159 Args.push_back(OpsList->getArgName(j));
1162 if (!OperandsMap.empty())
1163 P->error("Operands list does not contain an entry for operand '" +
1164 *OperandsMap.begin() + "'!");
1166 // If there is a code init for this fragment, emit the predicate code and
1167 // keep track of the fact that this fragment uses it.
1168 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1169 if (!Code.empty()) {
1170 if (P->getOnlyTree()->isLeaf())
1171 OS << "inline bool Predicate_" << Fragments[i]->getName()
1172 << "(SDNode *N) {\n";
1174 std::string ClassName =
1175 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1176 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1178 OS << "inline bool Predicate_" << Fragments[i]->getName()
1179 << "(SDNode *" << C2 << ") {\n";
1180 if (ClassName != "SDNode")
1181 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1183 OS << Code << "\n}\n";
1184 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1187 // If there is a node transformation corresponding to this, keep track of
1189 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1190 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1191 P->getOnlyTree()->setTransformFn(Transform);
1196 // Now that we've parsed all of the tree fragments, do a closure on them so
1197 // that there are not references to PatFrags left inside of them.
1198 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1199 E = PatternFragments.end(); I != E; ++I) {
1200 TreePattern *ThePat = I->second;
1201 ThePat->InlinePatternFragments();
1203 // Infer as many types as possible. Don't worry about it if we don't infer
1204 // all of them, some may depend on the inputs of the pattern.
1206 ThePat->InferAllTypes();
1208 // If this pattern fragment is not supported by this target (no types can
1209 // satisfy its constraints), just ignore it. If the bogus pattern is
1210 // actually used by instructions, the type consistency error will be
1214 // If debugging, print out the pattern fragment result.
1215 DEBUG(ThePat->dump());
1219 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1220 /// instruction input. Return true if this is a real use.
1221 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1222 std::map<std::string, TreePatternNode*> &InstInputs,
1223 std::vector<Record*> &InstImpInputs) {
1224 // No name -> not interesting.
1225 if (Pat->getName().empty()) {
1226 if (Pat->isLeaf()) {
1227 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1228 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1229 I->error("Input " + DI->getDef()->getName() + " must be named!");
1230 else if (DI && DI->getDef()->isSubClassOf("Register"))
1231 InstImpInputs.push_back(DI->getDef());
1237 if (Pat->isLeaf()) {
1238 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1239 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1242 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1243 Rec = Pat->getOperator();
1246 // SRCVALUE nodes are ignored.
1247 if (Rec->getName() == "srcvalue")
1250 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1255 if (Slot->isLeaf()) {
1256 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1258 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1259 SlotRec = Slot->getOperator();
1262 // Ensure that the inputs agree if we've already seen this input.
1264 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1265 if (Slot->getExtTypes() != Pat->getExtTypes())
1266 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1271 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1272 /// part of "I", the instruction), computing the set of inputs and outputs of
1273 /// the pattern. Report errors if we see anything naughty.
1274 void DAGISelEmitter::
1275 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1276 std::map<std::string, TreePatternNode*> &InstInputs,
1277 std::map<std::string, TreePatternNode*>&InstResults,
1278 std::vector<Record*> &InstImpInputs,
1279 std::vector<Record*> &InstImpResults) {
1280 if (Pat->isLeaf()) {
1281 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1282 if (!isUse && Pat->getTransformFn())
1283 I->error("Cannot specify a transform function for a non-input value!");
1285 } else if (Pat->getOperator()->getName() != "set") {
1286 // If this is not a set, verify that the children nodes are not void typed,
1288 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1289 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1290 I->error("Cannot have void nodes inside of patterns!");
1291 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1292 InstImpInputs, InstImpResults);
1295 // If this is a non-leaf node with no children, treat it basically as if
1296 // it were a leaf. This handles nodes like (imm).
1298 if (Pat->getNumChildren() == 0)
1299 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1301 if (!isUse && Pat->getTransformFn())
1302 I->error("Cannot specify a transform function for a non-input value!");
1306 // Otherwise, this is a set, validate and collect instruction results.
1307 if (Pat->getNumChildren() == 0)
1308 I->error("set requires operands!");
1309 else if (Pat->getNumChildren() & 1)
1310 I->error("set requires an even number of operands");
1312 if (Pat->getTransformFn())
1313 I->error("Cannot specify a transform function on a set node!");
1315 // Check the set destinations.
1316 unsigned NumValues = Pat->getNumChildren()/2;
1317 for (unsigned i = 0; i != NumValues; ++i) {
1318 TreePatternNode *Dest = Pat->getChild(i);
1319 if (!Dest->isLeaf())
1320 I->error("set destination should be a register!");
1322 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1324 I->error("set destination should be a register!");
1326 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1327 if (Dest->getName().empty())
1328 I->error("set destination must have a name!");
1329 if (InstResults.count(Dest->getName()))
1330 I->error("cannot set '" + Dest->getName() +"' multiple times");
1331 InstResults[Dest->getName()] = Dest;
1332 } else if (Val->getDef()->isSubClassOf("Register")) {
1333 InstImpResults.push_back(Val->getDef());
1335 I->error("set destination should be a register!");
1338 // Verify and collect info from the computation.
1339 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1340 InstInputs, InstResults,
1341 InstImpInputs, InstImpResults);
1345 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1346 /// any fragments involved. This populates the Instructions list with fully
1347 /// resolved instructions.
1348 void DAGISelEmitter::ParseInstructions() {
1349 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1351 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1354 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1355 LI = Instrs[i]->getValueAsListInit("Pattern");
1357 // If there is no pattern, only collect minimal information about the
1358 // instruction for its operand list. We have to assume that there is one
1359 // result, as we have no detailed info.
1360 if (!LI || LI->getSize() == 0) {
1361 std::vector<Record*> Results;
1362 std::vector<Record*> Operands;
1364 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1366 if (InstInfo.OperandList.size() != 0) {
1367 // FIXME: temporary hack...
1368 if (InstInfo.noResults) {
1369 // These produce no results
1370 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1371 Operands.push_back(InstInfo.OperandList[j].Rec);
1373 // Assume the first operand is the result.
1374 Results.push_back(InstInfo.OperandList[0].Rec);
1376 // The rest are inputs.
1377 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1378 Operands.push_back(InstInfo.OperandList[j].Rec);
1382 // Create and insert the instruction.
1383 std::vector<Record*> ImpResults;
1384 std::vector<Record*> ImpOperands;
1385 Instructions.insert(std::make_pair(Instrs[i],
1386 DAGInstruction(0, Results, Operands, ImpResults,
1388 continue; // no pattern.
1391 // Parse the instruction.
1392 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1393 // Inline pattern fragments into it.
1394 I->InlinePatternFragments();
1396 // Infer as many types as possible. If we cannot infer all of them, we can
1397 // never do anything with this instruction pattern: report it to the user.
1398 if (!I->InferAllTypes())
1399 I->error("Could not infer all types in pattern!");
1401 // InstInputs - Keep track of all of the inputs of the instruction, along
1402 // with the record they are declared as.
1403 std::map<std::string, TreePatternNode*> InstInputs;
1405 // InstResults - Keep track of all the virtual registers that are 'set'
1406 // in the instruction, including what reg class they are.
1407 std::map<std::string, TreePatternNode*> InstResults;
1409 std::vector<Record*> InstImpInputs;
1410 std::vector<Record*> InstImpResults;
1412 // Verify that the top-level forms in the instruction are of void type, and
1413 // fill in the InstResults map.
1414 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1415 TreePatternNode *Pat = I->getTree(j);
1416 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1417 I->error("Top-level forms in instruction pattern should have"
1420 // Find inputs and outputs, and verify the structure of the uses/defs.
1421 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1422 InstImpInputs, InstImpResults);
1425 // Now that we have inputs and outputs of the pattern, inspect the operands
1426 // list for the instruction. This determines the order that operands are
1427 // added to the machine instruction the node corresponds to.
1428 unsigned NumResults = InstResults.size();
1430 // Parse the operands list from the (ops) list, validating it.
1431 std::vector<std::string> &Args = I->getArgList();
1432 assert(Args.empty() && "Args list should still be empty here!");
1433 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1435 // Check that all of the results occur first in the list.
1436 std::vector<Record*> Results;
1437 TreePatternNode *Res0Node = NULL;
1438 for (unsigned i = 0; i != NumResults; ++i) {
1439 if (i == CGI.OperandList.size())
1440 I->error("'" + InstResults.begin()->first +
1441 "' set but does not appear in operand list!");
1442 const std::string &OpName = CGI.OperandList[i].Name;
1444 // Check that it exists in InstResults.
1445 TreePatternNode *RNode = InstResults[OpName];
1447 I->error("Operand $" + OpName + " does not exist in operand list!");
1451 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1453 I->error("Operand $" + OpName + " should be a set destination: all "
1454 "outputs must occur before inputs in operand list!");
1456 if (CGI.OperandList[i].Rec != R)
1457 I->error("Operand $" + OpName + " class mismatch!");
1459 // Remember the return type.
1460 Results.push_back(CGI.OperandList[i].Rec);
1462 // Okay, this one checks out.
1463 InstResults.erase(OpName);
1466 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1467 // the copy while we're checking the inputs.
1468 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1470 std::vector<TreePatternNode*> ResultNodeOperands;
1471 std::vector<Record*> Operands;
1472 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1473 const std::string &OpName = CGI.OperandList[i].Name;
1475 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1477 if (!InstInputsCheck.count(OpName))
1478 I->error("Operand $" + OpName +
1479 " does not appear in the instruction pattern");
1480 TreePatternNode *InVal = InstInputsCheck[OpName];
1481 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1483 if (InVal->isLeaf() &&
1484 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1485 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1486 if (CGI.OperandList[i].Rec != InRec &&
1487 !InRec->isSubClassOf("ComplexPattern"))
1488 I->error("Operand $" + OpName + "'s register class disagrees"
1489 " between the operand and pattern");
1491 Operands.push_back(CGI.OperandList[i].Rec);
1493 // Construct the result for the dest-pattern operand list.
1494 TreePatternNode *OpNode = InVal->clone();
1496 // No predicate is useful on the result.
1497 OpNode->setPredicateFn("");
1499 // Promote the xform function to be an explicit node if set.
1500 if (Record *Xform = OpNode->getTransformFn()) {
1501 OpNode->setTransformFn(0);
1502 std::vector<TreePatternNode*> Children;
1503 Children.push_back(OpNode);
1504 OpNode = new TreePatternNode(Xform, Children);
1507 ResultNodeOperands.push_back(OpNode);
1510 if (!InstInputsCheck.empty())
1511 I->error("Input operand $" + InstInputsCheck.begin()->first +
1512 " occurs in pattern but not in operands list!");
1514 TreePatternNode *ResultPattern =
1515 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1516 // Copy fully inferred output node type to instruction result pattern.
1518 ResultPattern->setTypes(Res0Node->getExtTypes());
1520 // Create and insert the instruction.
1521 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1522 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1524 // Use a temporary tree pattern to infer all types and make sure that the
1525 // constructed result is correct. This depends on the instruction already
1526 // being inserted into the Instructions map.
1527 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1528 Temp.InferAllTypes();
1530 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1531 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1536 // If we can, convert the instructions to be patterns that are matched!
1537 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1538 E = Instructions.end(); II != E; ++II) {
1539 DAGInstruction &TheInst = II->second;
1540 TreePattern *I = TheInst.getPattern();
1541 if (I == 0) continue; // No pattern.
1543 if (I->getNumTrees() != 1) {
1544 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1547 TreePatternNode *Pattern = I->getTree(0);
1548 TreePatternNode *SrcPattern;
1549 if (Pattern->getOperator()->getName() == "set") {
1550 if (Pattern->getNumChildren() != 2)
1551 continue; // Not a set of a single value (not handled so far)
1553 SrcPattern = Pattern->getChild(1)->clone();
1555 // Not a set (store or something?)
1556 SrcPattern = Pattern;
1560 if (!SrcPattern->canPatternMatch(Reason, *this))
1561 I->error("Instruction can never match: " + Reason);
1563 Record *Instr = II->first;
1564 TreePatternNode *DstPattern = TheInst.getResultPattern();
1566 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1567 SrcPattern, DstPattern,
1568 Instr->getValueAsInt("AddedComplexity")));
1572 void DAGISelEmitter::ParsePatterns() {
1573 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1575 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1576 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1577 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1579 // Inline pattern fragments into it.
1580 Pattern->InlinePatternFragments();
1582 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1583 if (LI->getSize() == 0) continue; // no pattern.
1585 // Parse the instruction.
1586 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1588 // Inline pattern fragments into it.
1589 Result->InlinePatternFragments();
1591 if (Result->getNumTrees() != 1)
1592 Result->error("Cannot handle instructions producing instructions "
1593 "with temporaries yet!");
1595 bool IterateInference;
1596 bool InferredAllPatternTypes, InferredAllResultTypes;
1598 // Infer as many types as possible. If we cannot infer all of them, we
1599 // can never do anything with this pattern: report it to the user.
1600 InferredAllPatternTypes = Pattern->InferAllTypes();
1602 // Infer as many types as possible. If we cannot infer all of them, we
1603 // can never do anything with this pattern: report it to the user.
1604 InferredAllResultTypes = Result->InferAllTypes();
1606 // Apply the type of the result to the source pattern. This helps us
1607 // resolve cases where the input type is known to be a pointer type (which
1608 // is considered resolved), but the result knows it needs to be 32- or
1609 // 64-bits. Infer the other way for good measure.
1610 IterateInference = Pattern->getOnlyTree()->
1611 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1612 IterateInference |= Result->getOnlyTree()->
1613 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1614 } while (IterateInference);
1616 // Verify that we inferred enough types that we can do something with the
1617 // pattern and result. If these fire the user has to add type casts.
1618 if (!InferredAllPatternTypes)
1619 Pattern->error("Could not infer all types in pattern!");
1620 if (!InferredAllResultTypes)
1621 Result->error("Could not infer all types in pattern result!");
1623 // Validate that the input pattern is correct.
1625 std::map<std::string, TreePatternNode*> InstInputs;
1626 std::map<std::string, TreePatternNode*> InstResults;
1627 std::vector<Record*> InstImpInputs;
1628 std::vector<Record*> InstImpResults;
1629 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1630 InstInputs, InstResults,
1631 InstImpInputs, InstImpResults);
1634 // Promote the xform function to be an explicit node if set.
1635 std::vector<TreePatternNode*> ResultNodeOperands;
1636 TreePatternNode *DstPattern = Result->getOnlyTree();
1637 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1638 TreePatternNode *OpNode = DstPattern->getChild(ii);
1639 if (Record *Xform = OpNode->getTransformFn()) {
1640 OpNode->setTransformFn(0);
1641 std::vector<TreePatternNode*> Children;
1642 Children.push_back(OpNode);
1643 OpNode = new TreePatternNode(Xform, Children);
1645 ResultNodeOperands.push_back(OpNode);
1647 DstPattern = Result->getOnlyTree();
1648 if (!DstPattern->isLeaf())
1649 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1650 ResultNodeOperands);
1651 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1652 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1653 Temp.InferAllTypes();
1656 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1657 Pattern->error("Pattern can never match: " + Reason);
1660 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1661 Pattern->getOnlyTree(),
1663 Patterns[i]->getValueAsInt("AddedComplexity")));
1667 /// CombineChildVariants - Given a bunch of permutations of each child of the
1668 /// 'operator' node, put them together in all possible ways.
1669 static void CombineChildVariants(TreePatternNode *Orig,
1670 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1671 std::vector<TreePatternNode*> &OutVariants,
1672 DAGISelEmitter &ISE) {
1673 // Make sure that each operand has at least one variant to choose from.
1674 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1675 if (ChildVariants[i].empty())
1678 // The end result is an all-pairs construction of the resultant pattern.
1679 std::vector<unsigned> Idxs;
1680 Idxs.resize(ChildVariants.size());
1681 bool NotDone = true;
1683 // Create the variant and add it to the output list.
1684 std::vector<TreePatternNode*> NewChildren;
1685 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1686 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1687 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1689 // Copy over properties.
1690 R->setName(Orig->getName());
1691 R->setPredicateFn(Orig->getPredicateFn());
1692 R->setTransformFn(Orig->getTransformFn());
1693 R->setTypes(Orig->getExtTypes());
1695 // If this pattern cannot every match, do not include it as a variant.
1696 std::string ErrString;
1697 if (!R->canPatternMatch(ErrString, ISE)) {
1700 bool AlreadyExists = false;
1702 // Scan to see if this pattern has already been emitted. We can get
1703 // duplication due to things like commuting:
1704 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1705 // which are the same pattern. Ignore the dups.
1706 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1707 if (R->isIsomorphicTo(OutVariants[i])) {
1708 AlreadyExists = true;
1715 OutVariants.push_back(R);
1718 // Increment indices to the next permutation.
1720 // Look for something we can increment without causing a wrap-around.
1721 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1722 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1723 NotDone = true; // Found something to increment.
1731 /// CombineChildVariants - A helper function for binary operators.
1733 static void CombineChildVariants(TreePatternNode *Orig,
1734 const std::vector<TreePatternNode*> &LHS,
1735 const std::vector<TreePatternNode*> &RHS,
1736 std::vector<TreePatternNode*> &OutVariants,
1737 DAGISelEmitter &ISE) {
1738 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1739 ChildVariants.push_back(LHS);
1740 ChildVariants.push_back(RHS);
1741 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1745 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1746 std::vector<TreePatternNode *> &Children) {
1747 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1748 Record *Operator = N->getOperator();
1750 // Only permit raw nodes.
1751 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1752 N->getTransformFn()) {
1753 Children.push_back(N);
1757 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1758 Children.push_back(N->getChild(0));
1760 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1762 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1763 Children.push_back(N->getChild(1));
1765 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1768 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1769 /// the (potentially recursive) pattern by using algebraic laws.
1771 static void GenerateVariantsOf(TreePatternNode *N,
1772 std::vector<TreePatternNode*> &OutVariants,
1773 DAGISelEmitter &ISE) {
1774 // We cannot permute leaves.
1776 OutVariants.push_back(N);
1780 // Look up interesting info about the node.
1781 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1783 // If this node is associative, reassociate.
1784 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1785 // Reassociate by pulling together all of the linked operators
1786 std::vector<TreePatternNode*> MaximalChildren;
1787 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1789 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1791 if (MaximalChildren.size() == 3) {
1792 // Find the variants of all of our maximal children.
1793 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1794 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1795 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1796 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1798 // There are only two ways we can permute the tree:
1799 // (A op B) op C and A op (B op C)
1800 // Within these forms, we can also permute A/B/C.
1802 // Generate legal pair permutations of A/B/C.
1803 std::vector<TreePatternNode*> ABVariants;
1804 std::vector<TreePatternNode*> BAVariants;
1805 std::vector<TreePatternNode*> ACVariants;
1806 std::vector<TreePatternNode*> CAVariants;
1807 std::vector<TreePatternNode*> BCVariants;
1808 std::vector<TreePatternNode*> CBVariants;
1809 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1810 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1811 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1812 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1813 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1814 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1816 // Combine those into the result: (x op x) op x
1817 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1818 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1819 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1820 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1821 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1822 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1824 // Combine those into the result: x op (x op x)
1825 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1826 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1827 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1828 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1829 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1830 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1835 // Compute permutations of all children.
1836 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1837 ChildVariants.resize(N->getNumChildren());
1838 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1839 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1841 // Build all permutations based on how the children were formed.
1842 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1844 // If this node is commutative, consider the commuted order.
1845 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1846 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1847 // Don't count children which are actually register references.
1849 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1850 TreePatternNode *Child = N->getChild(i);
1851 if (Child->isLeaf())
1852 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1853 Record *RR = DI->getDef();
1854 if (RR->isSubClassOf("Register"))
1859 // Consider the commuted order.
1861 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1867 // GenerateVariants - Generate variants. For example, commutative patterns can
1868 // match multiple ways. Add them to PatternsToMatch as well.
1869 void DAGISelEmitter::GenerateVariants() {
1871 DEBUG(std::cerr << "Generating instruction variants.\n");
1873 // Loop over all of the patterns we've collected, checking to see if we can
1874 // generate variants of the instruction, through the exploitation of
1875 // identities. This permits the target to provide agressive matching without
1876 // the .td file having to contain tons of variants of instructions.
1878 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1879 // intentionally do not reconsider these. Any variants of added patterns have
1880 // already been added.
1882 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1883 std::vector<TreePatternNode*> Variants;
1884 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1886 assert(!Variants.empty() && "Must create at least original variant!");
1887 Variants.erase(Variants.begin()); // Remove the original pattern.
1889 if (Variants.empty()) // No variants for this pattern.
1892 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1893 PatternsToMatch[i].getSrcPattern()->dump();
1896 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1897 TreePatternNode *Variant = Variants[v];
1899 DEBUG(std::cerr << " VAR#" << v << ": ";
1903 // Scan to see if an instruction or explicit pattern already matches this.
1904 bool AlreadyExists = false;
1905 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1906 // Check to see if this variant already exists.
1907 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1908 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1909 AlreadyExists = true;
1913 // If we already have it, ignore the variant.
1914 if (AlreadyExists) continue;
1916 // Otherwise, add it to the list of patterns we have.
1918 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1919 Variant, PatternsToMatch[i].getDstPattern(),
1920 PatternsToMatch[i].getAddedComplexity()));
1923 DEBUG(std::cerr << "\n");
1927 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1929 static bool NodeIsComplexPattern(TreePatternNode *N)
1931 return (N->isLeaf() &&
1932 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1933 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1934 isSubClassOf("ComplexPattern"));
1937 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1938 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1939 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1940 DAGISelEmitter &ISE)
1943 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1944 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1945 isSubClassOf("ComplexPattern")) {
1946 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1952 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1953 /// patterns before small ones. This is used to determine the size of a
1955 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1956 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1957 isExtFloatingPointInVTs(P->getExtTypes()) ||
1958 P->getExtTypeNum(0) == MVT::isVoid ||
1959 P->getExtTypeNum(0) == MVT::Flag ||
1960 P->getExtTypeNum(0) == MVT::iPTR) &&
1961 "Not a valid pattern node to size!");
1962 unsigned Size = 3; // The node itself.
1963 // If the root node is a ConstantSDNode, increases its size.
1964 // e.g. (set R32:$dst, 0).
1965 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1968 // FIXME: This is a hack to statically increase the priority of patterns
1969 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1970 // Later we can allow complexity / cost for each pattern to be (optionally)
1971 // specified. To get best possible pattern match we'll need to dynamically
1972 // calculate the complexity of all patterns a dag can potentially map to.
1973 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1975 Size += AM->getNumOperands() * 3;
1977 // If this node has some predicate function that must match, it adds to the
1978 // complexity of this node.
1979 if (!P->getPredicateFn().empty())
1982 // Count children in the count if they are also nodes.
1983 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1984 TreePatternNode *Child = P->getChild(i);
1985 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1986 Size += getPatternSize(Child, ISE);
1987 else if (Child->isLeaf()) {
1988 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1989 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1990 else if (NodeIsComplexPattern(Child))
1991 Size += getPatternSize(Child, ISE);
1992 else if (!Child->getPredicateFn().empty())
2000 /// getResultPatternCost - Compute the number of instructions for this pattern.
2001 /// This is a temporary hack. We should really include the instruction
2002 /// latencies in this calculation.
2003 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
2004 if (P->isLeaf()) return 0;
2007 Record *Op = P->getOperator();
2008 if (Op->isSubClassOf("Instruction")) {
2010 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
2011 if (II.usesCustomDAGSchedInserter)
2014 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2015 Cost += getResultPatternCost(P->getChild(i), ISE);
2019 /// getResultPatternCodeSize - Compute the code size of instructions for this
2021 static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2022 if (P->isLeaf()) return 0;
2025 Record *Op = P->getOperator();
2026 if (Op->isSubClassOf("Instruction")) {
2027 Cost += Op->getValueAsInt("CodeSize");
2029 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2030 Cost += getResultPatternSize(P->getChild(i), ISE);
2034 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2035 // In particular, we want to match maximal patterns first and lowest cost within
2036 // a particular complexity first.
2037 struct PatternSortingPredicate {
2038 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2039 DAGISelEmitter &ISE;
2041 bool operator()(PatternToMatch *LHS,
2042 PatternToMatch *RHS) {
2043 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2044 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
2045 LHSSize += LHS->getAddedComplexity();
2046 RHSSize += RHS->getAddedComplexity();
2047 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2048 if (LHSSize < RHSSize) return false;
2050 // If the patterns have equal complexity, compare generated instruction cost
2051 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2052 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2053 if (LHSCost < RHSCost) return true;
2054 if (LHSCost > RHSCost) return false;
2056 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2057 getResultPatternSize(RHS->getDstPattern(), ISE);
2061 /// getRegisterValueType - Look up and return the first ValueType of specified
2062 /// RegisterClass record
2063 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
2064 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2065 return RC->getValueTypeNum(0);
2070 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2071 /// type information from it.
2072 static void RemoveAllTypes(TreePatternNode *N) {
2075 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2076 RemoveAllTypes(N->getChild(i));
2079 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2080 Record *N = Records.getDef(Name);
2081 if (!N || !N->isSubClassOf("SDNode")) {
2082 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2088 /// NodeHasProperty - return true if TreePatternNode has the specified
2090 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2091 DAGISelEmitter &ISE)
2093 if (N->isLeaf()) return false;
2094 Record *Operator = N->getOperator();
2095 if (!Operator->isSubClassOf("SDNode")) return false;
2097 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2098 return NodeInfo.hasProperty(Property);
2101 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2102 DAGISelEmitter &ISE)
2104 if (NodeHasProperty(N, Property, ISE))
2107 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2108 TreePatternNode *Child = N->getChild(i);
2109 if (PatternHasProperty(Child, Property, ISE))
2116 class PatternCodeEmitter {
2118 DAGISelEmitter &ISE;
2121 ListInit *Predicates;
2124 // Instruction selector pattern.
2125 TreePatternNode *Pattern;
2126 // Matched instruction.
2127 TreePatternNode *Instruction;
2129 // Node to name mapping
2130 std::map<std::string, std::string> VariableMap;
2131 // Node to operator mapping
2132 std::map<std::string, Record*> OperatorMap;
2133 // Names of all the folded nodes which produce chains.
2134 std::vector<std::pair<std::string, unsigned> > FoldedChains;
2135 std::set<std::string> Duplicates;
2137 /// GeneratedCode - This is the buffer that we emit code to. The first int
2138 /// indicates whether this is an exit predicate (something that should be
2139 /// tested, and if true, the match fails) [when 1], or normal code to emit
2140 /// [when 0], or initialization code to emit [when 2].
2141 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
2142 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2143 /// the set of patterns for each top-level opcode.
2144 std::set<std::string> &GeneratedDecl;
2145 /// TargetOpcodes - The target specific opcodes used by the resulting
2147 std::vector<std::string> &TargetOpcodes;
2148 std::vector<std::string> &TargetVTs;
2150 std::string ChainName;
2155 void emitCheck(const std::string &S) {
2157 GeneratedCode.push_back(std::make_pair(1, S));
2159 void emitCode(const std::string &S) {
2161 GeneratedCode.push_back(std::make_pair(0, S));
2163 void emitInit(const std::string &S) {
2165 GeneratedCode.push_back(std::make_pair(2, S));
2167 void emitDecl(const std::string &S) {
2168 assert(!S.empty() && "Invalid declaration");
2169 GeneratedDecl.insert(S);
2171 void emitOpcode(const std::string &Opc) {
2172 TargetOpcodes.push_back(Opc);
2175 void emitVT(const std::string &VT) {
2176 TargetVTs.push_back(VT);
2180 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2181 TreePatternNode *pattern, TreePatternNode *instr,
2182 std::vector<std::pair<unsigned, std::string> > &gc,
2183 std::set<std::string> &gd,
2184 std::vector<std::string> &to,
2185 std::vector<std::string> &tv)
2186 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2187 GeneratedCode(gc), GeneratedDecl(gd),
2188 TargetOpcodes(to), TargetVTs(tv),
2189 TmpNo(0), OpcNo(0), VTNo(0) {}
2191 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2192 /// if the match fails. At this point, we already know that the opcode for N
2193 /// matches, and the SDNode for the result has the RootName specified name.
2194 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2195 const std::string &RootName, const std::string &ParentName,
2196 const std::string &ChainSuffix, bool &FoundChain) {
2197 bool isRoot = (P == NULL);
2198 // Emit instruction predicates. Each predicate is just a string for now.
2200 std::string PredicateCheck;
2201 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2202 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2203 Record *Def = Pred->getDef();
2204 if (!Def->isSubClassOf("Predicate")) {
2208 assert(0 && "Unknown predicate type!");
2210 if (!PredicateCheck.empty())
2211 PredicateCheck += " && ";
2212 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2216 emitCheck(PredicateCheck);
2220 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2221 emitCheck("cast<ConstantSDNode>(" + RootName +
2222 ")->getSignExtended() == " + itostr(II->getValue()));
2224 } else if (!NodeIsComplexPattern(N)) {
2225 assert(0 && "Cannot match this as a leaf value!");
2230 // If this node has a name associated with it, capture it in VariableMap. If
2231 // we already saw this in the pattern, emit code to verify dagness.
2232 if (!N->getName().empty()) {
2233 std::string &VarMapEntry = VariableMap[N->getName()];
2234 if (VarMapEntry.empty()) {
2235 VarMapEntry = RootName;
2237 // If we get here, this is a second reference to a specific name. Since
2238 // we already have checked that the first reference is valid, we don't
2239 // have to recursively match it, just check that it's the same as the
2240 // previously named thing.
2241 emitCheck(VarMapEntry + " == " + RootName);
2246 OperatorMap[N->getName()] = N->getOperator();
2250 // Emit code to load the child nodes and match their contents recursively.
2252 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2253 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2254 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
2255 bool EmittedUseCheck = false;
2260 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2261 // Multiple uses of actual result?
2262 emitCheck(RootName + ".hasOneUse()");
2263 EmittedUseCheck = true;
2265 // If the immediate use can somehow reach this node through another
2266 // path, then can't fold it either or it will create a cycle.
2267 // e.g. In the following diagram, XX can reach ld through YY. If
2268 // ld is folded into XX, then YY is both a predecessor and a successor
2278 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2279 if (PInfo.getNumOperands() > 1 ||
2280 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2281 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2282 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2283 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
2290 emitCheck("Chain.Val == " + RootName + ".Val");
2293 ChainName = "Chain" + ChainSuffix;
2294 emitInit("SDOperand " + ChainName + " = " + RootName +
2299 // Don't fold any node which reads or writes a flag and has multiple uses.
2300 // FIXME: We really need to separate the concepts of flag and "glue". Those
2301 // real flag results, e.g. X86CMP output, can have multiple uses.
2302 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2305 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2306 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2307 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2308 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2309 if (!EmittedUseCheck) {
2310 // Multiple uses of actual result?
2311 emitCheck(RootName + ".hasOneUse()");
2315 const ComplexPattern *CP;
2316 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2317 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
2318 RootName + ".getOperand(" +utostr(OpNo) + ");");
2320 TreePatternNode *Child = N->getChild(i);
2321 if (!Child->isLeaf()) {
2322 // If it's not a leaf, recursively match.
2323 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2324 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2325 CInfo.getEnumName());
2326 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2327 ChainSuffix + utostr(OpNo), FoundChain);
2328 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2329 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2330 CInfo.getNumResults()));
2332 // If this child has a name associated with it, capture it in VarMap. If
2333 // we already saw this in the pattern, emit code to verify dagness.
2334 if (!Child->getName().empty()) {
2335 std::string &VarMapEntry = VariableMap[Child->getName()];
2336 if (VarMapEntry.empty()) {
2337 VarMapEntry = RootName + utostr(OpNo);
2339 // If we get here, this is a second reference to a specific name.
2340 // Since we already have checked that the first reference is valid,
2341 // we don't have to recursively match it, just check that it's the
2342 // same as the previously named thing.
2343 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2344 Duplicates.insert(RootName + utostr(OpNo));
2349 // Handle leaves of various types.
2350 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2351 Record *LeafRec = DI->getDef();
2352 if (LeafRec->isSubClassOf("RegisterClass")) {
2353 // Handle register references. Nothing to do here.
2354 } else if (LeafRec->isSubClassOf("Register")) {
2355 // Handle register references.
2356 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2357 // Handle complex pattern.
2358 CP = NodeGetComplexPattern(Child, ISE);
2359 std::string Fn = CP->getSelectFunc();
2360 unsigned NumOps = CP->getNumOperands();
2361 for (unsigned i = 0; i < NumOps; ++i) {
2362 emitDecl("CPTmp" + utostr(i));
2363 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2366 std::string Code = Fn + "(" + RootName + utostr(OpNo);
2367 for (unsigned i = 0; i < NumOps; i++)
2368 Code += ", CPTmp" + utostr(i);
2369 emitCheck(Code + ")");
2370 } else if (LeafRec->getName() == "srcvalue") {
2371 // Place holder for SRCVALUE nodes. Nothing to do here.
2372 } else if (LeafRec->isSubClassOf("ValueType")) {
2373 // Make sure this is the specified value type.
2374 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2375 ")->getVT() == MVT::" + LeafRec->getName());
2376 } else if (LeafRec->isSubClassOf("CondCode")) {
2377 // Make sure this is the specified cond code.
2378 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2379 ")->get() == ISD::" + LeafRec->getName());
2385 assert(0 && "Unknown leaf type!");
2388 // If there is a node predicate for this, emit the call.
2389 if (!Child->getPredicateFn().empty())
2390 emitCheck(Child->getPredicateFn() + "(" + RootName + utostr(OpNo) +
2392 } else if (IntInit *II =
2393 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2394 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2395 unsigned CTmp = TmpNo++;
2396 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2397 RootName + utostr(OpNo) + ")->getSignExtended();");
2399 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2404 assert(0 && "Unknown leaf type!");
2409 // Handle cases when root is a complex pattern.
2410 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2411 std::string Fn = CP->getSelectFunc();
2412 unsigned NumOps = CP->getNumOperands();
2413 for (unsigned i = 0; i < NumOps; ++i) {
2414 emitDecl("CPTmp" + utostr(i));
2415 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2418 std::string Code = Fn + "(" + RootName;
2419 for (unsigned i = 0; i < NumOps; i++)
2420 Code += ", CPTmp" + utostr(i);
2421 emitCheck(Code + ")");
2424 // If there is a node predicate for this, emit the call.
2425 if (!N->getPredicateFn().empty())
2426 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2429 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2430 /// we actually have to build a DAG!
2431 std::vector<std::string>
2432 EmitResultCode(TreePatternNode *N, bool RetSelected,
2433 bool InFlagDecled, bool ResNodeDecled,
2434 bool LikeLeaf = false, bool isRoot = false) {
2435 // List of arguments of getTargetNode() or SelectNodeTo().
2436 std::vector<std::string> NodeOps;
2437 // This is something selected from the pattern we matched.
2438 if (!N->getName().empty()) {
2439 std::string &Val = VariableMap[N->getName()];
2440 assert(!Val.empty() &&
2441 "Variable referenced but not defined and not caught earlier!");
2442 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2443 // Already selected this operand, just return the tmpval.
2444 NodeOps.push_back(Val);
2448 const ComplexPattern *CP;
2449 unsigned ResNo = TmpNo++;
2450 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2451 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2452 std::string CastType;
2453 switch (N->getTypeNum(0)) {
2454 default: assert(0 && "Unknown type for constant node!");
2455 case MVT::i1: CastType = "bool"; break;
2456 case MVT::i8: CastType = "unsigned char"; break;
2457 case MVT::i16: CastType = "unsigned short"; break;
2458 case MVT::i32: CastType = "unsigned"; break;
2459 case MVT::i64: CastType = "uint64_t"; break;
2461 emitCode("SDOperand Tmp" + utostr(ResNo) +
2462 " = CurDAG->getTargetConstant(((" + CastType +
2463 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2464 getEnumName(N->getTypeNum(0)) + ");");
2465 NodeOps.push_back("Tmp" + utostr(ResNo));
2466 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2467 // value if used multiple times by this pattern result.
2468 Val = "Tmp"+utostr(ResNo);
2469 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2470 Record *Op = OperatorMap[N->getName()];
2471 // Transform ExternalSymbol to TargetExternalSymbol
2472 if (Op && Op->getName() == "externalsym") {
2473 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2474 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2475 Val + ")->getSymbol(), " +
2476 getEnumName(N->getTypeNum(0)) + ");");
2477 NodeOps.push_back("Tmp" + utostr(ResNo));
2478 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2479 // this value if used multiple times by this pattern result.
2480 Val = "Tmp"+utostr(ResNo);
2482 NodeOps.push_back(Val);
2484 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2485 Record *Op = OperatorMap[N->getName()];
2486 // Transform GlobalAddress to TargetGlobalAddress
2487 if (Op && Op->getName() == "globaladdr") {
2488 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2489 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2490 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2492 NodeOps.push_back("Tmp" + utostr(ResNo));
2493 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2494 // this value if used multiple times by this pattern result.
2495 Val = "Tmp"+utostr(ResNo);
2497 NodeOps.push_back(Val);
2499 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2500 NodeOps.push_back(Val);
2501 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2502 // value if used multiple times by this pattern result.
2503 Val = "Tmp"+utostr(ResNo);
2504 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2505 NodeOps.push_back(Val);
2506 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2507 // value if used multiple times by this pattern result.
2508 Val = "Tmp"+utostr(ResNo);
2509 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2510 std::string Fn = CP->getSelectFunc();
2511 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2512 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2513 NodeOps.push_back("CPTmp" + utostr(i));
2516 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
2517 // node even if it isn't one. Don't select it.
2519 emitCode("AddToISelQueue(" + Val + ");");
2520 if (isRoot && N->isLeaf()) {
2521 emitCode("ReplaceUses(N, " + Val + ");");
2522 emitCode("return NULL;");
2525 NodeOps.push_back(Val);
2530 // If this is an explicit register reference, handle it.
2531 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2532 unsigned ResNo = TmpNo++;
2533 if (DI->getDef()->isSubClassOf("Register")) {
2534 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2535 ISE.getQualifiedName(DI->getDef()) + ", " +
2536 getEnumName(N->getTypeNum(0)) + ");");
2537 NodeOps.push_back("Tmp" + utostr(ResNo));
2540 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2541 unsigned ResNo = TmpNo++;
2542 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2543 emitCode("SDOperand Tmp" + utostr(ResNo) +
2544 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2545 ", " + getEnumName(N->getTypeNum(0)) + ");");
2546 NodeOps.push_back("Tmp" + utostr(ResNo));
2553 assert(0 && "Unknown leaf type!");
2557 Record *Op = N->getOperator();
2558 if (Op->isSubClassOf("Instruction")) {
2559 const CodeGenTarget &CGT = ISE.getTargetInfo();
2560 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2561 const DAGInstruction &Inst = ISE.getInstruction(Op);
2562 TreePattern *InstPat = Inst.getPattern();
2563 TreePatternNode *InstPatNode =
2564 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2565 : (InstPat ? InstPat->getOnlyTree() : NULL);
2566 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2567 InstPatNode = InstPatNode->getChild(1);
2569 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
2570 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2571 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2572 bool NodeHasOptInFlag = isRoot &&
2573 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2574 bool NodeHasInFlag = isRoot &&
2575 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2576 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2577 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2578 bool NodeHasChain = InstPatNode &&
2579 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
2580 bool InputHasChain = isRoot &&
2581 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2583 if (NodeHasOptInFlag) {
2584 emitCode("bool HasInFlag = "
2585 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
2588 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
2590 // How many results is this pattern expected to produce?
2591 unsigned PatResults = 0;
2592 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2593 MVT::ValueType VT = Pattern->getTypeNum(i);
2594 if (VT != MVT::isVoid && VT != MVT::Flag)
2598 std::vector<std::string> AllOps;
2599 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2600 std::vector<std::string> Ops = EmitResultCode(N->getChild(i),
2601 RetSelected, InFlagDecled, ResNodeDecled);
2602 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2605 // Emit all the chain and CopyToReg stuff.
2606 bool ChainEmitted = NodeHasChain;
2608 emitCode("AddToISelQueue(" + ChainName + ");");
2609 if (NodeHasInFlag || HasImpInputs)
2610 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2611 InFlagDecled, ResNodeDecled, true);
2612 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
2613 if (!InFlagDecled) {
2614 emitCode("SDOperand InFlag(0, 0);");
2615 InFlagDecled = true;
2617 if (NodeHasOptInFlag) {
2618 emitCode("if (HasInFlag) {");
2619 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
2620 emitCode(" AddToISelQueue(InFlag);");
2625 unsigned NumResults = Inst.getNumResults();
2626 unsigned ResNo = TmpNo++;
2627 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2631 std::string NodeName;
2633 NodeName = "Tmp" + utostr(ResNo);
2634 Code2 = "SDOperand " + NodeName + " = SDOperand(";
2636 NodeName = "ResNode";
2638 Code2 = "SDNode *" + NodeName + " = ";
2640 Code2 = NodeName + " = ";
2643 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2644 unsigned OpsNo = OpcNo;
2645 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2647 // Output order: results, chain, flags
2649 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2650 Code += ", VT" + utostr(VTNo);
2651 emitVT(getEnumName(N->getTypeNum(0)));
2654 Code += ", MVT::Other";
2656 Code += ", MVT::Flag";
2660 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2661 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2666 if (NodeHasInFlag || HasImpInputs)
2667 emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2669 else if (NodeHasOptInFlag)
2670 emitCode("for (unsigned i = 2, e = N.getNumOperands()-"
2671 "(HasInFlag?1:0); i != e; ++i) {");
2673 emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2675 emitCode(" AddToISelQueue(N.getOperand(i));");
2676 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
2682 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
2684 AllOps.push_back(ChainName);
2688 if (NodeHasInFlag || HasImpInputs)
2689 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2690 else if (NodeHasOptInFlag) {
2691 emitCode("if (HasInFlag)");
2692 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2694 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2696 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2697 AllOps.push_back("InFlag");
2699 unsigned NumOps = AllOps.size();
2701 if (!NodeHasOptInFlag && NumOps < 4) {
2702 for (unsigned i = 0; i != NumOps; ++i)
2703 Code += ", " + AllOps[i];
2705 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
2706 for (unsigned i = 0; i != NumOps; ++i) {
2707 OpsCode += AllOps[i];
2711 emitCode(OpsCode + " };");
2712 Code += ", Ops" + utostr(OpsNo) + ", ";
2713 if (NodeHasOptInFlag) {
2714 Code += "HasInFlag ? ";
2715 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
2717 Code += utostr(NumOps);
2723 emitCode(Code2 + Code + ");");
2726 // Remember which op produces the chain.
2728 emitCode(ChainName + " = SDOperand(" + NodeName +
2729 ".Val, " + utostr(PatResults) + ");");
2731 emitCode(ChainName + " = SDOperand(" + NodeName +
2732 ", " + utostr(PatResults) + ");");
2735 NodeOps.push_back("Tmp" + utostr(ResNo));
2739 bool NeedReplace = false;
2740 if (NodeHasOutFlag) {
2741 if (!InFlagDecled) {
2742 emitCode("SDOperand InFlag = SDOperand(ResNode, " +
2743 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2744 InFlagDecled = true;
2746 emitCode("InFlag = SDOperand(ResNode, " +
2747 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2750 if (HasImpResults && EmitCopyFromRegs(N, ResNodeDecled, ChainEmitted)) {
2751 emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));");
2755 if (FoldedChains.size() > 0) {
2757 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2758 emitCode("ReplaceUses(SDOperand(" +
2759 FoldedChains[j].first + ".Val, " +
2760 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
2761 utostr(NumResults) + "));");
2765 if (NodeHasOutFlag) {
2766 emitCode("ReplaceUses(SDOperand(N.Val, " +
2767 utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);");
2772 for (unsigned i = 0; i < NumResults; i++)
2773 emitCode("ReplaceUses(SDOperand(N.Val, " +
2774 utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));");
2776 emitCode("ReplaceUses(SDOperand(N.Val, " +
2777 utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, "
2778 + ChainName + ".ResNo" + "));");
2782 // User does not expect the instruction would produce a chain!
2783 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
2785 } else if (InputHasChain && !NodeHasChain) {
2786 // One of the inner node produces a chain.
2788 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults+1) +
2789 "), SDOperand(ResNode, N.ResNo-1));");
2790 for (unsigned i = 0; i < PatResults; ++i)
2791 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(i) +
2792 "), SDOperand(ResNode, " + utostr(i) + "));");
2793 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults) +
2794 "), " + ChainName + ");");
2795 RetSelected = false;
2799 emitCode("return ResNode;");
2801 emitCode("return NULL;");
2803 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
2805 if (N->getTypeNum(0) != MVT::isVoid)
2806 Code += ", VT" + utostr(VTNo);
2808 Code += ", MVT::Flag";
2810 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2811 AllOps.push_back("InFlag");
2813 unsigned NumOps = AllOps.size();
2815 if (!NodeHasOptInFlag && NumOps < 4) {
2816 for (unsigned i = 0; i != NumOps; ++i)
2817 Code += ", " + AllOps[i];
2819 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
2820 for (unsigned i = 0; i != NumOps; ++i) {
2821 OpsCode += AllOps[i];
2825 emitCode(OpsCode + " };");
2826 Code += ", Ops" + utostr(OpcNo) + ", ";
2827 Code += utostr(NumOps);
2830 emitCode(Code + ");");
2831 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2832 if (N->getTypeNum(0) != MVT::isVoid)
2833 emitVT(getEnumName(N->getTypeNum(0)));
2837 } else if (Op->isSubClassOf("SDNodeXForm")) {
2838 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2839 // PatLeaf node - the operand may or may not be a leaf node. But it should
2841 std::vector<std::string> Ops =
2842 EmitResultCode(N->getChild(0), RetSelected, InFlagDecled,
2843 ResNodeDecled, true);
2844 unsigned ResNo = TmpNo++;
2845 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2846 + "(" + Ops.back() + ".Val);");
2847 NodeOps.push_back("Tmp" + utostr(ResNo));
2849 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
2854 throw std::string("Unknown node in result pattern!");
2858 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2859 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2860 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2861 /// for, this returns true otherwise false if Pat has all types.
2862 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2863 const std::string &Prefix, bool isRoot = false) {
2865 if (Pat->getExtTypes() != Other->getExtTypes()) {
2866 // Move a type over from 'other' to 'pat'.
2867 Pat->setTypes(Other->getExtTypes());
2868 // The top level node type is checked outside of the select function.
2870 emitCheck(Prefix + ".Val->getValueType(0) == " +
2871 getName(Pat->getTypeNum(0)));
2876 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2877 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2878 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2879 Prefix + utostr(OpNo)))
2885 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2887 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2888 bool &ChainEmitted, bool &InFlagDecled,
2889 bool &ResNodeDecled, bool isRoot = false) {
2890 const CodeGenTarget &T = ISE.getTargetInfo();
2892 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2893 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2894 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2895 TreePatternNode *Child = N->getChild(i);
2896 if (!Child->isLeaf()) {
2897 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
2898 InFlagDecled, ResNodeDecled);
2900 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2901 if (!Child->getName().empty()) {
2902 std::string Name = RootName + utostr(OpNo);
2903 if (Duplicates.find(Name) != Duplicates.end())
2904 // A duplicate! Do not emit a copy for this node.
2908 Record *RR = DI->getDef();
2909 if (RR->isSubClassOf("Register")) {
2910 MVT::ValueType RVT = getRegisterValueType(RR, T);
2911 if (RVT == MVT::Flag) {
2912 if (!InFlagDecled) {
2913 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
2914 InFlagDecled = true;
2916 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
2917 emitCode("AddToISelQueue(InFlag);");
2919 if (!ChainEmitted) {
2920 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
2921 ChainName = "Chain";
2922 ChainEmitted = true;
2924 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
2925 if (!InFlagDecled) {
2926 emitCode("SDOperand InFlag(0, 0);");
2927 InFlagDecled = true;
2929 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
2930 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
2931 ", " + ISE.getQualifiedName(RR) +
2932 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
2933 ResNodeDecled = true;
2934 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2935 emitCode("InFlag = SDOperand(ResNode, 1);");
2943 if (!InFlagDecled) {
2944 emitCode("SDOperand InFlag = " + RootName +
2945 ".getOperand(" + utostr(OpNo) + ");");
2946 InFlagDecled = true;
2948 emitCode("InFlag = " + RootName +
2949 ".getOperand(" + utostr(OpNo) + ");");
2950 emitCode("AddToISelQueue(InFlag);");
2954 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2955 /// as specified by the instruction. It returns true if any copy is
2957 bool EmitCopyFromRegs(TreePatternNode *N, bool &ResNodeDecled,
2958 bool &ChainEmitted) {
2959 bool RetVal = false;
2960 Record *Op = N->getOperator();
2961 if (Op->isSubClassOf("Instruction")) {
2962 const DAGInstruction &Inst = ISE.getInstruction(Op);
2963 const CodeGenTarget &CGT = ISE.getTargetInfo();
2964 unsigned NumImpResults = Inst.getNumImpResults();
2965 for (unsigned i = 0; i < NumImpResults; i++) {
2966 Record *RR = Inst.getImpResult(i);
2967 if (RR->isSubClassOf("Register")) {
2968 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2969 if (RVT != MVT::Flag) {
2970 if (!ChainEmitted) {
2971 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
2972 ChainEmitted = true;
2973 ChainName = "Chain";
2975 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
2976 emitCode(Decl + "ResNode = CurDAG->getCopyFromReg(" + ChainName +
2977 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
2979 ResNodeDecled = true;
2980 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2981 emitCode("InFlag = SDOperand(ResNode, 2);");
2991 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2992 /// stream to match the pattern, and generate the code for the match if it
2993 /// succeeds. Returns true if the pattern is not guaranteed to match.
2994 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2995 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
2996 std::set<std::string> &GeneratedDecl,
2997 std::vector<std::string> &TargetOpcodes,
2998 std::vector<std::string> &TargetVTs) {
2999 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3000 Pattern.getSrcPattern(), Pattern.getDstPattern(),
3001 GeneratedCode, GeneratedDecl,
3002 TargetOpcodes, TargetVTs);
3004 // Emit the matcher, capturing named arguments in VariableMap.
3005 bool FoundChain = false;
3006 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "",
3009 // TP - Get *SOME* tree pattern, we don't care which.
3010 TreePattern &TP = *PatternFragments.begin()->second;
3012 // At this point, we know that we structurally match the pattern, but the
3013 // types of the nodes may not match. Figure out the fewest number of type
3014 // comparisons we need to emit. For example, if there is only one integer
3015 // type supported by a target, there should be no type comparisons at all for
3016 // integer patterns!
3018 // To figure out the fewest number of type checks needed, clone the pattern,
3019 // remove the types, then perform type inference on the pattern as a whole.
3020 // If there are unresolved types, emit an explicit check for those types,
3021 // apply the type to the tree, then rerun type inference. Iterate until all
3022 // types are resolved.
3024 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
3025 RemoveAllTypes(Pat);
3028 // Resolve/propagate as many types as possible.
3030 bool MadeChange = true;
3032 MadeChange = Pat->ApplyTypeConstraints(TP,
3033 true/*Ignore reg constraints*/);
3035 assert(0 && "Error: could not find consistent types for something we"
3036 " already decided was ok!");
3040 // Insert a check for an unresolved type and add it to the tree. If we find
3041 // an unresolved type to add a check for, this returns true and we iterate,
3042 // otherwise we are done.
3043 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
3045 Emitter.EmitResultCode(Pattern.getDstPattern(),
3046 false, false, false, false, true);
3050 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
3051 /// a line causes any of them to be empty, remove them and return true when
3053 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
3054 std::vector<std::pair<unsigned, std::string> > > >
3056 bool ErasedPatterns = false;
3057 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3058 Patterns[i].second.pop_back();
3059 if (Patterns[i].second.empty()) {
3060 Patterns.erase(Patterns.begin()+i);
3062 ErasedPatterns = true;
3065 return ErasedPatterns;
3068 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3069 /// code together between the patterns.
3070 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3071 std::vector<std::pair<unsigned, std::string> > > >
3072 &Patterns, unsigned Indent,
3074 typedef std::pair<unsigned, std::string> CodeLine;
3075 typedef std::vector<CodeLine> CodeList;
3076 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3078 if (Patterns.empty()) return;
3080 // Figure out how many patterns share the next code line. Explicitly copy
3081 // FirstCodeLine so that we don't invalidate a reference when changing
3083 const CodeLine FirstCodeLine = Patterns.back().second.back();
3084 unsigned LastMatch = Patterns.size()-1;
3085 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3088 // If not all patterns share this line, split the list into two pieces. The
3089 // first chunk will use this line, the second chunk won't.
3090 if (LastMatch != 0) {
3091 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3092 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3094 // FIXME: Emit braces?
3095 if (Shared.size() == 1) {
3096 PatternToMatch &Pattern = *Shared.back().first;
3097 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3098 Pattern.getSrcPattern()->print(OS);
3099 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3100 Pattern.getDstPattern()->print(OS);
3102 unsigned AddedComplexity = Pattern.getAddedComplexity();
3103 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3104 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3106 << getResultPatternCost(Pattern.getDstPattern(), *this)
3108 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3110 if (FirstCodeLine.first != 1) {
3111 OS << std::string(Indent, ' ') << "{\n";
3114 EmitPatterns(Shared, Indent, OS);
3115 if (FirstCodeLine.first != 1) {
3117 OS << std::string(Indent, ' ') << "}\n";
3120 if (Other.size() == 1) {
3121 PatternToMatch &Pattern = *Other.back().first;
3122 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3123 Pattern.getSrcPattern()->print(OS);
3124 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3125 Pattern.getDstPattern()->print(OS);
3127 unsigned AddedComplexity = Pattern.getAddedComplexity();
3128 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3129 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3131 << getResultPatternCost(Pattern.getDstPattern(), *this)
3133 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3135 EmitPatterns(Other, Indent, OS);
3139 // Remove this code from all of the patterns that share it.
3140 bool ErasedPatterns = EraseCodeLine(Patterns);
3142 bool isPredicate = FirstCodeLine.first == 1;
3144 // Otherwise, every pattern in the list has this line. Emit it.
3147 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3149 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3151 // If the next code line is another predicate, and if all of the pattern
3152 // in this group share the same next line, emit it inline now. Do this
3153 // until we run out of common predicates.
3154 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
3155 // Check that all of fhe patterns in Patterns end with the same predicate.
3156 bool AllEndWithSamePredicate = true;
3157 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3158 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3159 AllEndWithSamePredicate = false;
3162 // If all of the predicates aren't the same, we can't share them.
3163 if (!AllEndWithSamePredicate) break;
3165 // Otherwise we can. Emit it shared now.
3166 OS << " &&\n" << std::string(Indent+4, ' ')
3167 << Patterns.back().second.back().second;
3168 ErasedPatterns = EraseCodeLine(Patterns);
3175 EmitPatterns(Patterns, Indent, OS);
3178 OS << std::string(Indent-2, ' ') << "}\n";
3184 /// CompareByRecordName - An ordering predicate that implements less-than by
3185 /// comparing the names records.
3186 struct CompareByRecordName {
3187 bool operator()(const Record *LHS, const Record *RHS) const {
3188 // Sort by name first.
3189 if (LHS->getName() < RHS->getName()) return true;
3190 // If both names are equal, sort by pointer.
3191 return LHS->getName() == RHS->getName() && LHS < RHS;
3196 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3197 std::string InstNS = Target.inst_begin()->second.Namespace;
3198 if (!InstNS.empty()) InstNS += "::";
3200 // Group the patterns by their top-level opcodes.
3201 std::map<Record*, std::vector<PatternToMatch*>,
3202 CompareByRecordName> PatternsByOpcode;
3203 // All unique target node emission functions.
3204 std::map<std::string, unsigned> EmitFunctions;
3205 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3206 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3207 if (!Node->isLeaf()) {
3208 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3210 const ComplexPattern *CP;
3212 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3213 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3214 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3215 std::vector<Record*> OpNodes = CP->getRootNodes();
3216 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3217 PatternsByOpcode[OpNodes[j]]
3218 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3221 std::cerr << "Unrecognized opcode '";
3223 std::cerr << "' on tree pattern '";
3225 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3226 std::cerr << "'!\n";
3232 // For each opcode, there might be multiple select functions, one per
3233 // ValueType of the node (or its first operand if it doesn't produce a
3234 // non-chain result.
3235 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3237 // Emit one Select_* method for each top-level opcode. We do this instead of
3238 // emitting one giant switch statement to support compilers where this will
3239 // result in the recursive functions taking less stack space.
3240 for (std::map<Record*, std::vector<PatternToMatch*>,
3241 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3242 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3243 const std::string &OpName = PBOI->first->getName();
3244 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3245 std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3246 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3248 // We want to emit all of the matching code now. However, we want to emit
3249 // the matches in order of minimal cost. Sort the patterns so the least
3250 // cost one is at the start.
3251 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
3252 PatternSortingPredicate(*this));
3254 // Split them into groups by type.
3255 std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3256 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3257 PatternToMatch *Pat = PatternsOfOp[i];
3258 TreePatternNode *SrcPat = Pat->getSrcPattern();
3259 if (OpcodeInfo.getNumResults() == 0 && SrcPat->getNumChildren() > 0)
3260 SrcPat = SrcPat->getChild(0);
3261 MVT::ValueType VT = SrcPat->getTypeNum(0);
3262 std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI =
3263 PatternsByType.find(VT);
3264 if (TI != PatternsByType.end())
3265 TI->second.push_back(Pat);
3267 std::vector<PatternToMatch*> PVec;
3268 PVec.push_back(Pat);
3269 PatternsByType.insert(std::make_pair(VT, PVec));
3273 for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3274 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3276 MVT::ValueType OpVT = II->first;
3277 std::vector<PatternToMatch*> &Patterns = II->second;
3278 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
3279 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
3281 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3282 std::vector<std::vector<std::string> > PatternOpcodes;
3283 std::vector<std::vector<std::string> > PatternVTs;
3284 std::vector<std::set<std::string> > PatternDecls;
3285 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3286 CodeList GeneratedCode;
3287 std::set<std::string> GeneratedDecl;
3288 std::vector<std::string> TargetOpcodes;
3289 std::vector<std::string> TargetVTs;
3290 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3291 TargetOpcodes, TargetVTs);
3292 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3293 PatternDecls.push_back(GeneratedDecl);
3294 PatternOpcodes.push_back(TargetOpcodes);
3295 PatternVTs.push_back(TargetVTs);
3298 // Scan the code to see if all of the patterns are reachable and if it is
3299 // possible that the last one might not match.
3300 bool mightNotMatch = true;
3301 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3302 CodeList &GeneratedCode = CodeForPatterns[i].second;
3303 mightNotMatch = false;
3305 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3306 if (GeneratedCode[j].first == 1) { // predicate.
3307 mightNotMatch = true;
3312 // If this pattern definitely matches, and if it isn't the last one, the
3313 // patterns after it CANNOT ever match. Error out.
3314 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3315 std::cerr << "Pattern '";
3316 CodeForPatterns[i].first->getSrcPattern()->print(std::cerr);
3317 std::cerr << "' is impossible to select!\n";
3322 // Factor target node emission code (emitted by EmitResultCode) into
3323 // separate functions. Uniquing and share them among all instruction
3324 // selection routines.
3325 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3326 CodeList &GeneratedCode = CodeForPatterns[i].second;
3327 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3328 std::vector<std::string> &TargetVTs = PatternVTs[i];
3329 std::set<std::string> Decls = PatternDecls[i];
3330 std::vector<std::string> AddedInits;
3331 int CodeSize = (int)GeneratedCode.size();
3333 for (int j = CodeSize-1; j >= 0; --j) {
3334 if (LastPred == -1 && GeneratedCode[j].first == 1)
3336 else if (LastPred != -1 && GeneratedCode[j].first == 2)
3337 AddedInits.push_back(GeneratedCode[j].second);
3340 std::string CalleeCode = "(const SDOperand &N";
3341 std::string CallerCode = "(N";
3342 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3343 CalleeCode += ", unsigned Opc" + utostr(j);
3344 CallerCode += ", " + TargetOpcodes[j];
3346 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3347 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3348 CallerCode += ", " + TargetVTs[j];
3350 for (std::set<std::string>::iterator
3351 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
3352 std::string Name = *I;
3353 CalleeCode += ", SDOperand &" + Name;
3354 CallerCode += ", " + Name;
3358 // Prevent emission routines from being inlined to reduce selection
3359 // routines stack frame sizes.
3360 CalleeCode += "DISABLE_INLINE ";
3361 CalleeCode += "{\n";
3363 for (std::vector<std::string>::const_reverse_iterator
3364 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3365 CalleeCode += " " + *I + "\n";
3367 for (int j = LastPred+1; j < CodeSize; ++j)
3368 CalleeCode += " " + GeneratedCode[j].second + "\n";
3369 for (int j = LastPred+1; j < CodeSize; ++j)
3370 GeneratedCode.pop_back();
3371 CalleeCode += "}\n";
3373 // Uniquing the emission routines.
3374 unsigned EmitFuncNum;
3375 std::map<std::string, unsigned>::iterator EFI =
3376 EmitFunctions.find(CalleeCode);
3377 if (EFI != EmitFunctions.end()) {
3378 EmitFuncNum = EFI->second;
3380 EmitFuncNum = EmitFunctions.size();
3381 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
3382 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
3385 // Replace the emission code within selection routines with calls to the
3386 // emission functions.
3387 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
3388 GeneratedCode.push_back(std::make_pair(false, CallerCode));
3392 std::string OpVTStr = (OpVT != MVT::isVoid && OpVT != MVT::iPTR)
3393 ? getEnumName(OpVT).substr(5) : "" ;
3394 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3395 OpcodeVTMap.find(OpName);
3396 if (OpVTI == OpcodeVTMap.end()) {
3397 std::vector<std::string> VTSet;
3398 VTSet.push_back(OpVTStr);
3399 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3401 OpVTI->second.push_back(OpVTStr);
3403 OS << "SDNode *Select_" << OpName << (OpVTStr != "" ? "_" : "")
3404 << OpVTStr << "(const SDOperand &N) {\n";
3406 // Loop through and reverse all of the CodeList vectors, as we will be
3407 // accessing them from their logical front, but accessing the end of a
3408 // vector is more efficient.
3409 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3410 CodeList &GeneratedCode = CodeForPatterns[i].second;
3411 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3414 // Next, reverse the list of patterns itself for the same reason.
3415 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3417 // Emit all of the patterns now, grouped together to share code.
3418 EmitPatterns(CodeForPatterns, 2, OS);
3420 // If the last pattern has predicates (which could fail) emit code to
3421 // catch the case where nothing handles a pattern.
3422 if (mightNotMatch) {
3423 OS << " std::cerr << \"Cannot yet select: \";\n";
3424 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3425 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3426 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3427 OS << " N.Val->dump(CurDAG);\n";
3429 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3430 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3431 << " std::cerr << \"intrinsic %\"<< "
3432 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3434 OS << " std::cerr << '\\n';\n"
3436 << " return NULL;\n";
3442 // Emit boilerplate.
3443 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
3444 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3445 << " AddToISelQueue(N.getOperand(0)); // Select the chain.\n\n"
3446 << " // Select the flag operand.\n"
3447 << " if (Ops.back().getValueType() == MVT::Flag)\n"
3448 << " AddToISelQueue(Ops.back());\n"
3449 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3450 << " std::vector<MVT::ValueType> VTs;\n"
3451 << " VTs.push_back(MVT::Other);\n"
3452 << " VTs.push_back(MVT::Flag);\n"
3453 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3455 << " return New.Val;\n"
3458 OS << "// The main instruction selector code.\n"
3459 << "SDNode *SelectCode(SDOperand N) {\n"
3460 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3461 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3462 << "INSTRUCTION_LIST_END)) {\n"
3463 << " return NULL; // Already selected.\n"
3465 << " switch (N.getOpcode()) {\n"
3466 << " default: break;\n"
3467 << " case ISD::EntryToken: // These leaves remain the same.\n"
3468 << " case ISD::BasicBlock:\n"
3469 << " case ISD::Register:\n"
3470 << " case ISD::HANDLENODE:\n"
3471 << " case ISD::TargetConstant:\n"
3472 << " case ISD::TargetConstantPool:\n"
3473 << " case ISD::TargetFrameIndex:\n"
3474 << " case ISD::TargetJumpTable:\n"
3475 << " case ISD::TargetGlobalAddress: {\n"
3476 << " return NULL;\n"
3478 << " case ISD::AssertSext:\n"
3479 << " case ISD::AssertZext: {\n"
3480 << " AddToISelQueue(N.getOperand(0));\n"
3481 << " ReplaceUses(N, N.getOperand(0));\n"
3482 << " return NULL;\n"
3484 << " case ISD::TokenFactor:\n"
3485 << " case ISD::CopyFromReg:\n"
3486 << " case ISD::CopyToReg: {\n"
3487 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3488 << " AddToISelQueue(N.getOperand(i));\n"
3489 << " return NULL;\n"
3491 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n";
3494 // Loop over all of the case statements, emiting a call to each method we
3496 for (std::map<Record*, std::vector<PatternToMatch*>,
3497 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3498 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3499 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3500 const std::string &OpName = PBOI->first->getName();
3501 // Potentially multiple versions of select for this opcode. One for each
3502 // ValueType of the node (or its first true operand if it doesn't produce a
3504 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3505 OpcodeVTMap.find(OpName);
3506 std::vector<std::string> &OpVTs = OpVTI->second;
3507 OS << " case " << OpcodeInfo.getEnumName() << ": {\n";
3508 if (OpVTs.size() == 1) {
3509 std::string &VTStr = OpVTs[0];
3510 OS << " return Select_" << OpName
3511 << (VTStr != "" ? "_" : "") << VTStr << "(N);\n";
3513 if (OpcodeInfo.getNumResults())
3514 OS << " MVT::ValueType NVT = N.Val->getValueType(0);\n";
3515 else if (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain))
3516 OS << " MVT::ValueType NVT = (N.getNumOperands() > 1) ?"
3517 << " N.getOperand(1).Val->getValueType(0) : MVT::isVoid;\n";
3519 OS << " MVT::ValueType NVT = (N.getNumOperands() > 0) ?"
3520 << " N.getOperand(0).Val->getValueType(0) : MVT::isVoid;\n";
3522 OS << " switch (NVT) {\n";
3523 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3524 std::string &VTStr = OpVTs[i];
3529 OS << " case MVT::" << VTStr << ":\n"
3530 << " return Select_" << OpName
3531 << "_" << VTStr << "(N);\n";
3533 OS << " default:\n";
3535 OS << " return Select_" << OpName << "(N);\n";
3544 OS << " } // end of big switch.\n\n"
3545 << " std::cerr << \"Cannot yet select: \";\n"
3546 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3547 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3548 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3549 << " N.Val->dump(CurDAG);\n"
3551 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3552 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3553 << " std::cerr << \"intrinsic %\"<< "
3554 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3556 << " std::cerr << '\\n';\n"
3558 << " return NULL;\n"
3562 void DAGISelEmitter::run(std::ostream &OS) {
3563 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3566 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3567 << "// *** instruction selector class. These functions are really "
3570 OS << "#include \"llvm/Support/Compiler.h\"\n";
3572 OS << "// Instruction selector priority queue:\n"
3573 << "std::vector<SDNode*> ISelQueue;\n";
3574 OS << "/// Keep track of nodes which have already been added to queue.\n"
3575 << "unsigned char *ISelQueued;\n";
3576 OS << "/// Keep track of nodes which have already been selected.\n"
3577 << "unsigned char *ISelSelected;\n";
3578 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3579 << "std::vector<SDNode*> ISelKilled;\n\n";
3581 OS << "/// Sorting functions for the selection queue.\n"
3582 << "struct isel_sort : public std::binary_function"
3583 << "<SDNode*, SDNode*, bool> {\n"
3584 << " bool operator()(const SDNode* left, const SDNode* right) "
3586 << " return (left->getNodeId() > right->getNodeId());\n"
3590 OS << "inline void setQueued(int Id) {\n";
3591 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
3593 OS << "inline bool isQueued(int Id) {\n";
3594 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
3596 OS << "inline void setSelected(int Id) {\n";
3597 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
3599 OS << "inline bool isSelected(int Id) {\n";
3600 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3603 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
3604 OS << " int Id = N.Val->getNodeId();\n";
3605 OS << " if (Id != -1 && !isQueued(Id)) {\n";
3606 OS << " ISelQueue.push_back(N.Val);\n";
3607 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3608 OS << " setQueued(Id);\n";
3612 OS << "inline void RemoveKilled() {\n";
3613 OS << " unsigned NumKilled = ISelKilled.size();\n";
3614 OS << " if (NumKilled) {\n";
3615 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
3616 OS << " SDNode *Temp = ISelKilled[i];\n";
3617 OS << " std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n";
3619 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3620 OS << " ISelKilled.clear();\n";
3624 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
3625 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n";
3626 OS << " setSelected(F.Val->getNodeId());\n";
3627 OS << " RemoveKilled();\n";
3629 OS << "inline void ReplaceUses(SDNode *F, SDNode *T) {\n";
3630 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3631 OS << " setSelected(F->getNodeId());\n";
3632 OS << " RemoveKilled();\n";
3635 OS << "void DeleteNode(SDNode *N) {\n";
3636 OS << " CurDAG->DeleteNode(N);\n";
3637 OS << " for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); "
3638 << "I != E; ++I) {\n";
3639 OS << " SDNode *Operand = I->Val;\n";
3640 OS << " if (Operand->use_empty())\n";
3641 OS << " DeleteNode(Operand);\n";
3645 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3646 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3647 OS << " SelectRootInit();\n";
3648 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
3649 OS << " ISelQueued = new unsigned char[NumBytes];\n";
3650 OS << " ISelSelected = new unsigned char[NumBytes];\n";
3651 OS << " memset(ISelQueued, 0, NumBytes);\n";
3652 OS << " memset(ISelSelected, 0, NumBytes);\n";
3654 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
3655 << " // a reference to the root node, preventing it from being deleted,\n"
3656 << " // and tracking any changes of the root.\n"
3657 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
3658 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
3659 OS << " while (!ISelQueue.empty()) {\n";
3660 OS << " SDNode *Node = ISelQueue.front();\n";
3661 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3662 OS << " ISelQueue.pop_back();\n";
3663 OS << " if (!isSelected(Node->getNodeId())) {\n";
3664 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
3665 OS << " if (ResNode != Node) {\n";
3666 OS << " if (ResNode)\n";
3667 OS << " ReplaceUses(Node, ResNode);\n";
3668 OS << " if (Node->use_empty()) // Don't delete EntryToken, etc.\n";
3669 OS << " DeleteNode(Node);\n";
3674 OS << " delete[] ISelQueued;\n";
3675 OS << " ISelQueued = NULL;\n";
3676 OS << " delete[] ISelSelected;\n";
3677 OS << " ISelSelected = NULL;\n";
3678 OS << " return Dummy.getValue();\n";
3681 Intrinsics = LoadIntrinsics(Records);
3683 ParseNodeTransforms(OS);
3684 ParseComplexPatterns();
3685 ParsePatternFragments(OS);
3686 ParseInstructions();
3689 // Generate variants. For example, commutative patterns can match
3690 // multiple ways. Add them to PatternsToMatch as well.
3694 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3695 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3696 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3697 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
3701 // At this point, we have full information about the 'Patterns' we need to
3702 // parse, both implicitly from instructions as well as from explicit pattern
3703 // definitions. Emit the resultant instruction selector.
3704 EmitInstructionSelector(OS);
3706 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3707 E = PatternFragments.end(); I != E; ++I)
3709 PatternFragments.clear();
3711 Instructions.clear();