1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
25 /// FilterVTs - Filter a list of VT's according to a predicate.
28 static std::vector<MVT::ValueType>
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
33 Result.push_back(InVTs[i]);
38 static std::vector<unsigned char>
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
67 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
71 /// isExtFloatingPointVT - Return true if the specified extended value type
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
74 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75 return EVTs[0] == MVT::isFP ||
76 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
79 //===----------------------------------------------------------------------===//
80 // SDTypeConstraint implementation
83 SDTypeConstraint::SDTypeConstraint(Record *R) {
84 OperandNo = R->getValueAsInt("OperandNum");
86 if (R->isSubClassOf("SDTCisVT")) {
87 ConstraintType = SDTCisVT;
88 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
89 } else if (R->isSubClassOf("SDTCisPtrTy")) {
90 ConstraintType = SDTCisPtrTy;
91 } else if (R->isSubClassOf("SDTCisInt")) {
92 ConstraintType = SDTCisInt;
93 } else if (R->isSubClassOf("SDTCisFP")) {
94 ConstraintType = SDTCisFP;
95 } else if (R->isSubClassOf("SDTCisSameAs")) {
96 ConstraintType = SDTCisSameAs;
97 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99 ConstraintType = SDTCisVTSmallerThanOp;
100 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
101 R->getValueAsInt("OtherOperandNum");
102 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103 ConstraintType = SDTCisOpSmallerThanOp;
104 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
105 R->getValueAsInt("BigOperandNum");
106 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107 ConstraintType = SDTCisIntVectorOfSameSize;
108 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109 R->getValueAsInt("OtherOpNum");
111 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
116 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
117 /// N, which has NumResults results.
118 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
120 unsigned NumResults) const {
121 assert(NumResults <= 1 &&
122 "We only work with nodes with zero or one result so far!");
124 if (OpNo >= (NumResults + N->getNumChildren())) {
125 std::cerr << "Invalid operand number " << OpNo << " ";
131 if (OpNo < NumResults)
132 return N; // FIXME: need value #
134 return N->getChild(OpNo-NumResults);
137 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
138 /// constraint to the nodes operands. This returns true if it makes a
139 /// change, false otherwise. If a type contradiction is found, throw an
141 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
142 const SDNodeInfo &NodeInfo,
143 TreePattern &TP) const {
144 unsigned NumResults = NodeInfo.getNumResults();
145 assert(NumResults <= 1 &&
146 "We only work with nodes with zero or one result so far!");
148 // Check that the number of operands is sane. Negative operands -> varargs.
149 if (NodeInfo.getNumOperands() >= 0) {
150 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
151 TP.error(N->getOperator()->getName() + " node requires exactly " +
152 itostr(NodeInfo.getNumOperands()) + " operands!");
155 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
157 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
159 switch (ConstraintType) {
160 default: assert(0 && "Unknown constraint type!");
162 // Operand must be a particular type.
163 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
165 // Operand must be same as target pointer type.
166 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
169 // If there is only one integer type supported, this must be it.
170 std::vector<MVT::ValueType> IntVTs =
171 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
173 // If we found exactly one supported integer type, apply it.
174 if (IntVTs.size() == 1)
175 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
176 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
179 // If there is only one FP type supported, this must be it.
180 std::vector<MVT::ValueType> FPVTs =
181 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
183 // If we found exactly one supported FP type, apply it.
184 if (FPVTs.size() == 1)
185 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
186 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
189 TreePatternNode *OtherNode =
190 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
191 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
192 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
194 case SDTCisVTSmallerThanOp: {
195 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
196 // have an integer type that is smaller than the VT.
197 if (!NodeToApply->isLeaf() ||
198 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
199 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
200 ->isSubClassOf("ValueType"))
201 TP.error(N->getOperator()->getName() + " expects a VT operand!");
203 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
204 if (!MVT::isInteger(VT))
205 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
207 TreePatternNode *OtherNode =
208 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
210 // It must be integer.
211 bool MadeChange = false;
212 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
214 // This code only handles nodes that have one type set. Assert here so
215 // that we can change this if we ever need to deal with multiple value
216 // types at this point.
217 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
218 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
219 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
222 case SDTCisOpSmallerThanOp: {
223 TreePatternNode *BigOperand =
224 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
226 // Both operands must be integer or FP, but we don't care which.
227 bool MadeChange = false;
229 // This code does not currently handle nodes which have multiple types,
230 // where some types are integer, and some are fp. Assert that this is not
232 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
233 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
234 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
235 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
236 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
237 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
238 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
239 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
240 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
241 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
242 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
243 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
244 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
246 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
248 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
249 VTs = FilterVTs(VTs, MVT::isInteger);
250 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
251 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
256 switch (VTs.size()) {
257 default: // Too many VT's to pick from.
258 case 0: break; // No info yet.
260 // Only one VT of this flavor. Cannot ever satisify the constraints.
261 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
263 // If we have exactly two possible types, the little operand must be the
264 // small one, the big operand should be the big one. Common with
265 // float/double for example.
266 assert(VTs[0] < VTs[1] && "Should be sorted!");
267 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
268 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
273 case SDTCisIntVectorOfSameSize: {
274 TreePatternNode *OtherOperand =
275 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
277 if (OtherOperand->hasTypeSet()) {
278 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
279 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
280 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
281 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
282 return NodeToApply->UpdateNodeType(IVT, TP);
291 //===----------------------------------------------------------------------===//
292 // SDNodeInfo implementation
294 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
295 EnumName = R->getValueAsString("Opcode");
296 SDClassName = R->getValueAsString("SDClass");
297 Record *TypeProfile = R->getValueAsDef("TypeProfile");
298 NumResults = TypeProfile->getValueAsInt("NumResults");
299 NumOperands = TypeProfile->getValueAsInt("NumOperands");
301 // Parse the properties.
303 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
304 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
305 if (PropList[i]->getName() == "SDNPCommutative") {
306 Properties |= 1 << SDNPCommutative;
307 } else if (PropList[i]->getName() == "SDNPAssociative") {
308 Properties |= 1 << SDNPAssociative;
309 } else if (PropList[i]->getName() == "SDNPHasChain") {
310 Properties |= 1 << SDNPHasChain;
311 } else if (PropList[i]->getName() == "SDNPOutFlag") {
312 Properties |= 1 << SDNPOutFlag;
313 } else if (PropList[i]->getName() == "SDNPInFlag") {
314 Properties |= 1 << SDNPInFlag;
315 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
316 Properties |= 1 << SDNPOptInFlag;
318 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
319 << "' on node '" << R->getName() << "'!\n";
325 // Parse the type constraints.
326 std::vector<Record*> ConstraintList =
327 TypeProfile->getValueAsListOfDefs("Constraints");
328 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
331 //===----------------------------------------------------------------------===//
332 // TreePatternNode implementation
335 TreePatternNode::~TreePatternNode() {
336 #if 0 // FIXME: implement refcounted tree nodes!
337 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
342 /// UpdateNodeType - Set the node type of N to VT if VT contains
343 /// information. If N already contains a conflicting type, then throw an
344 /// exception. This returns true if any information was updated.
346 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
348 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
350 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
352 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
357 if (getExtTypeNum(0) == MVT::iPTR) {
358 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
360 if (isExtIntegerInVTs(ExtVTs)) {
361 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
369 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
370 assert(hasTypeSet() && "should be handled above!");
371 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
372 if (getExtTypes() == FVTs)
377 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
378 //assert(hasTypeSet() && "should be handled above!");
379 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
380 if (getExtTypes() == FVTs)
387 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
388 assert(hasTypeSet() && "should be handled above!");
389 std::vector<unsigned char> FVTs =
390 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
391 if (getExtTypes() == FVTs)
397 // If we know this is an int or fp type, and we are told it is a specific one,
400 // Similarly, we should probably set the type here to the intersection of
401 // {isInt|isFP} and ExtVTs
402 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
403 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
407 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
415 TP.error("Type inference contradiction found in node!");
417 TP.error("Type inference contradiction found in node " +
418 getOperator()->getName() + "!");
420 return true; // unreachable
424 void TreePatternNode::print(std::ostream &OS) const {
426 OS << *getLeafValue();
428 OS << "(" << getOperator()->getName();
431 // FIXME: At some point we should handle printing all the value types for
432 // nodes that are multiply typed.
433 switch (getExtTypeNum(0)) {
434 case MVT::Other: OS << ":Other"; break;
435 case MVT::isInt: OS << ":isInt"; break;
436 case MVT::isFP : OS << ":isFP"; break;
437 case MVT::isUnknown: ; /*OS << ":?";*/ break;
438 case MVT::iPTR: OS << ":iPTR"; break;
440 std::string VTName = llvm::getName(getTypeNum(0));
441 // Strip off MVT:: prefix if present.
442 if (VTName.substr(0,5) == "MVT::")
443 VTName = VTName.substr(5);
450 if (getNumChildren() != 0) {
452 getChild(0)->print(OS);
453 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
455 getChild(i)->print(OS);
461 if (!PredicateFn.empty())
462 OS << "<<P:" << PredicateFn << ">>";
464 OS << "<<X:" << TransformFn->getName() << ">>";
465 if (!getName().empty())
466 OS << ":$" << getName();
469 void TreePatternNode::dump() const {
473 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
474 /// the specified node. For this comparison, all of the state of the node
475 /// is considered, except for the assigned name. Nodes with differing names
476 /// that are otherwise identical are considered isomorphic.
477 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
478 if (N == this) return true;
479 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
480 getPredicateFn() != N->getPredicateFn() ||
481 getTransformFn() != N->getTransformFn())
485 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
486 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
487 return DI->getDef() == NDI->getDef();
488 return getLeafValue() == N->getLeafValue();
491 if (N->getOperator() != getOperator() ||
492 N->getNumChildren() != getNumChildren()) return false;
493 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
494 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
499 /// clone - Make a copy of this tree and all of its children.
501 TreePatternNode *TreePatternNode::clone() const {
502 TreePatternNode *New;
504 New = new TreePatternNode(getLeafValue());
506 std::vector<TreePatternNode*> CChildren;
507 CChildren.reserve(Children.size());
508 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
509 CChildren.push_back(getChild(i)->clone());
510 New = new TreePatternNode(getOperator(), CChildren);
512 New->setName(getName());
513 New->setTypes(getExtTypes());
514 New->setPredicateFn(getPredicateFn());
515 New->setTransformFn(getTransformFn());
519 /// SubstituteFormalArguments - Replace the formal arguments in this tree
520 /// with actual values specified by ArgMap.
521 void TreePatternNode::
522 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
523 if (isLeaf()) return;
525 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
526 TreePatternNode *Child = getChild(i);
527 if (Child->isLeaf()) {
528 Init *Val = Child->getLeafValue();
529 if (dynamic_cast<DefInit*>(Val) &&
530 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
531 // We found a use of a formal argument, replace it with its value.
532 Child = ArgMap[Child->getName()];
533 assert(Child && "Couldn't find formal argument!");
537 getChild(i)->SubstituteFormalArguments(ArgMap);
543 /// InlinePatternFragments - If this pattern refers to any pattern
544 /// fragments, inline them into place, giving us a pattern without any
545 /// PatFrag references.
546 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
547 if (isLeaf()) return this; // nothing to do.
548 Record *Op = getOperator();
550 if (!Op->isSubClassOf("PatFrag")) {
551 // Just recursively inline children nodes.
552 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
553 setChild(i, getChild(i)->InlinePatternFragments(TP));
557 // Otherwise, we found a reference to a fragment. First, look up its
558 // TreePattern record.
559 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
561 // Verify that we are passing the right number of operands.
562 if (Frag->getNumArgs() != Children.size())
563 TP.error("'" + Op->getName() + "' fragment requires " +
564 utostr(Frag->getNumArgs()) + " operands!");
566 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
568 // Resolve formal arguments to their actual value.
569 if (Frag->getNumArgs()) {
570 // Compute the map of formal to actual arguments.
571 std::map<std::string, TreePatternNode*> ArgMap;
572 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
573 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
575 FragTree->SubstituteFormalArguments(ArgMap);
578 FragTree->setName(getName());
579 FragTree->UpdateNodeType(getExtTypes(), TP);
581 // Get a new copy of this fragment to stitch into here.
582 //delete this; // FIXME: implement refcounting!
586 /// getImplicitType - Check to see if the specified record has an implicit
587 /// type which should be applied to it. This infer the type of register
588 /// references from the register file information, for example.
590 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
592 // Some common return values
593 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
594 std::vector<unsigned char> Other(1, MVT::Other);
596 // Check to see if this is a register or a register class...
597 if (R->isSubClassOf("RegisterClass")) {
600 const CodeGenRegisterClass &RC =
601 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
602 return ConvertVTs(RC.getValueTypes());
603 } else if (R->isSubClassOf("PatFrag")) {
604 // Pattern fragment types will be resolved when they are inlined.
606 } else if (R->isSubClassOf("Register")) {
609 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
610 return T.getRegisterVTs(R);
611 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
612 // Using a VTSDNode or CondCodeSDNode.
614 } else if (R->isSubClassOf("ComplexPattern")) {
617 std::vector<unsigned char>
618 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
620 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
625 TP.error("Unknown node flavor used in pattern: " + R->getName());
629 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
630 /// this node and its children in the tree. This returns true if it makes a
631 /// change, false otherwise. If a type contradiction is found, throw an
633 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
634 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
636 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
637 // If it's a regclass or something else known, include the type.
638 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
639 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
640 // Int inits are always integers. :)
641 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
644 // At some point, it may make sense for this tree pattern to have
645 // multiple types. Assert here that it does not, so we revisit this
646 // code when appropriate.
647 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
648 MVT::ValueType VT = getTypeNum(0);
649 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
650 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
653 if (VT != MVT::iPTR) {
654 unsigned Size = MVT::getSizeInBits(VT);
655 // Make sure that the value is representable for this type.
657 int Val = (II->getValue() << (32-Size)) >> (32-Size);
658 if (Val != II->getValue())
659 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
660 "' is out of range for type '" +
661 getEnumName(getTypeNum(0)) + "'!");
671 // special handling for set, which isn't really an SDNode.
672 if (getOperator()->getName() == "set") {
673 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
674 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
675 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
677 // Types of operands must match.
678 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
679 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
680 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
682 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
683 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
684 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
686 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
687 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
688 bool MadeChange = false;
690 // Apply the result type to the node.
691 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
693 if (getNumChildren() != Int.ArgVTs.size())
694 TP.error("Intrinsic '" + Int.Name + "' expects " +
695 utostr(Int.ArgVTs.size()-1) + " operands, not " +
696 utostr(getNumChildren()-1) + " operands!");
698 // Apply type info to the intrinsic ID.
699 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
701 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
702 MVT::ValueType OpVT = Int.ArgVTs[i];
703 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
704 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
707 } else if (getOperator()->isSubClassOf("SDNode")) {
708 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
710 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
711 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
712 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
713 // Branch, etc. do not produce results and top-level forms in instr pattern
714 // must have void types.
715 if (NI.getNumResults() == 0)
716 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
718 // If this is a vector_shuffle operation, apply types to the build_vector
719 // operation. The types of the integers don't matter, but this ensures they
720 // won't get checked.
721 if (getOperator()->getName() == "vector_shuffle" &&
722 getChild(2)->getOperator()->getName() == "build_vector") {
723 TreePatternNode *BV = getChild(2);
724 const std::vector<MVT::ValueType> &LegalVTs
725 = ISE.getTargetInfo().getLegalValueTypes();
726 MVT::ValueType LegalIntVT = MVT::Other;
727 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
728 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
729 LegalIntVT = LegalVTs[i];
732 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
734 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
735 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
738 } else if (getOperator()->isSubClassOf("Instruction")) {
739 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
740 bool MadeChange = false;
741 unsigned NumResults = Inst.getNumResults();
743 assert(NumResults <= 1 &&
744 "Only supports zero or one result instrs!");
746 CodeGenInstruction &InstInfo =
747 ISE.getTargetInfo().getInstruction(getOperator()->getName());
748 // Apply the result type to the node
749 if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack...
750 MadeChange = UpdateNodeType(MVT::isVoid, TP);
752 Record *ResultNode = Inst.getResult(0);
753 assert(ResultNode->isSubClassOf("RegisterClass") &&
754 "Operands should be register classes!");
756 const CodeGenRegisterClass &RC =
757 ISE.getTargetInfo().getRegisterClass(ResultNode);
758 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
761 if (getNumChildren() != Inst.getNumOperands())
762 TP.error("Instruction '" + getOperator()->getName() + " expects " +
763 utostr(Inst.getNumOperands()) + " operands, not " +
764 utostr(getNumChildren()) + " operands!");
765 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
766 Record *OperandNode = Inst.getOperand(i);
768 if (OperandNode->isSubClassOf("RegisterClass")) {
769 const CodeGenRegisterClass &RC =
770 ISE.getTargetInfo().getRegisterClass(OperandNode);
771 //VT = RC.getValueTypeNum(0);
772 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
774 } else if (OperandNode->isSubClassOf("Operand")) {
775 VT = getValueType(OperandNode->getValueAsDef("Type"));
776 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
778 assert(0 && "Unknown operand type!");
781 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
785 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
787 // Node transforms always take one operand.
788 if (getNumChildren() != 1)
789 TP.error("Node transform '" + getOperator()->getName() +
790 "' requires one operand!");
792 // If either the output or input of the xform does not have exact
793 // type info. We assume they must be the same. Otherwise, it is perfectly
794 // legal to transform from one type to a completely different type.
795 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
796 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
797 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
804 /// canPatternMatch - If it is impossible for this pattern to match on this
805 /// target, fill in Reason and return false. Otherwise, return true. This is
806 /// used as a santity check for .td files (to prevent people from writing stuff
807 /// that can never possibly work), and to prevent the pattern permuter from
808 /// generating stuff that is useless.
809 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
810 if (isLeaf()) return true;
812 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
813 if (!getChild(i)->canPatternMatch(Reason, ISE))
816 // If this is an intrinsic, handle cases that would make it not match. For
817 // example, if an operand is required to be an immediate.
818 if (getOperator()->isSubClassOf("Intrinsic")) {
823 // If this node is a commutative operator, check that the LHS isn't an
825 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
826 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
827 // Scan all of the operands of the node and make sure that only the last one
828 // is a constant node.
829 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
830 if (!getChild(i)->isLeaf() &&
831 getChild(i)->getOperator()->getName() == "imm") {
832 Reason = "Immediate value must be on the RHS of commutative operators!";
840 //===----------------------------------------------------------------------===//
841 // TreePattern implementation
844 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
845 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
846 isInputPattern = isInput;
847 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
848 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
851 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
852 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
853 isInputPattern = isInput;
854 Trees.push_back(ParseTreePattern(Pat));
857 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
858 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
859 isInputPattern = isInput;
860 Trees.push_back(Pat);
865 void TreePattern::error(const std::string &Msg) const {
867 throw "In " + TheRecord->getName() + ": " + Msg;
870 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
871 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
872 if (!OpDef) error("Pattern has unexpected operator type!");
873 Record *Operator = OpDef->getDef();
875 if (Operator->isSubClassOf("ValueType")) {
876 // If the operator is a ValueType, then this must be "type cast" of a leaf
878 if (Dag->getNumArgs() != 1)
879 error("Type cast only takes one operand!");
881 Init *Arg = Dag->getArg(0);
882 TreePatternNode *New;
883 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
884 Record *R = DI->getDef();
885 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
886 Dag->setArg(0, new DagInit(DI,
887 std::vector<std::pair<Init*, std::string> >()));
888 return ParseTreePattern(Dag);
890 New = new TreePatternNode(DI);
891 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
892 New = ParseTreePattern(DI);
893 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
894 New = new TreePatternNode(II);
895 if (!Dag->getArgName(0).empty())
896 error("Constant int argument should not have a name!");
897 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
898 // Turn this into an IntInit.
899 Init *II = BI->convertInitializerTo(new IntRecTy());
900 if (II == 0 || !dynamic_cast<IntInit*>(II))
901 error("Bits value must be constants!");
903 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
904 if (!Dag->getArgName(0).empty())
905 error("Constant int argument should not have a name!");
908 error("Unknown leaf value for tree pattern!");
912 // Apply the type cast.
913 New->UpdateNodeType(getValueType(Operator), *this);
914 New->setName(Dag->getArgName(0));
918 // Verify that this is something that makes sense for an operator.
919 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
920 !Operator->isSubClassOf("Instruction") &&
921 !Operator->isSubClassOf("SDNodeXForm") &&
922 !Operator->isSubClassOf("Intrinsic") &&
923 Operator->getName() != "set")
924 error("Unrecognized node '" + Operator->getName() + "'!");
926 // Check to see if this is something that is illegal in an input pattern.
927 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
928 Operator->isSubClassOf("SDNodeXForm")))
929 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
931 std::vector<TreePatternNode*> Children;
933 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
934 Init *Arg = Dag->getArg(i);
935 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
936 Children.push_back(ParseTreePattern(DI));
937 if (Children.back()->getName().empty())
938 Children.back()->setName(Dag->getArgName(i));
939 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
940 Record *R = DefI->getDef();
941 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
942 // TreePatternNode if its own.
943 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
944 Dag->setArg(i, new DagInit(DefI,
945 std::vector<std::pair<Init*, std::string> >()));
946 --i; // Revisit this node...
948 TreePatternNode *Node = new TreePatternNode(DefI);
949 Node->setName(Dag->getArgName(i));
950 Children.push_back(Node);
953 if (R->getName() == "node") {
954 if (Dag->getArgName(i).empty())
955 error("'node' argument requires a name to match with operand list");
956 Args.push_back(Dag->getArgName(i));
959 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
960 TreePatternNode *Node = new TreePatternNode(II);
961 if (!Dag->getArgName(i).empty())
962 error("Constant int argument should not have a name!");
963 Children.push_back(Node);
964 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
965 // Turn this into an IntInit.
966 Init *II = BI->convertInitializerTo(new IntRecTy());
967 if (II == 0 || !dynamic_cast<IntInit*>(II))
968 error("Bits value must be constants!");
970 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
971 if (!Dag->getArgName(i).empty())
972 error("Constant int argument should not have a name!");
973 Children.push_back(Node);
978 error("Unknown leaf value for tree pattern!");
982 // If the operator is an intrinsic, then this is just syntactic sugar for for
983 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
984 // convert the intrinsic name to a number.
985 if (Operator->isSubClassOf("Intrinsic")) {
986 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
987 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
989 // If this intrinsic returns void, it must have side-effects and thus a
991 if (Int.ArgVTs[0] == MVT::isVoid) {
992 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
993 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
994 // Has side-effects, requires chain.
995 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
997 // Otherwise, no chain.
998 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1001 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1002 Children.insert(Children.begin(), IIDNode);
1005 return new TreePatternNode(Operator, Children);
1008 /// InferAllTypes - Infer/propagate as many types throughout the expression
1009 /// patterns as possible. Return true if all types are infered, false
1010 /// otherwise. Throw an exception if a type contradiction is found.
1011 bool TreePattern::InferAllTypes() {
1012 bool MadeChange = true;
1013 while (MadeChange) {
1015 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1016 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1019 bool HasUnresolvedTypes = false;
1020 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1021 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1022 return !HasUnresolvedTypes;
1025 void TreePattern::print(std::ostream &OS) const {
1026 OS << getRecord()->getName();
1027 if (!Args.empty()) {
1028 OS << "(" << Args[0];
1029 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1030 OS << ", " << Args[i];
1035 if (Trees.size() > 1)
1037 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1039 Trees[i]->print(OS);
1043 if (Trees.size() > 1)
1047 void TreePattern::dump() const { print(std::cerr); }
1051 //===----------------------------------------------------------------------===//
1052 // DAGISelEmitter implementation
1055 // Parse all of the SDNode definitions for the target, populating SDNodes.
1056 void DAGISelEmitter::ParseNodeInfo() {
1057 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1058 while (!Nodes.empty()) {
1059 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1063 // Get the buildin intrinsic nodes.
1064 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1065 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1066 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1069 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1070 /// map, and emit them to the file as functions.
1071 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1072 OS << "\n// Node transformations.\n";
1073 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1074 while (!Xforms.empty()) {
1075 Record *XFormNode = Xforms.back();
1076 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1077 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1078 SDNodeXForms.insert(std::make_pair(XFormNode,
1079 std::make_pair(SDNode, Code)));
1081 if (!Code.empty()) {
1082 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1083 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1085 OS << "inline SDOperand Transform_" << XFormNode->getName()
1086 << "(SDNode *" << C2 << ") {\n";
1087 if (ClassName != "SDNode")
1088 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1089 OS << Code << "\n}\n";
1096 void DAGISelEmitter::ParseComplexPatterns() {
1097 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1098 while (!AMs.empty()) {
1099 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1105 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1106 /// file, building up the PatternFragments map. After we've collected them all,
1107 /// inline fragments together as necessary, so that there are no references left
1108 /// inside a pattern fragment to a pattern fragment.
1110 /// This also emits all of the predicate functions to the output file.
1112 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1113 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1115 // First step, parse all of the fragments and emit predicate functions.
1116 OS << "\n// Predicate functions.\n";
1117 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1118 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1119 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1120 PatternFragments[Fragments[i]] = P;
1122 // Validate the argument list, converting it to map, to discard duplicates.
1123 std::vector<std::string> &Args = P->getArgList();
1124 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1126 if (OperandsMap.count(""))
1127 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1129 // Parse the operands list.
1130 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1131 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1132 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1133 P->error("Operands list should start with '(ops ... '!");
1135 // Copy over the arguments.
1137 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1138 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1139 static_cast<DefInit*>(OpsList->getArg(j))->
1140 getDef()->getName() != "node")
1141 P->error("Operands list should all be 'node' values.");
1142 if (OpsList->getArgName(j).empty())
1143 P->error("Operands list should have names for each operand!");
1144 if (!OperandsMap.count(OpsList->getArgName(j)))
1145 P->error("'" + OpsList->getArgName(j) +
1146 "' does not occur in pattern or was multiply specified!");
1147 OperandsMap.erase(OpsList->getArgName(j));
1148 Args.push_back(OpsList->getArgName(j));
1151 if (!OperandsMap.empty())
1152 P->error("Operands list does not contain an entry for operand '" +
1153 *OperandsMap.begin() + "'!");
1155 // If there is a code init for this fragment, emit the predicate code and
1156 // keep track of the fact that this fragment uses it.
1157 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1158 if (!Code.empty()) {
1159 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1160 std::string ClassName =
1161 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1162 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1164 OS << "inline bool Predicate_" << Fragments[i]->getName()
1165 << "(SDNode *" << C2 << ") {\n";
1166 if (ClassName != "SDNode")
1167 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1168 OS << Code << "\n}\n";
1169 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1172 // If there is a node transformation corresponding to this, keep track of
1174 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1175 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1176 P->getOnlyTree()->setTransformFn(Transform);
1181 // Now that we've parsed all of the tree fragments, do a closure on them so
1182 // that there are not references to PatFrags left inside of them.
1183 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1184 E = PatternFragments.end(); I != E; ++I) {
1185 TreePattern *ThePat = I->second;
1186 ThePat->InlinePatternFragments();
1188 // Infer as many types as possible. Don't worry about it if we don't infer
1189 // all of them, some may depend on the inputs of the pattern.
1191 ThePat->InferAllTypes();
1193 // If this pattern fragment is not supported by this target (no types can
1194 // satisfy its constraints), just ignore it. If the bogus pattern is
1195 // actually used by instructions, the type consistency error will be
1199 // If debugging, print out the pattern fragment result.
1200 DEBUG(ThePat->dump());
1204 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1205 /// instruction input. Return true if this is a real use.
1206 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1207 std::map<std::string, TreePatternNode*> &InstInputs,
1208 std::vector<Record*> &InstImpInputs) {
1209 // No name -> not interesting.
1210 if (Pat->getName().empty()) {
1211 if (Pat->isLeaf()) {
1212 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1213 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1214 I->error("Input " + DI->getDef()->getName() + " must be named!");
1215 else if (DI && DI->getDef()->isSubClassOf("Register"))
1216 InstImpInputs.push_back(DI->getDef());
1222 if (Pat->isLeaf()) {
1223 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1224 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1227 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1228 Rec = Pat->getOperator();
1231 // SRCVALUE nodes are ignored.
1232 if (Rec->getName() == "srcvalue")
1235 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1240 if (Slot->isLeaf()) {
1241 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1243 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1244 SlotRec = Slot->getOperator();
1247 // Ensure that the inputs agree if we've already seen this input.
1249 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1250 if (Slot->getExtTypes() != Pat->getExtTypes())
1251 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1256 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1257 /// part of "I", the instruction), computing the set of inputs and outputs of
1258 /// the pattern. Report errors if we see anything naughty.
1259 void DAGISelEmitter::
1260 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1261 std::map<std::string, TreePatternNode*> &InstInputs,
1262 std::map<std::string, TreePatternNode*>&InstResults,
1263 std::vector<Record*> &InstImpInputs,
1264 std::vector<Record*> &InstImpResults) {
1265 if (Pat->isLeaf()) {
1266 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1267 if (!isUse && Pat->getTransformFn())
1268 I->error("Cannot specify a transform function for a non-input value!");
1270 } else if (Pat->getOperator()->getName() != "set") {
1271 // If this is not a set, verify that the children nodes are not void typed,
1273 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1274 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1275 I->error("Cannot have void nodes inside of patterns!");
1276 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1277 InstImpInputs, InstImpResults);
1280 // If this is a non-leaf node with no children, treat it basically as if
1281 // it were a leaf. This handles nodes like (imm).
1283 if (Pat->getNumChildren() == 0)
1284 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1286 if (!isUse && Pat->getTransformFn())
1287 I->error("Cannot specify a transform function for a non-input value!");
1291 // Otherwise, this is a set, validate and collect instruction results.
1292 if (Pat->getNumChildren() == 0)
1293 I->error("set requires operands!");
1294 else if (Pat->getNumChildren() & 1)
1295 I->error("set requires an even number of operands");
1297 if (Pat->getTransformFn())
1298 I->error("Cannot specify a transform function on a set node!");
1300 // Check the set destinations.
1301 unsigned NumValues = Pat->getNumChildren()/2;
1302 for (unsigned i = 0; i != NumValues; ++i) {
1303 TreePatternNode *Dest = Pat->getChild(i);
1304 if (!Dest->isLeaf())
1305 I->error("set destination should be a register!");
1307 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1309 I->error("set destination should be a register!");
1311 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1312 if (Dest->getName().empty())
1313 I->error("set destination must have a name!");
1314 if (InstResults.count(Dest->getName()))
1315 I->error("cannot set '" + Dest->getName() +"' multiple times");
1316 InstResults[Dest->getName()] = Dest;
1317 } else if (Val->getDef()->isSubClassOf("Register")) {
1318 InstImpResults.push_back(Val->getDef());
1320 I->error("set destination should be a register!");
1323 // Verify and collect info from the computation.
1324 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1325 InstInputs, InstResults,
1326 InstImpInputs, InstImpResults);
1330 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1331 /// any fragments involved. This populates the Instructions list with fully
1332 /// resolved instructions.
1333 void DAGISelEmitter::ParseInstructions() {
1334 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1336 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1339 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1340 LI = Instrs[i]->getValueAsListInit("Pattern");
1342 // If there is no pattern, only collect minimal information about the
1343 // instruction for its operand list. We have to assume that there is one
1344 // result, as we have no detailed info.
1345 if (!LI || LI->getSize() == 0) {
1346 std::vector<Record*> Results;
1347 std::vector<Record*> Operands;
1349 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1351 if (InstInfo.OperandList.size() != 0) {
1352 // FIXME: temporary hack...
1353 if (InstInfo.noResults) {
1354 // These produce no results
1355 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1356 Operands.push_back(InstInfo.OperandList[j].Rec);
1358 // Assume the first operand is the result.
1359 Results.push_back(InstInfo.OperandList[0].Rec);
1361 // The rest are inputs.
1362 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1363 Operands.push_back(InstInfo.OperandList[j].Rec);
1367 // Create and insert the instruction.
1368 std::vector<Record*> ImpResults;
1369 std::vector<Record*> ImpOperands;
1370 Instructions.insert(std::make_pair(Instrs[i],
1371 DAGInstruction(0, Results, Operands, ImpResults,
1373 continue; // no pattern.
1376 // Parse the instruction.
1377 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1378 // Inline pattern fragments into it.
1379 I->InlinePatternFragments();
1381 // Infer as many types as possible. If we cannot infer all of them, we can
1382 // never do anything with this instruction pattern: report it to the user.
1383 if (!I->InferAllTypes())
1384 I->error("Could not infer all types in pattern!");
1386 // InstInputs - Keep track of all of the inputs of the instruction, along
1387 // with the record they are declared as.
1388 std::map<std::string, TreePatternNode*> InstInputs;
1390 // InstResults - Keep track of all the virtual registers that are 'set'
1391 // in the instruction, including what reg class they are.
1392 std::map<std::string, TreePatternNode*> InstResults;
1394 std::vector<Record*> InstImpInputs;
1395 std::vector<Record*> InstImpResults;
1397 // Verify that the top-level forms in the instruction are of void type, and
1398 // fill in the InstResults map.
1399 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1400 TreePatternNode *Pat = I->getTree(j);
1401 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1402 I->error("Top-level forms in instruction pattern should have"
1405 // Find inputs and outputs, and verify the structure of the uses/defs.
1406 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1407 InstImpInputs, InstImpResults);
1410 // Now that we have inputs and outputs of the pattern, inspect the operands
1411 // list for the instruction. This determines the order that operands are
1412 // added to the machine instruction the node corresponds to.
1413 unsigned NumResults = InstResults.size();
1415 // Parse the operands list from the (ops) list, validating it.
1416 std::vector<std::string> &Args = I->getArgList();
1417 assert(Args.empty() && "Args list should still be empty here!");
1418 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1420 // Check that all of the results occur first in the list.
1421 std::vector<Record*> Results;
1422 TreePatternNode *Res0Node = NULL;
1423 for (unsigned i = 0; i != NumResults; ++i) {
1424 if (i == CGI.OperandList.size())
1425 I->error("'" + InstResults.begin()->first +
1426 "' set but does not appear in operand list!");
1427 const std::string &OpName = CGI.OperandList[i].Name;
1429 // Check that it exists in InstResults.
1430 TreePatternNode *RNode = InstResults[OpName];
1432 I->error("Operand $" + OpName + " does not exist in operand list!");
1436 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1438 I->error("Operand $" + OpName + " should be a set destination: all "
1439 "outputs must occur before inputs in operand list!");
1441 if (CGI.OperandList[i].Rec != R)
1442 I->error("Operand $" + OpName + " class mismatch!");
1444 // Remember the return type.
1445 Results.push_back(CGI.OperandList[i].Rec);
1447 // Okay, this one checks out.
1448 InstResults.erase(OpName);
1451 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1452 // the copy while we're checking the inputs.
1453 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1455 std::vector<TreePatternNode*> ResultNodeOperands;
1456 std::vector<Record*> Operands;
1457 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1458 const std::string &OpName = CGI.OperandList[i].Name;
1460 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1462 if (!InstInputsCheck.count(OpName))
1463 I->error("Operand $" + OpName +
1464 " does not appear in the instruction pattern");
1465 TreePatternNode *InVal = InstInputsCheck[OpName];
1466 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1468 if (InVal->isLeaf() &&
1469 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1470 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1471 if (CGI.OperandList[i].Rec != InRec &&
1472 !InRec->isSubClassOf("ComplexPattern"))
1473 I->error("Operand $" + OpName + "'s register class disagrees"
1474 " between the operand and pattern");
1476 Operands.push_back(CGI.OperandList[i].Rec);
1478 // Construct the result for the dest-pattern operand list.
1479 TreePatternNode *OpNode = InVal->clone();
1481 // No predicate is useful on the result.
1482 OpNode->setPredicateFn("");
1484 // Promote the xform function to be an explicit node if set.
1485 if (Record *Xform = OpNode->getTransformFn()) {
1486 OpNode->setTransformFn(0);
1487 std::vector<TreePatternNode*> Children;
1488 Children.push_back(OpNode);
1489 OpNode = new TreePatternNode(Xform, Children);
1492 ResultNodeOperands.push_back(OpNode);
1495 if (!InstInputsCheck.empty())
1496 I->error("Input operand $" + InstInputsCheck.begin()->first +
1497 " occurs in pattern but not in operands list!");
1499 TreePatternNode *ResultPattern =
1500 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1501 // Copy fully inferred output node type to instruction result pattern.
1503 ResultPattern->setTypes(Res0Node->getExtTypes());
1505 // Create and insert the instruction.
1506 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1507 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1509 // Use a temporary tree pattern to infer all types and make sure that the
1510 // constructed result is correct. This depends on the instruction already
1511 // being inserted into the Instructions map.
1512 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1513 Temp.InferAllTypes();
1515 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1516 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1521 // If we can, convert the instructions to be patterns that are matched!
1522 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1523 E = Instructions.end(); II != E; ++II) {
1524 DAGInstruction &TheInst = II->second;
1525 TreePattern *I = TheInst.getPattern();
1526 if (I == 0) continue; // No pattern.
1528 if (I->getNumTrees() != 1) {
1529 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1532 TreePatternNode *Pattern = I->getTree(0);
1533 TreePatternNode *SrcPattern;
1534 if (Pattern->getOperator()->getName() == "set") {
1535 if (Pattern->getNumChildren() != 2)
1536 continue; // Not a set of a single value (not handled so far)
1538 SrcPattern = Pattern->getChild(1)->clone();
1540 // Not a set (store or something?)
1541 SrcPattern = Pattern;
1545 if (!SrcPattern->canPatternMatch(Reason, *this))
1546 I->error("Instruction can never match: " + Reason);
1548 Record *Instr = II->first;
1549 TreePatternNode *DstPattern = TheInst.getResultPattern();
1551 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1552 SrcPattern, DstPattern,
1553 Instr->getValueAsInt("AddedComplexity")));
1557 void DAGISelEmitter::ParsePatterns() {
1558 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1560 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1561 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1562 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1564 // Inline pattern fragments into it.
1565 Pattern->InlinePatternFragments();
1567 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1568 if (LI->getSize() == 0) continue; // no pattern.
1570 // Parse the instruction.
1571 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1573 // Inline pattern fragments into it.
1574 Result->InlinePatternFragments();
1576 if (Result->getNumTrees() != 1)
1577 Result->error("Cannot handle instructions producing instructions "
1578 "with temporaries yet!");
1580 bool IterateInference;
1581 bool InferredAllPatternTypes, InferredAllResultTypes;
1583 // Infer as many types as possible. If we cannot infer all of them, we
1584 // can never do anything with this pattern: report it to the user.
1585 InferredAllPatternTypes = Pattern->InferAllTypes();
1587 // Infer as many types as possible. If we cannot infer all of them, we can
1588 // never do anything with this pattern: report it to the user.
1589 InferredAllResultTypes = Result->InferAllTypes();
1591 // Apply the type of the result to the source pattern. This helps us
1592 // resolve cases where the input type is known to be a pointer type (which
1593 // is considered resolved), but the result knows it needs to be 32- or
1594 // 64-bits. Infer the other way for good measure.
1595 IterateInference = Pattern->getOnlyTree()->
1596 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1597 IterateInference |= Result->getOnlyTree()->
1598 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1599 } while (IterateInference);
1601 // Verify that we inferred enough types that we can do something with the
1602 // pattern and result. If these fire the user has to add type casts.
1603 if (!InferredAllPatternTypes)
1604 Pattern->error("Could not infer all types in pattern!");
1605 if (!InferredAllResultTypes)
1606 Result->error("Could not infer all types in pattern result!");
1608 // Validate that the input pattern is correct.
1610 std::map<std::string, TreePatternNode*> InstInputs;
1611 std::map<std::string, TreePatternNode*> InstResults;
1612 std::vector<Record*> InstImpInputs;
1613 std::vector<Record*> InstImpResults;
1614 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1615 InstInputs, InstResults,
1616 InstImpInputs, InstImpResults);
1619 // Promote the xform function to be an explicit node if set.
1620 std::vector<TreePatternNode*> ResultNodeOperands;
1621 TreePatternNode *DstPattern = Result->getOnlyTree();
1622 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1623 TreePatternNode *OpNode = DstPattern->getChild(ii);
1624 if (Record *Xform = OpNode->getTransformFn()) {
1625 OpNode->setTransformFn(0);
1626 std::vector<TreePatternNode*> Children;
1627 Children.push_back(OpNode);
1628 OpNode = new TreePatternNode(Xform, Children);
1630 ResultNodeOperands.push_back(OpNode);
1632 DstPattern = Result->getOnlyTree();
1633 if (!DstPattern->isLeaf())
1634 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1635 ResultNodeOperands);
1636 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1637 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1638 Temp.InferAllTypes();
1641 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1642 Pattern->error("Pattern can never match: " + Reason);
1645 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1646 Pattern->getOnlyTree(),
1648 Patterns[i]->getValueAsInt("AddedComplexity")));
1652 /// CombineChildVariants - Given a bunch of permutations of each child of the
1653 /// 'operator' node, put them together in all possible ways.
1654 static void CombineChildVariants(TreePatternNode *Orig,
1655 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1656 std::vector<TreePatternNode*> &OutVariants,
1657 DAGISelEmitter &ISE) {
1658 // Make sure that each operand has at least one variant to choose from.
1659 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1660 if (ChildVariants[i].empty())
1663 // The end result is an all-pairs construction of the resultant pattern.
1664 std::vector<unsigned> Idxs;
1665 Idxs.resize(ChildVariants.size());
1666 bool NotDone = true;
1668 // Create the variant and add it to the output list.
1669 std::vector<TreePatternNode*> NewChildren;
1670 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1671 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1672 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1674 // Copy over properties.
1675 R->setName(Orig->getName());
1676 R->setPredicateFn(Orig->getPredicateFn());
1677 R->setTransformFn(Orig->getTransformFn());
1678 R->setTypes(Orig->getExtTypes());
1680 // If this pattern cannot every match, do not include it as a variant.
1681 std::string ErrString;
1682 if (!R->canPatternMatch(ErrString, ISE)) {
1685 bool AlreadyExists = false;
1687 // Scan to see if this pattern has already been emitted. We can get
1688 // duplication due to things like commuting:
1689 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1690 // which are the same pattern. Ignore the dups.
1691 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1692 if (R->isIsomorphicTo(OutVariants[i])) {
1693 AlreadyExists = true;
1700 OutVariants.push_back(R);
1703 // Increment indices to the next permutation.
1705 // Look for something we can increment without causing a wrap-around.
1706 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1707 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1708 NotDone = true; // Found something to increment.
1716 /// CombineChildVariants - A helper function for binary operators.
1718 static void CombineChildVariants(TreePatternNode *Orig,
1719 const std::vector<TreePatternNode*> &LHS,
1720 const std::vector<TreePatternNode*> &RHS,
1721 std::vector<TreePatternNode*> &OutVariants,
1722 DAGISelEmitter &ISE) {
1723 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1724 ChildVariants.push_back(LHS);
1725 ChildVariants.push_back(RHS);
1726 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1730 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1731 std::vector<TreePatternNode *> &Children) {
1732 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1733 Record *Operator = N->getOperator();
1735 // Only permit raw nodes.
1736 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1737 N->getTransformFn()) {
1738 Children.push_back(N);
1742 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1743 Children.push_back(N->getChild(0));
1745 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1747 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1748 Children.push_back(N->getChild(1));
1750 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1753 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1754 /// the (potentially recursive) pattern by using algebraic laws.
1756 static void GenerateVariantsOf(TreePatternNode *N,
1757 std::vector<TreePatternNode*> &OutVariants,
1758 DAGISelEmitter &ISE) {
1759 // We cannot permute leaves.
1761 OutVariants.push_back(N);
1765 // Look up interesting info about the node.
1766 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1768 // If this node is associative, reassociate.
1769 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1770 // Reassociate by pulling together all of the linked operators
1771 std::vector<TreePatternNode*> MaximalChildren;
1772 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1774 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1776 if (MaximalChildren.size() == 3) {
1777 // Find the variants of all of our maximal children.
1778 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1779 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1780 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1781 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1783 // There are only two ways we can permute the tree:
1784 // (A op B) op C and A op (B op C)
1785 // Within these forms, we can also permute A/B/C.
1787 // Generate legal pair permutations of A/B/C.
1788 std::vector<TreePatternNode*> ABVariants;
1789 std::vector<TreePatternNode*> BAVariants;
1790 std::vector<TreePatternNode*> ACVariants;
1791 std::vector<TreePatternNode*> CAVariants;
1792 std::vector<TreePatternNode*> BCVariants;
1793 std::vector<TreePatternNode*> CBVariants;
1794 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1795 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1796 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1797 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1798 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1799 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1801 // Combine those into the result: (x op x) op x
1802 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1803 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1804 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1805 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1806 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1807 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1809 // Combine those into the result: x op (x op x)
1810 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1811 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1812 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1813 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1814 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1815 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1820 // Compute permutations of all children.
1821 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1822 ChildVariants.resize(N->getNumChildren());
1823 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1824 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1826 // Build all permutations based on how the children were formed.
1827 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1829 // If this node is commutative, consider the commuted order.
1830 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1831 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1832 // Consider the commuted order.
1833 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1839 // GenerateVariants - Generate variants. For example, commutative patterns can
1840 // match multiple ways. Add them to PatternsToMatch as well.
1841 void DAGISelEmitter::GenerateVariants() {
1843 DEBUG(std::cerr << "Generating instruction variants.\n");
1845 // Loop over all of the patterns we've collected, checking to see if we can
1846 // generate variants of the instruction, through the exploitation of
1847 // identities. This permits the target to provide agressive matching without
1848 // the .td file having to contain tons of variants of instructions.
1850 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1851 // intentionally do not reconsider these. Any variants of added patterns have
1852 // already been added.
1854 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1855 std::vector<TreePatternNode*> Variants;
1856 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1858 assert(!Variants.empty() && "Must create at least original variant!");
1859 Variants.erase(Variants.begin()); // Remove the original pattern.
1861 if (Variants.empty()) // No variants for this pattern.
1864 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1865 PatternsToMatch[i].getSrcPattern()->dump();
1868 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1869 TreePatternNode *Variant = Variants[v];
1871 DEBUG(std::cerr << " VAR#" << v << ": ";
1875 // Scan to see if an instruction or explicit pattern already matches this.
1876 bool AlreadyExists = false;
1877 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1878 // Check to see if this variant already exists.
1879 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1880 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1881 AlreadyExists = true;
1885 // If we already have it, ignore the variant.
1886 if (AlreadyExists) continue;
1888 // Otherwise, add it to the list of patterns we have.
1890 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1891 Variant, PatternsToMatch[i].getDstPattern(),
1892 PatternsToMatch[i].getAddedComplexity()));
1895 DEBUG(std::cerr << "\n");
1900 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1902 static bool NodeIsComplexPattern(TreePatternNode *N)
1904 return (N->isLeaf() &&
1905 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1906 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1907 isSubClassOf("ComplexPattern"));
1910 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1911 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1912 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1913 DAGISelEmitter &ISE)
1916 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1917 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1918 isSubClassOf("ComplexPattern")) {
1919 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1925 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1926 /// patterns before small ones. This is used to determine the size of a
1928 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1929 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1930 isExtFloatingPointInVTs(P->getExtTypes()) ||
1931 P->getExtTypeNum(0) == MVT::isVoid ||
1932 P->getExtTypeNum(0) == MVT::Flag ||
1933 P->getExtTypeNum(0) == MVT::iPTR) &&
1934 "Not a valid pattern node to size!");
1935 unsigned Size = 2; // The node itself.
1936 // If the root node is a ConstantSDNode, increases its size.
1937 // e.g. (set R32:$dst, 0).
1938 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1941 // FIXME: This is a hack to statically increase the priority of patterns
1942 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1943 // Later we can allow complexity / cost for each pattern to be (optionally)
1944 // specified. To get best possible pattern match we'll need to dynamically
1945 // calculate the complexity of all patterns a dag can potentially map to.
1946 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1948 Size += AM->getNumOperands() * 2;
1950 // If this node has some predicate function that must match, it adds to the
1951 // complexity of this node.
1952 if (!P->getPredicateFn().empty())
1955 // Count children in the count if they are also nodes.
1956 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1957 TreePatternNode *Child = P->getChild(i);
1958 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1959 Size += getPatternSize(Child, ISE);
1960 else if (Child->isLeaf()) {
1961 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1962 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
1963 else if (NodeIsComplexPattern(Child))
1964 Size += getPatternSize(Child, ISE);
1965 else if (!Child->getPredicateFn().empty())
1973 /// getResultPatternCost - Compute the number of instructions for this pattern.
1974 /// This is a temporary hack. We should really include the instruction
1975 /// latencies in this calculation.
1976 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1977 if (P->isLeaf()) return 0;
1980 Record *Op = P->getOperator();
1981 if (Op->isSubClassOf("Instruction")) {
1983 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1984 if (II.usesCustomDAGSchedInserter)
1987 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1988 Cost += getResultPatternCost(P->getChild(i), ISE);
1992 /// getResultPatternCodeSize - Compute the code size of instructions for this
1994 static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1995 if (P->isLeaf()) return 0;
1998 Record *Op = P->getOperator();
1999 if (Op->isSubClassOf("Instruction")) {
2000 Cost += Op->getValueAsInt("CodeSize");
2002 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2003 Cost += getResultPatternSize(P->getChild(i), ISE);
2007 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2008 // In particular, we want to match maximal patterns first and lowest cost within
2009 // a particular complexity first.
2010 struct PatternSortingPredicate {
2011 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2012 DAGISelEmitter &ISE;
2014 bool operator()(PatternToMatch *LHS,
2015 PatternToMatch *RHS) {
2016 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2017 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
2018 LHSSize += LHS->getAddedComplexity();
2019 RHSSize += RHS->getAddedComplexity();
2020 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2021 if (LHSSize < RHSSize) return false;
2023 // If the patterns have equal complexity, compare generated instruction cost
2024 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2025 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2026 if (LHSCost < RHSCost) return true;
2027 if (LHSCost > RHSCost) return false;
2029 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2030 getResultPatternSize(RHS->getDstPattern(), ISE);
2034 /// getRegisterValueType - Look up and return the first ValueType of specified
2035 /// RegisterClass record
2036 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
2037 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2038 return RC->getValueTypeNum(0);
2043 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2044 /// type information from it.
2045 static void RemoveAllTypes(TreePatternNode *N) {
2048 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2049 RemoveAllTypes(N->getChild(i));
2052 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2053 Record *N = Records.getDef(Name);
2054 if (!N || !N->isSubClassOf("SDNode")) {
2055 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2061 /// NodeHasProperty - return true if TreePatternNode has the specified
2063 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2064 DAGISelEmitter &ISE)
2066 if (N->isLeaf()) return false;
2067 Record *Operator = N->getOperator();
2068 if (!Operator->isSubClassOf("SDNode")) return false;
2070 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2071 return NodeInfo.hasProperty(Property);
2074 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2075 DAGISelEmitter &ISE)
2077 if (NodeHasProperty(N, Property, ISE))
2080 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2081 TreePatternNode *Child = N->getChild(i);
2082 if (PatternHasProperty(Child, Property, ISE))
2089 class PatternCodeEmitter {
2091 DAGISelEmitter &ISE;
2094 ListInit *Predicates;
2097 // Instruction selector pattern.
2098 TreePatternNode *Pattern;
2099 // Matched instruction.
2100 TreePatternNode *Instruction;
2102 // Node to name mapping
2103 std::map<std::string, std::string> VariableMap;
2104 // Node to operator mapping
2105 std::map<std::string, Record*> OperatorMap;
2106 // Names of all the folded nodes which produce chains.
2107 std::vector<std::pair<std::string, unsigned> > FoldedChains;
2108 std::set<std::string> Duplicates;
2110 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2111 /// indicates whether this is an exit predicate (something that should be
2112 /// tested, and if true, the match fails) [when true] or normal code to emit
2114 std::vector<std::pair<bool, std::string> > &GeneratedCode;
2115 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2116 /// the set of patterns for each top-level opcode.
2117 std::set<std::pair<unsigned, std::string> > &GeneratedDecl;
2118 /// TargetOpcodes - The target specific opcodes used by the resulting
2120 std::vector<std::string> &TargetOpcodes;
2121 std::vector<std::string> &TargetVTs;
2123 std::string ChainName;
2129 void emitCheck(const std::string &S) {
2131 GeneratedCode.push_back(std::make_pair(true, S));
2133 void emitCode(const std::string &S) {
2135 GeneratedCode.push_back(std::make_pair(false, S));
2137 void emitDecl(const std::string &S, unsigned T=0) {
2138 assert(!S.empty() && "Invalid declaration");
2139 GeneratedDecl.insert(std::make_pair(T, S));
2141 void emitOpcode(const std::string &Opc) {
2142 TargetOpcodes.push_back(Opc);
2145 void emitVT(const std::string &VT) {
2146 TargetVTs.push_back(VT);
2150 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2151 TreePatternNode *pattern, TreePatternNode *instr,
2152 std::vector<std::pair<bool, std::string> > &gc,
2153 std::set<std::pair<unsigned, std::string> > &gd,
2154 std::vector<std::string> &to,
2155 std::vector<std::string> &tv,
2157 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2158 GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to), TargetVTs(tv),
2159 DoReplace(dorep), TmpNo(0), OpcNo(0), VTNo(0) {}
2161 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2162 /// if the match fails. At this point, we already know that the opcode for N
2163 /// matches, and the SDNode for the result has the RootName specified name.
2164 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2165 const std::string &RootName, const std::string &ParentName,
2166 const std::string &ChainSuffix, bool &FoundChain) {
2167 bool isRoot = (P == NULL);
2168 // Emit instruction predicates. Each predicate is just a string for now.
2170 std::string PredicateCheck;
2171 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2172 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2173 Record *Def = Pred->getDef();
2174 if (!Def->isSubClassOf("Predicate")) {
2178 assert(0 && "Unknown predicate type!");
2180 if (!PredicateCheck.empty())
2181 PredicateCheck += " || ";
2182 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2186 emitCheck(PredicateCheck);
2190 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2191 emitCheck("cast<ConstantSDNode>(" + RootName +
2192 ")->getSignExtended() == " + itostr(II->getValue()));
2194 } else if (!NodeIsComplexPattern(N)) {
2195 assert(0 && "Cannot match this as a leaf value!");
2200 // If this node has a name associated with it, capture it in VariableMap. If
2201 // we already saw this in the pattern, emit code to verify dagness.
2202 if (!N->getName().empty()) {
2203 std::string &VarMapEntry = VariableMap[N->getName()];
2204 if (VarMapEntry.empty()) {
2205 VarMapEntry = RootName;
2207 // If we get here, this is a second reference to a specific name. Since
2208 // we already have checked that the first reference is valid, we don't
2209 // have to recursively match it, just check that it's the same as the
2210 // previously named thing.
2211 emitCheck(VarMapEntry + " == " + RootName);
2216 OperatorMap[N->getName()] = N->getOperator();
2220 // Emit code to load the child nodes and match their contents recursively.
2222 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2223 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2224 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
2225 bool EmittedUseCheck = false;
2226 bool EmittedSlctedCheck = false;
2231 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2232 // Multiple uses of actual result?
2233 emitCheck(RootName + ".hasOneUse()");
2234 EmittedUseCheck = true;
2235 // hasOneUse() check is not strong enough. If the original node has
2236 // already been selected, it may have been replaced with another.
2237 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2238 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2241 EmittedSlctedCheck = true;
2243 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2245 // This a workaround for this problem:
2250 // [XX]--/ \- [flag : cmp]
2255 // cmp + br should be considered as a single node as they are flagged
2256 // together. So, if the ld is folded into the cmp, the XX node in the
2257 // graph is now both an operand and a use of the ld/cmp/br node.
2258 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2259 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2261 // If the immediate use can somehow reach this node through another
2262 // path, then can't fold it either or it will create a cycle.
2263 // e.g. In the following diagram, XX can reach ld through YY. If
2264 // ld is folded into XX, then YY is both a predecessor and a successor
2274 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2275 if (PInfo.getNumOperands() > 1 ||
2276 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2277 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2278 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2279 emitCheck("IsFoldableBy(" + RootName + ".Val, " + ParentName +
2286 emitCheck("Chain.Val == " + RootName + ".Val");
2289 ChainName = "Chain" + ChainSuffix;
2290 emitDecl(ChainName);
2291 emitCode(ChainName + " = " + RootName +
2296 // Don't fold any node which reads or writes a flag and has multiple uses.
2297 // FIXME: We really need to separate the concepts of flag and "glue". Those
2298 // real flag results, e.g. X86CMP output, can have multiple uses.
2299 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2302 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2303 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2304 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2305 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2306 if (!EmittedUseCheck) {
2307 // Multiple uses of actual result?
2308 emitCheck(RootName + ".hasOneUse()");
2310 if (!EmittedSlctedCheck)
2311 // hasOneUse() check is not strong enough. If the original node has
2312 // already been selected, it may have been replaced with another.
2313 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2314 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2318 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2319 emitDecl(RootName + utostr(OpNo));
2320 emitCode(RootName + utostr(OpNo) + " = " +
2321 RootName + ".getOperand(" +utostr(OpNo) + ");");
2322 TreePatternNode *Child = N->getChild(i);
2324 if (!Child->isLeaf()) {
2325 // If it's not a leaf, recursively match.
2326 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2327 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2328 CInfo.getEnumName());
2329 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2330 ChainSuffix + utostr(OpNo), FoundChain);
2331 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2332 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2333 CInfo.getNumResults()));
2335 // If this child has a name associated with it, capture it in VarMap. If
2336 // we already saw this in the pattern, emit code to verify dagness.
2337 if (!Child->getName().empty()) {
2338 std::string &VarMapEntry = VariableMap[Child->getName()];
2339 if (VarMapEntry.empty()) {
2340 VarMapEntry = RootName + utostr(OpNo);
2342 // If we get here, this is a second reference to a specific name.
2343 // Since we already have checked that the first reference is valid,
2344 // we don't have to recursively match it, just check that it's the
2345 // same as the previously named thing.
2346 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2347 Duplicates.insert(RootName + utostr(OpNo));
2352 // Handle leaves of various types.
2353 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2354 Record *LeafRec = DI->getDef();
2355 if (LeafRec->isSubClassOf("RegisterClass")) {
2356 // Handle register references. Nothing to do here.
2357 } else if (LeafRec->isSubClassOf("Register")) {
2358 // Handle register references.
2359 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2360 // Handle complex pattern. Nothing to do here.
2361 } else if (LeafRec->getName() == "srcvalue") {
2362 // Place holder for SRCVALUE nodes. Nothing to do here.
2363 } else if (LeafRec->isSubClassOf("ValueType")) {
2364 // Make sure this is the specified value type.
2365 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2366 ")->getVT() == MVT::" + LeafRec->getName());
2367 } else if (LeafRec->isSubClassOf("CondCode")) {
2368 // Make sure this is the specified cond code.
2369 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2370 ")->get() == ISD::" + LeafRec->getName());
2376 assert(0 && "Unknown leaf type!");
2378 } else if (IntInit *II =
2379 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2380 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2381 unsigned CTmp = TmpNo++;
2382 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2383 RootName + utostr(OpNo) + ")->getSignExtended();");
2385 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2390 assert(0 && "Unknown leaf type!");
2395 // If there is a node predicate for this, emit the call.
2396 if (!N->getPredicateFn().empty())
2397 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2400 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2401 /// we actually have to build a DAG!
2402 std::pair<unsigned, unsigned>
2403 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2404 bool isRoot = false) {
2405 // This is something selected from the pattern we matched.
2406 if (!N->getName().empty()) {
2407 std::string &Val = VariableMap[N->getName()];
2408 assert(!Val.empty() &&
2409 "Variable referenced but not defined and not caught earlier!");
2410 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2411 // Already selected this operand, just return the tmpval.
2412 return std::make_pair(1, atoi(Val.c_str()+3));
2415 const ComplexPattern *CP;
2416 unsigned ResNo = TmpNo++;
2417 unsigned NumRes = 1;
2418 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2419 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2420 std::string CastType;
2421 switch (N->getTypeNum(0)) {
2422 default: assert(0 && "Unknown type for constant node!");
2423 case MVT::i1: CastType = "bool"; break;
2424 case MVT::i8: CastType = "unsigned char"; break;
2425 case MVT::i16: CastType = "unsigned short"; break;
2426 case MVT::i32: CastType = "unsigned"; break;
2427 case MVT::i64: CastType = "uint64_t"; break;
2429 emitDecl("Tmp" + utostr(ResNo));
2430 emitCode("Tmp" + utostr(ResNo) +
2431 " = CurDAG->getTargetConstant(((" + CastType +
2432 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2433 getEnumName(N->getTypeNum(0)) + ");");
2434 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2435 Record *Op = OperatorMap[N->getName()];
2436 // Transform ExternalSymbol to TargetExternalSymbol
2437 if (Op && Op->getName() == "externalsym") {
2438 emitDecl("Tmp" + utostr(ResNo));
2439 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2440 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2441 Val + ")->getSymbol(), " +
2442 getEnumName(N->getTypeNum(0)) + ");");
2444 emitDecl("Tmp" + utostr(ResNo));
2445 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2447 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2448 Record *Op = OperatorMap[N->getName()];
2449 // Transform GlobalAddress to TargetGlobalAddress
2450 if (Op && Op->getName() == "globaladdr") {
2451 emitDecl("Tmp" + utostr(ResNo));
2452 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2453 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2454 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2457 emitDecl("Tmp" + utostr(ResNo));
2458 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2460 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2461 emitDecl("Tmp" + utostr(ResNo));
2462 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2463 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2464 emitDecl("Tmp" + utostr(ResNo));
2465 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2466 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2467 std::string Fn = CP->getSelectFunc();
2468 NumRes = CP->getNumOperands();
2469 for (unsigned i = 0; i < NumRes; ++i)
2470 emitDecl("CPTmp" + utostr(i+ResNo));
2472 std::string Code = "bool Match = " + Fn + "(" + Val;
2473 for (unsigned i = 0; i < NumRes; i++)
2474 Code += ", CPTmp" + utostr(i + ResNo);
2475 emitCode(Code + ");");
2478 for (unsigned i = 0; i < NumRes; ++i) {
2479 emitDecl("Tmp" + utostr(i+ResNo));
2480 emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" +
2481 utostr(i+ResNo) + ");");
2484 TmpNo = ResNo + NumRes;
2486 emitDecl("Tmp" + utostr(ResNo));
2487 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2488 // node even if it isn't one. Don't select it.
2490 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2492 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2495 if (isRoot && N->isLeaf()) {
2496 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2497 emitCode("return;");
2500 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2501 // value if used multiple times by this pattern result.
2502 Val = "Tmp"+utostr(ResNo);
2503 return std::make_pair(NumRes, ResNo);
2506 // If this is an explicit register reference, handle it.
2507 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2508 unsigned ResNo = TmpNo++;
2509 if (DI->getDef()->isSubClassOf("Register")) {
2510 emitDecl("Tmp" + utostr(ResNo));
2511 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2512 ISE.getQualifiedName(DI->getDef()) + ", " +
2513 getEnumName(N->getTypeNum(0)) + ");");
2514 return std::make_pair(1, ResNo);
2516 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2517 unsigned ResNo = TmpNo++;
2518 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2519 emitDecl("Tmp" + utostr(ResNo));
2520 emitCode("Tmp" + utostr(ResNo) +
2521 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2522 ", " + getEnumName(N->getTypeNum(0)) + ");");
2523 return std::make_pair(1, ResNo);
2529 assert(0 && "Unknown leaf type!");
2530 return std::make_pair(1, ~0U);
2533 Record *Op = N->getOperator();
2534 if (Op->isSubClassOf("Instruction")) {
2535 const CodeGenTarget &CGT = ISE.getTargetInfo();
2536 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2537 const DAGInstruction &Inst = ISE.getInstruction(Op);
2538 TreePattern *InstPat = Inst.getPattern();
2539 TreePatternNode *InstPatNode =
2540 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2541 : (InstPat ? InstPat->getOnlyTree() : NULL);
2542 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2543 InstPatNode = InstPatNode->getChild(1);
2545 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
2546 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2547 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2548 bool NodeHasOptInFlag = isRoot &&
2549 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2550 bool NodeHasInFlag = isRoot &&
2551 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2552 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2553 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2554 bool NodeHasChain = InstPatNode &&
2555 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
2556 bool InputHasChain = isRoot &&
2557 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2559 if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
2561 if (NodeHasOptInFlag) {
2562 emitDecl("HasInFlag", 2);
2563 emitCode("HasInFlag = "
2564 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
2567 emitCode("std::vector<SDOperand> Ops;");
2569 // How many results is this pattern expected to produce?
2570 unsigned PatResults = 0;
2571 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2572 MVT::ValueType VT = Pattern->getTypeNum(i);
2573 if (VT != MVT::isVoid && VT != MVT::Flag)
2577 // Determine operand emission order. Complex pattern first.
2578 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2579 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2580 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2581 TreePatternNode *Child = N->getChild(i);
2583 EmitOrder.push_back(std::make_pair(i, Child));
2584 OI = EmitOrder.begin();
2585 } else if (NodeIsComplexPattern(Child)) {
2586 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2588 EmitOrder.push_back(std::make_pair(i, Child));
2592 // Emit all of the operands.
2593 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2594 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2595 unsigned OpOrder = EmitOrder[i].first;
2596 TreePatternNode *Child = EmitOrder[i].second;
2597 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2598 NumTemps[OpOrder] = NumTemp;
2601 // List all the operands in the right order.
2602 std::vector<unsigned> Ops;
2603 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2604 for (unsigned j = 0; j < NumTemps[i].first; j++)
2605 Ops.push_back(NumTemps[i].second + j);
2608 // Emit all the chain and CopyToReg stuff.
2609 bool ChainEmitted = NodeHasChain;
2611 emitCode("Select(" + ChainName + ", " + ChainName + ");");
2612 if (NodeHasInFlag || HasImpInputs)
2613 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2614 if (NodeHasOptInFlag) {
2615 emitCode("if (HasInFlag)");
2616 emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));");
2619 unsigned NumResults = Inst.getNumResults();
2620 unsigned ResNo = TmpNo++;
2621 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2625 std::string NodeName;
2627 NodeName = "Tmp" + utostr(ResNo);
2629 Code2 = NodeName + " = SDOperand(";
2631 NodeName = "ResNode";
2632 emitDecl(NodeName, true);
2633 Code2 = NodeName + " = ";
2635 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2636 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2638 // Output order: results, chain, flags
2640 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2641 Code += ", VT" + utostr(VTNo);
2642 emitVT(getEnumName(N->getTypeNum(0)));
2645 Code += ", MVT::Other";
2647 Code += ", MVT::Flag";
2650 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2652 emitCode("Ops.push_back(Tmp" + utostr(Ops[i]) + ");");
2654 Code += ", Tmp" + utostr(Ops[i]);
2658 if (NodeHasInFlag || HasImpInputs)
2659 emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2661 else if (NodeHasOptInFlag)
2662 emitCode("for (unsigned i = 2, e = N.getNumOperands()-"
2663 "(HasInFlag?1:0); i != e; ++i) {");
2665 emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2667 emitCode(" SDOperand VarOp(0, 0);");
2668 emitCode(" Select(VarOp, N.getOperand(i));");
2669 emitCode(" Ops.push_back(VarOp);");
2675 emitCode("Ops.push_back(" + ChainName + ");");
2677 Code += ", " + ChainName;
2679 if (NodeHasInFlag || HasImpInputs) {
2681 emitCode("Ops.push_back(InFlag);");
2684 } else if (NodeHasOptInFlag && HasVarOps) {
2685 emitCode("if (HasInFlag)");
2686 emitCode(" Ops.push_back(InFlag);");
2691 else if (NodeHasOptInFlag)
2692 Code = "HasInFlag ? " + Code + ", InFlag) : " + Code;
2696 emitCode(Code2 + Code + ");");
2699 // Remember which op produces the chain.
2701 emitCode(ChainName + " = SDOperand(" + NodeName +
2702 ".Val, " + utostr(PatResults) + ");");
2704 emitCode(ChainName + " = SDOperand(" + NodeName +
2705 ", " + utostr(PatResults) + ");");
2708 return std::make_pair(1, ResNo);
2710 for (unsigned i = 0; i < NumResults; i++)
2711 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2712 utostr(i) + ", ResNode, " + utostr(i) + ");");
2715 emitCode("InFlag = SDOperand(ResNode, " +
2716 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2718 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2719 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2724 if (InputHasChain) {
2725 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2726 utostr(PatResults) + ", " + ChainName + ".Val, " +
2727 ChainName + ".ResNo" + ");");
2729 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2730 utostr(PatResults) + ", " + ChainName + ".Val, " +
2731 ChainName + ".ResNo" + ");");
2734 if (FoldedChains.size() > 0) {
2736 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2737 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2738 FoldedChains[j].first + ".Val, " +
2739 utostr(FoldedChains[j].second) + ", ResNode, " +
2740 utostr(NumResults) + ");");
2742 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2744 FoldedChains[j].first + ".Val, " +
2745 utostr(FoldedChains[j].second) + ", ";
2746 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2747 utostr(NumResults) + ");");
2752 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2753 utostr(PatResults + (unsigned)InputHasChain) +
2754 ", InFlag.Val, InFlag.ResNo);");
2756 // User does not expect the instruction would produce a chain!
2757 bool AddedChain = NodeHasChain && !InputHasChain;
2758 if (AddedChain && NodeHasOutFlag) {
2759 if (PatResults == 0) {
2760 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2762 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2763 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2765 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
2767 } else if (InputHasChain && !NodeHasChain) {
2768 // One of the inner node produces a chain.
2769 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2770 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2771 if (NodeHasOutFlag) {
2772 emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2773 emitCode(" Result = SDOperand(ResNode, N.ResNo-1);");
2776 emitCode(" Result = SDOperand(" + ChainName + ".Val, " +
2777 ChainName + ".ResNo);");
2779 emitCode("Result = SDOperand(ResNode, N.ResNo);");
2782 // If this instruction is the root, and if there is only one use of it,
2783 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2784 emitCode("if (N.Val->hasOneUse()) {");
2785 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, Opc" +
2787 if (N->getTypeNum(0) != MVT::isVoid)
2788 Code += ", VT" + utostr(VTNo);
2790 Code += ", MVT::Flag";
2791 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2792 Code += ", Tmp" + utostr(Ops[i]);
2793 if (NodeHasInFlag || HasImpInputs)
2795 emitCode(Code + ");");
2796 emitCode("} else {");
2797 emitDecl("ResNode", 1);
2798 Code = " ResNode = CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2799 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2800 if (N->getTypeNum(0) != MVT::isVoid) {
2801 Code += ", VT" + utostr(VTNo);
2802 emitVT(getEnumName(N->getTypeNum(0)));
2805 Code += ", MVT::Flag";
2806 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2807 Code += ", Tmp" + utostr(Ops[i]);
2808 if (NodeHasInFlag || HasImpInputs)
2810 emitCode(Code + ");");
2811 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo"
2813 emitCode(" Result = SDOperand(ResNode, 0);");
2818 emitCode("return;");
2819 return std::make_pair(1, ResNo);
2820 } else if (Op->isSubClassOf("SDNodeXForm")) {
2821 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2822 // PatLeaf node - the operand may or may not be a leaf node. But it should
2824 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2825 unsigned ResNo = TmpNo++;
2826 emitDecl("Tmp" + utostr(ResNo));
2827 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2828 + "(Tmp" + utostr(OpVal) + ".Val);");
2830 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2831 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2832 utostr(ResNo) + ".ResNo);");
2833 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2834 emitCode("return;");
2836 return std::make_pair(1, ResNo);
2840 throw std::string("Unknown node in result pattern!");
2844 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2845 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2846 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2847 /// for, this returns true otherwise false if Pat has all types.
2848 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2849 const std::string &Prefix) {
2851 if (Pat->getExtTypes() != Other->getExtTypes()) {
2852 // Move a type over from 'other' to 'pat'.
2853 Pat->setTypes(Other->getExtTypes());
2854 emitCheck(Prefix + ".Val->getValueType(0) == " +
2855 getName(Pat->getTypeNum(0)));
2860 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2861 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2862 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2863 Prefix + utostr(OpNo)))
2869 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2871 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2872 bool &ChainEmitted, bool isRoot = false) {
2873 const CodeGenTarget &T = ISE.getTargetInfo();
2875 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2876 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2877 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2878 TreePatternNode *Child = N->getChild(i);
2879 if (!Child->isLeaf()) {
2880 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2882 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2883 if (!Child->getName().empty()) {
2884 std::string Name = RootName + utostr(OpNo);
2885 if (Duplicates.find(Name) != Duplicates.end())
2886 // A duplicate! Do not emit a copy for this node.
2890 Record *RR = DI->getDef();
2891 if (RR->isSubClassOf("Register")) {
2892 MVT::ValueType RVT = getRegisterValueType(RR, T);
2893 if (RVT == MVT::Flag) {
2894 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2896 if (!ChainEmitted) {
2898 emitCode("Chain = CurDAG->getEntryNode();");
2899 ChainName = "Chain";
2900 ChainEmitted = true;
2902 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2903 RootName + utostr(OpNo) + ");");
2904 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2905 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2906 ", " + getEnumName(RVT) + "), " +
2907 RootName + utostr(OpNo) + ", InFlag).Val;");
2908 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2909 emitCode("InFlag = SDOperand(ResNode, 1);");
2917 emitCode("Select(InFlag, " + RootName +
2918 ".getOperand(" + utostr(OpNo) + "));");
2921 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2922 /// as specified by the instruction. It returns true if any copy is
2924 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2925 bool RetVal = false;
2926 Record *Op = N->getOperator();
2927 if (Op->isSubClassOf("Instruction")) {
2928 const DAGInstruction &Inst = ISE.getInstruction(Op);
2929 const CodeGenTarget &CGT = ISE.getTargetInfo();
2930 unsigned NumImpResults = Inst.getNumImpResults();
2931 for (unsigned i = 0; i < NumImpResults; i++) {
2932 Record *RR = Inst.getImpResult(i);
2933 if (RR->isSubClassOf("Register")) {
2934 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2935 if (RVT != MVT::Flag) {
2936 if (!ChainEmitted) {
2938 emitCode("Chain = CurDAG->getEntryNode();");
2939 ChainEmitted = true;
2940 ChainName = "Chain";
2942 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName +
2943 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
2945 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2946 emitCode("InFlag = SDOperand(ResNode, 2);");
2956 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2957 /// stream to match the pattern, and generate the code for the match if it
2958 /// succeeds. Returns true if the pattern is not guaranteed to match.
2959 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2960 std::vector<std::pair<bool, std::string> > &GeneratedCode,
2961 std::set<std::pair<unsigned, std::string> > &GeneratedDecl,
2962 std::vector<std::string> &TargetOpcodes,
2963 std::vector<std::string> &TargetVTs,
2965 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2966 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2967 GeneratedCode, GeneratedDecl,
2968 TargetOpcodes, TargetVTs,
2971 // Emit the matcher, capturing named arguments in VariableMap.
2972 bool FoundChain = false;
2973 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
2975 // TP - Get *SOME* tree pattern, we don't care which.
2976 TreePattern &TP = *PatternFragments.begin()->second;
2978 // At this point, we know that we structurally match the pattern, but the
2979 // types of the nodes may not match. Figure out the fewest number of type
2980 // comparisons we need to emit. For example, if there is only one integer
2981 // type supported by a target, there should be no type comparisons at all for
2982 // integer patterns!
2984 // To figure out the fewest number of type checks needed, clone the pattern,
2985 // remove the types, then perform type inference on the pattern as a whole.
2986 // If there are unresolved types, emit an explicit check for those types,
2987 // apply the type to the tree, then rerun type inference. Iterate until all
2988 // types are resolved.
2990 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2991 RemoveAllTypes(Pat);
2994 // Resolve/propagate as many types as possible.
2996 bool MadeChange = true;
2998 MadeChange = Pat->ApplyTypeConstraints(TP,
2999 true/*Ignore reg constraints*/);
3001 assert(0 && "Error: could not find consistent types for something we"
3002 " already decided was ok!");
3006 // Insert a check for an unresolved type and add it to the tree. If we find
3007 // an unresolved type to add a check for, this returns true and we iterate,
3008 // otherwise we are done.
3009 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
3011 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
3015 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
3016 /// a line causes any of them to be empty, remove them and return true when
3018 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
3019 std::vector<std::pair<bool, std::string> > > >
3021 bool ErasedPatterns = false;
3022 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3023 Patterns[i].second.pop_back();
3024 if (Patterns[i].second.empty()) {
3025 Patterns.erase(Patterns.begin()+i);
3027 ErasedPatterns = true;
3030 return ErasedPatterns;
3033 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3034 /// code together between the patterns.
3035 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3036 std::vector<std::pair<bool, std::string> > > >
3037 &Patterns, unsigned Indent,
3039 typedef std::pair<bool, std::string> CodeLine;
3040 typedef std::vector<CodeLine> CodeList;
3041 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3043 if (Patterns.empty()) return;
3045 // Figure out how many patterns share the next code line. Explicitly copy
3046 // FirstCodeLine so that we don't invalidate a reference when changing
3048 const CodeLine FirstCodeLine = Patterns.back().second.back();
3049 unsigned LastMatch = Patterns.size()-1;
3050 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3053 // If not all patterns share this line, split the list into two pieces. The
3054 // first chunk will use this line, the second chunk won't.
3055 if (LastMatch != 0) {
3056 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3057 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3059 // FIXME: Emit braces?
3060 if (Shared.size() == 1) {
3061 PatternToMatch &Pattern = *Shared.back().first;
3062 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3063 Pattern.getSrcPattern()->print(OS);
3064 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3065 Pattern.getDstPattern()->print(OS);
3067 unsigned AddedComplexity = Pattern.getAddedComplexity();
3068 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3069 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3071 << getResultPatternCost(Pattern.getDstPattern(), *this)
3073 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3075 if (!FirstCodeLine.first) {
3076 OS << std::string(Indent, ' ') << "{\n";
3079 EmitPatterns(Shared, Indent, OS);
3080 if (!FirstCodeLine.first) {
3082 OS << std::string(Indent, ' ') << "}\n";
3085 if (Other.size() == 1) {
3086 PatternToMatch &Pattern = *Other.back().first;
3087 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3088 Pattern.getSrcPattern()->print(OS);
3089 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3090 Pattern.getDstPattern()->print(OS);
3092 unsigned AddedComplexity = Pattern.getAddedComplexity();
3093 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3094 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3096 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
3098 EmitPatterns(Other, Indent, OS);
3102 // Remove this code from all of the patterns that share it.
3103 bool ErasedPatterns = EraseCodeLine(Patterns);
3105 bool isPredicate = FirstCodeLine.first;
3107 // Otherwise, every pattern in the list has this line. Emit it.
3110 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3112 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3114 // If the next code line is another predicate, and if all of the pattern
3115 // in this group share the same next line, emit it inline now. Do this
3116 // until we run out of common predicates.
3117 while (!ErasedPatterns && Patterns.back().second.back().first) {
3118 // Check that all of fhe patterns in Patterns end with the same predicate.
3119 bool AllEndWithSamePredicate = true;
3120 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3121 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3122 AllEndWithSamePredicate = false;
3125 // If all of the predicates aren't the same, we can't share them.
3126 if (!AllEndWithSamePredicate) break;
3128 // Otherwise we can. Emit it shared now.
3129 OS << " &&\n" << std::string(Indent+4, ' ')
3130 << Patterns.back().second.back().second;
3131 ErasedPatterns = EraseCodeLine(Patterns);
3138 EmitPatterns(Patterns, Indent, OS);
3141 OS << std::string(Indent-2, ' ') << "}\n";
3147 /// CompareByRecordName - An ordering predicate that implements less-than by
3148 /// comparing the names records.
3149 struct CompareByRecordName {
3150 bool operator()(const Record *LHS, const Record *RHS) const {
3151 // Sort by name first.
3152 if (LHS->getName() < RHS->getName()) return true;
3153 // If both names are equal, sort by pointer.
3154 return LHS->getName() == RHS->getName() && LHS < RHS;
3159 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3160 std::string InstNS = Target.inst_begin()->second.Namespace;
3161 if (!InstNS.empty()) InstNS += "::";
3163 // Group the patterns by their top-level opcodes.
3164 std::map<Record*, std::vector<PatternToMatch*>,
3165 CompareByRecordName> PatternsByOpcode;
3166 // All unique target node emission functions.
3167 std::map<std::string, unsigned> EmitFunctions;
3168 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3169 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3170 if (!Node->isLeaf()) {
3171 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3173 const ComplexPattern *CP;
3175 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3176 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3177 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3178 std::vector<Record*> OpNodes = CP->getRootNodes();
3179 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3180 PatternsByOpcode[OpNodes[j]]
3181 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3184 std::cerr << "Unrecognized opcode '";
3186 std::cerr << "' on tree pattern '";
3188 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3189 std::cerr << "'!\n";
3195 // Emit one Select_* method for each top-level opcode. We do this instead of
3196 // emitting one giant switch statement to support compilers where this will
3197 // result in the recursive functions taking less stack space.
3198 for (std::map<Record*, std::vector<PatternToMatch*>,
3199 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3200 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3201 const std::string &OpName = PBOI->first->getName();
3202 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3204 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3205 OpcodeInfo.getNumResults() > 0);
3206 std::vector<PatternToMatch*> &Patterns = PBOI->second;
3207 assert(!Patterns.empty() && "No patterns but map has entry?");
3209 // We want to emit all of the matching code now. However, we want to emit
3210 // the matches in order of minimal cost. Sort the patterns so the least
3211 // cost one is at the start.
3212 std::stable_sort(Patterns.begin(), Patterns.end(),
3213 PatternSortingPredicate(*this));
3215 typedef std::vector<std::pair<bool, std::string> > CodeList;
3216 typedef std::vector<std::pair<bool, std::string> >::iterator CodeListI;
3218 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3219 std::vector<std::vector<std::string> > PatternOpcodes;
3220 std::vector<std::vector<std::string> > PatternVTs;
3221 std::vector<std::set<std::pair<unsigned, std::string> > > PatternDecls;
3222 std::set<std::pair<unsigned, std::string> > AllGenDecls;
3223 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3224 CodeList GeneratedCode;
3225 std::set<std::pair<unsigned, std::string> > GeneratedDecl;
3226 std::vector<std::string> TargetOpcodes;
3227 std::vector<std::string> TargetVTs;
3228 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3229 TargetOpcodes, TargetVTs, OptSlctOrder);
3230 for (std::set<std::pair<unsigned, std::string> >::iterator
3231 si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si)
3232 AllGenDecls.insert(*si);
3233 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3234 PatternDecls.push_back(GeneratedDecl);
3235 PatternOpcodes.push_back(TargetOpcodes);
3236 PatternVTs.push_back(TargetVTs);
3239 // Scan the code to see if all of the patterns are reachable and if it is
3240 // possible that the last one might not match.
3241 bool mightNotMatch = true;
3242 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3243 CodeList &GeneratedCode = CodeForPatterns[i].second;
3244 mightNotMatch = false;
3246 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3247 if (GeneratedCode[j].first) { // predicate.
3248 mightNotMatch = true;
3253 // If this pattern definitely matches, and if it isn't the last one, the
3254 // patterns after it CANNOT ever match. Error out.
3255 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3256 std::cerr << "Pattern '";
3257 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3258 std::cerr << "' is impossible to select!\n";
3263 // Factor target node emission code (emitted by EmitResultCode) into
3264 // separate functions. Uniquing and share them among all instruction
3265 // selection routines.
3266 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3267 CodeList &GeneratedCode = CodeForPatterns[i].second;
3268 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3269 std::vector<std::string> &TargetVTs = PatternVTs[i];
3270 std::set<std::pair<unsigned, std::string> > Decls = PatternDecls[i];
3271 int CodeSize = (int)GeneratedCode.size();
3273 for (int j = CodeSize-1; j >= 0; --j) {
3274 if (GeneratedCode[j].first) {
3280 std::string CalleeDecls;
3281 std::string CalleeCode = "(SDOperand &Result, SDOperand &N";
3282 std::string CallerCode = "(Result, N";
3283 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3284 CalleeCode += ", unsigned Opc" + utostr(j);
3285 CallerCode += ", " + TargetOpcodes[j];
3287 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3288 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3289 CallerCode += ", " + TargetVTs[j];
3291 for (std::set<std::pair<unsigned, std::string> >::iterator
3292 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
3293 std::string Name = I->second;
3294 if (I->first == 0) {
3295 if (Name == "InFlag" ||
3297 Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) {
3298 CalleeDecls += " SDOperand " + Name + "(0, 0);\n";
3301 CalleeCode += ", SDOperand &" + Name;
3302 CallerCode += ", " + Name;
3303 } else if (I->first == 1) {
3304 if (Name == "ResNode") {
3305 CalleeDecls += " SDNode *" + Name + " = NULL;\n";
3308 CalleeCode += ", SDNode *" + Name;
3309 CallerCode += ", " + Name;
3311 CalleeCode += ", bool " + Name;
3312 CallerCode += ", " + Name;
3317 // Prevent emission routines from being inlined to reduce selection
3318 // routines stack frame sizes.
3319 CalleeCode += "NOINLINE ";
3320 CalleeCode += "{\n" + CalleeDecls;
3321 for (int j = LastPred+1; j < CodeSize; ++j)
3322 CalleeCode += " " + GeneratedCode[j].second + '\n';
3323 for (int j = LastPred+1; j < CodeSize; ++j)
3324 GeneratedCode.pop_back();
3325 CalleeCode += "}\n";
3327 // Uniquing the emission routines.
3328 unsigned EmitFuncNum;
3329 std::map<std::string, unsigned>::iterator EFI =
3330 EmitFunctions.find(CalleeCode);
3331 if (EFI != EmitFunctions.end()) {
3332 EmitFuncNum = EFI->second;
3334 EmitFuncNum = EmitFunctions.size();
3335 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
3336 OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode;
3339 // Replace the emission code within selection routines with calls to the
3340 // emission functions.
3341 CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode;
3342 GeneratedCode.push_back(std::make_pair(false, CallerCode));
3343 GeneratedCode.push_back(std::make_pair(false, "return;"));
3347 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3349 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3350 << " && N.getValue(0).hasOneUse()) {\n"
3351 << " SDOperand Dummy = "
3352 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3353 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3354 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3355 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3356 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3357 << " Result = Dummy;\n"
3362 // Print all declarations.
3363 for (std::set<std::pair<unsigned, std::string> >::iterator
3364 I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I)
3366 OS << " SDOperand " << I->second << "(0, 0);\n";
3367 else if (I->first == 1)
3368 OS << " SDNode *" << I->second << " = NULL;\n";
3370 OS << " bool " << I->second << " = false;\n";
3372 // Loop through and reverse all of the CodeList vectors, as we will be
3373 // accessing them from their logical front, but accessing the end of a
3374 // vector is more efficient.
3375 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3376 CodeList &GeneratedCode = CodeForPatterns[i].second;
3377 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3380 // Next, reverse the list of patterns itself for the same reason.
3381 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3383 // Emit all of the patterns now, grouped together to share code.
3384 EmitPatterns(CodeForPatterns, 2, OS);
3386 // If the last pattern has predicates (which could fail) emit code to catch
3387 // the case where nothing handles a pattern.
3388 if (mightNotMatch) {
3389 OS << " std::cerr << \"Cannot yet select: \";\n";
3390 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3391 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3392 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3393 OS << " N.Val->dump(CurDAG);\n";
3395 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3396 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3397 << " std::cerr << \"intrinsic %\"<< "
3398 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3400 OS << " std::cerr << '\\n';\n"
3406 // Emit boilerplate.
3407 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3408 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3409 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3410 << " // Select the flag operand.\n"
3411 << " if (Ops.back().getValueType() == MVT::Flag)\n"
3412 << " Select(Ops.back(), Ops.back());\n"
3413 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3414 << " std::vector<MVT::ValueType> VTs;\n"
3415 << " VTs.push_back(MVT::Other);\n"
3416 << " VTs.push_back(MVT::Flag);\n"
3417 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3418 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3419 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3420 << " Result = New.getValue(N.ResNo);\n"
3424 OS << "// The main instruction selector code.\n"
3425 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3426 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3427 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3428 << "INSTRUCTION_LIST_END)) {\n"
3430 << " return; // Already selected.\n"
3432 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3433 << " if (CGMI != CodeGenMap.end()) {\n"
3434 << " Result = CGMI->second;\n"
3437 << " switch (N.getOpcode()) {\n"
3438 << " default: break;\n"
3439 << " case ISD::EntryToken: // These leaves remain the same.\n"
3440 << " case ISD::BasicBlock:\n"
3441 << " case ISD::Register:\n"
3442 << " case ISD::HANDLENODE:\n"
3443 << " case ISD::TargetConstant:\n"
3444 << " case ISD::TargetConstantPool:\n"
3445 << " case ISD::TargetFrameIndex:\n"
3446 << " case ISD::TargetJumpTable:\n"
3447 << " case ISD::TargetGlobalAddress: {\n"
3451 << " case ISD::AssertSext:\n"
3452 << " case ISD::AssertZext: {\n"
3453 << " SDOperand Tmp0;\n"
3454 << " Select(Tmp0, N.getOperand(0));\n"
3455 << " if (!N.Val->hasOneUse())\n"
3456 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3457 << "Tmp0.Val, Tmp0.ResNo);\n"
3458 << " Result = Tmp0;\n"
3461 << " case ISD::TokenFactor:\n"
3462 << " if (N.getNumOperands() == 2) {\n"
3463 << " SDOperand Op0, Op1;\n"
3464 << " Select(Op0, N.getOperand(0));\n"
3465 << " Select(Op1, N.getOperand(1));\n"
3467 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3468 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3469 << "Result.Val, Result.ResNo);\n"
3471 << " std::vector<SDOperand> Ops;\n"
3472 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3473 << " SDOperand Val;\n"
3474 << " Select(Val, N.getOperand(i));\n"
3475 << " Ops.push_back(Val);\n"
3478 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3479 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3480 << "Result.Val, Result.ResNo);\n"
3483 << " case ISD::CopyFromReg: {\n"
3484 << " SDOperand Chain;\n"
3485 << " Select(Chain, N.getOperand(0));\n"
3486 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3487 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
3488 << " if (N.Val->getNumValues() == 2) {\n"
3489 << " if (Chain == N.getOperand(0)) {\n"
3490 << " Result = N; // No change\n"
3493 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3494 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3496 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3498 << " Result = New.getValue(N.ResNo);\n"
3501 << " SDOperand Flag;\n"
3502 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3503 << " if (Chain == N.getOperand(0) &&\n"
3504 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3505 << " Result = N; // No change\n"
3508 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3509 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3511 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3513 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3515 << " Result = New.getValue(N.ResNo);\n"
3519 << " case ISD::CopyToReg: {\n"
3520 << " SDOperand Chain;\n"
3521 << " Select(Chain, N.getOperand(0));\n"
3522 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3523 << " SDOperand Val;\n"
3524 << " Select(Val, N.getOperand(2));\n"
3526 << " if (N.Val->getNumValues() == 1) {\n"
3527 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3528 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3529 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3530 << "Result.Val, 0);\n"
3532 << " SDOperand Flag(0, 0);\n"
3533 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3534 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3535 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3536 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3537 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3538 << "Result.Val, 0);\n"
3539 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3540 << "Result.Val, 1);\n"
3541 << " Result = Result.getValue(N.ResNo);\n"
3545 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
3548 // Loop over all of the case statements, emiting a call to each method we
3550 for (std::map<Record*, std::vector<PatternToMatch*>,
3551 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3552 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3553 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3554 OS << " case " << OpcodeInfo.getEnumName() << ": "
3555 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3556 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3559 OS << " } // end of big switch.\n\n"
3560 << " std::cerr << \"Cannot yet select: \";\n"
3561 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3562 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3563 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3564 << " N.Val->dump(CurDAG);\n"
3566 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3567 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3568 << " std::cerr << \"intrinsic %\"<< "
3569 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3571 << " std::cerr << '\\n';\n"
3576 void DAGISelEmitter::run(std::ostream &OS) {
3577 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3580 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3581 << "// *** instruction selector class. These functions are really "
3584 OS << "#if defined(__GNUC__) && \\\n";
3585 OS << " ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))\n";
3586 OS << "#define NOINLINE __attribute__((noinline))\n";
3589 OS << "// Instance var to keep track of multiply used nodes that have \n"
3590 << "// already been selected.\n"
3591 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3593 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3594 << "// and their place handle nodes.\n";
3595 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3596 OS << "// Instance var to keep track of mapping of place handle nodes\n"
3597 << "// and their replacement nodes.\n";
3598 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3601 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3602 << "// handle node in ReplaceMap.\n";
3603 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3604 << "unsigned RNum) {\n";
3605 OS << " SDOperand N(H, HNum);\n";
3606 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3607 OS << " if (HMI != HandleMap.end()) {\n";
3608 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3609 OS << " HandleMap.erase(N);\n";
3614 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3615 OS << "// handles.Some handles do not yet have replacements because the\n";
3616 OS << "// nodes they replacements have only dead readers.\n";
3617 OS << "void SelectDanglingHandles() {\n";
3618 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3619 << "HandleMap.begin(),\n"
3620 << " E = HandleMap.end(); I != E; ++I) {\n";
3621 OS << " SDOperand N = I->first;\n";
3622 OS << " SDOperand R;\n";
3623 OS << " Select(R, N.getValue(0));\n";
3624 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3628 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3629 OS << "// specific nodes.\n";
3630 OS << "void ReplaceHandles() {\n";
3631 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3632 << "ReplaceMap.begin(),\n"
3633 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3634 OS << " SDOperand From = I->first;\n";
3635 OS << " SDOperand To = I->second;\n";
3636 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3637 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3638 OS << " SDNode *Use = *UI;\n";
3639 OS << " std::vector<SDOperand> Ops;\n";
3640 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n";
3641 OS << " SDOperand O = Use->getOperand(i);\n";
3642 OS << " if (O.Val == From.Val)\n";
3643 OS << " Ops.push_back(To);\n";
3645 OS << " Ops.push_back(O);\n";
3647 OS << " SDOperand U = SDOperand(Use, 0);\n";
3648 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3654 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3655 OS << "SDOperand SelectRoot(SDOperand N) {\n";
3656 OS << " SDOperand ResNode;\n";
3657 OS << " Select(ResNode, N);\n";
3658 OS << " SelectDanglingHandles();\n";
3659 OS << " ReplaceHandles();\n";
3660 OS << " ReplaceMap.clear();\n";
3661 OS << " return ResNode;\n";
3664 Intrinsics = LoadIntrinsics(Records);
3666 ParseNodeTransforms(OS);
3667 ParseComplexPatterns();
3668 ParsePatternFragments(OS);
3669 ParseInstructions();
3672 // Generate variants. For example, commutative patterns can match
3673 // multiple ways. Add them to PatternsToMatch as well.
3677 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3678 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3679 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3680 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
3684 // At this point, we have full information about the 'Patterns' we need to
3685 // parse, both implicitly from instructions as well as from explicit pattern
3686 // definitions. Emit the resultant instruction selector.
3687 EmitInstructionSelector(OS);
3689 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3690 E = PatternFragments.end(); I != E; ++I)
3692 PatternFragments.clear();
3694 Instructions.clear();