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!");
745 // Apply the result type to the node
746 if (NumResults == 0) {
747 MadeChange = UpdateNodeType(MVT::isVoid, TP);
749 Record *ResultNode = Inst.getResult(0);
750 assert(ResultNode->isSubClassOf("RegisterClass") &&
751 "Operands should be register classes!");
753 const CodeGenRegisterClass &RC =
754 ISE.getTargetInfo().getRegisterClass(ResultNode);
755 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
758 if (getNumChildren() != Inst.getNumOperands())
759 TP.error("Instruction '" + getOperator()->getName() + " expects " +
760 utostr(Inst.getNumOperands()) + " operands, not " +
761 utostr(getNumChildren()) + " operands!");
762 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
763 Record *OperandNode = Inst.getOperand(i);
765 if (OperandNode->isSubClassOf("RegisterClass")) {
766 const CodeGenRegisterClass &RC =
767 ISE.getTargetInfo().getRegisterClass(OperandNode);
768 //VT = RC.getValueTypeNum(0);
769 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
771 } else if (OperandNode->isSubClassOf("Operand")) {
772 VT = getValueType(OperandNode->getValueAsDef("Type"));
773 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
775 assert(0 && "Unknown operand type!");
778 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
782 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
784 // Node transforms always take one operand.
785 if (getNumChildren() != 1)
786 TP.error("Node transform '" + getOperator()->getName() +
787 "' requires one operand!");
789 // If either the output or input of the xform does not have exact
790 // type info. We assume they must be the same. Otherwise, it is perfectly
791 // legal to transform from one type to a completely different type.
792 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
793 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
794 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
801 /// canPatternMatch - If it is impossible for this pattern to match on this
802 /// target, fill in Reason and return false. Otherwise, return true. This is
803 /// used as a santity check for .td files (to prevent people from writing stuff
804 /// that can never possibly work), and to prevent the pattern permuter from
805 /// generating stuff that is useless.
806 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
807 if (isLeaf()) return true;
809 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
810 if (!getChild(i)->canPatternMatch(Reason, ISE))
813 // If this is an intrinsic, handle cases that would make it not match. For
814 // example, if an operand is required to be an immediate.
815 if (getOperator()->isSubClassOf("Intrinsic")) {
820 // If this node is a commutative operator, check that the LHS isn't an
822 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
823 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
824 // Scan all of the operands of the node and make sure that only the last one
825 // is a constant node.
826 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
827 if (!getChild(i)->isLeaf() &&
828 getChild(i)->getOperator()->getName() == "imm") {
829 Reason = "Immediate value must be on the RHS of commutative operators!";
837 //===----------------------------------------------------------------------===//
838 // TreePattern implementation
841 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
842 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
843 isInputPattern = isInput;
844 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
845 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
848 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
849 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
850 isInputPattern = isInput;
851 Trees.push_back(ParseTreePattern(Pat));
854 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
855 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
856 isInputPattern = isInput;
857 Trees.push_back(Pat);
862 void TreePattern::error(const std::string &Msg) const {
864 throw "In " + TheRecord->getName() + ": " + Msg;
867 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
868 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
869 if (!OpDef) error("Pattern has unexpected operator type!");
870 Record *Operator = OpDef->getDef();
872 if (Operator->isSubClassOf("ValueType")) {
873 // If the operator is a ValueType, then this must be "type cast" of a leaf
875 if (Dag->getNumArgs() != 1)
876 error("Type cast only takes one operand!");
878 Init *Arg = Dag->getArg(0);
879 TreePatternNode *New;
880 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
881 Record *R = DI->getDef();
882 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
883 Dag->setArg(0, new DagInit(DI,
884 std::vector<std::pair<Init*, std::string> >()));
885 return ParseTreePattern(Dag);
887 New = new TreePatternNode(DI);
888 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
889 New = ParseTreePattern(DI);
890 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
891 New = new TreePatternNode(II);
892 if (!Dag->getArgName(0).empty())
893 error("Constant int argument should not have a name!");
894 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
895 // Turn this into an IntInit.
896 Init *II = BI->convertInitializerTo(new IntRecTy());
897 if (II == 0 || !dynamic_cast<IntInit*>(II))
898 error("Bits value must be constants!");
900 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
901 if (!Dag->getArgName(0).empty())
902 error("Constant int argument should not have a name!");
905 error("Unknown leaf value for tree pattern!");
909 // Apply the type cast.
910 New->UpdateNodeType(getValueType(Operator), *this);
911 New->setName(Dag->getArgName(0));
915 // Verify that this is something that makes sense for an operator.
916 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
917 !Operator->isSubClassOf("Instruction") &&
918 !Operator->isSubClassOf("SDNodeXForm") &&
919 !Operator->isSubClassOf("Intrinsic") &&
920 Operator->getName() != "set")
921 error("Unrecognized node '" + Operator->getName() + "'!");
923 // Check to see if this is something that is illegal in an input pattern.
924 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
925 Operator->isSubClassOf("SDNodeXForm")))
926 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
928 std::vector<TreePatternNode*> Children;
930 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
931 Init *Arg = Dag->getArg(i);
932 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
933 Children.push_back(ParseTreePattern(DI));
934 if (Children.back()->getName().empty())
935 Children.back()->setName(Dag->getArgName(i));
936 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
937 Record *R = DefI->getDef();
938 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
939 // TreePatternNode if its own.
940 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
941 Dag->setArg(i, new DagInit(DefI,
942 std::vector<std::pair<Init*, std::string> >()));
943 --i; // Revisit this node...
945 TreePatternNode *Node = new TreePatternNode(DefI);
946 Node->setName(Dag->getArgName(i));
947 Children.push_back(Node);
950 if (R->getName() == "node") {
951 if (Dag->getArgName(i).empty())
952 error("'node' argument requires a name to match with operand list");
953 Args.push_back(Dag->getArgName(i));
956 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
957 TreePatternNode *Node = new TreePatternNode(II);
958 if (!Dag->getArgName(i).empty())
959 error("Constant int argument should not have a name!");
960 Children.push_back(Node);
961 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
962 // Turn this into an IntInit.
963 Init *II = BI->convertInitializerTo(new IntRecTy());
964 if (II == 0 || !dynamic_cast<IntInit*>(II))
965 error("Bits value must be constants!");
967 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
968 if (!Dag->getArgName(i).empty())
969 error("Constant int argument should not have a name!");
970 Children.push_back(Node);
975 error("Unknown leaf value for tree pattern!");
979 // If the operator is an intrinsic, then this is just syntactic sugar for for
980 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
981 // convert the intrinsic name to a number.
982 if (Operator->isSubClassOf("Intrinsic")) {
983 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
984 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
986 // If this intrinsic returns void, it must have side-effects and thus a
988 if (Int.ArgVTs[0] == MVT::isVoid) {
989 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
990 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
991 // Has side-effects, requires chain.
992 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
994 // Otherwise, no chain.
995 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
998 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
999 Children.insert(Children.begin(), IIDNode);
1002 return new TreePatternNode(Operator, Children);
1005 /// InferAllTypes - Infer/propagate as many types throughout the expression
1006 /// patterns as possible. Return true if all types are infered, false
1007 /// otherwise. Throw an exception if a type contradiction is found.
1008 bool TreePattern::InferAllTypes() {
1009 bool MadeChange = true;
1010 while (MadeChange) {
1012 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1013 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1016 bool HasUnresolvedTypes = false;
1017 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1018 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1019 return !HasUnresolvedTypes;
1022 void TreePattern::print(std::ostream &OS) const {
1023 OS << getRecord()->getName();
1024 if (!Args.empty()) {
1025 OS << "(" << Args[0];
1026 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1027 OS << ", " << Args[i];
1032 if (Trees.size() > 1)
1034 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1036 Trees[i]->print(OS);
1040 if (Trees.size() > 1)
1044 void TreePattern::dump() const { print(std::cerr); }
1048 //===----------------------------------------------------------------------===//
1049 // DAGISelEmitter implementation
1052 // Parse all of the SDNode definitions for the target, populating SDNodes.
1053 void DAGISelEmitter::ParseNodeInfo() {
1054 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1055 while (!Nodes.empty()) {
1056 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1060 // Get the buildin intrinsic nodes.
1061 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1062 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1063 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1066 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1067 /// map, and emit them to the file as functions.
1068 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1069 OS << "\n// Node transformations.\n";
1070 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1071 while (!Xforms.empty()) {
1072 Record *XFormNode = Xforms.back();
1073 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1074 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1075 SDNodeXForms.insert(std::make_pair(XFormNode,
1076 std::make_pair(SDNode, Code)));
1078 if (!Code.empty()) {
1079 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1080 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1082 OS << "inline SDOperand Transform_" << XFormNode->getName()
1083 << "(SDNode *" << C2 << ") {\n";
1084 if (ClassName != "SDNode")
1085 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1086 OS << Code << "\n}\n";
1093 void DAGISelEmitter::ParseComplexPatterns() {
1094 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1095 while (!AMs.empty()) {
1096 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1102 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1103 /// file, building up the PatternFragments map. After we've collected them all,
1104 /// inline fragments together as necessary, so that there are no references left
1105 /// inside a pattern fragment to a pattern fragment.
1107 /// This also emits all of the predicate functions to the output file.
1109 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1110 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1112 // First step, parse all of the fragments and emit predicate functions.
1113 OS << "\n// Predicate functions.\n";
1114 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1115 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1116 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1117 PatternFragments[Fragments[i]] = P;
1119 // Validate the argument list, converting it to map, to discard duplicates.
1120 std::vector<std::string> &Args = P->getArgList();
1121 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1123 if (OperandsMap.count(""))
1124 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1126 // Parse the operands list.
1127 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1128 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1129 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1130 P->error("Operands list should start with '(ops ... '!");
1132 // Copy over the arguments.
1134 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1135 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1136 static_cast<DefInit*>(OpsList->getArg(j))->
1137 getDef()->getName() != "node")
1138 P->error("Operands list should all be 'node' values.");
1139 if (OpsList->getArgName(j).empty())
1140 P->error("Operands list should have names for each operand!");
1141 if (!OperandsMap.count(OpsList->getArgName(j)))
1142 P->error("'" + OpsList->getArgName(j) +
1143 "' does not occur in pattern or was multiply specified!");
1144 OperandsMap.erase(OpsList->getArgName(j));
1145 Args.push_back(OpsList->getArgName(j));
1148 if (!OperandsMap.empty())
1149 P->error("Operands list does not contain an entry for operand '" +
1150 *OperandsMap.begin() + "'!");
1152 // If there is a code init for this fragment, emit the predicate code and
1153 // keep track of the fact that this fragment uses it.
1154 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1155 if (!Code.empty()) {
1156 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1157 std::string ClassName =
1158 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1159 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1161 OS << "inline bool Predicate_" << Fragments[i]->getName()
1162 << "(SDNode *" << C2 << ") {\n";
1163 if (ClassName != "SDNode")
1164 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1165 OS << Code << "\n}\n";
1166 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1169 // If there is a node transformation corresponding to this, keep track of
1171 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1172 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1173 P->getOnlyTree()->setTransformFn(Transform);
1178 // Now that we've parsed all of the tree fragments, do a closure on them so
1179 // that there are not references to PatFrags left inside of them.
1180 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1181 E = PatternFragments.end(); I != E; ++I) {
1182 TreePattern *ThePat = I->second;
1183 ThePat->InlinePatternFragments();
1185 // Infer as many types as possible. Don't worry about it if we don't infer
1186 // all of them, some may depend on the inputs of the pattern.
1188 ThePat->InferAllTypes();
1190 // If this pattern fragment is not supported by this target (no types can
1191 // satisfy its constraints), just ignore it. If the bogus pattern is
1192 // actually used by instructions, the type consistency error will be
1196 // If debugging, print out the pattern fragment result.
1197 DEBUG(ThePat->dump());
1201 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1202 /// instruction input. Return true if this is a real use.
1203 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1204 std::map<std::string, TreePatternNode*> &InstInputs,
1205 std::vector<Record*> &InstImpInputs) {
1206 // No name -> not interesting.
1207 if (Pat->getName().empty()) {
1208 if (Pat->isLeaf()) {
1209 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1210 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1211 I->error("Input " + DI->getDef()->getName() + " must be named!");
1212 else if (DI && DI->getDef()->isSubClassOf("Register"))
1213 InstImpInputs.push_back(DI->getDef());
1219 if (Pat->isLeaf()) {
1220 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1221 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1224 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1225 Rec = Pat->getOperator();
1228 // SRCVALUE nodes are ignored.
1229 if (Rec->getName() == "srcvalue")
1232 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1237 if (Slot->isLeaf()) {
1238 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1240 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1241 SlotRec = Slot->getOperator();
1244 // Ensure that the inputs agree if we've already seen this input.
1246 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1247 if (Slot->getExtTypes() != Pat->getExtTypes())
1248 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1253 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1254 /// part of "I", the instruction), computing the set of inputs and outputs of
1255 /// the pattern. Report errors if we see anything naughty.
1256 void DAGISelEmitter::
1257 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1258 std::map<std::string, TreePatternNode*> &InstInputs,
1259 std::map<std::string, TreePatternNode*>&InstResults,
1260 std::vector<Record*> &InstImpInputs,
1261 std::vector<Record*> &InstImpResults) {
1262 if (Pat->isLeaf()) {
1263 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1264 if (!isUse && Pat->getTransformFn())
1265 I->error("Cannot specify a transform function for a non-input value!");
1267 } else if (Pat->getOperator()->getName() != "set") {
1268 // If this is not a set, verify that the children nodes are not void typed,
1270 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1271 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1272 I->error("Cannot have void nodes inside of patterns!");
1273 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1274 InstImpInputs, InstImpResults);
1277 // If this is a non-leaf node with no children, treat it basically as if
1278 // it were a leaf. This handles nodes like (imm).
1280 if (Pat->getNumChildren() == 0)
1281 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1283 if (!isUse && Pat->getTransformFn())
1284 I->error("Cannot specify a transform function for a non-input value!");
1288 // Otherwise, this is a set, validate and collect instruction results.
1289 if (Pat->getNumChildren() == 0)
1290 I->error("set requires operands!");
1291 else if (Pat->getNumChildren() & 1)
1292 I->error("set requires an even number of operands");
1294 if (Pat->getTransformFn())
1295 I->error("Cannot specify a transform function on a set node!");
1297 // Check the set destinations.
1298 unsigned NumValues = Pat->getNumChildren()/2;
1299 for (unsigned i = 0; i != NumValues; ++i) {
1300 TreePatternNode *Dest = Pat->getChild(i);
1301 if (!Dest->isLeaf())
1302 I->error("set destination should be a register!");
1304 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1306 I->error("set destination should be a register!");
1308 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1309 if (Dest->getName().empty())
1310 I->error("set destination must have a name!");
1311 if (InstResults.count(Dest->getName()))
1312 I->error("cannot set '" + Dest->getName() +"' multiple times");
1313 InstResults[Dest->getName()] = Dest;
1314 } else if (Val->getDef()->isSubClassOf("Register")) {
1315 InstImpResults.push_back(Val->getDef());
1317 I->error("set destination should be a register!");
1320 // Verify and collect info from the computation.
1321 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1322 InstInputs, InstResults,
1323 InstImpInputs, InstImpResults);
1327 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1328 /// any fragments involved. This populates the Instructions list with fully
1329 /// resolved instructions.
1330 void DAGISelEmitter::ParseInstructions() {
1331 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1333 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1336 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1337 LI = Instrs[i]->getValueAsListInit("Pattern");
1339 // If there is no pattern, only collect minimal information about the
1340 // instruction for its operand list. We have to assume that there is one
1341 // result, as we have no detailed info.
1342 if (!LI || LI->getSize() == 0) {
1343 std::vector<Record*> Results;
1344 std::vector<Record*> Operands;
1346 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1348 if (InstInfo.OperandList.size() != 0) {
1349 // FIXME: temporary hack...
1350 if (InstInfo.noResults) {
1351 // These produce no results
1352 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1353 Operands.push_back(InstInfo.OperandList[j].Rec);
1355 // Assume the first operand is the result.
1356 Results.push_back(InstInfo.OperandList[0].Rec);
1358 // The rest are inputs.
1359 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1360 Operands.push_back(InstInfo.OperandList[j].Rec);
1364 // Create and insert the instruction.
1365 std::vector<Record*> ImpResults;
1366 std::vector<Record*> ImpOperands;
1367 Instructions.insert(std::make_pair(Instrs[i],
1368 DAGInstruction(0, Results, Operands, ImpResults,
1370 continue; // no pattern.
1373 // Parse the instruction.
1374 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1375 // Inline pattern fragments into it.
1376 I->InlinePatternFragments();
1378 // Infer as many types as possible. If we cannot infer all of them, we can
1379 // never do anything with this instruction pattern: report it to the user.
1380 if (!I->InferAllTypes())
1381 I->error("Could not infer all types in pattern!");
1383 // InstInputs - Keep track of all of the inputs of the instruction, along
1384 // with the record they are declared as.
1385 std::map<std::string, TreePatternNode*> InstInputs;
1387 // InstResults - Keep track of all the virtual registers that are 'set'
1388 // in the instruction, including what reg class they are.
1389 std::map<std::string, TreePatternNode*> InstResults;
1391 std::vector<Record*> InstImpInputs;
1392 std::vector<Record*> InstImpResults;
1394 // Verify that the top-level forms in the instruction are of void type, and
1395 // fill in the InstResults map.
1396 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1397 TreePatternNode *Pat = I->getTree(j);
1398 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1399 I->error("Top-level forms in instruction pattern should have"
1402 // Find inputs and outputs, and verify the structure of the uses/defs.
1403 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1404 InstImpInputs, InstImpResults);
1407 // Now that we have inputs and outputs of the pattern, inspect the operands
1408 // list for the instruction. This determines the order that operands are
1409 // added to the machine instruction the node corresponds to.
1410 unsigned NumResults = InstResults.size();
1412 // Parse the operands list from the (ops) list, validating it.
1413 std::vector<std::string> &Args = I->getArgList();
1414 assert(Args.empty() && "Args list should still be empty here!");
1415 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1417 // Check that all of the results occur first in the list.
1418 std::vector<Record*> Results;
1419 TreePatternNode *Res0Node = NULL;
1420 for (unsigned i = 0; i != NumResults; ++i) {
1421 if (i == CGI.OperandList.size())
1422 I->error("'" + InstResults.begin()->first +
1423 "' set but does not appear in operand list!");
1424 const std::string &OpName = CGI.OperandList[i].Name;
1426 // Check that it exists in InstResults.
1427 TreePatternNode *RNode = InstResults[OpName];
1429 I->error("Operand $" + OpName + " does not exist in operand list!");
1433 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1435 I->error("Operand $" + OpName + " should be a set destination: all "
1436 "outputs must occur before inputs in operand list!");
1438 if (CGI.OperandList[i].Rec != R)
1439 I->error("Operand $" + OpName + " class mismatch!");
1441 // Remember the return type.
1442 Results.push_back(CGI.OperandList[i].Rec);
1444 // Okay, this one checks out.
1445 InstResults.erase(OpName);
1448 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1449 // the copy while we're checking the inputs.
1450 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1452 std::vector<TreePatternNode*> ResultNodeOperands;
1453 std::vector<Record*> Operands;
1454 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1455 const std::string &OpName = CGI.OperandList[i].Name;
1457 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1459 if (!InstInputsCheck.count(OpName))
1460 I->error("Operand $" + OpName +
1461 " does not appear in the instruction pattern");
1462 TreePatternNode *InVal = InstInputsCheck[OpName];
1463 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1465 if (InVal->isLeaf() &&
1466 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1467 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1468 if (CGI.OperandList[i].Rec != InRec &&
1469 !InRec->isSubClassOf("ComplexPattern"))
1470 I->error("Operand $" + OpName + "'s register class disagrees"
1471 " between the operand and pattern");
1473 Operands.push_back(CGI.OperandList[i].Rec);
1475 // Construct the result for the dest-pattern operand list.
1476 TreePatternNode *OpNode = InVal->clone();
1478 // No predicate is useful on the result.
1479 OpNode->setPredicateFn("");
1481 // Promote the xform function to be an explicit node if set.
1482 if (Record *Xform = OpNode->getTransformFn()) {
1483 OpNode->setTransformFn(0);
1484 std::vector<TreePatternNode*> Children;
1485 Children.push_back(OpNode);
1486 OpNode = new TreePatternNode(Xform, Children);
1489 ResultNodeOperands.push_back(OpNode);
1492 if (!InstInputsCheck.empty())
1493 I->error("Input operand $" + InstInputsCheck.begin()->first +
1494 " occurs in pattern but not in operands list!");
1496 TreePatternNode *ResultPattern =
1497 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1498 // Copy fully inferred output node type to instruction result pattern.
1500 ResultPattern->setTypes(Res0Node->getExtTypes());
1502 // Create and insert the instruction.
1503 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1504 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1506 // Use a temporary tree pattern to infer all types and make sure that the
1507 // constructed result is correct. This depends on the instruction already
1508 // being inserted into the Instructions map.
1509 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1510 Temp.InferAllTypes();
1512 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1513 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1518 // If we can, convert the instructions to be patterns that are matched!
1519 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1520 E = Instructions.end(); II != E; ++II) {
1521 DAGInstruction &TheInst = II->second;
1522 TreePattern *I = TheInst.getPattern();
1523 if (I == 0) continue; // No pattern.
1525 if (I->getNumTrees() != 1) {
1526 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1529 TreePatternNode *Pattern = I->getTree(0);
1530 TreePatternNode *SrcPattern;
1531 if (Pattern->getOperator()->getName() == "set") {
1532 if (Pattern->getNumChildren() != 2)
1533 continue; // Not a set of a single value (not handled so far)
1535 SrcPattern = Pattern->getChild(1)->clone();
1537 // Not a set (store or something?)
1538 SrcPattern = Pattern;
1542 if (!SrcPattern->canPatternMatch(Reason, *this))
1543 I->error("Instruction can never match: " + Reason);
1545 Record *Instr = II->first;
1546 TreePatternNode *DstPattern = TheInst.getResultPattern();
1548 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1549 SrcPattern, DstPattern,
1550 Instr->getValueAsInt("AddedComplexity")));
1554 void DAGISelEmitter::ParsePatterns() {
1555 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1557 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1558 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1559 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1561 // Inline pattern fragments into it.
1562 Pattern->InlinePatternFragments();
1564 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1565 if (LI->getSize() == 0) continue; // no pattern.
1567 // Parse the instruction.
1568 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1570 // Inline pattern fragments into it.
1571 Result->InlinePatternFragments();
1573 if (Result->getNumTrees() != 1)
1574 Result->error("Cannot handle instructions producing instructions "
1575 "with temporaries yet!");
1577 bool IterateInference;
1578 bool InferredAllPatternTypes, InferredAllResultTypes;
1580 // Infer as many types as possible. If we cannot infer all of them, we
1581 // can never do anything with this pattern: report it to the user.
1582 InferredAllPatternTypes = Pattern->InferAllTypes();
1584 // Infer as many types as possible. If we cannot infer all of them, we can
1585 // never do anything with this pattern: report it to the user.
1586 InferredAllResultTypes = Result->InferAllTypes();
1588 // Apply the type of the result to the source pattern. This helps us
1589 // resolve cases where the input type is known to be a pointer type (which
1590 // is considered resolved), but the result knows it needs to be 32- or
1591 // 64-bits. Infer the other way for good measure.
1592 IterateInference = Pattern->getOnlyTree()->
1593 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1594 IterateInference |= Result->getOnlyTree()->
1595 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1596 } while (IterateInference);
1598 // Verify that we inferred enough types that we can do something with the
1599 // pattern and result. If these fire the user has to add type casts.
1600 if (!InferredAllPatternTypes)
1601 Pattern->error("Could not infer all types in pattern!");
1602 if (!InferredAllResultTypes)
1603 Result->error("Could not infer all types in pattern result!");
1605 // Validate that the input pattern is correct.
1607 std::map<std::string, TreePatternNode*> InstInputs;
1608 std::map<std::string, TreePatternNode*> InstResults;
1609 std::vector<Record*> InstImpInputs;
1610 std::vector<Record*> InstImpResults;
1611 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1612 InstInputs, InstResults,
1613 InstImpInputs, InstImpResults);
1616 // Promote the xform function to be an explicit node if set.
1617 std::vector<TreePatternNode*> ResultNodeOperands;
1618 TreePatternNode *DstPattern = Result->getOnlyTree();
1619 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1620 TreePatternNode *OpNode = DstPattern->getChild(ii);
1621 if (Record *Xform = OpNode->getTransformFn()) {
1622 OpNode->setTransformFn(0);
1623 std::vector<TreePatternNode*> Children;
1624 Children.push_back(OpNode);
1625 OpNode = new TreePatternNode(Xform, Children);
1627 ResultNodeOperands.push_back(OpNode);
1629 DstPattern = Result->getOnlyTree();
1630 if (!DstPattern->isLeaf())
1631 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1632 ResultNodeOperands);
1633 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1634 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1635 Temp.InferAllTypes();
1638 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1639 Pattern->error("Pattern can never match: " + Reason);
1642 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1643 Pattern->getOnlyTree(),
1645 Patterns[i]->getValueAsInt("AddedComplexity")));
1649 /// CombineChildVariants - Given a bunch of permutations of each child of the
1650 /// 'operator' node, put them together in all possible ways.
1651 static void CombineChildVariants(TreePatternNode *Orig,
1652 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1653 std::vector<TreePatternNode*> &OutVariants,
1654 DAGISelEmitter &ISE) {
1655 // Make sure that each operand has at least one variant to choose from.
1656 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1657 if (ChildVariants[i].empty())
1660 // The end result is an all-pairs construction of the resultant pattern.
1661 std::vector<unsigned> Idxs;
1662 Idxs.resize(ChildVariants.size());
1663 bool NotDone = true;
1665 // Create the variant and add it to the output list.
1666 std::vector<TreePatternNode*> NewChildren;
1667 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1668 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1669 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1671 // Copy over properties.
1672 R->setName(Orig->getName());
1673 R->setPredicateFn(Orig->getPredicateFn());
1674 R->setTransformFn(Orig->getTransformFn());
1675 R->setTypes(Orig->getExtTypes());
1677 // If this pattern cannot every match, do not include it as a variant.
1678 std::string ErrString;
1679 if (!R->canPatternMatch(ErrString, ISE)) {
1682 bool AlreadyExists = false;
1684 // Scan to see if this pattern has already been emitted. We can get
1685 // duplication due to things like commuting:
1686 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1687 // which are the same pattern. Ignore the dups.
1688 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1689 if (R->isIsomorphicTo(OutVariants[i])) {
1690 AlreadyExists = true;
1697 OutVariants.push_back(R);
1700 // Increment indices to the next permutation.
1702 // Look for something we can increment without causing a wrap-around.
1703 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1704 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1705 NotDone = true; // Found something to increment.
1713 /// CombineChildVariants - A helper function for binary operators.
1715 static void CombineChildVariants(TreePatternNode *Orig,
1716 const std::vector<TreePatternNode*> &LHS,
1717 const std::vector<TreePatternNode*> &RHS,
1718 std::vector<TreePatternNode*> &OutVariants,
1719 DAGISelEmitter &ISE) {
1720 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1721 ChildVariants.push_back(LHS);
1722 ChildVariants.push_back(RHS);
1723 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1727 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1728 std::vector<TreePatternNode *> &Children) {
1729 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1730 Record *Operator = N->getOperator();
1732 // Only permit raw nodes.
1733 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1734 N->getTransformFn()) {
1735 Children.push_back(N);
1739 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1740 Children.push_back(N->getChild(0));
1742 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1744 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1745 Children.push_back(N->getChild(1));
1747 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1750 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1751 /// the (potentially recursive) pattern by using algebraic laws.
1753 static void GenerateVariantsOf(TreePatternNode *N,
1754 std::vector<TreePatternNode*> &OutVariants,
1755 DAGISelEmitter &ISE) {
1756 // We cannot permute leaves.
1758 OutVariants.push_back(N);
1762 // Look up interesting info about the node.
1763 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1765 // If this node is associative, reassociate.
1766 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1767 // Reassociate by pulling together all of the linked operators
1768 std::vector<TreePatternNode*> MaximalChildren;
1769 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1771 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1773 if (MaximalChildren.size() == 3) {
1774 // Find the variants of all of our maximal children.
1775 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1776 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1777 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1778 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1780 // There are only two ways we can permute the tree:
1781 // (A op B) op C and A op (B op C)
1782 // Within these forms, we can also permute A/B/C.
1784 // Generate legal pair permutations of A/B/C.
1785 std::vector<TreePatternNode*> ABVariants;
1786 std::vector<TreePatternNode*> BAVariants;
1787 std::vector<TreePatternNode*> ACVariants;
1788 std::vector<TreePatternNode*> CAVariants;
1789 std::vector<TreePatternNode*> BCVariants;
1790 std::vector<TreePatternNode*> CBVariants;
1791 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1792 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1793 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1794 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1795 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1796 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1798 // Combine those into the result: (x op x) op x
1799 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1800 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1801 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1802 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1803 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1804 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1806 // Combine those into the result: x op (x op x)
1807 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1808 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1809 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1810 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1811 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1812 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1817 // Compute permutations of all children.
1818 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1819 ChildVariants.resize(N->getNumChildren());
1820 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1821 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1823 // Build all permutations based on how the children were formed.
1824 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1826 // If this node is commutative, consider the commuted order.
1827 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1828 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1829 // Consider the commuted order.
1830 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1836 // GenerateVariants - Generate variants. For example, commutative patterns can
1837 // match multiple ways. Add them to PatternsToMatch as well.
1838 void DAGISelEmitter::GenerateVariants() {
1840 DEBUG(std::cerr << "Generating instruction variants.\n");
1842 // Loop over all of the patterns we've collected, checking to see if we can
1843 // generate variants of the instruction, through the exploitation of
1844 // identities. This permits the target to provide agressive matching without
1845 // the .td file having to contain tons of variants of instructions.
1847 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1848 // intentionally do not reconsider these. Any variants of added patterns have
1849 // already been added.
1851 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1852 std::vector<TreePatternNode*> Variants;
1853 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1855 assert(!Variants.empty() && "Must create at least original variant!");
1856 Variants.erase(Variants.begin()); // Remove the original pattern.
1858 if (Variants.empty()) // No variants for this pattern.
1861 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1862 PatternsToMatch[i].getSrcPattern()->dump();
1865 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1866 TreePatternNode *Variant = Variants[v];
1868 DEBUG(std::cerr << " VAR#" << v << ": ";
1872 // Scan to see if an instruction or explicit pattern already matches this.
1873 bool AlreadyExists = false;
1874 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1875 // Check to see if this variant already exists.
1876 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1877 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1878 AlreadyExists = true;
1882 // If we already have it, ignore the variant.
1883 if (AlreadyExists) continue;
1885 // Otherwise, add it to the list of patterns we have.
1887 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1888 Variant, PatternsToMatch[i].getDstPattern(),
1889 PatternsToMatch[i].getAddedComplexity()));
1892 DEBUG(std::cerr << "\n");
1897 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1899 static bool NodeIsComplexPattern(TreePatternNode *N)
1901 return (N->isLeaf() &&
1902 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1903 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1904 isSubClassOf("ComplexPattern"));
1907 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1908 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1909 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1910 DAGISelEmitter &ISE)
1913 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1914 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1915 isSubClassOf("ComplexPattern")) {
1916 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1922 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1923 /// patterns before small ones. This is used to determine the size of a
1925 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1926 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1927 isExtFloatingPointInVTs(P->getExtTypes()) ||
1928 P->getExtTypeNum(0) == MVT::isVoid ||
1929 P->getExtTypeNum(0) == MVT::Flag ||
1930 P->getExtTypeNum(0) == MVT::iPTR) &&
1931 "Not a valid pattern node to size!");
1932 unsigned Size = 2; // The node itself.
1933 // If the root node is a ConstantSDNode, increases its size.
1934 // e.g. (set R32:$dst, 0).
1935 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1938 // FIXME: This is a hack to statically increase the priority of patterns
1939 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1940 // Later we can allow complexity / cost for each pattern to be (optionally)
1941 // specified. To get best possible pattern match we'll need to dynamically
1942 // calculate the complexity of all patterns a dag can potentially map to.
1943 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1945 Size += AM->getNumOperands() * 2;
1947 // If this node has some predicate function that must match, it adds to the
1948 // complexity of this node.
1949 if (!P->getPredicateFn().empty())
1952 // Count children in the count if they are also nodes.
1953 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1954 TreePatternNode *Child = P->getChild(i);
1955 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1956 Size += getPatternSize(Child, ISE);
1957 else if (Child->isLeaf()) {
1958 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1959 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
1960 else if (NodeIsComplexPattern(Child))
1961 Size += getPatternSize(Child, ISE);
1962 else if (!Child->getPredicateFn().empty())
1970 /// getResultPatternCost - Compute the number of instructions for this pattern.
1971 /// This is a temporary hack. We should really include the instruction
1972 /// latencies in this calculation.
1973 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1974 if (P->isLeaf()) return 0;
1977 Record *Op = P->getOperator();
1978 if (Op->isSubClassOf("Instruction")) {
1980 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1981 if (II.usesCustomDAGSchedInserter)
1984 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1985 Cost += getResultPatternCost(P->getChild(i), ISE);
1989 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1990 // In particular, we want to match maximal patterns first and lowest cost within
1991 // a particular complexity first.
1992 struct PatternSortingPredicate {
1993 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1994 DAGISelEmitter &ISE;
1996 bool operator()(PatternToMatch *LHS,
1997 PatternToMatch *RHS) {
1998 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1999 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
2000 LHSSize += LHS->getAddedComplexity();
2001 RHSSize += RHS->getAddedComplexity();
2002 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2003 if (LHSSize < RHSSize) return false;
2005 // If the patterns have equal complexity, compare generated instruction cost
2006 return getResultPatternCost(LHS->getDstPattern(), ISE) <
2007 getResultPatternCost(RHS->getDstPattern(), ISE);
2011 /// getRegisterValueType - Look up and return the first ValueType of specified
2012 /// RegisterClass record
2013 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
2014 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2015 return RC->getValueTypeNum(0);
2020 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2021 /// type information from it.
2022 static void RemoveAllTypes(TreePatternNode *N) {
2025 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2026 RemoveAllTypes(N->getChild(i));
2029 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2030 Record *N = Records.getDef(Name);
2031 if (!N || !N->isSubClassOf("SDNode")) {
2032 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2038 /// NodeHasProperty - return true if TreePatternNode has the specified
2040 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2041 DAGISelEmitter &ISE)
2043 if (N->isLeaf()) return false;
2044 Record *Operator = N->getOperator();
2045 if (!Operator->isSubClassOf("SDNode")) return false;
2047 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2048 return NodeInfo.hasProperty(Property);
2051 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2052 DAGISelEmitter &ISE)
2054 if (NodeHasProperty(N, Property, ISE))
2057 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2058 TreePatternNode *Child = N->getChild(i);
2059 if (PatternHasProperty(Child, Property, ISE))
2066 class PatternCodeEmitter {
2068 DAGISelEmitter &ISE;
2071 ListInit *Predicates;
2074 // Instruction selector pattern.
2075 TreePatternNode *Pattern;
2076 // Matched instruction.
2077 TreePatternNode *Instruction;
2079 // Node to name mapping
2080 std::map<std::string, std::string> VariableMap;
2081 // Node to operator mapping
2082 std::map<std::string, Record*> OperatorMap;
2083 // Names of all the folded nodes which produce chains.
2084 std::vector<std::pair<std::string, unsigned> > FoldedChains;
2085 std::set<std::string> Duplicates;
2086 /// These nodes are being marked "in-flight" so they cannot be folded.
2087 std::vector<std::string> InflightNodes;
2089 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2090 /// indicates whether this is an exit predicate (something that should be
2091 /// tested, and if true, the match fails) [when true] or normal code to emit
2093 std::vector<std::pair<bool, std::string> > &GeneratedCode;
2094 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2095 /// the set of patterns for each top-level opcode.
2096 std::set<std::pair<unsigned, std::string> > &GeneratedDecl;
2097 /// TargetOpcodes - The target specific opcodes used by the resulting
2099 std::vector<std::string> &TargetOpcodes;
2100 std::vector<std::string> &TargetVTs;
2102 std::string ChainName;
2109 void emitCheck(const std::string &S) {
2111 GeneratedCode.push_back(std::make_pair(true, S));
2113 void emitCode(const std::string &S) {
2115 GeneratedCode.push_back(std::make_pair(false, S));
2117 void emitDecl(const std::string &S, unsigned T=0) {
2118 assert(!S.empty() && "Invalid declaration");
2119 GeneratedDecl.insert(std::make_pair(T, S));
2121 void emitOpcode(const std::string &Opc) {
2122 TargetOpcodes.push_back(Opc);
2125 void emitVT(const std::string &VT) {
2126 TargetVTs.push_back(VT);
2130 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2131 TreePatternNode *pattern, TreePatternNode *instr,
2132 std::vector<std::pair<bool, std::string> > &gc,
2133 std::set<std::pair<unsigned, std::string> > &gd,
2134 std::vector<std::string> &to,
2135 std::vector<std::string> &tv,
2137 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2138 GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to), TargetVTs(tv),
2139 NewTF(false), DoReplace(dorep), TmpNo(0), OpcNo(0), VTNo(0) {}
2141 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2142 /// if the match fails. At this point, we already know that the opcode for N
2143 /// matches, and the SDNode for the result has the RootName specified name.
2144 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2145 const std::string &RootName, const std::string &ParentName,
2146 const std::string &ChainSuffix, bool &FoundChain) {
2147 bool isRoot = (P == NULL);
2148 // Emit instruction predicates. Each predicate is just a string for now.
2150 std::string PredicateCheck;
2151 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2152 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2153 Record *Def = Pred->getDef();
2154 if (!Def->isSubClassOf("Predicate")) {
2158 assert(0 && "Unknown predicate type!");
2160 if (!PredicateCheck.empty())
2161 PredicateCheck += " || ";
2162 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2166 emitCheck(PredicateCheck);
2170 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2171 emitCheck("cast<ConstantSDNode>(" + RootName +
2172 ")->getSignExtended() == " + itostr(II->getValue()));
2174 } else if (!NodeIsComplexPattern(N)) {
2175 assert(0 && "Cannot match this as a leaf value!");
2180 // If this node has a name associated with it, capture it in VariableMap. If
2181 // we already saw this in the pattern, emit code to verify dagness.
2182 if (!N->getName().empty()) {
2183 std::string &VarMapEntry = VariableMap[N->getName()];
2184 if (VarMapEntry.empty()) {
2185 VarMapEntry = RootName;
2187 // If we get here, this is a second reference to a specific name. Since
2188 // we already have checked that the first reference is valid, we don't
2189 // have to recursively match it, just check that it's the same as the
2190 // previously named thing.
2191 emitCheck(VarMapEntry + " == " + RootName);
2196 OperatorMap[N->getName()] = N->getOperator();
2200 // Emit code to load the child nodes and match their contents recursively.
2202 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2203 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2204 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
2205 bool EmittedUseCheck = false;
2206 bool EmittedSlctedCheck = false;
2211 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2213 emitCheck("InFlightSet.count(" + RootName + ".Val) == 0");
2214 // Multiple uses of actual result?
2215 emitCheck(RootName + ".hasOneUse()");
2216 EmittedUseCheck = true;
2217 // hasOneUse() check is not strong enough. If the original node has
2218 // already been selected, it may have been replaced with another.
2219 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2220 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2223 EmittedSlctedCheck = true;
2225 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2227 // This a workaround for this problem:
2232 // [XX]--/ \- [flag : cmp]
2237 // cmp + br should be considered as a single node as they are flagged
2238 // together. So, if the ld is folded into the cmp, the XX node in the
2239 // graph is now both an operand and a use of the ld/cmp/br node.
2240 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2241 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2243 // If the immediate use can somehow reach this node through another
2244 // path, then can't fold it either or it will create a cycle.
2245 // e.g. In the following diagram, XX can reach ld through YY. If
2246 // ld is folded into XX, then YY is both a predecessor and a successor
2256 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2257 if (PInfo.getNumOperands() > 1 ||
2258 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2259 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2260 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2261 if (PInfo.getNumOperands() > 1) {
2262 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2265 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2266 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2273 ChainName = "Chain" + ChainSuffix;
2274 emitDecl(ChainName);
2276 // FIXME: temporary workaround for a common case where chain
2277 // is a TokenFactor and the previous "inner" chain is an operand.
2279 emitDecl("OldTF", 1);
2280 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2281 RootName + ".Val, Chain.Val, OldTF)).Val");
2284 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2289 // Don't fold any node which reads or writes a flag and has multiple uses.
2290 // FIXME: We really need to separate the concepts of flag and "glue". Those
2291 // real flag results, e.g. X86CMP output, can have multiple uses.
2292 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2295 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2296 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2297 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2298 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2299 if (!EmittedUseCheck) {
2300 // Multiple uses of actual result?
2301 emitCheck(RootName + ".hasOneUse()");
2303 if (!EmittedSlctedCheck)
2304 // hasOneUse() check is not strong enough. If the original node has
2305 // already been selected, it may have been replaced with another.
2306 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2307 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2311 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2312 emitDecl(RootName + utostr(OpNo));
2313 emitCode(RootName + utostr(OpNo) + " = " +
2314 RootName + ".getOperand(" +utostr(OpNo) + ");");
2315 TreePatternNode *Child = N->getChild(i);
2317 if (!Child->isLeaf()) {
2318 // If it's not a leaf, recursively match.
2319 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2320 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2321 CInfo.getEnumName());
2322 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2323 ChainSuffix + utostr(OpNo), FoundChain);
2324 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2325 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2326 CInfo.getNumResults()));
2328 // If this child has a name associated with it, capture it in VarMap. If
2329 // we already saw this in the pattern, emit code to verify dagness.
2330 if (!Child->getName().empty()) {
2331 std::string &VarMapEntry = VariableMap[Child->getName()];
2332 if (VarMapEntry.empty()) {
2333 VarMapEntry = RootName + utostr(OpNo);
2335 // If we get here, this is a second reference to a specific name.
2336 // Since we already have checked that the first reference is valid,
2337 // we don't have to recursively match it, just check that it's the
2338 // same as the previously named thing.
2339 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2340 Duplicates.insert(RootName + utostr(OpNo));
2345 // Handle leaves of various types.
2346 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2347 Record *LeafRec = DI->getDef();
2348 if (LeafRec->isSubClassOf("RegisterClass")) {
2349 // Handle register references. Nothing to do here.
2350 } else if (LeafRec->isSubClassOf("Register")) {
2351 // Handle register references.
2352 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2353 // Handle complex pattern. Nothing to do here.
2354 } else if (LeafRec->getName() == "srcvalue") {
2355 // Place holder for SRCVALUE nodes. Nothing to do here.
2356 } else if (LeafRec->isSubClassOf("ValueType")) {
2357 // Make sure this is the specified value type.
2358 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2359 ")->getVT() == MVT::" + LeafRec->getName());
2360 } else if (LeafRec->isSubClassOf("CondCode")) {
2361 // Make sure this is the specified cond code.
2362 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2363 ")->get() == ISD::" + LeafRec->getName());
2369 assert(0 && "Unknown leaf type!");
2371 } else if (IntInit *II =
2372 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2373 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2374 unsigned CTmp = TmpNo++;
2375 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2376 RootName + utostr(OpNo) + ")->getSignExtended();");
2378 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2383 assert(0 && "Unknown leaf type!");
2388 // If there is a node predicate for this, emit the call.
2389 if (!N->getPredicateFn().empty())
2390 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2393 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2394 /// we actually have to build a DAG!
2395 std::pair<unsigned, unsigned>
2396 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2397 bool isRoot = false) {
2398 // This is something selected from the pattern we matched.
2399 if (!N->getName().empty()) {
2400 std::string &Val = VariableMap[N->getName()];
2401 assert(!Val.empty() &&
2402 "Variable referenced but not defined and not caught earlier!");
2403 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2404 // Already selected this operand, just return the tmpval.
2405 return std::make_pair(1, atoi(Val.c_str()+3));
2408 const ComplexPattern *CP;
2409 unsigned ResNo = TmpNo++;
2410 unsigned NumRes = 1;
2411 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2412 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2413 std::string CastType;
2414 switch (N->getTypeNum(0)) {
2415 default: assert(0 && "Unknown type for constant node!");
2416 case MVT::i1: CastType = "bool"; break;
2417 case MVT::i8: CastType = "unsigned char"; break;
2418 case MVT::i16: CastType = "unsigned short"; break;
2419 case MVT::i32: CastType = "unsigned"; break;
2420 case MVT::i64: CastType = "uint64_t"; break;
2422 emitDecl("Tmp" + utostr(ResNo));
2423 emitCode("Tmp" + utostr(ResNo) +
2424 " = CurDAG->getTargetConstant(((" + CastType +
2425 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2426 getEnumName(N->getTypeNum(0)) + ");");
2427 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2428 Record *Op = OperatorMap[N->getName()];
2429 // Transform ExternalSymbol to TargetExternalSymbol
2430 if (Op && Op->getName() == "externalsym") {
2431 emitDecl("Tmp" + utostr(ResNo));
2432 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2433 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2434 Val + ")->getSymbol(), " +
2435 getEnumName(N->getTypeNum(0)) + ");");
2437 emitDecl("Tmp" + utostr(ResNo));
2438 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2440 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2441 Record *Op = OperatorMap[N->getName()];
2442 // Transform GlobalAddress to TargetGlobalAddress
2443 if (Op && Op->getName() == "globaladdr") {
2444 emitDecl("Tmp" + utostr(ResNo));
2445 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2446 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2447 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2450 emitDecl("Tmp" + utostr(ResNo));
2451 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2453 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2454 emitDecl("Tmp" + utostr(ResNo));
2455 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2456 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2457 emitDecl("Tmp" + utostr(ResNo));
2458 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2459 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2460 std::string Fn = CP->getSelectFunc();
2461 NumRes = CP->getNumOperands();
2462 for (unsigned i = 0; i < NumRes; ++i)
2463 emitDecl("CPTmp" + utostr(i+ResNo));
2465 std::string Code = "bool Match = " + Fn + "(" + Val;
2466 for (unsigned i = 0; i < NumRes; i++)
2467 Code += ", CPTmp" + utostr(i + ResNo);
2468 emitCode(Code + ");");
2469 if (InflightNodes.size()) {
2470 // Remove the in-flight nodes if the ComplexPattern does not match!
2471 emitCode("if (!Match) {");
2472 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2473 AE = InflightNodes.end(); AI != AE; ++AI)
2474 emitCode(" SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " +
2481 for (unsigned i = 0; i < NumRes; ++i) {
2482 emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, CPTmp" +
2483 utostr(i+ResNo) + ".Val);");
2484 InflightNodes.push_back("CPTmp" + utostr(i+ResNo));
2486 for (unsigned i = 0; i < NumRes; ++i) {
2487 emitDecl("Tmp" + utostr(i+ResNo));
2488 emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" +
2489 utostr(i+ResNo) + ");");
2492 TmpNo = ResNo + NumRes;
2494 emitDecl("Tmp" + utostr(ResNo));
2495 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2496 // node even if it isn't one. Don't select it.
2498 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2500 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2503 if (isRoot && N->isLeaf()) {
2504 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2505 emitCode("return;");
2508 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2509 // value if used multiple times by this pattern result.
2510 Val = "Tmp"+utostr(ResNo);
2511 return std::make_pair(NumRes, ResNo);
2514 // If this is an explicit register reference, handle it.
2515 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2516 unsigned ResNo = TmpNo++;
2517 if (DI->getDef()->isSubClassOf("Register")) {
2518 emitDecl("Tmp" + utostr(ResNo));
2519 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2520 ISE.getQualifiedName(DI->getDef()) + ", " +
2521 getEnumName(N->getTypeNum(0)) + ");");
2522 return std::make_pair(1, ResNo);
2524 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2525 unsigned ResNo = TmpNo++;
2526 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2527 emitDecl("Tmp" + utostr(ResNo));
2528 emitCode("Tmp" + utostr(ResNo) +
2529 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2530 ", " + getEnumName(N->getTypeNum(0)) + ");");
2531 return std::make_pair(1, ResNo);
2537 assert(0 && "Unknown leaf type!");
2538 return std::make_pair(1, ~0U);
2541 Record *Op = N->getOperator();
2542 if (Op->isSubClassOf("Instruction")) {
2543 const CodeGenTarget &CGT = ISE.getTargetInfo();
2544 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2545 const DAGInstruction &Inst = ISE.getInstruction(Op);
2546 TreePattern *InstPat = Inst.getPattern();
2547 TreePatternNode *InstPatNode =
2548 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2549 : (InstPat ? InstPat->getOnlyTree() : NULL);
2550 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2551 InstPatNode = InstPatNode->getChild(1);
2553 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
2554 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2555 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2556 bool NodeHasOptInFlag = isRoot &&
2557 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2558 bool NodeHasInFlag = isRoot &&
2559 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2560 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2561 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2562 bool NodeHasChain = InstPatNode &&
2563 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
2564 bool InputHasChain = isRoot &&
2565 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2567 if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
2569 if (NodeHasOptInFlag) {
2570 emitDecl("HasInFlag", 2);
2571 emitCode("HasInFlag = "
2572 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
2575 emitCode("std::vector<SDOperand> Ops;");
2577 // How many results is this pattern expected to produce?
2578 unsigned PatResults = 0;
2579 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2580 MVT::ValueType VT = Pattern->getTypeNum(i);
2581 if (VT != MVT::isVoid && VT != MVT::Flag)
2585 // Determine operand emission order. Complex pattern first.
2586 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2587 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2588 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2589 TreePatternNode *Child = N->getChild(i);
2591 EmitOrder.push_back(std::make_pair(i, Child));
2592 OI = EmitOrder.begin();
2593 } else if (NodeIsComplexPattern(Child)) {
2594 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2596 EmitOrder.push_back(std::make_pair(i, Child));
2600 // Make sure these operands which would be selected won't be folded while
2601 // the isel traverses the DAG upward.
2602 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2603 TreePatternNode *Child = EmitOrder[i].second;
2604 if (!Child->getName().empty()) {
2605 std::string &Val = VariableMap[Child->getName()];
2606 assert(!Val.empty() &&
2607 "Variable referenced but not defined and not caught earlier!");
2608 if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) {
2609 emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, " +
2611 InflightNodes.push_back(Val);
2616 // Emit all of the operands.
2617 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2618 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2619 unsigned OpOrder = EmitOrder[i].first;
2620 TreePatternNode *Child = EmitOrder[i].second;
2621 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2622 NumTemps[OpOrder] = NumTemp;
2625 // List all the operands in the right order.
2626 std::vector<unsigned> Ops;
2627 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2628 for (unsigned j = 0; j < NumTemps[i].first; j++)
2629 Ops.push_back(NumTemps[i].second + j);
2632 // Emit all the chain and CopyToReg stuff.
2633 bool ChainEmitted = NodeHasChain;
2635 emitCode("Select(" + ChainName + ", " + ChainName + ");");
2636 if (NodeHasInFlag || HasImpInputs)
2637 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2638 if (NodeHasOptInFlag) {
2639 emitCode("if (HasInFlag)");
2640 emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));");
2644 // The operands have been selected. Remove them from InFlightSet.
2645 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2646 AE = InflightNodes.end(); AI != AE; ++AI)
2647 emitCode("SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " +
2651 unsigned NumResults = Inst.getNumResults();
2652 unsigned ResNo = TmpNo++;
2653 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2657 std::string NodeName;
2659 NodeName = "Tmp" + utostr(ResNo);
2661 Code2 = NodeName + " = SDOperand(";
2663 NodeName = "ResNode";
2664 emitDecl(NodeName, true);
2665 Code2 = NodeName + " = ";
2667 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2668 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2670 // Output order: results, chain, flags
2672 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2673 Code += ", VT" + utostr(VTNo);
2674 emitVT(getEnumName(N->getTypeNum(0)));
2677 Code += ", MVT::Other";
2679 Code += ", MVT::Flag";
2682 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2684 emitCode("Ops.push_back(Tmp" + utostr(Ops[i]) + ");");
2686 Code += ", Tmp" + utostr(Ops[i]);
2690 if (NodeHasInFlag || HasImpInputs)
2691 emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2693 else if (NodeHasOptInFlag)
2694 emitCode("for (unsigned i = 2, e = N.getNumOperands()-"
2695 "(HasInFlag?1:0); i != e; ++i) {");
2697 emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2699 emitCode(" SDOperand VarOp(0, 0);");
2700 emitCode(" Select(VarOp, N.getOperand(i));");
2701 emitCode(" Ops.push_back(VarOp);");
2707 emitCode("Ops.push_back(" + ChainName + ");");
2709 Code += ", " + ChainName;
2711 if (NodeHasInFlag || HasImpInputs) {
2713 emitCode("Ops.push_back(InFlag);");
2716 } else if (NodeHasOptInFlag && HasVarOps) {
2717 emitCode("if (HasInFlag)");
2718 emitCode(" Ops.push_back(InFlag);");
2723 else if (NodeHasOptInFlag)
2724 Code = "HasInFlag ? " + Code + ", InFlag) : " + Code;
2728 emitCode(Code2 + Code + ");");
2731 // Remember which op produces the chain.
2733 emitCode(ChainName + " = SDOperand(" + NodeName +
2734 ".Val, " + utostr(PatResults) + ");");
2736 emitCode(ChainName + " = SDOperand(" + NodeName +
2737 ", " + utostr(PatResults) + ");");
2740 return std::make_pair(1, ResNo);
2743 emitCode("if (OldTF) "
2744 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2745 ChainName + ".Val, 0);");
2747 for (unsigned i = 0; i < NumResults; i++)
2748 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2749 utostr(i) + ", ResNode, " + utostr(i) + ");");
2752 emitCode("InFlag = SDOperand(ResNode, " +
2753 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2755 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2756 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2761 if (InputHasChain) {
2762 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2763 utostr(PatResults) + ", " + ChainName + ".Val, " +
2764 ChainName + ".ResNo" + ");");
2766 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2767 utostr(PatResults) + ", " + ChainName + ".Val, " +
2768 ChainName + ".ResNo" + ");");
2771 if (FoldedChains.size() > 0) {
2773 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2774 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2775 FoldedChains[j].first + ".Val, " +
2776 utostr(FoldedChains[j].second) + ", ResNode, " +
2777 utostr(NumResults) + ");");
2779 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2781 FoldedChains[j].first + ".Val, " +
2782 utostr(FoldedChains[j].second) + ", ";
2783 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2784 utostr(NumResults) + ");");
2789 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2790 utostr(PatResults + (unsigned)InputHasChain) +
2791 ", InFlag.Val, InFlag.ResNo);");
2793 // User does not expect the instruction would produce a chain!
2794 bool AddedChain = NodeHasChain && !InputHasChain;
2795 if (AddedChain && NodeHasOutFlag) {
2796 if (PatResults == 0) {
2797 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2799 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2800 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2802 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
2804 } else if (InputHasChain && !NodeHasChain) {
2805 // One of the inner node produces a chain.
2806 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2807 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2808 if (NodeHasOutFlag) {
2809 emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2810 emitCode(" Result = SDOperand(ResNode, N.ResNo-1);");
2813 emitCode(" Result = SDOperand(" + ChainName + ".Val, " +
2814 ChainName + ".ResNo);");
2816 emitCode("Result = SDOperand(ResNode, N.ResNo);");
2819 // If this instruction is the root, and if there is only one use of it,
2820 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2821 emitCode("if (N.Val->hasOneUse()) {");
2822 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, Opc" +
2824 if (N->getTypeNum(0) != MVT::isVoid)
2825 Code += ", VT" + utostr(VTNo);
2827 Code += ", MVT::Flag";
2828 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2829 Code += ", Tmp" + utostr(Ops[i]);
2830 if (NodeHasInFlag || HasImpInputs)
2832 emitCode(Code + ");");
2833 emitCode("} else {");
2834 emitDecl("ResNode", 1);
2835 Code = " ResNode = CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2836 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2837 if (N->getTypeNum(0) != MVT::isVoid) {
2838 Code += ", VT" + utostr(VTNo);
2839 emitVT(getEnumName(N->getTypeNum(0)));
2842 Code += ", MVT::Flag";
2843 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2844 Code += ", Tmp" + utostr(Ops[i]);
2845 if (NodeHasInFlag || HasImpInputs)
2847 emitCode(Code + ");");
2848 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo"
2850 emitCode(" Result = SDOperand(ResNode, 0);");
2855 emitCode("return;");
2856 return std::make_pair(1, ResNo);
2857 } else if (Op->isSubClassOf("SDNodeXForm")) {
2858 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2859 // PatLeaf node - the operand may or may not be a leaf node. But it should
2861 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2862 unsigned ResNo = TmpNo++;
2863 emitDecl("Tmp" + utostr(ResNo));
2864 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2865 + "(Tmp" + utostr(OpVal) + ".Val);");
2867 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2868 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2869 utostr(ResNo) + ".ResNo);");
2870 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2871 emitCode("return;");
2873 return std::make_pair(1, ResNo);
2877 throw std::string("Unknown node in result pattern!");
2881 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2882 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2883 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2884 /// for, this returns true otherwise false if Pat has all types.
2885 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2886 const std::string &Prefix) {
2888 if (Pat->getExtTypes() != Other->getExtTypes()) {
2889 // Move a type over from 'other' to 'pat'.
2890 Pat->setTypes(Other->getExtTypes());
2891 emitCheck(Prefix + ".Val->getValueType(0) == " +
2892 getName(Pat->getTypeNum(0)));
2897 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2898 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2899 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2900 Prefix + utostr(OpNo)))
2906 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2908 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2909 bool &ChainEmitted, bool isRoot = false) {
2910 const CodeGenTarget &T = ISE.getTargetInfo();
2912 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2913 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2914 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2915 TreePatternNode *Child = N->getChild(i);
2916 if (!Child->isLeaf()) {
2917 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2919 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2920 if (!Child->getName().empty()) {
2921 std::string Name = RootName + utostr(OpNo);
2922 if (Duplicates.find(Name) != Duplicates.end())
2923 // A duplicate! Do not emit a copy for this node.
2927 Record *RR = DI->getDef();
2928 if (RR->isSubClassOf("Register")) {
2929 MVT::ValueType RVT = getRegisterValueType(RR, T);
2930 if (RVT == MVT::Flag) {
2931 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2933 if (!ChainEmitted) {
2935 emitCode("Chain = CurDAG->getEntryNode();");
2936 ChainName = "Chain";
2937 ChainEmitted = true;
2939 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2940 RootName + utostr(OpNo) + ");");
2941 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2942 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2943 ", " + getEnumName(RVT) + "), " +
2944 RootName + utostr(OpNo) + ", InFlag).Val;");
2945 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2946 emitCode("InFlag = SDOperand(ResNode, 1);");
2954 emitCode("Select(InFlag, " + RootName +
2955 ".getOperand(" + utostr(OpNo) + "));");
2958 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2959 /// as specified by the instruction. It returns true if any copy is
2961 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2962 bool RetVal = false;
2963 Record *Op = N->getOperator();
2964 if (Op->isSubClassOf("Instruction")) {
2965 const DAGInstruction &Inst = ISE.getInstruction(Op);
2966 const CodeGenTarget &CGT = ISE.getTargetInfo();
2967 unsigned NumImpResults = Inst.getNumImpResults();
2968 for (unsigned i = 0; i < NumImpResults; i++) {
2969 Record *RR = Inst.getImpResult(i);
2970 if (RR->isSubClassOf("Register")) {
2971 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2972 if (RVT != MVT::Flag) {
2973 if (!ChainEmitted) {
2975 emitCode("Chain = CurDAG->getEntryNode();");
2976 ChainEmitted = true;
2977 ChainName = "Chain";
2979 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName +
2980 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
2982 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2983 emitCode("InFlag = SDOperand(ResNode, 2);");
2993 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2994 /// stream to match the pattern, and generate the code for the match if it
2995 /// succeeds. Returns true if the pattern is not guaranteed to match.
2996 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2997 std::vector<std::pair<bool, std::string> > &GeneratedCode,
2998 std::set<std::pair<unsigned, std::string> > &GeneratedDecl,
2999 std::vector<std::string> &TargetOpcodes,
3000 std::vector<std::string> &TargetVTs,
3002 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3003 Pattern.getSrcPattern(), Pattern.getDstPattern(),
3004 GeneratedCode, GeneratedDecl,
3005 TargetOpcodes, TargetVTs,
3008 // Emit the matcher, capturing named arguments in VariableMap.
3009 bool FoundChain = false;
3010 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
3012 // TP - Get *SOME* tree pattern, we don't care which.
3013 TreePattern &TP = *PatternFragments.begin()->second;
3015 // At this point, we know that we structurally match the pattern, but the
3016 // types of the nodes may not match. Figure out the fewest number of type
3017 // comparisons we need to emit. For example, if there is only one integer
3018 // type supported by a target, there should be no type comparisons at all for
3019 // integer patterns!
3021 // To figure out the fewest number of type checks needed, clone the pattern,
3022 // remove the types, then perform type inference on the pattern as a whole.
3023 // If there are unresolved types, emit an explicit check for those types,
3024 // apply the type to the tree, then rerun type inference. Iterate until all
3025 // types are resolved.
3027 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
3028 RemoveAllTypes(Pat);
3031 // Resolve/propagate as many types as possible.
3033 bool MadeChange = true;
3035 MadeChange = Pat->ApplyTypeConstraints(TP,
3036 true/*Ignore reg constraints*/);
3038 assert(0 && "Error: could not find consistent types for something we"
3039 " already decided was ok!");
3043 // Insert a check for an unresolved type and add it to the tree. If we find
3044 // an unresolved type to add a check for, this returns true and we iterate,
3045 // otherwise we are done.
3046 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
3048 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
3052 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
3053 /// a line causes any of them to be empty, remove them and return true when
3055 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
3056 std::vector<std::pair<bool, std::string> > > >
3058 bool ErasedPatterns = false;
3059 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3060 Patterns[i].second.pop_back();
3061 if (Patterns[i].second.empty()) {
3062 Patterns.erase(Patterns.begin()+i);
3064 ErasedPatterns = true;
3067 return ErasedPatterns;
3070 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3071 /// code together between the patterns.
3072 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3073 std::vector<std::pair<bool, std::string> > > >
3074 &Patterns, unsigned Indent,
3076 typedef std::pair<bool, std::string> CodeLine;
3077 typedef std::vector<CodeLine> CodeList;
3078 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3080 if (Patterns.empty()) return;
3082 // Figure out how many patterns share the next code line. Explicitly copy
3083 // FirstCodeLine so that we don't invalidate a reference when changing
3085 const CodeLine FirstCodeLine = Patterns.back().second.back();
3086 unsigned LastMatch = Patterns.size()-1;
3087 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3090 // If not all patterns share this line, split the list into two pieces. The
3091 // first chunk will use this line, the second chunk won't.
3092 if (LastMatch != 0) {
3093 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3094 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3096 // FIXME: Emit braces?
3097 if (Shared.size() == 1) {
3098 PatternToMatch &Pattern = *Shared.back().first;
3099 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3100 Pattern.getSrcPattern()->print(OS);
3101 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3102 Pattern.getDstPattern()->print(OS);
3104 unsigned AddedComplexity = Pattern.getAddedComplexity();
3105 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3106 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3108 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
3110 if (!FirstCodeLine.first) {
3111 OS << std::string(Indent, ' ') << "{\n";
3114 EmitPatterns(Shared, Indent, OS);
3115 if (!FirstCodeLine.first) {
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) << "\n";
3133 EmitPatterns(Other, Indent, OS);
3137 // Remove this code from all of the patterns that share it.
3138 bool ErasedPatterns = EraseCodeLine(Patterns);
3140 bool isPredicate = FirstCodeLine.first;
3142 // Otherwise, every pattern in the list has this line. Emit it.
3145 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3147 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3149 // If the next code line is another predicate, and if all of the pattern
3150 // in this group share the same next line, emit it inline now. Do this
3151 // until we run out of common predicates.
3152 while (!ErasedPatterns && Patterns.back().second.back().first) {
3153 // Check that all of fhe patterns in Patterns end with the same predicate.
3154 bool AllEndWithSamePredicate = true;
3155 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3156 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3157 AllEndWithSamePredicate = false;
3160 // If all of the predicates aren't the same, we can't share them.
3161 if (!AllEndWithSamePredicate) break;
3163 // Otherwise we can. Emit it shared now.
3164 OS << " &&\n" << std::string(Indent+4, ' ')
3165 << Patterns.back().second.back().second;
3166 ErasedPatterns = EraseCodeLine(Patterns);
3173 EmitPatterns(Patterns, Indent, OS);
3176 OS << std::string(Indent-2, ' ') << "}\n";
3182 /// CompareByRecordName - An ordering predicate that implements less-than by
3183 /// comparing the names records.
3184 struct CompareByRecordName {
3185 bool operator()(const Record *LHS, const Record *RHS) const {
3186 // Sort by name first.
3187 if (LHS->getName() < RHS->getName()) return true;
3188 // If both names are equal, sort by pointer.
3189 return LHS->getName() == RHS->getName() && LHS < RHS;
3194 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3195 std::string InstNS = Target.inst_begin()->second.Namespace;
3196 if (!InstNS.empty()) InstNS += "::";
3198 // Group the patterns by their top-level opcodes.
3199 std::map<Record*, std::vector<PatternToMatch*>,
3200 CompareByRecordName> PatternsByOpcode;
3201 // All unique target node emission functions.
3202 std::map<std::string, unsigned> EmitFunctions;
3203 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3204 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3205 if (!Node->isLeaf()) {
3206 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3208 const ComplexPattern *CP;
3210 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3211 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3212 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3213 std::vector<Record*> OpNodes = CP->getRootNodes();
3214 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3215 PatternsByOpcode[OpNodes[j]]
3216 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3219 std::cerr << "Unrecognized opcode '";
3221 std::cerr << "' on tree pattern '";
3223 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3224 std::cerr << "'!\n";
3230 // Emit one Select_* method for each top-level opcode. We do this instead of
3231 // emitting one giant switch statement to support compilers where this will
3232 // result in the recursive functions taking less stack space.
3233 for (std::map<Record*, std::vector<PatternToMatch*>,
3234 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3235 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3236 const std::string &OpName = PBOI->first->getName();
3237 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3239 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3240 OpcodeInfo.getNumResults() > 0);
3241 std::vector<PatternToMatch*> &Patterns = PBOI->second;
3242 assert(!Patterns.empty() && "No patterns but map has entry?");
3244 // We want to emit all of the matching code now. However, we want to emit
3245 // the matches in order of minimal cost. Sort the patterns so the least
3246 // cost one is at the start.
3247 std::stable_sort(Patterns.begin(), Patterns.end(),
3248 PatternSortingPredicate(*this));
3250 typedef std::vector<std::pair<bool, std::string> > CodeList;
3251 typedef std::vector<std::pair<bool, std::string> >::iterator CodeListI;
3253 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3254 std::vector<std::vector<std::string> > PatternOpcodes;
3255 std::vector<std::vector<std::string> > PatternVTs;
3256 std::vector<std::set<std::pair<unsigned, std::string> > > PatternDecls;
3257 std::set<std::pair<unsigned, std::string> > AllGenDecls;
3258 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3259 CodeList GeneratedCode;
3260 std::set<std::pair<unsigned, std::string> > GeneratedDecl;
3261 std::vector<std::string> TargetOpcodes;
3262 std::vector<std::string> TargetVTs;
3263 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3264 TargetOpcodes, TargetVTs, OptSlctOrder);
3265 for (std::set<std::pair<unsigned, std::string> >::iterator
3266 si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si)
3267 AllGenDecls.insert(*si);
3268 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3269 PatternDecls.push_back(GeneratedDecl);
3270 PatternOpcodes.push_back(TargetOpcodes);
3271 PatternVTs.push_back(TargetVTs);
3274 // Scan the code to see if all of the patterns are reachable and if it is
3275 // possible that the last one might not match.
3276 bool mightNotMatch = true;
3277 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3278 CodeList &GeneratedCode = CodeForPatterns[i].second;
3279 mightNotMatch = false;
3281 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3282 if (GeneratedCode[j].first) { // predicate.
3283 mightNotMatch = true;
3288 // If this pattern definitely matches, and if it isn't the last one, the
3289 // patterns after it CANNOT ever match. Error out.
3290 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3291 std::cerr << "Pattern '";
3292 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3293 std::cerr << "' is impossible to select!\n";
3298 // Factor target node emission code (emitted by EmitResultCode) into
3299 // separate functions. Uniquing and share them among all instruction
3300 // selection routines.
3301 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3302 CodeList &GeneratedCode = CodeForPatterns[i].second;
3303 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3304 std::vector<std::string> &TargetVTs = PatternVTs[i];
3305 std::set<std::pair<unsigned, std::string> > Decls = PatternDecls[i];
3306 int CodeSize = (int)GeneratedCode.size();
3308 for (int j = CodeSize-1; j >= 0; --j) {
3309 if (GeneratedCode[j].first) {
3315 std::string CalleeDecls;
3316 std::string CalleeCode = "(SDOperand &Result, SDOperand &N";
3317 std::string CallerCode = "(Result, N";
3318 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3319 CalleeCode += ", unsigned Opc" + utostr(j);
3320 CallerCode += ", " + TargetOpcodes[j];
3322 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3323 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3324 CallerCode += ", " + TargetVTs[j];
3326 for (std::set<std::pair<unsigned, std::string> >::iterator
3327 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
3328 std::string Name = I->second;
3329 if (I->first == 0) {
3330 if (Name == "InFlag" ||
3332 Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) {
3333 CalleeDecls += " SDOperand " + Name + "(0, 0);\n";
3336 CalleeCode += ", SDOperand &" + Name;
3337 CallerCode += ", " + Name;
3338 } else if (I->first == 1) {
3339 if (Name == "ResNode") {
3340 CalleeDecls += " SDNode *" + Name + " = NULL;\n";
3343 CalleeCode += ", SDNode *" + Name;
3344 CallerCode += ", " + Name;
3346 CalleeCode += ", bool " + Name;
3347 CallerCode += ", " + Name;
3353 // Prevent emission routines from being inlined to reduce selection
3354 // routines stack frame sizes.
3355 CalleeCode += "__attribute__((noinline)) ";
3357 CalleeCode += "{\n" + CalleeDecls;
3358 for (int j = LastPred+1; j < CodeSize; ++j)
3359 CalleeCode += " " + GeneratedCode[j].second + '\n';
3360 for (int j = LastPred+1; j < CodeSize; ++j)
3361 GeneratedCode.pop_back();
3362 CalleeCode += "}\n";
3364 // Uniquing the emission routines.
3365 unsigned EmitFuncNum;
3366 std::map<std::string, unsigned>::iterator EFI =
3367 EmitFunctions.find(CalleeCode);
3368 if (EFI != EmitFunctions.end()) {
3369 EmitFuncNum = EFI->second;
3371 EmitFuncNum = EmitFunctions.size();
3372 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
3373 OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode;
3376 // Replace the emission code within selection routines with calls to the
3377 // emission functions.
3378 CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode;
3379 GeneratedCode.push_back(std::make_pair(false, CallerCode));
3380 GeneratedCode.push_back(std::make_pair(false, "return;"));
3384 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3386 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3387 << " && N.getValue(0).hasOneUse()) {\n"
3388 << " SDOperand Dummy = "
3389 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3390 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3391 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3392 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3393 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3394 << " Result = Dummy;\n"
3399 // Print all declarations.
3400 for (std::set<std::pair<unsigned, std::string> >::iterator
3401 I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I)
3403 OS << " SDOperand " << I->second << "(0, 0);\n";
3404 else if (I->first == 1)
3405 OS << " SDNode *" << I->second << " = NULL;\n";
3407 OS << " bool " << I->second << " = false;\n";
3409 // Loop through and reverse all of the CodeList vectors, as we will be
3410 // accessing them from their logical front, but accessing the end of a
3411 // vector is more efficient.
3412 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3413 CodeList &GeneratedCode = CodeForPatterns[i].second;
3414 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3417 // Next, reverse the list of patterns itself for the same reason.
3418 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3420 // Emit all of the patterns now, grouped together to share code.
3421 EmitPatterns(CodeForPatterns, 2, OS);
3423 // If the last pattern has predicates (which could fail) emit code to catch
3424 // the case where nothing handles a pattern.
3425 if (mightNotMatch) {
3426 OS << " std::cerr << \"Cannot yet select: \";\n";
3427 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3428 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3429 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3430 OS << " N.Val->dump(CurDAG);\n";
3432 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3433 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3434 << " std::cerr << \"intrinsic %\"<< "
3435 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3437 OS << " std::cerr << '\\n';\n"
3443 // Emit boilerplate.
3444 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3445 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3446 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3447 << " // Select the flag operand.\n"
3448 << " if (Ops.back().getValueType() == MVT::Flag)\n"
3449 << " Select(Ops.back(), Ops.back());\n"
3450 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3451 << " std::vector<MVT::ValueType> VTs;\n"
3452 << " VTs.push_back(MVT::Other);\n"
3453 << " VTs.push_back(MVT::Flag);\n"
3454 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3455 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3456 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3457 << " Result = New.getValue(N.ResNo);\n"
3461 OS << "// The main instruction selector code.\n"
3462 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3463 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3464 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3465 << "INSTRUCTION_LIST_END)) {\n"
3467 << " return; // Already selected.\n"
3469 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3470 << " if (CGMI != CodeGenMap.end()) {\n"
3471 << " Result = CGMI->second;\n"
3474 << " switch (N.getOpcode()) {\n"
3475 << " default: break;\n"
3476 << " case ISD::EntryToken: // These leaves remain the same.\n"
3477 << " case ISD::BasicBlock:\n"
3478 << " case ISD::Register:\n"
3479 << " case ISD::HANDLENODE:\n"
3480 << " case ISD::TargetConstant:\n"
3481 << " case ISD::TargetConstantPool:\n"
3482 << " case ISD::TargetFrameIndex:\n"
3483 << " case ISD::TargetJumpTable:\n"
3484 << " case ISD::TargetGlobalAddress: {\n"
3488 << " case ISD::AssertSext:\n"
3489 << " case ISD::AssertZext: {\n"
3490 << " SDOperand Tmp0;\n"
3491 << " Select(Tmp0, N.getOperand(0));\n"
3492 << " if (!N.Val->hasOneUse())\n"
3493 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3494 << "Tmp0.Val, Tmp0.ResNo);\n"
3495 << " Result = Tmp0;\n"
3498 << " case ISD::TokenFactor:\n"
3499 << " if (N.getNumOperands() == 2) {\n"
3500 << " SDOperand Op0, Op1;\n"
3501 << " Select(Op0, N.getOperand(0));\n"
3502 << " Select(Op1, N.getOperand(1));\n"
3504 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3505 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3506 << "Result.Val, Result.ResNo);\n"
3508 << " std::vector<SDOperand> Ops;\n"
3509 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3510 << " SDOperand Val;\n"
3511 << " Select(Val, N.getOperand(i));\n"
3512 << " Ops.push_back(Val);\n"
3515 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3516 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3517 << "Result.Val, Result.ResNo);\n"
3520 << " case ISD::CopyFromReg: {\n"
3521 << " SDOperand Chain;\n"
3522 << " Select(Chain, N.getOperand(0));\n"
3523 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3524 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
3525 << " if (N.Val->getNumValues() == 2) {\n"
3526 << " if (Chain == N.getOperand(0)) {\n"
3527 << " Result = N; // No change\n"
3530 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3531 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3533 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3535 << " Result = New.getValue(N.ResNo);\n"
3538 << " SDOperand Flag;\n"
3539 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3540 << " if (Chain == N.getOperand(0) &&\n"
3541 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3542 << " Result = N; // No change\n"
3545 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3546 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3548 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3550 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3552 << " Result = New.getValue(N.ResNo);\n"
3556 << " case ISD::CopyToReg: {\n"
3557 << " SDOperand Chain;\n"
3558 << " Select(Chain, N.getOperand(0));\n"
3559 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3560 << " SDOperand Val;\n"
3561 << " Select(Val, N.getOperand(2));\n"
3563 << " if (N.Val->getNumValues() == 1) {\n"
3564 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3565 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3566 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3567 << "Result.Val, 0);\n"
3569 << " SDOperand Flag(0, 0);\n"
3570 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3571 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3572 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3573 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3574 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3575 << "Result.Val, 0);\n"
3576 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3577 << "Result.Val, 1);\n"
3578 << " Result = Result.getValue(N.ResNo);\n"
3582 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
3585 // Loop over all of the case statements, emiting a call to each method we
3587 for (std::map<Record*, std::vector<PatternToMatch*>,
3588 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3589 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3590 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3591 OS << " case " << OpcodeInfo.getEnumName() << ": "
3592 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3593 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3596 OS << " } // end of big switch.\n\n"
3597 << " std::cerr << \"Cannot yet select: \";\n"
3598 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3599 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3600 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3601 << " N.Val->dump(CurDAG);\n"
3603 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3604 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3605 << " std::cerr << \"intrinsic %\"<< "
3606 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3608 << " std::cerr << '\\n';\n"
3613 void DAGISelEmitter::run(std::ostream &OS) {
3614 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3617 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3618 << "// *** instruction selector class. These functions are really "
3621 OS << "// Instance var to keep track of multiply used nodes that have \n"
3622 << "// already been selected.\n"
3623 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3625 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3626 << "// and their place handle nodes.\n";
3627 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3628 OS << "// Instance var to keep track of mapping of place handle nodes\n"
3629 << "// and their replacement nodes.\n";
3630 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3631 OS << "// Keep track of nodes that are currently being selecte and therefore\n"
3632 << "// should not be folded.\n";
3633 OS << "std::set<SDNode*> InFlightSet;\n";
3636 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3637 << "std::set<SDNode *> &Visited) {\n";
3638 OS << " if (found || !Visited.insert(Use).second) return;\n";
3639 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3640 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3641 OS << " if (N != Def) {\n";
3642 OS << " findNonImmUse(N, Def, found, Visited);\n";
3643 OS << " } else {\n";
3644 OS << " found = true;\n";
3651 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3652 OS << " std::set<SDNode *> Visited;\n";
3653 OS << " bool found = false;\n";
3654 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3655 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3656 OS << " if (N != Def) {\n";
3657 OS << " findNonImmUse(N, Def, found, Visited);\n";
3658 OS << " if (found) break;\n";
3661 OS << " return found;\n";
3665 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3666 << "// handle node in ReplaceMap.\n";
3667 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3668 << "unsigned RNum) {\n";
3669 OS << " SDOperand N(H, HNum);\n";
3670 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3671 OS << " if (HMI != HandleMap.end()) {\n";
3672 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3673 OS << " HandleMap.erase(N);\n";
3678 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3679 OS << "// handles.Some handles do not yet have replacements because the\n";
3680 OS << "// nodes they replacements have only dead readers.\n";
3681 OS << "void SelectDanglingHandles() {\n";
3682 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3683 << "HandleMap.begin(),\n"
3684 << " E = HandleMap.end(); I != E; ++I) {\n";
3685 OS << " SDOperand N = I->first;\n";
3686 OS << " SDOperand R;\n";
3687 OS << " Select(R, N.getValue(0));\n";
3688 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3692 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3693 OS << "// specific nodes.\n";
3694 OS << "void ReplaceHandles() {\n";
3695 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3696 << "ReplaceMap.begin(),\n"
3697 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3698 OS << " SDOperand From = I->first;\n";
3699 OS << " SDOperand To = I->second;\n";
3700 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3701 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3702 OS << " SDNode *Use = *UI;\n";
3703 OS << " std::vector<SDOperand> Ops;\n";
3704 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n";
3705 OS << " SDOperand O = Use->getOperand(i);\n";
3706 OS << " if (O.Val == From.Val)\n";
3707 OS << " Ops.push_back(To);\n";
3709 OS << " Ops.push_back(O);\n";
3711 OS << " SDOperand U = SDOperand(Use, 0);\n";
3712 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3718 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3719 OS << "// if the folding were to happen. This is called when, for example,\n";
3720 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3721 OS << "// then the resulting node's input chain would be the load's input\n";
3722 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3723 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3724 OS << "// with the other operands along with the input chain of the load.\n";
3725 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3726 << "SDNode *Chain, SDNode* &OldTF) {\n";
3727 OS << " OldTF = NULL;\n";
3728 OS << " if (N == Chain) {\n";
3729 OS << " return N->getOperand(0);\n";
3730 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3731 OS << " N->isOperand(Chain)) {\n";
3732 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3733 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3734 << "CodeGenMap.find(Ch);\n";
3735 OS << " if (CGMI != CodeGenMap.end())\n";
3736 OS << " return SDOperand(0, 0);\n";
3737 OS << " OldTF = Chain;\n";
3738 OS << " std::vector<SDOperand> Ops;\n";
3739 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3740 OS << " SDOperand Op = Chain->getOperand(i);\n";
3741 OS << " if (Op.Val == N)\n";
3742 OS << " Ops.push_back(N->getOperand(0));\n";
3744 OS << " Ops.push_back(Op);\n";
3746 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3748 OS << " return SDOperand(0, 0);\n";
3752 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3753 OS << "SDOperand SelectRoot(SDOperand N) {\n";
3754 OS << " SDOperand ResNode;\n";
3755 OS << " Select(ResNode, N);\n";
3756 OS << " SelectDanglingHandles();\n";
3757 OS << " ReplaceHandles();\n";
3758 OS << " ReplaceMap.clear();\n";
3759 OS << " return ResNode;\n";
3762 Intrinsics = LoadIntrinsics(Records);
3764 ParseNodeTransforms(OS);
3765 ParseComplexPatterns();
3766 ParsePatternFragments(OS);
3767 ParseInstructions();
3770 // Generate variants. For example, commutative patterns can match
3771 // multiple ways. Add them to PatternsToMatch as well.
3775 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3776 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3777 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3778 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
3782 // At this point, we have full information about the 'Patterns' we need to
3783 // parse, both implicitly from instructions as well as from explicit pattern
3784 // definitions. Emit the resultant instruction selector.
3785 EmitInstructionSelector(OS);
3787 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3788 E = PatternFragments.end(); I != E; ++I)
3790 PatternFragments.clear();
3792 Instructions.clear();