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)
125 return N; // FIXME: need value #
127 return N->getChild(OpNo-NumResults);
130 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
131 /// constraint to the nodes operands. This returns true if it makes a
132 /// change, false otherwise. If a type contradiction is found, throw an
134 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
135 const SDNodeInfo &NodeInfo,
136 TreePattern &TP) const {
137 unsigned NumResults = NodeInfo.getNumResults();
138 assert(NumResults <= 1 &&
139 "We only work with nodes with zero or one result so far!");
141 // Check that the number of operands is sane.
142 if (NodeInfo.getNumOperands() >= 0) {
143 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
144 TP.error(N->getOperator()->getName() + " node requires exactly " +
145 itostr(NodeInfo.getNumOperands()) + " operands!");
148 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
150 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
152 switch (ConstraintType) {
153 default: assert(0 && "Unknown constraint type!");
155 // Operand must be a particular type.
156 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
158 // Operand must be same as target pointer type.
159 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
162 // If there is only one integer type supported, this must be it.
163 std::vector<MVT::ValueType> IntVTs =
164 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
166 // If we found exactly one supported integer type, apply it.
167 if (IntVTs.size() == 1)
168 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
169 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
172 // If there is only one FP type supported, this must be it.
173 std::vector<MVT::ValueType> FPVTs =
174 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
176 // If we found exactly one supported FP type, apply it.
177 if (FPVTs.size() == 1)
178 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
179 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
182 TreePatternNode *OtherNode =
183 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
184 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
185 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
187 case SDTCisVTSmallerThanOp: {
188 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
189 // have an integer type that is smaller than the VT.
190 if (!NodeToApply->isLeaf() ||
191 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
192 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
193 ->isSubClassOf("ValueType"))
194 TP.error(N->getOperator()->getName() + " expects a VT operand!");
196 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
197 if (!MVT::isInteger(VT))
198 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
200 TreePatternNode *OtherNode =
201 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
203 // It must be integer.
204 bool MadeChange = false;
205 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
207 // This code only handles nodes that have one type set. Assert here so
208 // that we can change this if we ever need to deal with multiple value
209 // types at this point.
210 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
211 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
212 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
215 case SDTCisOpSmallerThanOp: {
216 TreePatternNode *BigOperand =
217 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
219 // Both operands must be integer or FP, but we don't care which.
220 bool MadeChange = false;
222 // This code does not currently handle nodes which have multiple types,
223 // where some types are integer, and some are fp. Assert that this is not
225 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
226 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
227 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
228 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
229 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
230 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
231 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
232 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
233 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
234 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
235 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
236 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
237 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
239 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
241 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
242 VTs = FilterVTs(VTs, MVT::isInteger);
243 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
244 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
249 switch (VTs.size()) {
250 default: // Too many VT's to pick from.
251 case 0: break; // No info yet.
253 // Only one VT of this flavor. Cannot ever satisify the constraints.
254 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
256 // If we have exactly two possible types, the little operand must be the
257 // small one, the big operand should be the big one. Common with
258 // float/double for example.
259 assert(VTs[0] < VTs[1] && "Should be sorted!");
260 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
261 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
266 case SDTCisIntVectorOfSameSize: {
267 TreePatternNode *OtherOperand =
268 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
270 if (OtherOperand->hasTypeSet()) {
271 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
272 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
273 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
274 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
275 return NodeToApply->UpdateNodeType(IVT, TP);
284 //===----------------------------------------------------------------------===//
285 // SDNodeInfo implementation
287 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
288 EnumName = R->getValueAsString("Opcode");
289 SDClassName = R->getValueAsString("SDClass");
290 Record *TypeProfile = R->getValueAsDef("TypeProfile");
291 NumResults = TypeProfile->getValueAsInt("NumResults");
292 NumOperands = TypeProfile->getValueAsInt("NumOperands");
294 // Parse the properties.
296 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
297 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
298 if (PropList[i]->getName() == "SDNPCommutative") {
299 Properties |= 1 << SDNPCommutative;
300 } else if (PropList[i]->getName() == "SDNPAssociative") {
301 Properties |= 1 << SDNPAssociative;
302 } else if (PropList[i]->getName() == "SDNPHasChain") {
303 Properties |= 1 << SDNPHasChain;
304 } else if (PropList[i]->getName() == "SDNPOutFlag") {
305 Properties |= 1 << SDNPOutFlag;
306 } else if (PropList[i]->getName() == "SDNPInFlag") {
307 Properties |= 1 << SDNPInFlag;
308 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
309 Properties |= 1 << SDNPOptInFlag;
311 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
312 << "' on node '" << R->getName() << "'!\n";
318 // Parse the type constraints.
319 std::vector<Record*> ConstraintList =
320 TypeProfile->getValueAsListOfDefs("Constraints");
321 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
324 //===----------------------------------------------------------------------===//
325 // TreePatternNode implementation
328 TreePatternNode::~TreePatternNode() {
329 #if 0 // FIXME: implement refcounted tree nodes!
330 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
335 /// UpdateNodeType - Set the node type of N to VT if VT contains
336 /// information. If N already contains a conflicting type, then throw an
337 /// exception. This returns true if any information was updated.
339 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
341 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
343 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
345 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
350 if (getExtTypeNum(0) == MVT::iPTR) {
351 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
353 if (isExtIntegerInVTs(ExtVTs)) {
354 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
362 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
363 assert(hasTypeSet() && "should be handled above!");
364 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
365 if (getExtTypes() == FVTs)
370 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
371 //assert(hasTypeSet() && "should be handled above!");
372 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
373 if (getExtTypes() == FVTs)
380 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
381 assert(hasTypeSet() && "should be handled above!");
382 std::vector<unsigned char> FVTs =
383 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
384 if (getExtTypes() == FVTs)
390 // If we know this is an int or fp type, and we are told it is a specific one,
393 // Similarly, we should probably set the type here to the intersection of
394 // {isInt|isFP} and ExtVTs
395 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
396 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
400 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
408 TP.error("Type inference contradiction found in node!");
410 TP.error("Type inference contradiction found in node " +
411 getOperator()->getName() + "!");
413 return true; // unreachable
417 void TreePatternNode::print(std::ostream &OS) const {
419 OS << *getLeafValue();
421 OS << "(" << getOperator()->getName();
424 // FIXME: At some point we should handle printing all the value types for
425 // nodes that are multiply typed.
426 switch (getExtTypeNum(0)) {
427 case MVT::Other: OS << ":Other"; break;
428 case MVT::isInt: OS << ":isInt"; break;
429 case MVT::isFP : OS << ":isFP"; break;
430 case MVT::isUnknown: ; /*OS << ":?";*/ break;
431 case MVT::iPTR: OS << ":iPTR"; break;
432 default: OS << ":" << getTypeNum(0); break;
436 if (getNumChildren() != 0) {
438 getChild(0)->print(OS);
439 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
441 getChild(i)->print(OS);
447 if (!PredicateFn.empty())
448 OS << "<<P:" << PredicateFn << ">>";
450 OS << "<<X:" << TransformFn->getName() << ">>";
451 if (!getName().empty())
452 OS << ":$" << getName();
455 void TreePatternNode::dump() const {
459 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
460 /// the specified node. For this comparison, all of the state of the node
461 /// is considered, except for the assigned name. Nodes with differing names
462 /// that are otherwise identical are considered isomorphic.
463 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
464 if (N == this) return true;
465 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
466 getPredicateFn() != N->getPredicateFn() ||
467 getTransformFn() != N->getTransformFn())
471 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
472 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
473 return DI->getDef() == NDI->getDef();
474 return getLeafValue() == N->getLeafValue();
477 if (N->getOperator() != getOperator() ||
478 N->getNumChildren() != getNumChildren()) return false;
479 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
480 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
485 /// clone - Make a copy of this tree and all of its children.
487 TreePatternNode *TreePatternNode::clone() const {
488 TreePatternNode *New;
490 New = new TreePatternNode(getLeafValue());
492 std::vector<TreePatternNode*> CChildren;
493 CChildren.reserve(Children.size());
494 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
495 CChildren.push_back(getChild(i)->clone());
496 New = new TreePatternNode(getOperator(), CChildren);
498 New->setName(getName());
499 New->setTypes(getExtTypes());
500 New->setPredicateFn(getPredicateFn());
501 New->setTransformFn(getTransformFn());
505 /// SubstituteFormalArguments - Replace the formal arguments in this tree
506 /// with actual values specified by ArgMap.
507 void TreePatternNode::
508 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
509 if (isLeaf()) return;
511 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
512 TreePatternNode *Child = getChild(i);
513 if (Child->isLeaf()) {
514 Init *Val = Child->getLeafValue();
515 if (dynamic_cast<DefInit*>(Val) &&
516 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
517 // We found a use of a formal argument, replace it with its value.
518 Child = ArgMap[Child->getName()];
519 assert(Child && "Couldn't find formal argument!");
523 getChild(i)->SubstituteFormalArguments(ArgMap);
529 /// InlinePatternFragments - If this pattern refers to any pattern
530 /// fragments, inline them into place, giving us a pattern without any
531 /// PatFrag references.
532 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
533 if (isLeaf()) return this; // nothing to do.
534 Record *Op = getOperator();
536 if (!Op->isSubClassOf("PatFrag")) {
537 // Just recursively inline children nodes.
538 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
539 setChild(i, getChild(i)->InlinePatternFragments(TP));
543 // Otherwise, we found a reference to a fragment. First, look up its
544 // TreePattern record.
545 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
547 // Verify that we are passing the right number of operands.
548 if (Frag->getNumArgs() != Children.size())
549 TP.error("'" + Op->getName() + "' fragment requires " +
550 utostr(Frag->getNumArgs()) + " operands!");
552 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
554 // Resolve formal arguments to their actual value.
555 if (Frag->getNumArgs()) {
556 // Compute the map of formal to actual arguments.
557 std::map<std::string, TreePatternNode*> ArgMap;
558 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
559 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
561 FragTree->SubstituteFormalArguments(ArgMap);
564 FragTree->setName(getName());
565 FragTree->UpdateNodeType(getExtTypes(), TP);
567 // Get a new copy of this fragment to stitch into here.
568 //delete this; // FIXME: implement refcounting!
572 /// getImplicitType - Check to see if the specified record has an implicit
573 /// type which should be applied to it. This infer the type of register
574 /// references from the register file information, for example.
576 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
578 // Some common return values
579 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
580 std::vector<unsigned char> Other(1, MVT::Other);
582 // Check to see if this is a register or a register class...
583 if (R->isSubClassOf("RegisterClass")) {
586 const CodeGenRegisterClass &RC =
587 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
588 return ConvertVTs(RC.getValueTypes());
589 } else if (R->isSubClassOf("PatFrag")) {
590 // Pattern fragment types will be resolved when they are inlined.
592 } else if (R->isSubClassOf("Register")) {
595 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
596 return T.getRegisterVTs(R);
597 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
598 // Using a VTSDNode or CondCodeSDNode.
600 } else if (R->isSubClassOf("ComplexPattern")) {
603 std::vector<unsigned char>
604 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
606 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
611 TP.error("Unknown node flavor used in pattern: " + R->getName());
615 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
616 /// this node and its children in the tree. This returns true if it makes a
617 /// change, false otherwise. If a type contradiction is found, throw an
619 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
620 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
622 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
623 // If it's a regclass or something else known, include the type.
624 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
625 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
626 // Int inits are always integers. :)
627 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
630 // At some point, it may make sense for this tree pattern to have
631 // multiple types. Assert here that it does not, so we revisit this
632 // code when appropriate.
633 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
634 MVT::ValueType VT = getTypeNum(0);
635 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
636 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
639 if (VT != MVT::iPTR) {
640 unsigned Size = MVT::getSizeInBits(VT);
641 // Make sure that the value is representable for this type.
643 int Val = (II->getValue() << (32-Size)) >> (32-Size);
644 if (Val != II->getValue())
645 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
646 "' is out of range for type '" +
647 getEnumName(getTypeNum(0)) + "'!");
657 // special handling for set, which isn't really an SDNode.
658 if (getOperator()->getName() == "set") {
659 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
660 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
661 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
663 // Types of operands must match.
664 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
665 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
666 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
668 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
669 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
670 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
672 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
673 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
674 bool MadeChange = false;
676 // Apply the result type to the node.
677 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
679 if (getNumChildren() != Int.ArgVTs.size())
680 TP.error("Intrinsic '" + Int.Name + "' expects " +
681 utostr(Int.ArgVTs.size()-1) + " operands, not " +
682 utostr(getNumChildren()-1) + " operands!");
684 // Apply type info to the intrinsic ID.
685 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
687 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
688 MVT::ValueType OpVT = Int.ArgVTs[i];
689 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
690 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
693 } else if (getOperator()->isSubClassOf("SDNode")) {
694 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
696 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
697 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
698 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
699 // Branch, etc. do not produce results and top-level forms in instr pattern
700 // must have void types.
701 if (NI.getNumResults() == 0)
702 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
704 // If this is a vector_shuffle operation, apply types to the build_vector
705 // operation. The types of the integers don't matter, but this ensures they
706 // won't get checked.
707 if (getOperator()->getName() == "vector_shuffle" &&
708 getChild(2)->getOperator()->getName() == "build_vector") {
709 TreePatternNode *BV = getChild(2);
710 const std::vector<MVT::ValueType> &LegalVTs
711 = ISE.getTargetInfo().getLegalValueTypes();
712 MVT::ValueType LegalIntVT = MVT::Other;
713 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
714 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
715 LegalIntVT = LegalVTs[i];
718 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
720 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
721 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
724 } else if (getOperator()->isSubClassOf("Instruction")) {
725 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
726 bool MadeChange = false;
727 unsigned NumResults = Inst.getNumResults();
729 assert(NumResults <= 1 &&
730 "Only supports zero or one result instrs!");
731 // Apply the result type to the node
732 if (NumResults == 0) {
733 MadeChange = UpdateNodeType(MVT::isVoid, TP);
735 Record *ResultNode = Inst.getResult(0);
736 assert(ResultNode->isSubClassOf("RegisterClass") &&
737 "Operands should be register classes!");
739 const CodeGenRegisterClass &RC =
740 ISE.getTargetInfo().getRegisterClass(ResultNode);
741 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
744 if (getNumChildren() != Inst.getNumOperands())
745 TP.error("Instruction '" + getOperator()->getName() + " expects " +
746 utostr(Inst.getNumOperands()) + " operands, not " +
747 utostr(getNumChildren()) + " operands!");
748 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
749 Record *OperandNode = Inst.getOperand(i);
751 if (OperandNode->isSubClassOf("RegisterClass")) {
752 const CodeGenRegisterClass &RC =
753 ISE.getTargetInfo().getRegisterClass(OperandNode);
754 //VT = RC.getValueTypeNum(0);
755 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
757 } else if (OperandNode->isSubClassOf("Operand")) {
758 VT = getValueType(OperandNode->getValueAsDef("Type"));
759 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
761 assert(0 && "Unknown operand type!");
764 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
768 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
770 // Node transforms always take one operand.
771 if (getNumChildren() != 1)
772 TP.error("Node transform '" + getOperator()->getName() +
773 "' requires one operand!");
775 // If either the output or input of the xform does not have exact
776 // type info. We assume they must be the same. Otherwise, it is perfectly
777 // legal to transform from one type to a completely different type.
778 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
779 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
780 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
787 /// canPatternMatch - If it is impossible for this pattern to match on this
788 /// target, fill in Reason and return false. Otherwise, return true. This is
789 /// used as a santity check for .td files (to prevent people from writing stuff
790 /// that can never possibly work), and to prevent the pattern permuter from
791 /// generating stuff that is useless.
792 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
793 if (isLeaf()) return true;
795 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
796 if (!getChild(i)->canPatternMatch(Reason, ISE))
799 // If this is an intrinsic, handle cases that would make it not match. For
800 // example, if an operand is required to be an immediate.
801 if (getOperator()->isSubClassOf("Intrinsic")) {
806 // If this node is a commutative operator, check that the LHS isn't an
808 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
809 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
810 // Scan all of the operands of the node and make sure that only the last one
811 // is a constant node.
812 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
813 if (!getChild(i)->isLeaf() &&
814 getChild(i)->getOperator()->getName() == "imm") {
815 Reason = "Immediate value must be on the RHS of commutative operators!";
823 //===----------------------------------------------------------------------===//
824 // TreePattern implementation
827 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
828 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
829 isInputPattern = isInput;
830 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
831 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
834 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
835 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
836 isInputPattern = isInput;
837 Trees.push_back(ParseTreePattern(Pat));
840 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
841 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
842 isInputPattern = isInput;
843 Trees.push_back(Pat);
848 void TreePattern::error(const std::string &Msg) const {
850 throw "In " + TheRecord->getName() + ": " + Msg;
853 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
854 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
855 if (!OpDef) error("Pattern has unexpected operator type!");
856 Record *Operator = OpDef->getDef();
858 if (Operator->isSubClassOf("ValueType")) {
859 // If the operator is a ValueType, then this must be "type cast" of a leaf
861 if (Dag->getNumArgs() != 1)
862 error("Type cast only takes one operand!");
864 Init *Arg = Dag->getArg(0);
865 TreePatternNode *New;
866 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
867 Record *R = DI->getDef();
868 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
869 Dag->setArg(0, new DagInit(DI,
870 std::vector<std::pair<Init*, std::string> >()));
871 return ParseTreePattern(Dag);
873 New = new TreePatternNode(DI);
874 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
875 New = ParseTreePattern(DI);
876 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
877 New = new TreePatternNode(II);
878 if (!Dag->getArgName(0).empty())
879 error("Constant int argument should not have a name!");
880 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
881 // Turn this into an IntInit.
882 Init *II = BI->convertInitializerTo(new IntRecTy());
883 if (II == 0 || !dynamic_cast<IntInit*>(II))
884 error("Bits value must be constants!");
886 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
887 if (!Dag->getArgName(0).empty())
888 error("Constant int argument should not have a name!");
891 error("Unknown leaf value for tree pattern!");
895 // Apply the type cast.
896 New->UpdateNodeType(getValueType(Operator), *this);
897 New->setName(Dag->getArgName(0));
901 // Verify that this is something that makes sense for an operator.
902 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
903 !Operator->isSubClassOf("Instruction") &&
904 !Operator->isSubClassOf("SDNodeXForm") &&
905 !Operator->isSubClassOf("Intrinsic") &&
906 Operator->getName() != "set")
907 error("Unrecognized node '" + Operator->getName() + "'!");
909 // Check to see if this is something that is illegal in an input pattern.
910 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
911 Operator->isSubClassOf("SDNodeXForm")))
912 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
914 std::vector<TreePatternNode*> Children;
916 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
917 Init *Arg = Dag->getArg(i);
918 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
919 Children.push_back(ParseTreePattern(DI));
920 if (Children.back()->getName().empty())
921 Children.back()->setName(Dag->getArgName(i));
922 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
923 Record *R = DefI->getDef();
924 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
925 // TreePatternNode if its own.
926 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
927 Dag->setArg(i, new DagInit(DefI,
928 std::vector<std::pair<Init*, std::string> >()));
929 --i; // Revisit this node...
931 TreePatternNode *Node = new TreePatternNode(DefI);
932 Node->setName(Dag->getArgName(i));
933 Children.push_back(Node);
936 if (R->getName() == "node") {
937 if (Dag->getArgName(i).empty())
938 error("'node' argument requires a name to match with operand list");
939 Args.push_back(Dag->getArgName(i));
942 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
943 TreePatternNode *Node = new TreePatternNode(II);
944 if (!Dag->getArgName(i).empty())
945 error("Constant int argument should not have a name!");
946 Children.push_back(Node);
947 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
948 // Turn this into an IntInit.
949 Init *II = BI->convertInitializerTo(new IntRecTy());
950 if (II == 0 || !dynamic_cast<IntInit*>(II))
951 error("Bits value must be constants!");
953 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
954 if (!Dag->getArgName(i).empty())
955 error("Constant int argument should not have a name!");
956 Children.push_back(Node);
961 error("Unknown leaf value for tree pattern!");
965 // If the operator is an intrinsic, then this is just syntactic sugar for for
966 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
967 // convert the intrinsic name to a number.
968 if (Operator->isSubClassOf("Intrinsic")) {
969 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
970 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
972 // If this intrinsic returns void, it must have side-effects and thus a
974 if (Int.ArgVTs[0] == MVT::isVoid) {
975 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
976 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
977 // Has side-effects, requires chain.
978 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
980 // Otherwise, no chain.
981 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
984 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
985 Children.insert(Children.begin(), IIDNode);
988 return new TreePatternNode(Operator, Children);
991 /// InferAllTypes - Infer/propagate as many types throughout the expression
992 /// patterns as possible. Return true if all types are infered, false
993 /// otherwise. Throw an exception if a type contradiction is found.
994 bool TreePattern::InferAllTypes() {
995 bool MadeChange = true;
998 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
999 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1002 bool HasUnresolvedTypes = false;
1003 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1004 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1005 return !HasUnresolvedTypes;
1008 void TreePattern::print(std::ostream &OS) const {
1009 OS << getRecord()->getName();
1010 if (!Args.empty()) {
1011 OS << "(" << Args[0];
1012 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1013 OS << ", " << Args[i];
1018 if (Trees.size() > 1)
1020 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1022 Trees[i]->print(OS);
1026 if (Trees.size() > 1)
1030 void TreePattern::dump() const { print(std::cerr); }
1034 //===----------------------------------------------------------------------===//
1035 // DAGISelEmitter implementation
1038 // Parse all of the SDNode definitions for the target, populating SDNodes.
1039 void DAGISelEmitter::ParseNodeInfo() {
1040 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1041 while (!Nodes.empty()) {
1042 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1046 // Get the buildin intrinsic nodes.
1047 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1048 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1049 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1052 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1053 /// map, and emit them to the file as functions.
1054 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1055 OS << "\n// Node transformations.\n";
1056 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1057 while (!Xforms.empty()) {
1058 Record *XFormNode = Xforms.back();
1059 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1060 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1061 SDNodeXForms.insert(std::make_pair(XFormNode,
1062 std::make_pair(SDNode, Code)));
1064 if (!Code.empty()) {
1065 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1066 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1068 OS << "inline SDOperand Transform_" << XFormNode->getName()
1069 << "(SDNode *" << C2 << ") {\n";
1070 if (ClassName != "SDNode")
1071 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1072 OS << Code << "\n}\n";
1079 void DAGISelEmitter::ParseComplexPatterns() {
1080 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1081 while (!AMs.empty()) {
1082 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1088 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1089 /// file, building up the PatternFragments map. After we've collected them all,
1090 /// inline fragments together as necessary, so that there are no references left
1091 /// inside a pattern fragment to a pattern fragment.
1093 /// This also emits all of the predicate functions to the output file.
1095 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1096 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1098 // First step, parse all of the fragments and emit predicate functions.
1099 OS << "\n// Predicate functions.\n";
1100 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1101 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1102 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1103 PatternFragments[Fragments[i]] = P;
1105 // Validate the argument list, converting it to map, to discard duplicates.
1106 std::vector<std::string> &Args = P->getArgList();
1107 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1109 if (OperandsMap.count(""))
1110 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1112 // Parse the operands list.
1113 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1114 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1115 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1116 P->error("Operands list should start with '(ops ... '!");
1118 // Copy over the arguments.
1120 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1121 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1122 static_cast<DefInit*>(OpsList->getArg(j))->
1123 getDef()->getName() != "node")
1124 P->error("Operands list should all be 'node' values.");
1125 if (OpsList->getArgName(j).empty())
1126 P->error("Operands list should have names for each operand!");
1127 if (!OperandsMap.count(OpsList->getArgName(j)))
1128 P->error("'" + OpsList->getArgName(j) +
1129 "' does not occur in pattern or was multiply specified!");
1130 OperandsMap.erase(OpsList->getArgName(j));
1131 Args.push_back(OpsList->getArgName(j));
1134 if (!OperandsMap.empty())
1135 P->error("Operands list does not contain an entry for operand '" +
1136 *OperandsMap.begin() + "'!");
1138 // If there is a code init for this fragment, emit the predicate code and
1139 // keep track of the fact that this fragment uses it.
1140 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1141 if (!Code.empty()) {
1142 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1143 std::string ClassName =
1144 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1145 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1147 OS << "inline bool Predicate_" << Fragments[i]->getName()
1148 << "(SDNode *" << C2 << ") {\n";
1149 if (ClassName != "SDNode")
1150 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1151 OS << Code << "\n}\n";
1152 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1155 // If there is a node transformation corresponding to this, keep track of
1157 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1158 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1159 P->getOnlyTree()->setTransformFn(Transform);
1164 // Now that we've parsed all of the tree fragments, do a closure on them so
1165 // that there are not references to PatFrags left inside of them.
1166 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1167 E = PatternFragments.end(); I != E; ++I) {
1168 TreePattern *ThePat = I->second;
1169 ThePat->InlinePatternFragments();
1171 // Infer as many types as possible. Don't worry about it if we don't infer
1172 // all of them, some may depend on the inputs of the pattern.
1174 ThePat->InferAllTypes();
1176 // If this pattern fragment is not supported by this target (no types can
1177 // satisfy its constraints), just ignore it. If the bogus pattern is
1178 // actually used by instructions, the type consistency error will be
1182 // If debugging, print out the pattern fragment result.
1183 DEBUG(ThePat->dump());
1187 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1188 /// instruction input. Return true if this is a real use.
1189 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1190 std::map<std::string, TreePatternNode*> &InstInputs,
1191 std::vector<Record*> &InstImpInputs) {
1192 // No name -> not interesting.
1193 if (Pat->getName().empty()) {
1194 if (Pat->isLeaf()) {
1195 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1196 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1197 I->error("Input " + DI->getDef()->getName() + " must be named!");
1198 else if (DI && DI->getDef()->isSubClassOf("Register"))
1199 InstImpInputs.push_back(DI->getDef());
1205 if (Pat->isLeaf()) {
1206 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1207 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1210 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1211 Rec = Pat->getOperator();
1214 // SRCVALUE nodes are ignored.
1215 if (Rec->getName() == "srcvalue")
1218 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1223 if (Slot->isLeaf()) {
1224 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1226 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1227 SlotRec = Slot->getOperator();
1230 // Ensure that the inputs agree if we've already seen this input.
1232 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1233 if (Slot->getExtTypes() != Pat->getExtTypes())
1234 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1239 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1240 /// part of "I", the instruction), computing the set of inputs and outputs of
1241 /// the pattern. Report errors if we see anything naughty.
1242 void DAGISelEmitter::
1243 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1244 std::map<std::string, TreePatternNode*> &InstInputs,
1245 std::map<std::string, TreePatternNode*>&InstResults,
1246 std::vector<Record*> &InstImpInputs,
1247 std::vector<Record*> &InstImpResults) {
1248 if (Pat->isLeaf()) {
1249 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1250 if (!isUse && Pat->getTransformFn())
1251 I->error("Cannot specify a transform function for a non-input value!");
1253 } else if (Pat->getOperator()->getName() != "set") {
1254 // If this is not a set, verify that the children nodes are not void typed,
1256 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1257 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1258 I->error("Cannot have void nodes inside of patterns!");
1259 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1260 InstImpInputs, InstImpResults);
1263 // If this is a non-leaf node with no children, treat it basically as if
1264 // it were a leaf. This handles nodes like (imm).
1266 if (Pat->getNumChildren() == 0)
1267 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1269 if (!isUse && Pat->getTransformFn())
1270 I->error("Cannot specify a transform function for a non-input value!");
1274 // Otherwise, this is a set, validate and collect instruction results.
1275 if (Pat->getNumChildren() == 0)
1276 I->error("set requires operands!");
1277 else if (Pat->getNumChildren() & 1)
1278 I->error("set requires an even number of operands");
1280 if (Pat->getTransformFn())
1281 I->error("Cannot specify a transform function on a set node!");
1283 // Check the set destinations.
1284 unsigned NumValues = Pat->getNumChildren()/2;
1285 for (unsigned i = 0; i != NumValues; ++i) {
1286 TreePatternNode *Dest = Pat->getChild(i);
1287 if (!Dest->isLeaf())
1288 I->error("set destination should be a register!");
1290 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1292 I->error("set destination should be a register!");
1294 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1295 if (Dest->getName().empty())
1296 I->error("set destination must have a name!");
1297 if (InstResults.count(Dest->getName()))
1298 I->error("cannot set '" + Dest->getName() +"' multiple times");
1299 InstResults[Dest->getName()] = Dest;
1300 } else if (Val->getDef()->isSubClassOf("Register")) {
1301 InstImpResults.push_back(Val->getDef());
1303 I->error("set destination should be a register!");
1306 // Verify and collect info from the computation.
1307 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1308 InstInputs, InstResults,
1309 InstImpInputs, InstImpResults);
1313 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1314 /// any fragments involved. This populates the Instructions list with fully
1315 /// resolved instructions.
1316 void DAGISelEmitter::ParseInstructions() {
1317 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1319 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1322 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1323 LI = Instrs[i]->getValueAsListInit("Pattern");
1325 // If there is no pattern, only collect minimal information about the
1326 // instruction for its operand list. We have to assume that there is one
1327 // result, as we have no detailed info.
1328 if (!LI || LI->getSize() == 0) {
1329 std::vector<Record*> Results;
1330 std::vector<Record*> Operands;
1332 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1334 if (InstInfo.OperandList.size() != 0) {
1335 // FIXME: temporary hack...
1336 if (InstInfo.noResults) {
1337 // These produce no results
1338 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1339 Operands.push_back(InstInfo.OperandList[j].Rec);
1341 // Assume the first operand is the result.
1342 Results.push_back(InstInfo.OperandList[0].Rec);
1344 // The rest are inputs.
1345 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1346 Operands.push_back(InstInfo.OperandList[j].Rec);
1350 // Create and insert the instruction.
1351 std::vector<Record*> ImpResults;
1352 std::vector<Record*> ImpOperands;
1353 Instructions.insert(std::make_pair(Instrs[i],
1354 DAGInstruction(0, Results, Operands, ImpResults,
1356 continue; // no pattern.
1359 // Parse the instruction.
1360 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1361 // Inline pattern fragments into it.
1362 I->InlinePatternFragments();
1364 // Infer as many types as possible. If we cannot infer all of them, we can
1365 // never do anything with this instruction pattern: report it to the user.
1366 if (!I->InferAllTypes())
1367 I->error("Could not infer all types in pattern!");
1369 // InstInputs - Keep track of all of the inputs of the instruction, along
1370 // with the record they are declared as.
1371 std::map<std::string, TreePatternNode*> InstInputs;
1373 // InstResults - Keep track of all the virtual registers that are 'set'
1374 // in the instruction, including what reg class they are.
1375 std::map<std::string, TreePatternNode*> InstResults;
1377 std::vector<Record*> InstImpInputs;
1378 std::vector<Record*> InstImpResults;
1380 // Verify that the top-level forms in the instruction are of void type, and
1381 // fill in the InstResults map.
1382 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1383 TreePatternNode *Pat = I->getTree(j);
1384 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1385 I->error("Top-level forms in instruction pattern should have"
1388 // Find inputs and outputs, and verify the structure of the uses/defs.
1389 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1390 InstImpInputs, InstImpResults);
1393 // Now that we have inputs and outputs of the pattern, inspect the operands
1394 // list for the instruction. This determines the order that operands are
1395 // added to the machine instruction the node corresponds to.
1396 unsigned NumResults = InstResults.size();
1398 // Parse the operands list from the (ops) list, validating it.
1399 std::vector<std::string> &Args = I->getArgList();
1400 assert(Args.empty() && "Args list should still be empty here!");
1401 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1403 // Check that all of the results occur first in the list.
1404 std::vector<Record*> Results;
1405 TreePatternNode *Res0Node = NULL;
1406 for (unsigned i = 0; i != NumResults; ++i) {
1407 if (i == CGI.OperandList.size())
1408 I->error("'" + InstResults.begin()->first +
1409 "' set but does not appear in operand list!");
1410 const std::string &OpName = CGI.OperandList[i].Name;
1412 // Check that it exists in InstResults.
1413 TreePatternNode *RNode = InstResults[OpName];
1415 I->error("Operand $" + OpName + " does not exist in operand list!");
1419 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1421 I->error("Operand $" + OpName + " should be a set destination: all "
1422 "outputs must occur before inputs in operand list!");
1424 if (CGI.OperandList[i].Rec != R)
1425 I->error("Operand $" + OpName + " class mismatch!");
1427 // Remember the return type.
1428 Results.push_back(CGI.OperandList[i].Rec);
1430 // Okay, this one checks out.
1431 InstResults.erase(OpName);
1434 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1435 // the copy while we're checking the inputs.
1436 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1438 std::vector<TreePatternNode*> ResultNodeOperands;
1439 std::vector<Record*> Operands;
1440 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1441 const std::string &OpName = CGI.OperandList[i].Name;
1443 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1445 if (!InstInputsCheck.count(OpName))
1446 I->error("Operand $" + OpName +
1447 " does not appear in the instruction pattern");
1448 TreePatternNode *InVal = InstInputsCheck[OpName];
1449 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1451 if (InVal->isLeaf() &&
1452 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1453 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1454 if (CGI.OperandList[i].Rec != InRec &&
1455 !InRec->isSubClassOf("ComplexPattern"))
1456 I->error("Operand $" + OpName + "'s register class disagrees"
1457 " between the operand and pattern");
1459 Operands.push_back(CGI.OperandList[i].Rec);
1461 // Construct the result for the dest-pattern operand list.
1462 TreePatternNode *OpNode = InVal->clone();
1464 // No predicate is useful on the result.
1465 OpNode->setPredicateFn("");
1467 // Promote the xform function to be an explicit node if set.
1468 if (Record *Xform = OpNode->getTransformFn()) {
1469 OpNode->setTransformFn(0);
1470 std::vector<TreePatternNode*> Children;
1471 Children.push_back(OpNode);
1472 OpNode = new TreePatternNode(Xform, Children);
1475 ResultNodeOperands.push_back(OpNode);
1478 if (!InstInputsCheck.empty())
1479 I->error("Input operand $" + InstInputsCheck.begin()->first +
1480 " occurs in pattern but not in operands list!");
1482 TreePatternNode *ResultPattern =
1483 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1484 // Copy fully inferred output node type to instruction result pattern.
1486 ResultPattern->setTypes(Res0Node->getExtTypes());
1488 // Create and insert the instruction.
1489 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1490 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1492 // Use a temporary tree pattern to infer all types and make sure that the
1493 // constructed result is correct. This depends on the instruction already
1494 // being inserted into the Instructions map.
1495 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1496 Temp.InferAllTypes();
1498 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1499 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1504 // If we can, convert the instructions to be patterns that are matched!
1505 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1506 E = Instructions.end(); II != E; ++II) {
1507 DAGInstruction &TheInst = II->second;
1508 TreePattern *I = TheInst.getPattern();
1509 if (I == 0) continue; // No pattern.
1511 if (I->getNumTrees() != 1) {
1512 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1515 TreePatternNode *Pattern = I->getTree(0);
1516 TreePatternNode *SrcPattern;
1517 if (Pattern->getOperator()->getName() == "set") {
1518 if (Pattern->getNumChildren() != 2)
1519 continue; // Not a set of a single value (not handled so far)
1521 SrcPattern = Pattern->getChild(1)->clone();
1523 // Not a set (store or something?)
1524 SrcPattern = Pattern;
1528 if (!SrcPattern->canPatternMatch(Reason, *this))
1529 I->error("Instruction can never match: " + Reason);
1531 Record *Instr = II->first;
1532 TreePatternNode *DstPattern = TheInst.getResultPattern();
1534 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1535 SrcPattern, DstPattern,
1536 Instr->getValueAsInt("AddedComplexity")));
1540 void DAGISelEmitter::ParsePatterns() {
1541 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1543 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1544 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1545 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1547 // Inline pattern fragments into it.
1548 Pattern->InlinePatternFragments();
1550 // Infer as many types as possible. If we cannot infer all of them, we can
1551 // never do anything with this pattern: report it to the user.
1552 if (!Pattern->InferAllTypes())
1553 Pattern->error("Could not infer all types in pattern!");
1555 // Validate that the input pattern is correct.
1557 std::map<std::string, TreePatternNode*> InstInputs;
1558 std::map<std::string, TreePatternNode*> InstResults;
1559 std::vector<Record*> InstImpInputs;
1560 std::vector<Record*> InstImpResults;
1561 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1562 InstInputs, InstResults,
1563 InstImpInputs, InstImpResults);
1566 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1567 if (LI->getSize() == 0) continue; // no pattern.
1569 // Parse the instruction.
1570 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1572 // Inline pattern fragments into it.
1573 Result->InlinePatternFragments();
1575 // Infer as many types as possible. If we cannot infer all of them, we can
1576 // never do anything with this pattern: report it to the user.
1577 if (!Result->InferAllTypes())
1578 Result->error("Could not infer all types in pattern result!");
1580 if (Result->getNumTrees() != 1)
1581 Result->error("Cannot handle instructions producing instructions "
1582 "with temporaries yet!");
1584 // Promote the xform function to be an explicit node if set.
1585 std::vector<TreePatternNode*> ResultNodeOperands;
1586 TreePatternNode *DstPattern = Result->getOnlyTree();
1587 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1588 TreePatternNode *OpNode = DstPattern->getChild(ii);
1589 if (Record *Xform = OpNode->getTransformFn()) {
1590 OpNode->setTransformFn(0);
1591 std::vector<TreePatternNode*> Children;
1592 Children.push_back(OpNode);
1593 OpNode = new TreePatternNode(Xform, Children);
1595 ResultNodeOperands.push_back(OpNode);
1597 DstPattern = Result->getOnlyTree();
1598 if (!DstPattern->isLeaf())
1599 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1600 ResultNodeOperands);
1601 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1602 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1603 Temp.InferAllTypes();
1606 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1607 Pattern->error("Pattern can never match: " + Reason);
1610 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1611 Pattern->getOnlyTree(),
1613 Patterns[i]->getValueAsInt("AddedComplexity")));
1617 /// CombineChildVariants - Given a bunch of permutations of each child of the
1618 /// 'operator' node, put them together in all possible ways.
1619 static void CombineChildVariants(TreePatternNode *Orig,
1620 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1621 std::vector<TreePatternNode*> &OutVariants,
1622 DAGISelEmitter &ISE) {
1623 // Make sure that each operand has at least one variant to choose from.
1624 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1625 if (ChildVariants[i].empty())
1628 // The end result is an all-pairs construction of the resultant pattern.
1629 std::vector<unsigned> Idxs;
1630 Idxs.resize(ChildVariants.size());
1631 bool NotDone = true;
1633 // Create the variant and add it to the output list.
1634 std::vector<TreePatternNode*> NewChildren;
1635 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1636 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1637 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1639 // Copy over properties.
1640 R->setName(Orig->getName());
1641 R->setPredicateFn(Orig->getPredicateFn());
1642 R->setTransformFn(Orig->getTransformFn());
1643 R->setTypes(Orig->getExtTypes());
1645 // If this pattern cannot every match, do not include it as a variant.
1646 std::string ErrString;
1647 if (!R->canPatternMatch(ErrString, ISE)) {
1650 bool AlreadyExists = false;
1652 // Scan to see if this pattern has already been emitted. We can get
1653 // duplication due to things like commuting:
1654 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1655 // which are the same pattern. Ignore the dups.
1656 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1657 if (R->isIsomorphicTo(OutVariants[i])) {
1658 AlreadyExists = true;
1665 OutVariants.push_back(R);
1668 // Increment indices to the next permutation.
1670 // Look for something we can increment without causing a wrap-around.
1671 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1672 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1673 NotDone = true; // Found something to increment.
1681 /// CombineChildVariants - A helper function for binary operators.
1683 static void CombineChildVariants(TreePatternNode *Orig,
1684 const std::vector<TreePatternNode*> &LHS,
1685 const std::vector<TreePatternNode*> &RHS,
1686 std::vector<TreePatternNode*> &OutVariants,
1687 DAGISelEmitter &ISE) {
1688 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1689 ChildVariants.push_back(LHS);
1690 ChildVariants.push_back(RHS);
1691 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1695 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1696 std::vector<TreePatternNode *> &Children) {
1697 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1698 Record *Operator = N->getOperator();
1700 // Only permit raw nodes.
1701 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1702 N->getTransformFn()) {
1703 Children.push_back(N);
1707 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1708 Children.push_back(N->getChild(0));
1710 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1712 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1713 Children.push_back(N->getChild(1));
1715 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1718 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1719 /// the (potentially recursive) pattern by using algebraic laws.
1721 static void GenerateVariantsOf(TreePatternNode *N,
1722 std::vector<TreePatternNode*> &OutVariants,
1723 DAGISelEmitter &ISE) {
1724 // We cannot permute leaves.
1726 OutVariants.push_back(N);
1730 // Look up interesting info about the node.
1731 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1733 // If this node is associative, reassociate.
1734 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1735 // Reassociate by pulling together all of the linked operators
1736 std::vector<TreePatternNode*> MaximalChildren;
1737 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1739 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1741 if (MaximalChildren.size() == 3) {
1742 // Find the variants of all of our maximal children.
1743 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1744 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1745 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1746 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1748 // There are only two ways we can permute the tree:
1749 // (A op B) op C and A op (B op C)
1750 // Within these forms, we can also permute A/B/C.
1752 // Generate legal pair permutations of A/B/C.
1753 std::vector<TreePatternNode*> ABVariants;
1754 std::vector<TreePatternNode*> BAVariants;
1755 std::vector<TreePatternNode*> ACVariants;
1756 std::vector<TreePatternNode*> CAVariants;
1757 std::vector<TreePatternNode*> BCVariants;
1758 std::vector<TreePatternNode*> CBVariants;
1759 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1760 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1761 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1762 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1763 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1764 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1766 // Combine those into the result: (x op x) op x
1767 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1768 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1769 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1770 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1771 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1772 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1774 // Combine those into the result: x op (x op x)
1775 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1776 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1777 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1778 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1779 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1780 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1785 // Compute permutations of all children.
1786 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1787 ChildVariants.resize(N->getNumChildren());
1788 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1789 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1791 // Build all permutations based on how the children were formed.
1792 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1794 // If this node is commutative, consider the commuted order.
1795 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1796 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1797 // Consider the commuted order.
1798 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1804 // GenerateVariants - Generate variants. For example, commutative patterns can
1805 // match multiple ways. Add them to PatternsToMatch as well.
1806 void DAGISelEmitter::GenerateVariants() {
1808 DEBUG(std::cerr << "Generating instruction variants.\n");
1810 // Loop over all of the patterns we've collected, checking to see if we can
1811 // generate variants of the instruction, through the exploitation of
1812 // identities. This permits the target to provide agressive matching without
1813 // the .td file having to contain tons of variants of instructions.
1815 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1816 // intentionally do not reconsider these. Any variants of added patterns have
1817 // already been added.
1819 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1820 std::vector<TreePatternNode*> Variants;
1821 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1823 assert(!Variants.empty() && "Must create at least original variant!");
1824 Variants.erase(Variants.begin()); // Remove the original pattern.
1826 if (Variants.empty()) // No variants for this pattern.
1829 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1830 PatternsToMatch[i].getSrcPattern()->dump();
1833 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1834 TreePatternNode *Variant = Variants[v];
1836 DEBUG(std::cerr << " VAR#" << v << ": ";
1840 // Scan to see if an instruction or explicit pattern already matches this.
1841 bool AlreadyExists = false;
1842 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1843 // Check to see if this variant already exists.
1844 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1845 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1846 AlreadyExists = true;
1850 // If we already have it, ignore the variant.
1851 if (AlreadyExists) continue;
1853 // Otherwise, add it to the list of patterns we have.
1855 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1856 Variant, PatternsToMatch[i].getDstPattern(),
1857 PatternsToMatch[i].getAddedComplexity()));
1860 DEBUG(std::cerr << "\n");
1865 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1867 static bool NodeIsComplexPattern(TreePatternNode *N)
1869 return (N->isLeaf() &&
1870 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1871 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1872 isSubClassOf("ComplexPattern"));
1875 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1876 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1877 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1878 DAGISelEmitter &ISE)
1881 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1882 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1883 isSubClassOf("ComplexPattern")) {
1884 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1890 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1891 /// patterns before small ones. This is used to determine the size of a
1893 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1894 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1895 isExtFloatingPointInVTs(P->getExtTypes()) ||
1896 P->getExtTypeNum(0) == MVT::isVoid ||
1897 P->getExtTypeNum(0) == MVT::Flag ||
1898 P->getExtTypeNum(0) == MVT::iPTR) &&
1899 "Not a valid pattern node to size!");
1900 unsigned Size = 2; // The node itself.
1901 // If the root node is a ConstantSDNode, increases its size.
1902 // e.g. (set R32:$dst, 0).
1903 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1906 // FIXME: This is a hack to statically increase the priority of patterns
1907 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1908 // Later we can allow complexity / cost for each pattern to be (optionally)
1909 // specified. To get best possible pattern match we'll need to dynamically
1910 // calculate the complexity of all patterns a dag can potentially map to.
1911 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1913 Size += AM->getNumOperands() * 2;
1915 // If this node has some predicate function that must match, it adds to the
1916 // complexity of this node.
1917 if (!P->getPredicateFn().empty())
1920 // Count children in the count if they are also nodes.
1921 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1922 TreePatternNode *Child = P->getChild(i);
1923 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1924 Size += getPatternSize(Child, ISE);
1925 else if (Child->isLeaf()) {
1926 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1927 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
1928 else if (NodeIsComplexPattern(Child))
1929 Size += getPatternSize(Child, ISE);
1930 else if (!Child->getPredicateFn().empty())
1938 /// getResultPatternCost - Compute the number of instructions for this pattern.
1939 /// This is a temporary hack. We should really include the instruction
1940 /// latencies in this calculation.
1941 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1942 if (P->isLeaf()) return 0;
1945 Record *Op = P->getOperator();
1946 if (Op->isSubClassOf("Instruction")) {
1948 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1949 if (II.usesCustomDAGSchedInserter)
1952 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1953 Cost += getResultPatternCost(P->getChild(i), ISE);
1957 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1958 // In particular, we want to match maximal patterns first and lowest cost within
1959 // a particular complexity first.
1960 struct PatternSortingPredicate {
1961 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1962 DAGISelEmitter &ISE;
1964 bool operator()(PatternToMatch *LHS,
1965 PatternToMatch *RHS) {
1966 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1967 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1968 LHSSize += LHS->getAddedComplexity();
1969 RHSSize += RHS->getAddedComplexity();
1970 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1971 if (LHSSize < RHSSize) return false;
1973 // If the patterns have equal complexity, compare generated instruction cost
1974 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1975 getResultPatternCost(RHS->getDstPattern(), ISE);
1979 /// getRegisterValueType - Look up and return the first ValueType of specified
1980 /// RegisterClass record
1981 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1982 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1983 return RC->getValueTypeNum(0);
1988 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1989 /// type information from it.
1990 static void RemoveAllTypes(TreePatternNode *N) {
1993 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1994 RemoveAllTypes(N->getChild(i));
1997 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1998 Record *N = Records.getDef(Name);
1999 if (!N || !N->isSubClassOf("SDNode")) {
2000 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2006 /// NodeHasProperty - return true if TreePatternNode has the specified
2008 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2009 DAGISelEmitter &ISE)
2011 if (N->isLeaf()) return false;
2012 Record *Operator = N->getOperator();
2013 if (!Operator->isSubClassOf("SDNode")) return false;
2015 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2016 return NodeInfo.hasProperty(Property);
2019 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2020 DAGISelEmitter &ISE)
2022 if (NodeHasProperty(N, Property, ISE))
2025 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2026 TreePatternNode *Child = N->getChild(i);
2027 if (PatternHasProperty(Child, Property, ISE))
2034 class PatternCodeEmitter {
2036 DAGISelEmitter &ISE;
2039 ListInit *Predicates;
2042 // Instruction selector pattern.
2043 TreePatternNode *Pattern;
2044 // Matched instruction.
2045 TreePatternNode *Instruction;
2047 // Node to name mapping
2048 std::map<std::string, std::string> VariableMap;
2049 // Node to operator mapping
2050 std::map<std::string, Record*> OperatorMap;
2051 // Names of all the folded nodes which produce chains.
2052 std::vector<std::pair<std::string, unsigned> > FoldedChains;
2053 std::set<std::string> Duplicates;
2054 /// These nodes are being marked "in-flight" so they cannot be folded.
2055 std::vector<std::string> InflightNodes;
2057 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2058 /// indicates whether this is an exit predicate (something that should be
2059 /// tested, and if true, the match fails) [when true] or normal code to emit
2061 std::vector<std::pair<bool, std::string> > &GeneratedCode;
2062 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2063 /// the set of patterns for each top-level opcode.
2064 std::set<std::pair<bool, std::string> > &GeneratedDecl;
2066 std::string ChainName;
2071 void emitCheck(const std::string &S) {
2073 GeneratedCode.push_back(std::make_pair(true, S));
2075 void emitCode(const std::string &S) {
2077 GeneratedCode.push_back(std::make_pair(false, S));
2079 void emitDecl(const std::string &S, bool isSDNode=false) {
2080 assert(!S.empty() && "Invalid declaration");
2081 GeneratedDecl.insert(std::make_pair(isSDNode, S));
2084 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2085 TreePatternNode *pattern, TreePatternNode *instr,
2086 std::vector<std::pair<bool, std::string> > &gc,
2087 std::set<std::pair<bool, std::string> > &gd,
2089 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2090 GeneratedCode(gc), GeneratedDecl(gd),
2091 NewTF(false), DoReplace(dorep), TmpNo(0) {}
2093 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2094 /// if the match fails. At this point, we already know that the opcode for N
2095 /// matches, and the SDNode for the result has the RootName specified name.
2096 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2097 const std::string &RootName, const std::string &ParentName,
2098 const std::string &ChainSuffix, bool &FoundChain) {
2099 bool isRoot = (P == NULL);
2100 // Emit instruction predicates. Each predicate is just a string for now.
2102 std::string PredicateCheck;
2103 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2104 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2105 Record *Def = Pred->getDef();
2106 if (!Def->isSubClassOf("Predicate")) {
2108 assert(0 && "Unknown predicate type!");
2110 if (!PredicateCheck.empty())
2111 PredicateCheck += " || ";
2112 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2116 emitCheck(PredicateCheck);
2120 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2121 emitCheck("cast<ConstantSDNode>(" + RootName +
2122 ")->getSignExtended() == " + itostr(II->getValue()));
2124 } else if (!NodeIsComplexPattern(N)) {
2125 assert(0 && "Cannot match this as a leaf value!");
2130 // If this node has a name associated with it, capture it in VariableMap. If
2131 // we already saw this in the pattern, emit code to verify dagness.
2132 if (!N->getName().empty()) {
2133 std::string &VarMapEntry = VariableMap[N->getName()];
2134 if (VarMapEntry.empty()) {
2135 VarMapEntry = RootName;
2137 // If we get here, this is a second reference to a specific name. Since
2138 // we already have checked that the first reference is valid, we don't
2139 // have to recursively match it, just check that it's the same as the
2140 // previously named thing.
2141 emitCheck(VarMapEntry + " == " + RootName);
2146 OperatorMap[N->getName()] = N->getOperator();
2150 // Emit code to load the child nodes and match their contents recursively.
2152 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2153 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2154 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
2155 bool EmittedUseCheck = false;
2156 bool EmittedSlctedCheck = false;
2161 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2163 emitCheck("InFlightSet.count(" + RootName + ".Val) == 0");
2164 // Multiple uses of actual result?
2165 emitCheck(RootName + ".hasOneUse()");
2166 EmittedUseCheck = true;
2167 // hasOneUse() check is not strong enough. If the original node has
2168 // already been selected, it may have been replaced with another.
2169 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2170 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2173 EmittedSlctedCheck = true;
2175 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2177 // This a workaround for this problem:
2182 // [XX]--/ \- [flag : cmp]
2187 // cmp + br should be considered as a single node as they are flagged
2188 // together. So, if the ld is folded into the cmp, the XX node in the
2189 // graph is now both an operand and a use of the ld/cmp/br node.
2190 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2191 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2193 // If the immediate use can somehow reach this node through another
2194 // path, then can't fold it either or it will create a cycle.
2195 // e.g. In the following diagram, XX can reach ld through YY. If
2196 // ld is folded into XX, then YY is both a predecessor and a successor
2206 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2207 if (PInfo.getNumOperands() > 1 ||
2208 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2209 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2210 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2211 if (PInfo.getNumOperands() > 1) {
2212 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2215 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2216 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2223 ChainName = "Chain" + ChainSuffix;
2224 emitDecl(ChainName);
2226 // FIXME: temporary workaround for a common case where chain
2227 // is a TokenFactor and the previous "inner" chain is an operand.
2229 emitDecl("OldTF", true);
2230 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2231 RootName + ".Val, Chain.Val, OldTF)).Val");
2234 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2239 // Don't fold any node which reads or writes a flag and has multiple uses.
2240 // FIXME: We really need to separate the concepts of flag and "glue". Those
2241 // real flag results, e.g. X86CMP output, can have multiple uses.
2242 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2245 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2246 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2247 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2248 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2249 if (!EmittedUseCheck) {
2250 // Multiple uses of actual result?
2251 emitCheck(RootName + ".hasOneUse()");
2253 if (!EmittedSlctedCheck)
2254 // hasOneUse() check is not strong enough. If the original node has
2255 // already been selected, it may have been replaced with another.
2256 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2257 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2261 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2262 emitDecl(RootName + utostr(OpNo));
2263 emitCode(RootName + utostr(OpNo) + " = " +
2264 RootName + ".getOperand(" +utostr(OpNo) + ");");
2265 TreePatternNode *Child = N->getChild(i);
2267 if (!Child->isLeaf()) {
2268 // If it's not a leaf, recursively match.
2269 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2270 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2271 CInfo.getEnumName());
2272 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2273 ChainSuffix + utostr(OpNo), FoundChain);
2274 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2275 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2276 CInfo.getNumResults()));
2278 // If this child has a name associated with it, capture it in VarMap. If
2279 // we already saw this in the pattern, emit code to verify dagness.
2280 if (!Child->getName().empty()) {
2281 std::string &VarMapEntry = VariableMap[Child->getName()];
2282 if (VarMapEntry.empty()) {
2283 VarMapEntry = RootName + utostr(OpNo);
2285 // If we get here, this is a second reference to a specific name.
2286 // Since we already have checked that the first reference is valid,
2287 // we don't have to recursively match it, just check that it's the
2288 // same as the previously named thing.
2289 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2290 Duplicates.insert(RootName + utostr(OpNo));
2295 // Handle leaves of various types.
2296 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2297 Record *LeafRec = DI->getDef();
2298 if (LeafRec->isSubClassOf("RegisterClass")) {
2299 // Handle register references. Nothing to do here.
2300 } else if (LeafRec->isSubClassOf("Register")) {
2301 // Handle register references.
2302 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2303 // Handle complex pattern. Nothing to do here.
2304 } else if (LeafRec->getName() == "srcvalue") {
2305 // Place holder for SRCVALUE nodes. Nothing to do here.
2306 } else if (LeafRec->isSubClassOf("ValueType")) {
2307 // Make sure this is the specified value type.
2308 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2309 ")->getVT() == MVT::" + LeafRec->getName());
2310 } else if (LeafRec->isSubClassOf("CondCode")) {
2311 // Make sure this is the specified cond code.
2312 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2313 ")->get() == ISD::" + LeafRec->getName());
2317 assert(0 && "Unknown leaf type!");
2319 } else if (IntInit *II =
2320 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2321 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2322 unsigned CTmp = TmpNo++;
2323 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2324 RootName + utostr(OpNo) + ")->getSignExtended();");
2326 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2329 assert(0 && "Unknown leaf type!");
2334 // If there is a node predicate for this, emit the call.
2335 if (!N->getPredicateFn().empty())
2336 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2339 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2340 /// we actually have to build a DAG!
2341 std::pair<unsigned, unsigned>
2342 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2343 bool isRoot = false) {
2344 // This is something selected from the pattern we matched.
2345 if (!N->getName().empty()) {
2346 std::string &Val = VariableMap[N->getName()];
2347 assert(!Val.empty() &&
2348 "Variable referenced but not defined and not caught earlier!");
2349 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2350 // Already selected this operand, just return the tmpval.
2351 return std::make_pair(1, atoi(Val.c_str()+3));
2354 const ComplexPattern *CP;
2355 unsigned ResNo = TmpNo++;
2356 unsigned NumRes = 1;
2357 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2358 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2359 std::string CastType;
2360 switch (N->getTypeNum(0)) {
2361 default: assert(0 && "Unknown type for constant node!");
2362 case MVT::i1: CastType = "bool"; break;
2363 case MVT::i8: CastType = "unsigned char"; break;
2364 case MVT::i16: CastType = "unsigned short"; break;
2365 case MVT::i32: CastType = "unsigned"; break;
2366 case MVT::i64: CastType = "uint64_t"; break;
2368 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
2369 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
2370 emitDecl("Tmp" + utostr(ResNo));
2371 emitCode("Tmp" + utostr(ResNo) +
2372 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2373 "C, " + getEnumName(N->getTypeNum(0)) + ");");
2374 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2375 Record *Op = OperatorMap[N->getName()];
2376 // Transform ExternalSymbol to TargetExternalSymbol
2377 if (Op && Op->getName() == "externalsym") {
2378 emitDecl("Tmp" + utostr(ResNo));
2379 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2380 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2381 Val + ")->getSymbol(), " +
2382 getEnumName(N->getTypeNum(0)) + ");");
2384 emitDecl("Tmp" + utostr(ResNo));
2385 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2387 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2388 Record *Op = OperatorMap[N->getName()];
2389 // Transform GlobalAddress to TargetGlobalAddress
2390 if (Op && Op->getName() == "globaladdr") {
2391 emitDecl("Tmp" + utostr(ResNo));
2392 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2393 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2394 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2397 emitDecl("Tmp" + utostr(ResNo));
2398 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2400 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2401 emitDecl("Tmp" + utostr(ResNo));
2402 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2403 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2404 emitDecl("Tmp" + utostr(ResNo));
2405 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2406 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2407 std::string Fn = CP->getSelectFunc();
2408 NumRes = CP->getNumOperands();
2409 for (unsigned i = 0; i < NumRes; ++i)
2410 emitDecl("Tmp" + utostr(i+ResNo));
2412 std::string Code = Fn + "(" + Val;
2413 for (unsigned i = 0; i < NumRes; i++)
2414 Code += ", Tmp" + utostr(i + ResNo);
2415 emitCheck(Code + ")");
2417 for (unsigned i = 0; i < NumRes; ++i) {
2418 emitCode("InFlightSet.insert(Tmp" + utostr(i+ResNo) + ".Val);");
2419 InflightNodes.push_back("Tmp" + utostr(i+ResNo));
2421 for (unsigned i = 0; i < NumRes; ++i)
2422 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
2423 utostr(i+ResNo) + ");");
2425 TmpNo = ResNo + NumRes;
2427 emitDecl("Tmp" + utostr(ResNo));
2428 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2429 // node even if it isn't one. Don't select it.
2431 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2433 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2436 if (isRoot && N->isLeaf()) {
2437 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2438 emitCode("return;");
2441 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2442 // value if used multiple times by this pattern result.
2443 Val = "Tmp"+utostr(ResNo);
2444 return std::make_pair(NumRes, ResNo);
2447 // If this is an explicit register reference, handle it.
2448 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2449 unsigned ResNo = TmpNo++;
2450 if (DI->getDef()->isSubClassOf("Register")) {
2451 emitDecl("Tmp" + utostr(ResNo));
2452 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2453 ISE.getQualifiedName(DI->getDef()) + ", " +
2454 getEnumName(N->getTypeNum(0)) + ");");
2455 return std::make_pair(1, ResNo);
2457 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2458 unsigned ResNo = TmpNo++;
2459 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2460 emitDecl("Tmp" + utostr(ResNo));
2461 emitCode("Tmp" + utostr(ResNo) +
2462 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2463 ", " + getEnumName(N->getTypeNum(0)) + ");");
2464 return std::make_pair(1, ResNo);
2468 assert(0 && "Unknown leaf type!");
2469 return std::make_pair(1, ~0U);
2472 Record *Op = N->getOperator();
2473 if (Op->isSubClassOf("Instruction")) {
2474 const CodeGenTarget &CGT = ISE.getTargetInfo();
2475 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2476 const DAGInstruction &Inst = ISE.getInstruction(Op);
2477 TreePattern *InstPat = Inst.getPattern();
2478 TreePatternNode *InstPatNode =
2479 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2480 : (InstPat ? InstPat->getOnlyTree() : NULL);
2481 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2482 InstPatNode = InstPatNode->getChild(1);
2484 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2485 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2486 bool NodeHasOptInFlag = isRoot &&
2487 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2488 bool NodeHasInFlag = isRoot &&
2489 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2490 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2491 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2492 bool NodeHasChain = InstPatNode &&
2493 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
2494 bool InputHasChain = isRoot &&
2495 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2497 if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
2499 if (NodeHasOptInFlag)
2500 emitCode("bool HasOptInFlag = false;");
2502 // How many results is this pattern expected to produce?
2503 unsigned PatResults = 0;
2504 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2505 MVT::ValueType VT = Pattern->getTypeNum(i);
2506 if (VT != MVT::isVoid && VT != MVT::Flag)
2510 // Determine operand emission order. Complex pattern first.
2511 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2512 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2513 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2514 TreePatternNode *Child = N->getChild(i);
2516 EmitOrder.push_back(std::make_pair(i, Child));
2517 OI = EmitOrder.begin();
2518 } else if (NodeIsComplexPattern(Child)) {
2519 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2521 EmitOrder.push_back(std::make_pair(i, Child));
2525 // Make sure these operands which would be selected won't be folded while
2526 // the isel traverses the DAG upward.
2527 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2528 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2529 TreePatternNode *Child = EmitOrder[i].second;
2530 if (!Child->getName().empty()) {
2531 std::string &Val = VariableMap[Child->getName()];
2532 assert(!Val.empty() &&
2533 "Variable referenced but not defined and not caught earlier!");
2534 if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) {
2535 emitCode("InFlightSet.insert(" + Val + ".Val);");
2536 InflightNodes.push_back(Val);
2541 // Emit all of the operands.
2542 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2543 unsigned OpOrder = EmitOrder[i].first;
2544 TreePatternNode *Child = EmitOrder[i].second;
2545 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2546 NumTemps[OpOrder] = NumTemp;
2549 // List all the operands in the right order.
2550 std::vector<unsigned> Ops;
2551 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2552 for (unsigned j = 0; j < NumTemps[i].first; j++)
2553 Ops.push_back(NumTemps[i].second + j);
2556 // Emit all the chain and CopyToReg stuff.
2557 bool ChainEmitted = NodeHasChain;
2559 emitCode("Select(" + ChainName + ", " + ChainName + ");");
2560 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2561 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2564 // The operands have been selected. Remove them from InFlightSet.
2565 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2566 AE = InflightNodes.end(); AI != AE; ++AI)
2567 emitCode("InFlightSet.erase(" + *AI + ".Val);");
2570 unsigned NumResults = Inst.getNumResults();
2571 unsigned ResNo = TmpNo++;
2572 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2574 if (NodeHasOptInFlag) {
2575 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2576 emitDecl("ResNode", true);
2577 emitCode("if (HasOptInFlag)");
2578 std::string Code = " ResNode = CurDAG->getTargetNode(" +
2579 II.Namespace + "::" + II.TheDef->getName();
2581 // Output order: results, chain, flags
2583 if (PatResults > 0) {
2584 if (N->getTypeNum(0) != MVT::isVoid)
2585 Code += ", " + getEnumName(N->getTypeNum(0));
2588 Code += ", MVT::Other";
2590 Code += ", MVT::Flag";
2593 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2594 Code += ", Tmp" + utostr(Ops[i]);
2595 if (NodeHasChain) Code += ", " + ChainName;
2596 emitCode(Code + ", InFlag);");
2599 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
2600 II.TheDef->getName();
2602 // Output order: results, chain, flags
2604 if (PatResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2605 Code += ", " + getEnumName(N->getTypeNum(0));
2607 Code += ", MVT::Other";
2609 Code += ", MVT::Flag";
2612 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2613 Code += ", Tmp" + utostr(Ops[i]);
2614 if (NodeHasChain) Code += ", " + ChainName + ");";
2618 // Remember which op produces the chain.
2619 emitCode(ChainName + " = SDOperand(ResNode" +
2620 ", " + utostr(PatResults) + ");");
2623 std::string NodeName;
2625 NodeName = "Tmp" + utostr(ResNo);
2627 Code = NodeName + " = SDOperand(";
2629 NodeName = "ResNode";
2630 emitDecl(NodeName, true);
2631 Code = NodeName + " = ";
2633 Code += "CurDAG->getTargetNode(" +
2634 II.Namespace + "::" + II.TheDef->getName();
2636 // Output order: results, chain, flags
2638 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2639 Code += ", " + getEnumName(N->getTypeNum(0));
2641 Code += ", MVT::Other";
2643 Code += ", MVT::Flag";
2646 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2647 Code += ", Tmp" + utostr(Ops[i]);
2648 if (NodeHasChain) Code += ", " + ChainName;
2649 if (NodeHasInFlag || HasImpInputs) Code += ", InFlag";
2651 emitCode(Code + "), 0);");
2653 emitCode(Code + ");");
2656 // Remember which op produces the chain.
2658 emitCode(ChainName + " = SDOperand(" + NodeName +
2659 ".Val, " + utostr(PatResults) + ");");
2661 emitCode(ChainName + " = SDOperand(" + NodeName +
2662 ", " + utostr(PatResults) + ");");
2666 return std::make_pair(1, ResNo);
2669 emitCode("if (OldTF) "
2670 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2671 ChainName + ".Val, 0);");
2673 for (unsigned i = 0; i < NumResults; i++)
2674 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2675 utostr(i) + ", ResNode, " + utostr(i) + ");");
2678 emitCode("InFlag = SDOperand(ResNode, " +
2679 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2681 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2682 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2687 if (InputHasChain) {
2688 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2689 utostr(PatResults) + ", " + ChainName + ".Val, " +
2690 ChainName + ".ResNo" + ");");
2692 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2693 utostr(PatResults) + ", " + ChainName + ".Val, " +
2694 ChainName + ".ResNo" + ");");
2697 if (FoldedChains.size() > 0) {
2699 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2700 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2701 FoldedChains[j].first + ".Val, " +
2702 utostr(FoldedChains[j].second) + ", ResNode, " +
2703 utostr(NumResults) + ");");
2705 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2707 FoldedChains[j].first + ".Val, " +
2708 utostr(FoldedChains[j].second) + ", ";
2709 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2710 utostr(NumResults) + ");");
2715 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2716 utostr(PatResults + (unsigned)InputHasChain) +
2717 ", InFlag.Val, InFlag.ResNo);");
2719 // User does not expect the instruction would produce a chain!
2720 bool AddedChain = NodeHasChain && !InputHasChain;
2721 if (AddedChain && NodeHasOutFlag) {
2722 if (PatResults == 0) {
2723 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2725 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2726 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2728 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
2730 } else if (InputHasChain && !NodeHasChain) {
2731 // One of the inner node produces a chain.
2732 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2733 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2734 if (NodeHasOutFlag) {
2735 emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2736 emitCode(" Result = SDOperand(ResNode, N.ResNo-1);");
2739 emitCode(" Result = SDOperand(" + ChainName + ".Val, " + ChainName + ".ResNo);");
2741 emitCode("Result = SDOperand(ResNode, N.ResNo);");
2744 // If this instruction is the root, and if there is only one use of it,
2745 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2746 emitCode("if (N.Val->hasOneUse()) {");
2747 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
2748 II.Namespace + "::" + II.TheDef->getName();
2749 if (N->getTypeNum(0) != MVT::isVoid)
2750 Code += ", " + getEnumName(N->getTypeNum(0));
2752 Code += ", MVT::Flag";
2753 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2754 Code += ", Tmp" + utostr(Ops[i]);
2755 if (NodeHasInFlag || HasImpInputs)
2757 emitCode(Code + ");");
2758 emitCode("} else {");
2759 emitDecl("ResNode", true);
2760 Code = " ResNode = CurDAG->getTargetNode(" +
2761 II.Namespace + "::" + II.TheDef->getName();
2762 if (N->getTypeNum(0) != MVT::isVoid)
2763 Code += ", " + getEnumName(N->getTypeNum(0));
2765 Code += ", MVT::Flag";
2766 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2767 Code += ", Tmp" + utostr(Ops[i]);
2768 if (NodeHasInFlag || HasImpInputs)
2770 emitCode(Code + ");");
2771 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2773 emitCode(" Result = SDOperand(ResNode, 0);");
2778 emitCode("return;");
2779 return std::make_pair(1, ResNo);
2780 } else if (Op->isSubClassOf("SDNodeXForm")) {
2781 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2782 // PatLeaf node - the operand may or may not be a leaf node. But it should
2784 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2785 unsigned ResNo = TmpNo++;
2786 emitDecl("Tmp" + utostr(ResNo));
2787 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2788 + "(Tmp" + utostr(OpVal) + ".Val);");
2790 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2791 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2792 utostr(ResNo) + ".ResNo);");
2793 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2794 emitCode("return;");
2796 return std::make_pair(1, ResNo);
2800 throw std::string("Unknown node in result pattern!");
2804 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2805 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2806 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2807 /// for, this returns true otherwise false if Pat has all types.
2808 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2809 const std::string &Prefix) {
2811 if (!Pat->hasTypeSet()) {
2812 // Move a type over from 'other' to 'pat'.
2813 Pat->setTypes(Other->getExtTypes());
2814 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2815 getName(Pat->getTypeNum(0)));
2820 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2821 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2822 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2823 Prefix + utostr(OpNo)))
2829 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2831 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2832 bool &ChainEmitted, bool isRoot = false) {
2833 const CodeGenTarget &T = ISE.getTargetInfo();
2835 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2836 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2837 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2838 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2839 TreePatternNode *Child = N->getChild(i);
2840 if (!Child->isLeaf()) {
2841 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2843 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2844 if (!Child->getName().empty()) {
2845 std::string Name = RootName + utostr(OpNo);
2846 if (Duplicates.find(Name) != Duplicates.end())
2847 // A duplicate! Do not emit a copy for this node.
2851 Record *RR = DI->getDef();
2852 if (RR->isSubClassOf("Register")) {
2853 MVT::ValueType RVT = getRegisterValueType(RR, T);
2854 if (RVT == MVT::Flag) {
2855 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2857 if (!ChainEmitted) {
2859 emitCode("Chain = CurDAG->getEntryNode();");
2860 ChainName = "Chain";
2861 ChainEmitted = true;
2863 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2864 RootName + utostr(OpNo) + ");");
2865 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2866 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2867 ", " + getEnumName(RVT) + "), " +
2868 RootName + utostr(OpNo) + ", InFlag).Val;");
2869 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2870 emitCode("InFlag = SDOperand(ResNode, 1);");
2877 if (HasInFlag || HasOptInFlag) {
2880 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2884 emitCode(Code + "Select(InFlag, " + RootName +
2885 ".getOperand(" + utostr(OpNo) + "));");
2887 emitCode(" HasOptInFlag = true;");
2893 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2894 /// as specified by the instruction. It returns true if any copy is
2896 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2897 bool RetVal = false;
2898 Record *Op = N->getOperator();
2899 if (Op->isSubClassOf("Instruction")) {
2900 const DAGInstruction &Inst = ISE.getInstruction(Op);
2901 const CodeGenTarget &CGT = ISE.getTargetInfo();
2902 unsigned NumImpResults = Inst.getNumImpResults();
2903 for (unsigned i = 0; i < NumImpResults; i++) {
2904 Record *RR = Inst.getImpResult(i);
2905 if (RR->isSubClassOf("Register")) {
2906 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2907 if (RVT != MVT::Flag) {
2908 if (!ChainEmitted) {
2910 emitCode("Chain = CurDAG->getEntryNode();");
2911 ChainEmitted = true;
2912 ChainName = "Chain";
2914 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
2915 ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
2917 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2918 emitCode("InFlag = SDOperand(ResNode, 2);");
2928 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2929 /// stream to match the pattern, and generate the code for the match if it
2930 /// succeeds. Returns true if the pattern is not guaranteed to match.
2931 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2932 std::vector<std::pair<bool, std::string> > &GeneratedCode,
2933 std::set<std::pair<bool, std::string> > &GeneratedDecl,
2935 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2936 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2937 GeneratedCode, GeneratedDecl, DoReplace);
2939 // Emit the matcher, capturing named arguments in VariableMap.
2940 bool FoundChain = false;
2941 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
2943 // TP - Get *SOME* tree pattern, we don't care which.
2944 TreePattern &TP = *PatternFragments.begin()->second;
2946 // At this point, we know that we structurally match the pattern, but the
2947 // types of the nodes may not match. Figure out the fewest number of type
2948 // comparisons we need to emit. For example, if there is only one integer
2949 // type supported by a target, there should be no type comparisons at all for
2950 // integer patterns!
2952 // To figure out the fewest number of type checks needed, clone the pattern,
2953 // remove the types, then perform type inference on the pattern as a whole.
2954 // If there are unresolved types, emit an explicit check for those types,
2955 // apply the type to the tree, then rerun type inference. Iterate until all
2956 // types are resolved.
2958 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2959 RemoveAllTypes(Pat);
2962 // Resolve/propagate as many types as possible.
2964 bool MadeChange = true;
2966 MadeChange = Pat->ApplyTypeConstraints(TP,
2967 true/*Ignore reg constraints*/);
2969 assert(0 && "Error: could not find consistent types for something we"
2970 " already decided was ok!");
2974 // Insert a check for an unresolved type and add it to the tree. If we find
2975 // an unresolved type to add a check for, this returns true and we iterate,
2976 // otherwise we are done.
2977 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2979 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
2983 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
2984 /// a line causes any of them to be empty, remove them and return true when
2986 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2987 std::vector<std::pair<bool, std::string> > > >
2989 bool ErasedPatterns = false;
2990 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2991 Patterns[i].second.pop_back();
2992 if (Patterns[i].second.empty()) {
2993 Patterns.erase(Patterns.begin()+i);
2995 ErasedPatterns = true;
2998 return ErasedPatterns;
3001 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3002 /// code together between the patterns.
3003 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3004 std::vector<std::pair<bool, std::string> > > >
3005 &Patterns, unsigned Indent,
3007 typedef std::pair<bool, std::string> CodeLine;
3008 typedef std::vector<CodeLine> CodeList;
3009 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3011 if (Patterns.empty()) return;
3013 // Figure out how many patterns share the next code line. Explicitly copy
3014 // FirstCodeLine so that we don't invalidate a reference when changing
3016 const CodeLine FirstCodeLine = Patterns.back().second.back();
3017 unsigned LastMatch = Patterns.size()-1;
3018 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3021 // If not all patterns share this line, split the list into two pieces. The
3022 // first chunk will use this line, the second chunk won't.
3023 if (LastMatch != 0) {
3024 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3025 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3027 // FIXME: Emit braces?
3028 if (Shared.size() == 1) {
3029 PatternToMatch &Pattern = *Shared.back().first;
3030 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3031 Pattern.getSrcPattern()->print(OS);
3032 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3033 Pattern.getDstPattern()->print(OS);
3035 unsigned AddedComplexity = Pattern.getAddedComplexity();
3036 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3037 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3039 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
3041 if (!FirstCodeLine.first) {
3042 OS << std::string(Indent, ' ') << "{\n";
3045 EmitPatterns(Shared, Indent, OS);
3046 if (!FirstCodeLine.first) {
3048 OS << std::string(Indent, ' ') << "}\n";
3051 if (Other.size() == 1) {
3052 PatternToMatch &Pattern = *Other.back().first;
3053 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3054 Pattern.getSrcPattern()->print(OS);
3055 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3056 Pattern.getDstPattern()->print(OS);
3058 unsigned AddedComplexity = Pattern.getAddedComplexity();
3059 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3060 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3062 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
3064 EmitPatterns(Other, Indent, OS);
3068 // Remove this code from all of the patterns that share it.
3069 bool ErasedPatterns = EraseCodeLine(Patterns);
3071 bool isPredicate = FirstCodeLine.first;
3073 // Otherwise, every pattern in the list has this line. Emit it.
3076 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3078 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3080 // If the next code line is another predicate, and if all of the pattern
3081 // in this group share the same next line, emit it inline now. Do this
3082 // until we run out of common predicates.
3083 while (!ErasedPatterns && Patterns.back().second.back().first) {
3084 // Check that all of fhe patterns in Patterns end with the same predicate.
3085 bool AllEndWithSamePredicate = true;
3086 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3087 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3088 AllEndWithSamePredicate = false;
3091 // If all of the predicates aren't the same, we can't share them.
3092 if (!AllEndWithSamePredicate) break;
3094 // Otherwise we can. Emit it shared now.
3095 OS << " &&\n" << std::string(Indent+4, ' ')
3096 << Patterns.back().second.back().second;
3097 ErasedPatterns = EraseCodeLine(Patterns);
3104 EmitPatterns(Patterns, Indent, OS);
3107 OS << std::string(Indent-2, ' ') << "}\n";
3113 /// CompareByRecordName - An ordering predicate that implements less-than by
3114 /// comparing the names records.
3115 struct CompareByRecordName {
3116 bool operator()(const Record *LHS, const Record *RHS) const {
3117 // Sort by name first.
3118 if (LHS->getName() < RHS->getName()) return true;
3119 // If both names are equal, sort by pointer.
3120 return LHS->getName() == RHS->getName() && LHS < RHS;
3125 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3126 std::string InstNS = Target.inst_begin()->second.Namespace;
3127 if (!InstNS.empty()) InstNS += "::";
3129 // Group the patterns by their top-level opcodes.
3130 std::map<Record*, std::vector<PatternToMatch*>,
3131 CompareByRecordName> PatternsByOpcode;
3132 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3133 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3134 if (!Node->isLeaf()) {
3135 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3137 const ComplexPattern *CP;
3139 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3140 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3141 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3142 std::vector<Record*> OpNodes = CP->getRootNodes();
3143 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3144 PatternsByOpcode[OpNodes[j]]
3145 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3148 std::cerr << "Unrecognized opcode '";
3150 std::cerr << "' on tree pattern '";
3152 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3153 std::cerr << "'!\n";
3159 // Emit one Select_* method for each top-level opcode. We do this instead of
3160 // emitting one giant switch statement to support compilers where this will
3161 // result in the recursive functions taking less stack space.
3162 for (std::map<Record*, std::vector<PatternToMatch*>,
3163 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3164 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3165 const std::string &OpName = PBOI->first->getName();
3166 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3168 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3170 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3171 OpcodeInfo.getNumResults() > 0);
3174 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3175 << " && N.getValue(0).hasOneUse()) {\n"
3176 << " SDOperand Dummy = "
3177 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3178 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3179 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3180 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3181 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3182 << " Result = Dummy;\n"
3187 std::vector<PatternToMatch*> &Patterns = PBOI->second;
3188 assert(!Patterns.empty() && "No patterns but map has entry?");
3190 // We want to emit all of the matching code now. However, we want to emit
3191 // the matches in order of minimal cost. Sort the patterns so the least
3192 // cost one is at the start.
3193 std::stable_sort(Patterns.begin(), Patterns.end(),
3194 PatternSortingPredicate(*this));
3196 typedef std::vector<std::pair<bool, std::string> > CodeList;
3197 typedef std::set<std::string> DeclSet;
3199 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3200 std::set<std::pair<bool, std::string> > GeneratedDecl;
3201 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3202 CodeList GeneratedCode;
3203 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3205 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3208 // Scan the code to see if all of the patterns are reachable and if it is
3209 // possible that the last one might not match.
3210 bool mightNotMatch = true;
3211 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3212 CodeList &GeneratedCode = CodeForPatterns[i].second;
3213 mightNotMatch = false;
3215 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3216 if (GeneratedCode[j].first) { // predicate.
3217 mightNotMatch = true;
3222 // If this pattern definitely matches, and if it isn't the last one, the
3223 // patterns after it CANNOT ever match. Error out.
3224 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3225 std::cerr << "Pattern '";
3226 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3227 std::cerr << "' is impossible to select!\n";
3232 // Print all declarations.
3233 for (std::set<std::pair<bool, std::string> >::iterator
3234 I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
3236 OS << " SDNode *" << I->second << ";\n";
3238 OS << " SDOperand " << I->second << "(0, 0);\n";
3240 // Loop through and reverse all of the CodeList vectors, as we will be
3241 // accessing them from their logical front, but accessing the end of a
3242 // vector is more efficient.
3243 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3244 CodeList &GeneratedCode = CodeForPatterns[i].second;
3245 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3248 // Next, reverse the list of patterns itself for the same reason.
3249 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3251 // Emit all of the patterns now, grouped together to share code.
3252 EmitPatterns(CodeForPatterns, 2, OS);
3254 // If the last pattern has predicates (which could fail) emit code to catch
3255 // the case where nothing handles a pattern.
3256 if (mightNotMatch) {
3257 OS << " std::cerr << \"Cannot yet select: \";\n";
3258 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3259 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3260 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3261 OS << " N.Val->dump(CurDAG);\n";
3263 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3264 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3265 << " std::cerr << \"intrinsic %\"<< "
3266 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3268 OS << " std::cerr << '\\n';\n"
3274 // Emit boilerplate.
3275 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3276 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3277 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3278 << " // Select the flag operand.\n"
3279 << " if (Ops.back().getValueType() == MVT::Flag)\n"
3280 << " Select(Ops.back(), Ops.back());\n"
3281 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3282 << " std::vector<MVT::ValueType> VTs;\n"
3283 << " VTs.push_back(MVT::Other);\n"
3284 << " VTs.push_back(MVT::Flag);\n"
3285 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3286 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3287 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3288 << " Result = New.getValue(N.ResNo);\n"
3292 OS << "// The main instruction selector code.\n"
3293 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3294 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3295 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3296 << "INSTRUCTION_LIST_END)) {\n"
3298 << " return; // Already selected.\n"
3300 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3301 << " if (CGMI != CodeGenMap.end()) {\n"
3302 << " Result = CGMI->second;\n"
3305 << " switch (N.getOpcode()) {\n"
3306 << " default: break;\n"
3307 << " case ISD::EntryToken: // These leaves remain the same.\n"
3308 << " case ISD::BasicBlock:\n"
3309 << " case ISD::Register:\n"
3310 << " case ISD::HANDLENODE:\n"
3311 << " case ISD::TargetConstant:\n"
3312 << " case ISD::TargetConstantPool:\n"
3313 << " case ISD::TargetFrameIndex:\n"
3314 << " case ISD::TargetJumpTable:\n"
3315 << " case ISD::TargetGlobalAddress: {\n"
3319 << " case ISD::AssertSext:\n"
3320 << " case ISD::AssertZext: {\n"
3321 << " SDOperand Tmp0;\n"
3322 << " Select(Tmp0, N.getOperand(0));\n"
3323 << " if (!N.Val->hasOneUse())\n"
3324 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3325 << "Tmp0.Val, Tmp0.ResNo);\n"
3326 << " Result = Tmp0;\n"
3329 << " case ISD::TokenFactor:\n"
3330 << " if (N.getNumOperands() == 2) {\n"
3331 << " SDOperand Op0, Op1;\n"
3332 << " Select(Op0, N.getOperand(0));\n"
3333 << " Select(Op1, N.getOperand(1));\n"
3335 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3336 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3337 << "Result.Val, Result.ResNo);\n"
3339 << " std::vector<SDOperand> Ops;\n"
3340 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3341 << " SDOperand Val;\n"
3342 << " Select(Val, N.getOperand(i));\n"
3343 << " Ops.push_back(Val);\n"
3346 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3347 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3348 << "Result.Val, Result.ResNo);\n"
3351 << " case ISD::CopyFromReg: {\n"
3352 << " SDOperand Chain;\n"
3353 << " Select(Chain, N.getOperand(0));\n"
3354 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3355 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
3356 << " if (N.Val->getNumValues() == 2) {\n"
3357 << " if (Chain == N.getOperand(0)) {\n"
3358 << " Result = N; // No change\n"
3361 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3362 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3364 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3366 << " Result = New.getValue(N.ResNo);\n"
3369 << " SDOperand Flag;\n"
3370 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3371 << " if (Chain == N.getOperand(0) &&\n"
3372 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3373 << " Result = N; // No change\n"
3376 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3377 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3379 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3381 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3383 << " Result = New.getValue(N.ResNo);\n"
3387 << " case ISD::CopyToReg: {\n"
3388 << " SDOperand Chain;\n"
3389 << " Select(Chain, N.getOperand(0));\n"
3390 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3391 << " SDOperand Val;\n"
3392 << " Select(Val, N.getOperand(2));\n"
3394 << " if (N.Val->getNumValues() == 1) {\n"
3395 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3396 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3397 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3398 << "Result.Val, 0);\n"
3400 << " SDOperand Flag(0, 0);\n"
3401 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3402 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3403 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3404 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3405 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3406 << "Result.Val, 0);\n"
3407 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3408 << "Result.Val, 1);\n"
3409 << " Result = Result.getValue(N.ResNo);\n"
3413 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
3416 // Loop over all of the case statements, emiting a call to each method we
3418 for (std::map<Record*, std::vector<PatternToMatch*>,
3419 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3420 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3421 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3422 OS << " case " << OpcodeInfo.getEnumName() << ": "
3423 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3424 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3427 OS << " } // end of big switch.\n\n"
3428 << " std::cerr << \"Cannot yet select: \";\n"
3429 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3430 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3431 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3432 << " N.Val->dump(CurDAG);\n"
3434 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3435 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3436 << " std::cerr << \"intrinsic %\"<< "
3437 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3439 << " std::cerr << '\\n';\n"
3444 void DAGISelEmitter::run(std::ostream &OS) {
3445 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3448 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3449 << "// *** instruction selector class. These functions are really "
3452 OS << "// Instance var to keep track of multiply used nodes that have \n"
3453 << "// already been selected.\n"
3454 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3456 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3457 << "// and their place handle nodes.\n";
3458 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3459 OS << "// Instance var to keep track of mapping of place handle nodes\n"
3460 << "// and their replacement nodes.\n";
3461 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3462 OS << "// Keep track of nodes that are currently being selecte and therefore\n"
3463 << "// should not be folded.\n";
3464 OS << "std::set<SDNode*> InFlightSet;\n";
3467 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3468 << "std::set<SDNode *> &Visited) {\n";
3469 OS << " if (found || !Visited.insert(Use).second) return;\n";
3470 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3471 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3472 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3473 OS << " if (N != Def) {\n";
3474 OS << " findNonImmUse(N, Def, found, Visited);\n";
3475 OS << " } else {\n";
3476 OS << " found = true;\n";
3484 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3485 OS << " std::set<SDNode *> Visited;\n";
3486 OS << " bool found = false;\n";
3487 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3488 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3489 OS << " if (N != Def) {\n";
3490 OS << " findNonImmUse(N, Def, found, Visited);\n";
3491 OS << " if (found) break;\n";
3494 OS << " return found;\n";
3498 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3499 << "// handle node in ReplaceMap.\n";
3500 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3501 << "unsigned RNum) {\n";
3502 OS << " SDOperand N(H, HNum);\n";
3503 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3504 OS << " if (HMI != HandleMap.end()) {\n";
3505 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3506 OS << " HandleMap.erase(N);\n";
3511 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3512 OS << "// handles.Some handles do not yet have replacements because the\n";
3513 OS << "// nodes they replacements have only dead readers.\n";
3514 OS << "void SelectDanglingHandles() {\n";
3515 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3516 << "HandleMap.begin(),\n"
3517 << " E = HandleMap.end(); I != E; ++I) {\n";
3518 OS << " SDOperand N = I->first;\n";
3519 OS << " SDOperand R;\n";
3520 OS << " Select(R, N.getValue(0));\n";
3521 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3525 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3526 OS << "// specific nodes.\n";
3527 OS << "void ReplaceHandles() {\n";
3528 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3529 << "ReplaceMap.begin(),\n"
3530 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3531 OS << " SDOperand From = I->first;\n";
3532 OS << " SDOperand To = I->second;\n";
3533 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3534 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3535 OS << " SDNode *Use = *UI;\n";
3536 OS << " std::vector<SDOperand> Ops;\n";
3537 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3538 OS << " SDOperand O = Use->getOperand(i);\n";
3539 OS << " if (O.Val == From.Val)\n";
3540 OS << " Ops.push_back(To);\n";
3542 OS << " Ops.push_back(O);\n";
3544 OS << " SDOperand U = SDOperand(Use, 0);\n";
3545 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3551 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3552 OS << "// if the folding were to happen. This is called when, for example,\n";
3553 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3554 OS << "// then the resulting node's input chain would be the load's input\n";
3555 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3556 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3557 OS << "// with the other operands along with the input chain of the load.\n";
3558 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3559 << "SDNode *Chain, SDNode* &OldTF) {\n";
3560 OS << " OldTF = NULL;\n";
3561 OS << " if (N == Chain) {\n";
3562 OS << " return N->getOperand(0);\n";
3563 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3564 OS << " N->isOperand(Chain)) {\n";
3565 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3566 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3567 << "CodeGenMap.find(Ch);\n";
3568 OS << " if (CGMI != CodeGenMap.end())\n";
3569 OS << " return SDOperand(0, 0);\n";
3570 OS << " OldTF = Chain;\n";
3571 OS << " std::vector<SDOperand> Ops;\n";
3572 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3573 OS << " SDOperand Op = Chain->getOperand(i);\n";
3574 OS << " if (Op.Val == N)\n";
3575 OS << " Ops.push_back(N->getOperand(0));\n";
3577 OS << " Ops.push_back(Op);\n";
3579 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3581 OS << " return SDOperand(0, 0);\n";
3585 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3586 OS << "SDOperand SelectRoot(SDOperand N) {\n";
3587 OS << " SDOperand ResNode;\n";
3588 OS << " Select(ResNode, N);\n";
3589 OS << " SelectDanglingHandles();\n";
3590 OS << " ReplaceHandles();\n";
3591 OS << " ReplaceMap.clear();\n";
3592 OS << " return ResNode;\n";
3595 Intrinsics = LoadIntrinsics(Records);
3597 ParseNodeTransforms(OS);
3598 ParseComplexPatterns();
3599 ParsePatternFragments(OS);
3600 ParseInstructions();
3603 // Generate variants. For example, commutative patterns can match
3604 // multiple ways. Add them to PatternsToMatch as well.
3608 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3609 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3610 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3611 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
3615 // At this point, we have full information about the 'Patterns' we need to
3616 // parse, both implicitly from instructions as well as from explicit pattern
3617 // definitions. Emit the resultant instruction selector.
3618 EmitInstructionSelector(OS);
3620 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3621 E = PatternFragments.end(); I != E; ++I)
3623 PatternFragments.clear();
3625 Instructions.clear();