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"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Streams.h"
24 //===----------------------------------------------------------------------===//
25 // Helpers for working with extended types.
27 /// FilterVTs - Filter a list of VT's according to a predicate.
30 static std::vector<MVT::ValueType>
31 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
32 std::vector<MVT::ValueType> Result;
33 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
35 Result.push_back(InVTs[i]);
40 static std::vector<unsigned char>
41 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44 if (Filter((MVT::ValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
49 static std::vector<unsigned char>
50 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
51 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
57 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
58 const std::vector<unsigned char> &RHS) {
59 if (LHS.size() > RHS.size()) return false;
60 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
61 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
66 /// isExtIntegerVT - Return true if the specified extended value type vector
67 /// contains isInt or an integer value type.
68 static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
69 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
70 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
73 /// isExtFloatingPointVT - Return true if the specified extended value type
74 /// vector contains isFP or a FP value type.
75 static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
76 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
77 return EVTs[0] == MVT::isFP ||
78 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
81 //===----------------------------------------------------------------------===//
82 // SDTypeConstraint implementation
85 SDTypeConstraint::SDTypeConstraint(Record *R) {
86 OperandNo = R->getValueAsInt("OperandNum");
88 if (R->isSubClassOf("SDTCisVT")) {
89 ConstraintType = SDTCisVT;
90 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
91 } else if (R->isSubClassOf("SDTCisPtrTy")) {
92 ConstraintType = SDTCisPtrTy;
93 } else if (R->isSubClassOf("SDTCisInt")) {
94 ConstraintType = SDTCisInt;
95 } else if (R->isSubClassOf("SDTCisFP")) {
96 ConstraintType = SDTCisFP;
97 } else if (R->isSubClassOf("SDTCisSameAs")) {
98 ConstraintType = SDTCisSameAs;
99 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
100 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
101 ConstraintType = SDTCisVTSmallerThanOp;
102 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
103 R->getValueAsInt("OtherOperandNum");
104 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
105 ConstraintType = SDTCisOpSmallerThanOp;
106 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
107 R->getValueAsInt("BigOperandNum");
108 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
109 ConstraintType = SDTCisIntVectorOfSameSize;
110 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
111 R->getValueAsInt("OtherOpNum");
113 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
118 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
119 /// N, which has NumResults results.
120 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
122 unsigned NumResults) const {
123 assert(NumResults <= 1 &&
124 "We only work with nodes with zero or one result so far!");
126 if (OpNo >= (NumResults + N->getNumChildren())) {
127 cerr << "Invalid operand number " << OpNo << " ";
133 if (OpNo < NumResults)
134 return N; // FIXME: need value #
136 return N->getChild(OpNo-NumResults);
139 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
140 /// constraint to the nodes operands. This returns true if it makes a
141 /// change, false otherwise. If a type contradiction is found, throw an
143 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
144 const SDNodeInfo &NodeInfo,
145 TreePattern &TP) const {
146 unsigned NumResults = NodeInfo.getNumResults();
147 assert(NumResults <= 1 &&
148 "We only work with nodes with zero or one result so far!");
150 // Check that the number of operands is sane. Negative operands -> varargs.
151 if (NodeInfo.getNumOperands() >= 0) {
152 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
153 TP.error(N->getOperator()->getName() + " node requires exactly " +
154 itostr(NodeInfo.getNumOperands()) + " operands!");
157 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
159 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
161 switch (ConstraintType) {
162 default: assert(0 && "Unknown constraint type!");
164 // Operand must be a particular type.
165 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
167 // Operand must be same as target pointer type.
168 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
171 // If there is only one integer type supported, this must be it.
172 std::vector<MVT::ValueType> IntVTs =
173 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
175 // If we found exactly one supported integer type, apply it.
176 if (IntVTs.size() == 1)
177 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
178 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
181 // If there is only one FP type supported, this must be it.
182 std::vector<MVT::ValueType> FPVTs =
183 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
185 // If we found exactly one supported FP type, apply it.
186 if (FPVTs.size() == 1)
187 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
188 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
191 TreePatternNode *OtherNode =
192 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
193 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
194 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
196 case SDTCisVTSmallerThanOp: {
197 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
198 // have an integer type that is smaller than the VT.
199 if (!NodeToApply->isLeaf() ||
200 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
201 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
202 ->isSubClassOf("ValueType"))
203 TP.error(N->getOperator()->getName() + " expects a VT operand!");
205 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
206 if (!MVT::isInteger(VT))
207 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
209 TreePatternNode *OtherNode =
210 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
212 // It must be integer.
213 bool MadeChange = false;
214 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
216 // This code only handles nodes that have one type set. Assert here so
217 // that we can change this if we ever need to deal with multiple value
218 // types at this point.
219 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
220 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
221 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
224 case SDTCisOpSmallerThanOp: {
225 TreePatternNode *BigOperand =
226 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
228 // Both operands must be integer or FP, but we don't care which.
229 bool MadeChange = false;
231 // This code does not currently handle nodes which have multiple types,
232 // where some types are integer, and some are fp. Assert that this is not
234 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
235 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
236 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
237 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
238 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
239 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
240 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
241 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
242 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
243 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
244 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
245 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
246 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
248 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
250 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
251 VTs = FilterVTs(VTs, MVT::isInteger);
252 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
253 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
258 switch (VTs.size()) {
259 default: // Too many VT's to pick from.
260 case 0: break; // No info yet.
262 // Only one VT of this flavor. Cannot ever satisify the constraints.
263 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
265 // If we have exactly two possible types, the little operand must be the
266 // small one, the big operand should be the big one. Common with
267 // float/double for example.
268 assert(VTs[0] < VTs[1] && "Should be sorted!");
269 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
270 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
275 case SDTCisIntVectorOfSameSize: {
276 TreePatternNode *OtherOperand =
277 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
279 if (OtherOperand->hasTypeSet()) {
280 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
281 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
282 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
283 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
284 return NodeToApply->UpdateNodeType(IVT, TP);
293 //===----------------------------------------------------------------------===//
294 // SDNodeInfo implementation
296 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
297 EnumName = R->getValueAsString("Opcode");
298 SDClassName = R->getValueAsString("SDClass");
299 Record *TypeProfile = R->getValueAsDef("TypeProfile");
300 NumResults = TypeProfile->getValueAsInt("NumResults");
301 NumOperands = TypeProfile->getValueAsInt("NumOperands");
303 // Parse the properties.
305 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
306 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
307 if (PropList[i]->getName() == "SDNPCommutative") {
308 Properties |= 1 << SDNPCommutative;
309 } else if (PropList[i]->getName() == "SDNPAssociative") {
310 Properties |= 1 << SDNPAssociative;
311 } else if (PropList[i]->getName() == "SDNPHasChain") {
312 Properties |= 1 << SDNPHasChain;
313 } else if (PropList[i]->getName() == "SDNPOutFlag") {
314 Properties |= 1 << SDNPOutFlag;
315 } else if (PropList[i]->getName() == "SDNPInFlag") {
316 Properties |= 1 << SDNPInFlag;
317 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
318 Properties |= 1 << SDNPOptInFlag;
320 cerr << "Unknown SD Node property '" << PropList[i]->getName()
321 << "' on node '" << R->getName() << "'!\n";
327 // Parse the type constraints.
328 std::vector<Record*> ConstraintList =
329 TypeProfile->getValueAsListOfDefs("Constraints");
330 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
333 //===----------------------------------------------------------------------===//
334 // TreePatternNode implementation
337 TreePatternNode::~TreePatternNode() {
338 #if 0 // FIXME: implement refcounted tree nodes!
339 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
344 /// UpdateNodeType - Set the node type of N to VT if VT contains
345 /// information. If N already contains a conflicting type, then throw an
346 /// exception. This returns true if any information was updated.
348 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
350 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
352 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
354 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
359 if (getExtTypeNum(0) == MVT::iPTR) {
360 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
362 if (isExtIntegerInVTs(ExtVTs)) {
363 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
371 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
372 assert(hasTypeSet() && "should be handled above!");
373 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
374 if (getExtTypes() == FVTs)
379 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
380 //assert(hasTypeSet() && "should be handled above!");
381 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
382 if (getExtTypes() == FVTs)
389 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
390 assert(hasTypeSet() && "should be handled above!");
391 std::vector<unsigned char> FVTs =
392 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
393 if (getExtTypes() == FVTs)
399 // If we know this is an int or fp type, and we are told it is a specific one,
402 // Similarly, we should probably set the type here to the intersection of
403 // {isInt|isFP} and ExtVTs
404 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
405 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
409 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
417 TP.error("Type inference contradiction found in node!");
419 TP.error("Type inference contradiction found in node " +
420 getOperator()->getName() + "!");
422 return true; // unreachable
426 void TreePatternNode::print(std::ostream &OS) const {
428 OS << *getLeafValue();
430 OS << "(" << getOperator()->getName();
433 // FIXME: At some point we should handle printing all the value types for
434 // nodes that are multiply typed.
435 switch (getExtTypeNum(0)) {
436 case MVT::Other: OS << ":Other"; break;
437 case MVT::isInt: OS << ":isInt"; break;
438 case MVT::isFP : OS << ":isFP"; break;
439 case MVT::isUnknown: ; /*OS << ":?";*/ break;
440 case MVT::iPTR: OS << ":iPTR"; break;
442 std::string VTName = llvm::getName(getTypeNum(0));
443 // Strip off MVT:: prefix if present.
444 if (VTName.substr(0,5) == "MVT::")
445 VTName = VTName.substr(5);
452 if (getNumChildren() != 0) {
454 getChild(0)->print(OS);
455 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
457 getChild(i)->print(OS);
463 if (!PredicateFn.empty())
464 OS << "<<P:" << PredicateFn << ">>";
466 OS << "<<X:" << TransformFn->getName() << ">>";
467 if (!getName().empty())
468 OS << ":$" << getName();
471 void TreePatternNode::dump() const {
472 print(*cerr.stream());
475 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
476 /// the specified node. For this comparison, all of the state of the node
477 /// is considered, except for the assigned name. Nodes with differing names
478 /// that are otherwise identical are considered isomorphic.
479 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
480 if (N == this) return true;
481 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
482 getPredicateFn() != N->getPredicateFn() ||
483 getTransformFn() != N->getTransformFn())
487 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
488 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
489 return DI->getDef() == NDI->getDef();
490 return getLeafValue() == N->getLeafValue();
493 if (N->getOperator() != getOperator() ||
494 N->getNumChildren() != getNumChildren()) return false;
495 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
496 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
501 /// clone - Make a copy of this tree and all of its children.
503 TreePatternNode *TreePatternNode::clone() const {
504 TreePatternNode *New;
506 New = new TreePatternNode(getLeafValue());
508 std::vector<TreePatternNode*> CChildren;
509 CChildren.reserve(Children.size());
510 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
511 CChildren.push_back(getChild(i)->clone());
512 New = new TreePatternNode(getOperator(), CChildren);
514 New->setName(getName());
515 New->setTypes(getExtTypes());
516 New->setPredicateFn(getPredicateFn());
517 New->setTransformFn(getTransformFn());
521 /// SubstituteFormalArguments - Replace the formal arguments in this tree
522 /// with actual values specified by ArgMap.
523 void TreePatternNode::
524 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
525 if (isLeaf()) return;
527 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
528 TreePatternNode *Child = getChild(i);
529 if (Child->isLeaf()) {
530 Init *Val = Child->getLeafValue();
531 if (dynamic_cast<DefInit*>(Val) &&
532 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
533 // We found a use of a formal argument, replace it with its value.
534 Child = ArgMap[Child->getName()];
535 assert(Child && "Couldn't find formal argument!");
539 getChild(i)->SubstituteFormalArguments(ArgMap);
545 /// InlinePatternFragments - If this pattern refers to any pattern
546 /// fragments, inline them into place, giving us a pattern without any
547 /// PatFrag references.
548 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
549 if (isLeaf()) return this; // nothing to do.
550 Record *Op = getOperator();
552 if (!Op->isSubClassOf("PatFrag")) {
553 // Just recursively inline children nodes.
554 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
555 setChild(i, getChild(i)->InlinePatternFragments(TP));
559 // Otherwise, we found a reference to a fragment. First, look up its
560 // TreePattern record.
561 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
563 // Verify that we are passing the right number of operands.
564 if (Frag->getNumArgs() != Children.size())
565 TP.error("'" + Op->getName() + "' fragment requires " +
566 utostr(Frag->getNumArgs()) + " operands!");
568 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
570 // Resolve formal arguments to their actual value.
571 if (Frag->getNumArgs()) {
572 // Compute the map of formal to actual arguments.
573 std::map<std::string, TreePatternNode*> ArgMap;
574 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
575 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
577 FragTree->SubstituteFormalArguments(ArgMap);
580 FragTree->setName(getName());
581 FragTree->UpdateNodeType(getExtTypes(), TP);
583 // Get a new copy of this fragment to stitch into here.
584 //delete this; // FIXME: implement refcounting!
588 /// getImplicitType - Check to see if the specified record has an implicit
589 /// type which should be applied to it. This infer the type of register
590 /// references from the register file information, for example.
592 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
594 // Some common return values
595 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
596 std::vector<unsigned char> Other(1, MVT::Other);
598 // Check to see if this is a register or a register class...
599 if (R->isSubClassOf("RegisterClass")) {
602 const CodeGenRegisterClass &RC =
603 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
604 return ConvertVTs(RC.getValueTypes());
605 } else if (R->isSubClassOf("PatFrag")) {
606 // Pattern fragment types will be resolved when they are inlined.
608 } else if (R->isSubClassOf("Register")) {
611 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
612 return T.getRegisterVTs(R);
613 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
614 // Using a VTSDNode or CondCodeSDNode.
616 } else if (R->isSubClassOf("ComplexPattern")) {
619 std::vector<unsigned char>
620 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
622 } else if (R->getName() == "ptr_rc") {
623 Other[0] = MVT::iPTR;
625 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
626 R->getName() == "zero_reg") {
631 TP.error("Unknown node flavor used in pattern: " + R->getName());
635 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
636 /// this node and its children in the tree. This returns true if it makes a
637 /// change, false otherwise. If a type contradiction is found, throw an
639 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
640 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
642 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
643 // If it's a regclass or something else known, include the type.
644 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
645 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
646 // Int inits are always integers. :)
647 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
650 // At some point, it may make sense for this tree pattern to have
651 // multiple types. Assert here that it does not, so we revisit this
652 // code when appropriate.
653 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
654 MVT::ValueType VT = getTypeNum(0);
655 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
656 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
659 if (VT != MVT::iPTR) {
660 unsigned Size = MVT::getSizeInBits(VT);
661 // Make sure that the value is representable for this type.
663 int Val = (II->getValue() << (32-Size)) >> (32-Size);
664 if (Val != II->getValue())
665 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
666 "' is out of range for type '" +
667 getEnumName(getTypeNum(0)) + "'!");
677 // special handling for set, which isn't really an SDNode.
678 if (getOperator()->getName() == "set") {
679 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
680 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
681 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
683 // Types of operands must match.
684 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
685 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
686 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
688 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
689 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
690 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
692 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
693 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
694 bool MadeChange = false;
696 // Apply the result type to the node.
697 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
699 if (getNumChildren() != Int.ArgVTs.size())
700 TP.error("Intrinsic '" + Int.Name + "' expects " +
701 utostr(Int.ArgVTs.size()-1) + " operands, not " +
702 utostr(getNumChildren()-1) + " operands!");
704 // Apply type info to the intrinsic ID.
705 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
707 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
708 MVT::ValueType OpVT = Int.ArgVTs[i];
709 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
710 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
713 } else if (getOperator()->isSubClassOf("SDNode")) {
714 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
716 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
717 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
718 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
719 // Branch, etc. do not produce results and top-level forms in instr pattern
720 // must have void types.
721 if (NI.getNumResults() == 0)
722 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
724 // If this is a vector_shuffle operation, apply types to the build_vector
725 // operation. The types of the integers don't matter, but this ensures they
726 // won't get checked.
727 if (getOperator()->getName() == "vector_shuffle" &&
728 getChild(2)->getOperator()->getName() == "build_vector") {
729 TreePatternNode *BV = getChild(2);
730 const std::vector<MVT::ValueType> &LegalVTs
731 = ISE.getTargetInfo().getLegalValueTypes();
732 MVT::ValueType LegalIntVT = MVT::Other;
733 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
734 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
735 LegalIntVT = LegalVTs[i];
738 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
740 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
741 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
744 } else if (getOperator()->isSubClassOf("Instruction")) {
745 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
746 bool MadeChange = false;
747 unsigned NumResults = Inst.getNumResults();
749 assert(NumResults <= 1 &&
750 "Only supports zero or one result instrs!");
752 CodeGenInstruction &InstInfo =
753 ISE.getTargetInfo().getInstruction(getOperator()->getName());
754 // Apply the result type to the node
755 if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack.
756 MadeChange = UpdateNodeType(MVT::isVoid, TP);
758 Record *ResultNode = Inst.getResult(0);
760 if (ResultNode->getName() == "ptr_rc") {
761 std::vector<unsigned char> VT;
762 VT.push_back(MVT::iPTR);
763 MadeChange = UpdateNodeType(VT, TP);
765 assert(ResultNode->isSubClassOf("RegisterClass") &&
766 "Operands should be register classes!");
768 const CodeGenRegisterClass &RC =
769 ISE.getTargetInfo().getRegisterClass(ResultNode);
770 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
774 unsigned ChildNo = 0;
775 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
776 Record *OperandNode = Inst.getOperand(i);
778 // If the instruction expects a predicate operand, we codegen this by
779 // setting the predicate to it's "execute always" value if it has a
780 // non-empty ExecuteAlways field.
781 if (OperandNode->isSubClassOf("PredicateOperand") &&
782 !ISE.getPredicateOperand(OperandNode).AlwaysOps.empty())
785 // Verify that we didn't run out of provided operands.
786 if (ChildNo >= getNumChildren())
787 TP.error("Instruction '" + getOperator()->getName() +
788 "' expects more operands than were provided.");
791 TreePatternNode *Child = getChild(ChildNo++);
792 if (OperandNode->isSubClassOf("RegisterClass")) {
793 const CodeGenRegisterClass &RC =
794 ISE.getTargetInfo().getRegisterClass(OperandNode);
795 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
796 } else if (OperandNode->isSubClassOf("Operand")) {
797 VT = getValueType(OperandNode->getValueAsDef("Type"));
798 MadeChange |= Child->UpdateNodeType(VT, TP);
799 } else if (OperandNode->getName() == "ptr_rc") {
800 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
802 assert(0 && "Unknown operand type!");
805 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
808 if (ChildNo != getNumChildren())
809 TP.error("Instruction '" + getOperator()->getName() +
810 "' was provided too many operands!");
814 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
816 // Node transforms always take one operand.
817 if (getNumChildren() != 1)
818 TP.error("Node transform '" + getOperator()->getName() +
819 "' requires one operand!");
821 // If either the output or input of the xform does not have exact
822 // type info. We assume they must be the same. Otherwise, it is perfectly
823 // legal to transform from one type to a completely different type.
824 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
825 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
826 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
833 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
834 /// RHS of a commutative operation, not the on LHS.
835 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
836 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
838 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
844 /// canPatternMatch - If it is impossible for this pattern to match on this
845 /// target, fill in Reason and return false. Otherwise, return true. This is
846 /// used as a santity check for .td files (to prevent people from writing stuff
847 /// that can never possibly work), and to prevent the pattern permuter from
848 /// generating stuff that is useless.
849 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
850 if (isLeaf()) return true;
852 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
853 if (!getChild(i)->canPatternMatch(Reason, ISE))
856 // If this is an intrinsic, handle cases that would make it not match. For
857 // example, if an operand is required to be an immediate.
858 if (getOperator()->isSubClassOf("Intrinsic")) {
863 // If this node is a commutative operator, check that the LHS isn't an
865 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
866 if (NodeInfo.hasProperty(SDNPCommutative)) {
867 // Scan all of the operands of the node and make sure that only the last one
868 // is a constant node, unless the RHS also is.
869 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
870 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
871 if (OnlyOnRHSOfCommutative(getChild(i))) {
872 Reason="Immediate value must be on the RHS of commutative operators!";
881 //===----------------------------------------------------------------------===//
882 // TreePattern implementation
885 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
886 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
887 isInputPattern = isInput;
888 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
889 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
892 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
893 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
894 isInputPattern = isInput;
895 Trees.push_back(ParseTreePattern(Pat));
898 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
899 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
900 isInputPattern = isInput;
901 Trees.push_back(Pat);
906 void TreePattern::error(const std::string &Msg) const {
908 throw "In " + TheRecord->getName() + ": " + Msg;
911 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
912 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
913 if (!OpDef) error("Pattern has unexpected operator type!");
914 Record *Operator = OpDef->getDef();
916 if (Operator->isSubClassOf("ValueType")) {
917 // If the operator is a ValueType, then this must be "type cast" of a leaf
919 if (Dag->getNumArgs() != 1)
920 error("Type cast only takes one operand!");
922 Init *Arg = Dag->getArg(0);
923 TreePatternNode *New;
924 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
925 Record *R = DI->getDef();
926 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
927 Dag->setArg(0, new DagInit(DI,
928 std::vector<std::pair<Init*, std::string> >()));
929 return ParseTreePattern(Dag);
931 New = new TreePatternNode(DI);
932 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
933 New = ParseTreePattern(DI);
934 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
935 New = new TreePatternNode(II);
936 if (!Dag->getArgName(0).empty())
937 error("Constant int argument should not have a name!");
938 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
939 // Turn this into an IntInit.
940 Init *II = BI->convertInitializerTo(new IntRecTy());
941 if (II == 0 || !dynamic_cast<IntInit*>(II))
942 error("Bits value must be constants!");
944 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
945 if (!Dag->getArgName(0).empty())
946 error("Constant int argument should not have a name!");
949 error("Unknown leaf value for tree pattern!");
953 // Apply the type cast.
954 New->UpdateNodeType(getValueType(Operator), *this);
955 New->setName(Dag->getArgName(0));
959 // Verify that this is something that makes sense for an operator.
960 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
961 !Operator->isSubClassOf("Instruction") &&
962 !Operator->isSubClassOf("SDNodeXForm") &&
963 !Operator->isSubClassOf("Intrinsic") &&
964 Operator->getName() != "set")
965 error("Unrecognized node '" + Operator->getName() + "'!");
967 // Check to see if this is something that is illegal in an input pattern.
968 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
969 Operator->isSubClassOf("SDNodeXForm")))
970 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
972 std::vector<TreePatternNode*> Children;
974 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
975 Init *Arg = Dag->getArg(i);
976 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
977 Children.push_back(ParseTreePattern(DI));
978 if (Children.back()->getName().empty())
979 Children.back()->setName(Dag->getArgName(i));
980 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
981 Record *R = DefI->getDef();
982 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
983 // TreePatternNode if its own.
984 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
985 Dag->setArg(i, new DagInit(DefI,
986 std::vector<std::pair<Init*, std::string> >()));
987 --i; // Revisit this node...
989 TreePatternNode *Node = new TreePatternNode(DefI);
990 Node->setName(Dag->getArgName(i));
991 Children.push_back(Node);
994 if (R->getName() == "node") {
995 if (Dag->getArgName(i).empty())
996 error("'node' argument requires a name to match with operand list");
997 Args.push_back(Dag->getArgName(i));
1000 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1001 TreePatternNode *Node = new TreePatternNode(II);
1002 if (!Dag->getArgName(i).empty())
1003 error("Constant int argument should not have a name!");
1004 Children.push_back(Node);
1005 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1006 // Turn this into an IntInit.
1007 Init *II = BI->convertInitializerTo(new IntRecTy());
1008 if (II == 0 || !dynamic_cast<IntInit*>(II))
1009 error("Bits value must be constants!");
1011 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1012 if (!Dag->getArgName(i).empty())
1013 error("Constant int argument should not have a name!");
1014 Children.push_back(Node);
1019 error("Unknown leaf value for tree pattern!");
1023 // If the operator is an intrinsic, then this is just syntactic sugar for for
1024 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1025 // convert the intrinsic name to a number.
1026 if (Operator->isSubClassOf("Intrinsic")) {
1027 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
1028 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
1030 // If this intrinsic returns void, it must have side-effects and thus a
1032 if (Int.ArgVTs[0] == MVT::isVoid) {
1033 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
1034 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1035 // Has side-effects, requires chain.
1036 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
1038 // Otherwise, no chain.
1039 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1042 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1043 Children.insert(Children.begin(), IIDNode);
1046 return new TreePatternNode(Operator, Children);
1049 /// InferAllTypes - Infer/propagate as many types throughout the expression
1050 /// patterns as possible. Return true if all types are infered, false
1051 /// otherwise. Throw an exception if a type contradiction is found.
1052 bool TreePattern::InferAllTypes() {
1053 bool MadeChange = true;
1054 while (MadeChange) {
1056 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1057 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1060 bool HasUnresolvedTypes = false;
1061 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1062 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1063 return !HasUnresolvedTypes;
1066 void TreePattern::print(std::ostream &OS) const {
1067 OS << getRecord()->getName();
1068 if (!Args.empty()) {
1069 OS << "(" << Args[0];
1070 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1071 OS << ", " << Args[i];
1076 if (Trees.size() > 1)
1078 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1080 Trees[i]->print(OS);
1084 if (Trees.size() > 1)
1088 void TreePattern::dump() const { print(*cerr.stream()); }
1092 //===----------------------------------------------------------------------===//
1093 // DAGISelEmitter implementation
1096 // Parse all of the SDNode definitions for the target, populating SDNodes.
1097 void DAGISelEmitter::ParseNodeInfo() {
1098 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1099 while (!Nodes.empty()) {
1100 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1104 // Get the buildin intrinsic nodes.
1105 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1106 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1107 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1110 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1111 /// map, and emit them to the file as functions.
1112 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1113 OS << "\n// Node transformations.\n";
1114 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1115 while (!Xforms.empty()) {
1116 Record *XFormNode = Xforms.back();
1117 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1118 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1119 SDNodeXForms.insert(std::make_pair(XFormNode,
1120 std::make_pair(SDNode, Code)));
1122 if (!Code.empty()) {
1123 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1124 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1126 OS << "inline SDOperand Transform_" << XFormNode->getName()
1127 << "(SDNode *" << C2 << ") {\n";
1128 if (ClassName != "SDNode")
1129 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1130 OS << Code << "\n}\n";
1137 void DAGISelEmitter::ParseComplexPatterns() {
1138 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1139 while (!AMs.empty()) {
1140 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1146 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1147 /// file, building up the PatternFragments map. After we've collected them all,
1148 /// inline fragments together as necessary, so that there are no references left
1149 /// inside a pattern fragment to a pattern fragment.
1151 /// This also emits all of the predicate functions to the output file.
1153 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1154 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1156 // First step, parse all of the fragments and emit predicate functions.
1157 OS << "\n// Predicate functions.\n";
1158 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1159 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1160 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1161 PatternFragments[Fragments[i]] = P;
1163 // Validate the argument list, converting it to map, to discard duplicates.
1164 std::vector<std::string> &Args = P->getArgList();
1165 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1167 if (OperandsMap.count(""))
1168 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1170 // Parse the operands list.
1171 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1172 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1173 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1174 P->error("Operands list should start with '(ops ... '!");
1176 // Copy over the arguments.
1178 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1179 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1180 static_cast<DefInit*>(OpsList->getArg(j))->
1181 getDef()->getName() != "node")
1182 P->error("Operands list should all be 'node' values.");
1183 if (OpsList->getArgName(j).empty())
1184 P->error("Operands list should have names for each operand!");
1185 if (!OperandsMap.count(OpsList->getArgName(j)))
1186 P->error("'" + OpsList->getArgName(j) +
1187 "' does not occur in pattern or was multiply specified!");
1188 OperandsMap.erase(OpsList->getArgName(j));
1189 Args.push_back(OpsList->getArgName(j));
1192 if (!OperandsMap.empty())
1193 P->error("Operands list does not contain an entry for operand '" +
1194 *OperandsMap.begin() + "'!");
1196 // If there is a code init for this fragment, emit the predicate code and
1197 // keep track of the fact that this fragment uses it.
1198 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1199 if (!Code.empty()) {
1200 if (P->getOnlyTree()->isLeaf())
1201 OS << "inline bool Predicate_" << Fragments[i]->getName()
1202 << "(SDNode *N) {\n";
1204 std::string ClassName =
1205 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1206 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1208 OS << "inline bool Predicate_" << Fragments[i]->getName()
1209 << "(SDNode *" << C2 << ") {\n";
1210 if (ClassName != "SDNode")
1211 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1213 OS << Code << "\n}\n";
1214 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1217 // If there is a node transformation corresponding to this, keep track of
1219 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1220 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1221 P->getOnlyTree()->setTransformFn(Transform);
1226 // Now that we've parsed all of the tree fragments, do a closure on them so
1227 // that there are not references to PatFrags left inside of them.
1228 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1229 E = PatternFragments.end(); I != E; ++I) {
1230 TreePattern *ThePat = I->second;
1231 ThePat->InlinePatternFragments();
1233 // Infer as many types as possible. Don't worry about it if we don't infer
1234 // all of them, some may depend on the inputs of the pattern.
1236 ThePat->InferAllTypes();
1238 // If this pattern fragment is not supported by this target (no types can
1239 // satisfy its constraints), just ignore it. If the bogus pattern is
1240 // actually used by instructions, the type consistency error will be
1244 // If debugging, print out the pattern fragment result.
1245 DEBUG(ThePat->dump());
1249 void DAGISelEmitter::ParsePredicateOperands() {
1250 std::vector<Record*> PredOps =
1251 Records.getAllDerivedDefinitions("PredicateOperand");
1253 // Find some SDNode.
1254 assert(!SDNodes.empty() && "No SDNodes parsed?");
1255 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1257 for (unsigned i = 0, e = PredOps.size(); i != e; ++i) {
1258 DagInit *AlwaysInfo = PredOps[i]->getValueAsDag("ExecuteAlways");
1260 // Clone the AlwaysInfo dag node, changing the operator from 'ops' to
1261 // SomeSDnode so that we can parse this.
1262 std::vector<std::pair<Init*, std::string> > Ops;
1263 for (unsigned op = 0, e = AlwaysInfo->getNumArgs(); op != e; ++op)
1264 Ops.push_back(std::make_pair(AlwaysInfo->getArg(op),
1265 AlwaysInfo->getArgName(op)));
1266 DagInit *DI = new DagInit(SomeSDNode, Ops);
1268 // Create a TreePattern to parse this.
1269 TreePattern P(PredOps[i], DI, false, *this);
1270 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1272 // Copy the operands over into a DAGPredicateOperand.
1273 DAGPredicateOperand PredOpInfo;
1275 TreePatternNode *T = P.getTree(0);
1276 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1277 TreePatternNode *TPN = T->getChild(op);
1278 while (TPN->ApplyTypeConstraints(P, false))
1279 /* Resolve all types */;
1281 if (TPN->ContainsUnresolvedType())
1282 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1283 PredOps[i]->getName() + "' doesn't have a concrete type!";
1285 PredOpInfo.AlwaysOps.push_back(TPN);
1288 // Insert it into the PredicateOperands map so we can find it later.
1289 PredicateOperands[PredOps[i]] = PredOpInfo;
1293 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1294 /// instruction input. Return true if this is a real use.
1295 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1296 std::map<std::string, TreePatternNode*> &InstInputs,
1297 std::vector<Record*> &InstImpInputs) {
1298 // No name -> not interesting.
1299 if (Pat->getName().empty()) {
1300 if (Pat->isLeaf()) {
1301 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1302 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1303 I->error("Input " + DI->getDef()->getName() + " must be named!");
1304 else if (DI && DI->getDef()->isSubClassOf("Register"))
1305 InstImpInputs.push_back(DI->getDef());
1311 if (Pat->isLeaf()) {
1312 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1313 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1316 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1317 Rec = Pat->getOperator();
1320 // SRCVALUE nodes are ignored.
1321 if (Rec->getName() == "srcvalue")
1324 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1329 if (Slot->isLeaf()) {
1330 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1332 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1333 SlotRec = Slot->getOperator();
1336 // Ensure that the inputs agree if we've already seen this input.
1338 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1339 if (Slot->getExtTypes() != Pat->getExtTypes())
1340 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1345 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1346 /// part of "I", the instruction), computing the set of inputs and outputs of
1347 /// the pattern. Report errors if we see anything naughty.
1348 void DAGISelEmitter::
1349 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1350 std::map<std::string, TreePatternNode*> &InstInputs,
1351 std::map<std::string, TreePatternNode*>&InstResults,
1352 std::vector<Record*> &InstImpInputs,
1353 std::vector<Record*> &InstImpResults) {
1354 if (Pat->isLeaf()) {
1355 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1356 if (!isUse && Pat->getTransformFn())
1357 I->error("Cannot specify a transform function for a non-input value!");
1359 } else if (Pat->getOperator()->getName() != "set") {
1360 // If this is not a set, verify that the children nodes are not void typed,
1362 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1363 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1364 I->error("Cannot have void nodes inside of patterns!");
1365 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1366 InstImpInputs, InstImpResults);
1369 // If this is a non-leaf node with no children, treat it basically as if
1370 // it were a leaf. This handles nodes like (imm).
1372 if (Pat->getNumChildren() == 0)
1373 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1375 if (!isUse && Pat->getTransformFn())
1376 I->error("Cannot specify a transform function for a non-input value!");
1380 // Otherwise, this is a set, validate and collect instruction results.
1381 if (Pat->getNumChildren() == 0)
1382 I->error("set requires operands!");
1383 else if (Pat->getNumChildren() & 1)
1384 I->error("set requires an even number of operands");
1386 if (Pat->getTransformFn())
1387 I->error("Cannot specify a transform function on a set node!");
1389 // Check the set destinations.
1390 unsigned NumValues = Pat->getNumChildren()/2;
1391 for (unsigned i = 0; i != NumValues; ++i) {
1392 TreePatternNode *Dest = Pat->getChild(i);
1393 if (!Dest->isLeaf())
1394 I->error("set destination should be a register!");
1396 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1398 I->error("set destination should be a register!");
1400 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1401 Val->getDef()->getName() == "ptr_rc") {
1402 if (Dest->getName().empty())
1403 I->error("set destination must have a name!");
1404 if (InstResults.count(Dest->getName()))
1405 I->error("cannot set '" + Dest->getName() +"' multiple times");
1406 InstResults[Dest->getName()] = Dest;
1407 } else if (Val->getDef()->isSubClassOf("Register")) {
1408 InstImpResults.push_back(Val->getDef());
1410 I->error("set destination should be a register!");
1413 // Verify and collect info from the computation.
1414 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1415 InstInputs, InstResults,
1416 InstImpInputs, InstImpResults);
1420 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1421 /// any fragments involved. This populates the Instructions list with fully
1422 /// resolved instructions.
1423 void DAGISelEmitter::ParseInstructions() {
1424 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1426 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1429 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1430 LI = Instrs[i]->getValueAsListInit("Pattern");
1432 // If there is no pattern, only collect minimal information about the
1433 // instruction for its operand list. We have to assume that there is one
1434 // result, as we have no detailed info.
1435 if (!LI || LI->getSize() == 0) {
1436 std::vector<Record*> Results;
1437 std::vector<Record*> Operands;
1439 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1441 if (InstInfo.OperandList.size() != 0) {
1442 // FIXME: temporary hack...
1443 if (InstInfo.noResults) {
1444 // These produce no results
1445 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1446 Operands.push_back(InstInfo.OperandList[j].Rec);
1448 // Assume the first operand is the result.
1449 Results.push_back(InstInfo.OperandList[0].Rec);
1451 // The rest are inputs.
1452 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1453 Operands.push_back(InstInfo.OperandList[j].Rec);
1457 // Create and insert the instruction.
1458 std::vector<Record*> ImpResults;
1459 std::vector<Record*> ImpOperands;
1460 Instructions.insert(std::make_pair(Instrs[i],
1461 DAGInstruction(0, Results, Operands, ImpResults,
1463 continue; // no pattern.
1466 // Parse the instruction.
1467 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1468 // Inline pattern fragments into it.
1469 I->InlinePatternFragments();
1471 // Infer as many types as possible. If we cannot infer all of them, we can
1472 // never do anything with this instruction pattern: report it to the user.
1473 if (!I->InferAllTypes())
1474 I->error("Could not infer all types in pattern!");
1476 // InstInputs - Keep track of all of the inputs of the instruction, along
1477 // with the record they are declared as.
1478 std::map<std::string, TreePatternNode*> InstInputs;
1480 // InstResults - Keep track of all the virtual registers that are 'set'
1481 // in the instruction, including what reg class they are.
1482 std::map<std::string, TreePatternNode*> InstResults;
1484 std::vector<Record*> InstImpInputs;
1485 std::vector<Record*> InstImpResults;
1487 // Verify that the top-level forms in the instruction are of void type, and
1488 // fill in the InstResults map.
1489 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1490 TreePatternNode *Pat = I->getTree(j);
1491 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1492 I->error("Top-level forms in instruction pattern should have"
1495 // Find inputs and outputs, and verify the structure of the uses/defs.
1496 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1497 InstImpInputs, InstImpResults);
1500 // Now that we have inputs and outputs of the pattern, inspect the operands
1501 // list for the instruction. This determines the order that operands are
1502 // added to the machine instruction the node corresponds to.
1503 unsigned NumResults = InstResults.size();
1505 // Parse the operands list from the (ops) list, validating it.
1506 assert(I->getArgList().empty() && "Args list should still be empty here!");
1507 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1509 // Check that all of the results occur first in the list.
1510 std::vector<Record*> Results;
1511 TreePatternNode *Res0Node = NULL;
1512 for (unsigned i = 0; i != NumResults; ++i) {
1513 if (i == CGI.OperandList.size())
1514 I->error("'" + InstResults.begin()->first +
1515 "' set but does not appear in operand list!");
1516 const std::string &OpName = CGI.OperandList[i].Name;
1518 // Check that it exists in InstResults.
1519 TreePatternNode *RNode = InstResults[OpName];
1521 I->error("Operand $" + OpName + " does not exist in operand list!");
1525 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1527 I->error("Operand $" + OpName + " should be a set destination: all "
1528 "outputs must occur before inputs in operand list!");
1530 if (CGI.OperandList[i].Rec != R)
1531 I->error("Operand $" + OpName + " class mismatch!");
1533 // Remember the return type.
1534 Results.push_back(CGI.OperandList[i].Rec);
1536 // Okay, this one checks out.
1537 InstResults.erase(OpName);
1540 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1541 // the copy while we're checking the inputs.
1542 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1544 std::vector<TreePatternNode*> ResultNodeOperands;
1545 std::vector<Record*> Operands;
1546 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1547 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1548 const std::string &OpName = Op.Name;
1550 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1552 if (!InstInputsCheck.count(OpName)) {
1553 // If this is an predicate operand with an ExecuteAlways set filled in,
1554 // we can ignore this. When we codegen it, we will do so as always
1556 if (Op.Rec->isSubClassOf("PredicateOperand")) {
1557 // Does it have a non-empty ExecuteAlways field? If so, ignore this
1559 if (!getPredicateOperand(Op.Rec).AlwaysOps.empty())
1562 I->error("Operand $" + OpName +
1563 " does not appear in the instruction pattern");
1565 TreePatternNode *InVal = InstInputsCheck[OpName];
1566 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1568 if (InVal->isLeaf() &&
1569 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1570 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1571 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1572 I->error("Operand $" + OpName + "'s register class disagrees"
1573 " between the operand and pattern");
1575 Operands.push_back(Op.Rec);
1577 // Construct the result for the dest-pattern operand list.
1578 TreePatternNode *OpNode = InVal->clone();
1580 // No predicate is useful on the result.
1581 OpNode->setPredicateFn("");
1583 // Promote the xform function to be an explicit node if set.
1584 if (Record *Xform = OpNode->getTransformFn()) {
1585 OpNode->setTransformFn(0);
1586 std::vector<TreePatternNode*> Children;
1587 Children.push_back(OpNode);
1588 OpNode = new TreePatternNode(Xform, Children);
1591 ResultNodeOperands.push_back(OpNode);
1594 if (!InstInputsCheck.empty())
1595 I->error("Input operand $" + InstInputsCheck.begin()->first +
1596 " occurs in pattern but not in operands list!");
1598 TreePatternNode *ResultPattern =
1599 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1600 // Copy fully inferred output node type to instruction result pattern.
1602 ResultPattern->setTypes(Res0Node->getExtTypes());
1604 // Create and insert the instruction.
1605 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1606 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1608 // Use a temporary tree pattern to infer all types and make sure that the
1609 // constructed result is correct. This depends on the instruction already
1610 // being inserted into the Instructions map.
1611 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1612 Temp.InferAllTypes();
1614 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1615 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1620 // If we can, convert the instructions to be patterns that are matched!
1621 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1622 E = Instructions.end(); II != E; ++II) {
1623 DAGInstruction &TheInst = II->second;
1624 TreePattern *I = TheInst.getPattern();
1625 if (I == 0) continue; // No pattern.
1627 if (I->getNumTrees() != 1) {
1628 cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1631 TreePatternNode *Pattern = I->getTree(0);
1632 TreePatternNode *SrcPattern;
1633 if (Pattern->getOperator()->getName() == "set") {
1634 if (Pattern->getNumChildren() != 2)
1635 continue; // Not a set of a single value (not handled so far)
1637 SrcPattern = Pattern->getChild(1)->clone();
1639 // Not a set (store or something?)
1640 SrcPattern = Pattern;
1644 if (!SrcPattern->canPatternMatch(Reason, *this))
1645 I->error("Instruction can never match: " + Reason);
1647 Record *Instr = II->first;
1648 TreePatternNode *DstPattern = TheInst.getResultPattern();
1650 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1651 SrcPattern, DstPattern,
1652 Instr->getValueAsInt("AddedComplexity")));
1656 void DAGISelEmitter::ParsePatterns() {
1657 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1659 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1660 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1661 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1663 // Inline pattern fragments into it.
1664 Pattern->InlinePatternFragments();
1666 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1667 if (LI->getSize() == 0) continue; // no pattern.
1669 // Parse the instruction.
1670 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1672 // Inline pattern fragments into it.
1673 Result->InlinePatternFragments();
1675 if (Result->getNumTrees() != 1)
1676 Result->error("Cannot handle instructions producing instructions "
1677 "with temporaries yet!");
1679 bool IterateInference;
1680 bool InferredAllPatternTypes, InferredAllResultTypes;
1682 // Infer as many types as possible. If we cannot infer all of them, we
1683 // can never do anything with this pattern: report it to the user.
1684 InferredAllPatternTypes = Pattern->InferAllTypes();
1686 // Infer as many types as possible. If we cannot infer all of them, we
1687 // can never do anything with this pattern: report it to the user.
1688 InferredAllResultTypes = Result->InferAllTypes();
1690 // Apply the type of the result to the source pattern. This helps us
1691 // resolve cases where the input type is known to be a pointer type (which
1692 // is considered resolved), but the result knows it needs to be 32- or
1693 // 64-bits. Infer the other way for good measure.
1694 IterateInference = Pattern->getOnlyTree()->
1695 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1696 IterateInference |= Result->getOnlyTree()->
1697 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1698 } while (IterateInference);
1700 // Verify that we inferred enough types that we can do something with the
1701 // pattern and result. If these fire the user has to add type casts.
1702 if (!InferredAllPatternTypes)
1703 Pattern->error("Could not infer all types in pattern!");
1704 if (!InferredAllResultTypes)
1705 Result->error("Could not infer all types in pattern result!");
1707 // Validate that the input pattern is correct.
1709 std::map<std::string, TreePatternNode*> InstInputs;
1710 std::map<std::string, TreePatternNode*> InstResults;
1711 std::vector<Record*> InstImpInputs;
1712 std::vector<Record*> InstImpResults;
1713 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1714 InstInputs, InstResults,
1715 InstImpInputs, InstImpResults);
1718 // Promote the xform function to be an explicit node if set.
1719 std::vector<TreePatternNode*> ResultNodeOperands;
1720 TreePatternNode *DstPattern = Result->getOnlyTree();
1721 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1722 TreePatternNode *OpNode = DstPattern->getChild(ii);
1723 if (Record *Xform = OpNode->getTransformFn()) {
1724 OpNode->setTransformFn(0);
1725 std::vector<TreePatternNode*> Children;
1726 Children.push_back(OpNode);
1727 OpNode = new TreePatternNode(Xform, Children);
1729 ResultNodeOperands.push_back(OpNode);
1731 DstPattern = Result->getOnlyTree();
1732 if (!DstPattern->isLeaf())
1733 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1734 ResultNodeOperands);
1735 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1736 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1737 Temp.InferAllTypes();
1740 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1741 Pattern->error("Pattern can never match: " + Reason);
1744 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1745 Pattern->getOnlyTree(),
1747 Patterns[i]->getValueAsInt("AddedComplexity")));
1751 /// CombineChildVariants - Given a bunch of permutations of each child of the
1752 /// 'operator' node, put them together in all possible ways.
1753 static void CombineChildVariants(TreePatternNode *Orig,
1754 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1755 std::vector<TreePatternNode*> &OutVariants,
1756 DAGISelEmitter &ISE) {
1757 // Make sure that each operand has at least one variant to choose from.
1758 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1759 if (ChildVariants[i].empty())
1762 // The end result is an all-pairs construction of the resultant pattern.
1763 std::vector<unsigned> Idxs;
1764 Idxs.resize(ChildVariants.size());
1765 bool NotDone = true;
1767 // Create the variant and add it to the output list.
1768 std::vector<TreePatternNode*> NewChildren;
1769 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1770 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1771 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1773 // Copy over properties.
1774 R->setName(Orig->getName());
1775 R->setPredicateFn(Orig->getPredicateFn());
1776 R->setTransformFn(Orig->getTransformFn());
1777 R->setTypes(Orig->getExtTypes());
1779 // If this pattern cannot every match, do not include it as a variant.
1780 std::string ErrString;
1781 if (!R->canPatternMatch(ErrString, ISE)) {
1784 bool AlreadyExists = false;
1786 // Scan to see if this pattern has already been emitted. We can get
1787 // duplication due to things like commuting:
1788 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1789 // which are the same pattern. Ignore the dups.
1790 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1791 if (R->isIsomorphicTo(OutVariants[i])) {
1792 AlreadyExists = true;
1799 OutVariants.push_back(R);
1802 // Increment indices to the next permutation.
1804 // Look for something we can increment without causing a wrap-around.
1805 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1806 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1807 NotDone = true; // Found something to increment.
1815 /// CombineChildVariants - A helper function for binary operators.
1817 static void CombineChildVariants(TreePatternNode *Orig,
1818 const std::vector<TreePatternNode*> &LHS,
1819 const std::vector<TreePatternNode*> &RHS,
1820 std::vector<TreePatternNode*> &OutVariants,
1821 DAGISelEmitter &ISE) {
1822 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1823 ChildVariants.push_back(LHS);
1824 ChildVariants.push_back(RHS);
1825 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1829 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1830 std::vector<TreePatternNode *> &Children) {
1831 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1832 Record *Operator = N->getOperator();
1834 // Only permit raw nodes.
1835 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1836 N->getTransformFn()) {
1837 Children.push_back(N);
1841 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1842 Children.push_back(N->getChild(0));
1844 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1846 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1847 Children.push_back(N->getChild(1));
1849 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1852 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1853 /// the (potentially recursive) pattern by using algebraic laws.
1855 static void GenerateVariantsOf(TreePatternNode *N,
1856 std::vector<TreePatternNode*> &OutVariants,
1857 DAGISelEmitter &ISE) {
1858 // We cannot permute leaves.
1860 OutVariants.push_back(N);
1864 // Look up interesting info about the node.
1865 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1867 // If this node is associative, reassociate.
1868 if (NodeInfo.hasProperty(SDNPAssociative)) {
1869 // Reassociate by pulling together all of the linked operators
1870 std::vector<TreePatternNode*> MaximalChildren;
1871 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1873 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1875 if (MaximalChildren.size() == 3) {
1876 // Find the variants of all of our maximal children.
1877 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1878 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1879 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1880 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1882 // There are only two ways we can permute the tree:
1883 // (A op B) op C and A op (B op C)
1884 // Within these forms, we can also permute A/B/C.
1886 // Generate legal pair permutations of A/B/C.
1887 std::vector<TreePatternNode*> ABVariants;
1888 std::vector<TreePatternNode*> BAVariants;
1889 std::vector<TreePatternNode*> ACVariants;
1890 std::vector<TreePatternNode*> CAVariants;
1891 std::vector<TreePatternNode*> BCVariants;
1892 std::vector<TreePatternNode*> CBVariants;
1893 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1894 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1895 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1896 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1897 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1898 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1900 // Combine those into the result: (x op x) op x
1901 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1902 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1903 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1904 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1905 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1906 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1908 // Combine those into the result: x op (x op x)
1909 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1910 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1911 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1912 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1913 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1914 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1919 // Compute permutations of all children.
1920 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1921 ChildVariants.resize(N->getNumChildren());
1922 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1923 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1925 // Build all permutations based on how the children were formed.
1926 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1928 // If this node is commutative, consider the commuted order.
1929 if (NodeInfo.hasProperty(SDNPCommutative)) {
1930 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1931 // Don't count children which are actually register references.
1933 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1934 TreePatternNode *Child = N->getChild(i);
1935 if (Child->isLeaf())
1936 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1937 Record *RR = DI->getDef();
1938 if (RR->isSubClassOf("Register"))
1943 // Consider the commuted order.
1945 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1951 // GenerateVariants - Generate variants. For example, commutative patterns can
1952 // match multiple ways. Add them to PatternsToMatch as well.
1953 void DAGISelEmitter::GenerateVariants() {
1955 DOUT << "Generating instruction variants.\n";
1957 // Loop over all of the patterns we've collected, checking to see if we can
1958 // generate variants of the instruction, through the exploitation of
1959 // identities. This permits the target to provide agressive matching without
1960 // the .td file having to contain tons of variants of instructions.
1962 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1963 // intentionally do not reconsider these. Any variants of added patterns have
1964 // already been added.
1966 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1967 std::vector<TreePatternNode*> Variants;
1968 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1970 assert(!Variants.empty() && "Must create at least original variant!");
1971 Variants.erase(Variants.begin()); // Remove the original pattern.
1973 if (Variants.empty()) // No variants for this pattern.
1976 DOUT << "FOUND VARIANTS OF: ";
1977 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
1980 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1981 TreePatternNode *Variant = Variants[v];
1983 DOUT << " VAR#" << v << ": ";
1984 DEBUG(Variant->dump());
1987 // Scan to see if an instruction or explicit pattern already matches this.
1988 bool AlreadyExists = false;
1989 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1990 // Check to see if this variant already exists.
1991 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1992 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
1993 AlreadyExists = true;
1997 // If we already have it, ignore the variant.
1998 if (AlreadyExists) continue;
2000 // Otherwise, add it to the list of patterns we have.
2002 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2003 Variant, PatternsToMatch[i].getDstPattern(),
2004 PatternsToMatch[i].getAddedComplexity()));
2011 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
2013 static bool NodeIsComplexPattern(TreePatternNode *N)
2015 return (N->isLeaf() &&
2016 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2017 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2018 isSubClassOf("ComplexPattern"));
2021 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
2022 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
2023 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
2024 DAGISelEmitter &ISE)
2027 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2028 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2029 isSubClassOf("ComplexPattern")) {
2030 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
2036 /// getPatternSize - Return the 'size' of this pattern. We want to match large
2037 /// patterns before small ones. This is used to determine the size of a
2039 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2040 assert((isExtIntegerInVTs(P->getExtTypes()) ||
2041 isExtFloatingPointInVTs(P->getExtTypes()) ||
2042 P->getExtTypeNum(0) == MVT::isVoid ||
2043 P->getExtTypeNum(0) == MVT::Flag ||
2044 P->getExtTypeNum(0) == MVT::iPTR) &&
2045 "Not a valid pattern node to size!");
2046 unsigned Size = 3; // The node itself.
2047 // If the root node is a ConstantSDNode, increases its size.
2048 // e.g. (set R32:$dst, 0).
2049 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
2052 // FIXME: This is a hack to statically increase the priority of patterns
2053 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
2054 // Later we can allow complexity / cost for each pattern to be (optionally)
2055 // specified. To get best possible pattern match we'll need to dynamically
2056 // calculate the complexity of all patterns a dag can potentially map to.
2057 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
2059 Size += AM->getNumOperands() * 3;
2061 // If this node has some predicate function that must match, it adds to the
2062 // complexity of this node.
2063 if (!P->getPredicateFn().empty())
2066 // Count children in the count if they are also nodes.
2067 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
2068 TreePatternNode *Child = P->getChild(i);
2069 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
2070 Size += getPatternSize(Child, ISE);
2071 else if (Child->isLeaf()) {
2072 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
2073 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
2074 else if (NodeIsComplexPattern(Child))
2075 Size += getPatternSize(Child, ISE);
2076 else if (!Child->getPredicateFn().empty())
2084 /// getResultPatternCost - Compute the number of instructions for this pattern.
2085 /// This is a temporary hack. We should really include the instruction
2086 /// latencies in this calculation.
2087 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
2088 if (P->isLeaf()) return 0;
2091 Record *Op = P->getOperator();
2092 if (Op->isSubClassOf("Instruction")) {
2094 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
2095 if (II.usesCustomDAGSchedInserter)
2098 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2099 Cost += getResultPatternCost(P->getChild(i), ISE);
2103 /// getResultPatternCodeSize - Compute the code size of instructions for this
2105 static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2106 if (P->isLeaf()) return 0;
2109 Record *Op = P->getOperator();
2110 if (Op->isSubClassOf("Instruction")) {
2111 Cost += Op->getValueAsInt("CodeSize");
2113 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2114 Cost += getResultPatternSize(P->getChild(i), ISE);
2118 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2119 // In particular, we want to match maximal patterns first and lowest cost within
2120 // a particular complexity first.
2121 struct PatternSortingPredicate {
2122 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2123 DAGISelEmitter &ISE;
2125 bool operator()(PatternToMatch *LHS,
2126 PatternToMatch *RHS) {
2127 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2128 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
2129 LHSSize += LHS->getAddedComplexity();
2130 RHSSize += RHS->getAddedComplexity();
2131 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2132 if (LHSSize < RHSSize) return false;
2134 // If the patterns have equal complexity, compare generated instruction cost
2135 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2136 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2137 if (LHSCost < RHSCost) return true;
2138 if (LHSCost > RHSCost) return false;
2140 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2141 getResultPatternSize(RHS->getDstPattern(), ISE);
2145 /// getRegisterValueType - Look up and return the first ValueType of specified
2146 /// RegisterClass record
2147 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
2148 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2149 return RC->getValueTypeNum(0);
2154 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2155 /// type information from it.
2156 static void RemoveAllTypes(TreePatternNode *N) {
2159 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2160 RemoveAllTypes(N->getChild(i));
2163 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2164 Record *N = Records.getDef(Name);
2165 if (!N || !N->isSubClassOf("SDNode")) {
2166 cerr << "Error getting SDNode '" << Name << "'!\n";
2172 /// NodeHasProperty - return true if TreePatternNode has the specified
2174 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
2175 DAGISelEmitter &ISE)
2178 const ComplexPattern *CP = NodeGetComplexPattern(N, ISE);
2180 return CP->hasProperty(Property);
2183 Record *Operator = N->getOperator();
2184 if (!Operator->isSubClassOf("SDNode")) return false;
2186 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2187 return NodeInfo.hasProperty(Property);
2190 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
2191 DAGISelEmitter &ISE)
2193 if (NodeHasProperty(N, Property, ISE))
2196 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2197 TreePatternNode *Child = N->getChild(i);
2198 if (PatternHasProperty(Child, Property, ISE))
2205 class PatternCodeEmitter {
2207 DAGISelEmitter &ISE;
2210 ListInit *Predicates;
2213 // Instruction selector pattern.
2214 TreePatternNode *Pattern;
2215 // Matched instruction.
2216 TreePatternNode *Instruction;
2218 // Node to name mapping
2219 std::map<std::string, std::string> VariableMap;
2220 // Node to operator mapping
2221 std::map<std::string, Record*> OperatorMap;
2222 // Names of all the folded nodes which produce chains.
2223 std::vector<std::pair<std::string, unsigned> > FoldedChains;
2224 // Original input chain(s).
2225 std::vector<std::pair<std::string, std::string> > OrigChains;
2226 std::set<std::string> Duplicates;
2228 /// GeneratedCode - This is the buffer that we emit code to. The first int
2229 /// indicates whether this is an exit predicate (something that should be
2230 /// tested, and if true, the match fails) [when 1], or normal code to emit
2231 /// [when 0], or initialization code to emit [when 2].
2232 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
2233 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2234 /// the set of patterns for each top-level opcode.
2235 std::set<std::string> &GeneratedDecl;
2236 /// TargetOpcodes - The target specific opcodes used by the resulting
2238 std::vector<std::string> &TargetOpcodes;
2239 std::vector<std::string> &TargetVTs;
2241 std::string ChainName;
2246 void emitCheck(const std::string &S) {
2248 GeneratedCode.push_back(std::make_pair(1, S));
2250 void emitCode(const std::string &S) {
2252 GeneratedCode.push_back(std::make_pair(0, S));
2254 void emitInit(const std::string &S) {
2256 GeneratedCode.push_back(std::make_pair(2, S));
2258 void emitDecl(const std::string &S) {
2259 assert(!S.empty() && "Invalid declaration");
2260 GeneratedDecl.insert(S);
2262 void emitOpcode(const std::string &Opc) {
2263 TargetOpcodes.push_back(Opc);
2266 void emitVT(const std::string &VT) {
2267 TargetVTs.push_back(VT);
2271 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2272 TreePatternNode *pattern, TreePatternNode *instr,
2273 std::vector<std::pair<unsigned, std::string> > &gc,
2274 std::set<std::string> &gd,
2275 std::vector<std::string> &to,
2276 std::vector<std::string> &tv)
2277 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2278 GeneratedCode(gc), GeneratedDecl(gd),
2279 TargetOpcodes(to), TargetVTs(tv),
2280 TmpNo(0), OpcNo(0), VTNo(0) {}
2282 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2283 /// if the match fails. At this point, we already know that the opcode for N
2284 /// matches, and the SDNode for the result has the RootName specified name.
2285 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2286 const std::string &RootName, const std::string &ChainSuffix,
2288 bool isRoot = (P == NULL);
2289 // Emit instruction predicates. Each predicate is just a string for now.
2291 std::string PredicateCheck;
2292 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2293 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2294 Record *Def = Pred->getDef();
2295 if (!Def->isSubClassOf("Predicate")) {
2299 assert(0 && "Unknown predicate type!");
2301 if (!PredicateCheck.empty())
2302 PredicateCheck += " && ";
2303 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2307 emitCheck(PredicateCheck);
2311 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2312 emitCheck("cast<ConstantSDNode>(" + RootName +
2313 ")->getSignExtended() == " + itostr(II->getValue()));
2315 } else if (!NodeIsComplexPattern(N)) {
2316 assert(0 && "Cannot match this as a leaf value!");
2321 // If this node has a name associated with it, capture it in VariableMap. If
2322 // we already saw this in the pattern, emit code to verify dagness.
2323 if (!N->getName().empty()) {
2324 std::string &VarMapEntry = VariableMap[N->getName()];
2325 if (VarMapEntry.empty()) {
2326 VarMapEntry = RootName;
2328 // If we get here, this is a second reference to a specific name. Since
2329 // we already have checked that the first reference is valid, we don't
2330 // have to recursively match it, just check that it's the same as the
2331 // previously named thing.
2332 emitCheck(VarMapEntry + " == " + RootName);
2337 OperatorMap[N->getName()] = N->getOperator();
2341 // Emit code to load the child nodes and match their contents recursively.
2343 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, ISE);
2344 bool HasChain = PatternHasProperty(N, SDNPHasChain, ISE);
2345 bool EmittedUseCheck = false;
2350 // Multiple uses of actual result?
2351 emitCheck(RootName + ".hasOneUse()");
2352 EmittedUseCheck = true;
2354 // If the immediate use can somehow reach this node through another
2355 // path, then can't fold it either or it will create a cycle.
2356 // e.g. In the following diagram, XX can reach ld through YY. If
2357 // ld is folded into XX, then YY is both a predecessor and a successor
2367 bool NeedCheck = false;
2371 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2373 P->getOperator() == ISE.get_intrinsic_void_sdnode() ||
2374 P->getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
2375 P->getOperator() == ISE.get_intrinsic_wo_chain_sdnode() ||
2376 PInfo.getNumOperands() > 1 ||
2377 PInfo.hasProperty(SDNPHasChain) ||
2378 PInfo.hasProperty(SDNPInFlag) ||
2379 PInfo.hasProperty(SDNPOptInFlag);
2383 std::string ParentName(RootName.begin(), RootName.end()-1);
2384 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
2392 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
2393 "IsChainCompatible(" + ChainName + ".Val, " +
2394 RootName + ".Val))");
2395 OrigChains.push_back(std::make_pair(ChainName, RootName));
2398 ChainName = "Chain" + ChainSuffix;
2399 emitInit("SDOperand " + ChainName + " = " + RootName +
2404 // Don't fold any node which reads or writes a flag and has multiple uses.
2405 // FIXME: We really need to separate the concepts of flag and "glue". Those
2406 // real flag results, e.g. X86CMP output, can have multiple uses.
2407 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2410 (PatternHasProperty(N, SDNPInFlag, ISE) ||
2411 PatternHasProperty(N, SDNPOptInFlag, ISE) ||
2412 PatternHasProperty(N, SDNPOutFlag, ISE))) {
2413 if (!EmittedUseCheck) {
2414 // Multiple uses of actual result?
2415 emitCheck(RootName + ".hasOneUse()");
2419 // If there is a node predicate for this, emit the call.
2420 if (!N->getPredicateFn().empty())
2421 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2424 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
2425 // a constant without a predicate fn that has more that one bit set, handle
2426 // this as a special case. This is usually for targets that have special
2427 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
2428 // handling stuff). Using these instructions is often far more efficient
2429 // than materializing the constant. Unfortunately, both the instcombiner
2430 // and the dag combiner can often infer that bits are dead, and thus drop
2431 // them from the mask in the dag. For example, it might turn 'AND X, 255'
2432 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
2435 (N->getOperator()->getName() == "and" ||
2436 N->getOperator()->getName() == "or") &&
2437 N->getChild(1)->isLeaf() &&
2438 N->getChild(1)->getPredicateFn().empty()) {
2439 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
2440 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
2441 emitInit("SDOperand " + RootName + "0" + " = " +
2442 RootName + ".getOperand(" + utostr(0) + ");");
2443 emitInit("SDOperand " + RootName + "1" + " = " +
2444 RootName + ".getOperand(" + utostr(1) + ");");
2446 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
2447 const char *MaskPredicate = N->getOperator()->getName() == "or"
2448 ? "CheckOrMask(" : "CheckAndMask(";
2449 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
2450 RootName + "1), " + itostr(II->getValue()) + ")");
2452 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
2453 ChainSuffix + utostr(0), FoundChain);
2459 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2460 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
2461 RootName + ".getOperand(" +utostr(OpNo) + ");");
2463 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
2464 ChainSuffix + utostr(OpNo), FoundChain);
2467 // Handle cases when root is a complex pattern.
2468 const ComplexPattern *CP;
2469 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2470 std::string Fn = CP->getSelectFunc();
2471 unsigned NumOps = CP->getNumOperands();
2472 for (unsigned i = 0; i < NumOps; ++i) {
2473 emitDecl("CPTmp" + utostr(i));
2474 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2476 if (CP->hasProperty(SDNPHasChain)) {
2477 emitDecl("CPInChain");
2478 emitDecl("Chain" + ChainSuffix);
2479 emitCode("SDOperand CPInChain;");
2480 emitCode("SDOperand Chain" + ChainSuffix + ";");
2483 std::string Code = Fn + "(" + RootName + ", " + RootName;
2484 for (unsigned i = 0; i < NumOps; i++)
2485 Code += ", CPTmp" + utostr(i);
2486 if (CP->hasProperty(SDNPHasChain)) {
2487 ChainName = "Chain" + ChainSuffix;
2488 Code += ", CPInChain, Chain" + ChainSuffix;
2490 emitCheck(Code + ")");
2494 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
2495 const std::string &RootName,
2496 const std::string &ChainSuffix, bool &FoundChain) {
2497 if (!Child->isLeaf()) {
2498 // If it's not a leaf, recursively match.
2499 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2500 emitCheck(RootName + ".getOpcode() == " +
2501 CInfo.getEnumName());
2502 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
2503 if (NodeHasProperty(Child, SDNPHasChain, ISE))
2504 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
2506 // If this child has a name associated with it, capture it in VarMap. If
2507 // we already saw this in the pattern, emit code to verify dagness.
2508 if (!Child->getName().empty()) {
2509 std::string &VarMapEntry = VariableMap[Child->getName()];
2510 if (VarMapEntry.empty()) {
2511 VarMapEntry = RootName;
2513 // If we get here, this is a second reference to a specific name.
2514 // Since we already have checked that the first reference is valid,
2515 // we don't have to recursively match it, just check that it's the
2516 // same as the previously named thing.
2517 emitCheck(VarMapEntry + " == " + RootName);
2518 Duplicates.insert(RootName);
2523 // Handle leaves of various types.
2524 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2525 Record *LeafRec = DI->getDef();
2526 if (LeafRec->isSubClassOf("RegisterClass") ||
2527 LeafRec->getName() == "ptr_rc") {
2528 // Handle register references. Nothing to do here.
2529 } else if (LeafRec->isSubClassOf("Register")) {
2530 // Handle register references.
2531 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2532 // Handle complex pattern.
2533 const ComplexPattern *CP = NodeGetComplexPattern(Child, ISE);
2534 std::string Fn = CP->getSelectFunc();
2535 unsigned NumOps = CP->getNumOperands();
2536 for (unsigned i = 0; i < NumOps; ++i) {
2537 emitDecl("CPTmp" + utostr(i));
2538 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2540 if (CP->hasProperty(SDNPHasChain)) {
2541 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(Parent->getOperator());
2542 FoldedChains.push_back(std::make_pair("CPInChain",
2543 PInfo.getNumResults()));
2544 ChainName = "Chain" + ChainSuffix;
2545 emitDecl("CPInChain");
2546 emitDecl(ChainName);
2547 emitCode("SDOperand CPInChain;");
2548 emitCode("SDOperand " + ChainName + ";");
2551 std::string Code = Fn + "(N, ";
2552 if (CP->hasProperty(SDNPHasChain)) {
2553 std::string ParentName(RootName.begin(), RootName.end()-1);
2554 Code += ParentName + ", ";
2557 for (unsigned i = 0; i < NumOps; i++)
2558 Code += ", CPTmp" + utostr(i);
2559 if (CP->hasProperty(SDNPHasChain))
2560 Code += ", CPInChain, Chain" + ChainSuffix;
2561 emitCheck(Code + ")");
2562 } else if (LeafRec->getName() == "srcvalue") {
2563 // Place holder for SRCVALUE nodes. Nothing to do here.
2564 } else if (LeafRec->isSubClassOf("ValueType")) {
2565 // Make sure this is the specified value type.
2566 emitCheck("cast<VTSDNode>(" + RootName +
2567 ")->getVT() == MVT::" + LeafRec->getName());
2568 } else if (LeafRec->isSubClassOf("CondCode")) {
2569 // Make sure this is the specified cond code.
2570 emitCheck("cast<CondCodeSDNode>(" + RootName +
2571 ")->get() == ISD::" + LeafRec->getName());
2577 assert(0 && "Unknown leaf type!");
2580 // If there is a node predicate for this, emit the call.
2581 if (!Child->getPredicateFn().empty())
2582 emitCheck(Child->getPredicateFn() + "(" + RootName +
2584 } else if (IntInit *II =
2585 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2586 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
2587 unsigned CTmp = TmpNo++;
2588 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2589 RootName + ")->getSignExtended();");
2591 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2596 assert(0 && "Unknown leaf type!");
2601 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2602 /// we actually have to build a DAG!
2603 std::vector<std::string>
2604 EmitResultCode(TreePatternNode *N, bool RetSelected,
2605 bool InFlagDecled, bool ResNodeDecled,
2606 bool LikeLeaf = false, bool isRoot = false) {
2607 // List of arguments of getTargetNode() or SelectNodeTo().
2608 std::vector<std::string> NodeOps;
2609 // This is something selected from the pattern we matched.
2610 if (!N->getName().empty()) {
2611 std::string &Val = VariableMap[N->getName()];
2612 assert(!Val.empty() &&
2613 "Variable referenced but not defined and not caught earlier!");
2614 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2615 // Already selected this operand, just return the tmpval.
2616 NodeOps.push_back(Val);
2620 const ComplexPattern *CP;
2621 unsigned ResNo = TmpNo++;
2622 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2623 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2624 std::string CastType;
2625 switch (N->getTypeNum(0)) {
2627 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
2628 << " type as an immediate constant. Aborting\n";
2630 case MVT::i1: CastType = "bool"; break;
2631 case MVT::i8: CastType = "unsigned char"; break;
2632 case MVT::i16: CastType = "unsigned short"; break;
2633 case MVT::i32: CastType = "unsigned"; break;
2634 case MVT::i64: CastType = "uint64_t"; break;
2636 emitCode("SDOperand Tmp" + utostr(ResNo) +
2637 " = CurDAG->getTargetConstant(((" + CastType +
2638 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2639 getEnumName(N->getTypeNum(0)) + ");");
2640 NodeOps.push_back("Tmp" + utostr(ResNo));
2641 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2642 // value if used multiple times by this pattern result.
2643 Val = "Tmp"+utostr(ResNo);
2644 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2645 Record *Op = OperatorMap[N->getName()];
2646 // Transform ExternalSymbol to TargetExternalSymbol
2647 if (Op && Op->getName() == "externalsym") {
2648 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2649 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2650 Val + ")->getSymbol(), " +
2651 getEnumName(N->getTypeNum(0)) + ");");
2652 NodeOps.push_back("Tmp" + utostr(ResNo));
2653 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2654 // this value if used multiple times by this pattern result.
2655 Val = "Tmp"+utostr(ResNo);
2657 NodeOps.push_back(Val);
2659 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
2660 || N->getOperator()->getName() == "tglobaltlsaddr")) {
2661 Record *Op = OperatorMap[N->getName()];
2662 // Transform GlobalAddress to TargetGlobalAddress
2663 if (Op && (Op->getName() == "globaladdr" ||
2664 Op->getName() == "globaltlsaddr")) {
2665 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2666 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2667 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2669 NodeOps.push_back("Tmp" + utostr(ResNo));
2670 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2671 // this value if used multiple times by this pattern result.
2672 Val = "Tmp"+utostr(ResNo);
2674 NodeOps.push_back(Val);
2676 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2677 NodeOps.push_back(Val);
2678 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2679 // value if used multiple times by this pattern result.
2680 Val = "Tmp"+utostr(ResNo);
2681 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2682 NodeOps.push_back(Val);
2683 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2684 // value if used multiple times by this pattern result.
2685 Val = "Tmp"+utostr(ResNo);
2686 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2687 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2688 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2689 NodeOps.push_back("CPTmp" + utostr(i));
2692 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
2693 // node even if it isn't one. Don't select it.
2695 emitCode("AddToISelQueue(" + Val + ");");
2696 if (isRoot && N->isLeaf()) {
2697 emitCode("ReplaceUses(N, " + Val + ");");
2698 emitCode("return NULL;");
2701 NodeOps.push_back(Val);
2706 // If this is an explicit register reference, handle it.
2707 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2708 unsigned ResNo = TmpNo++;
2709 if (DI->getDef()->isSubClassOf("Register")) {
2710 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2711 ISE.getQualifiedName(DI->getDef()) + ", " +
2712 getEnumName(N->getTypeNum(0)) + ");");
2713 NodeOps.push_back("Tmp" + utostr(ResNo));
2715 } else if (DI->getDef()->getName() == "zero_reg") {
2716 emitCode("SDOperand Tmp" + utostr(ResNo) +
2717 " = CurDAG->getRegister(0, " +
2718 getEnumName(N->getTypeNum(0)) + ");");
2719 NodeOps.push_back("Tmp" + utostr(ResNo));
2722 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2723 unsigned ResNo = TmpNo++;
2724 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2725 emitCode("SDOperand Tmp" + utostr(ResNo) +
2726 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2727 ", " + getEnumName(N->getTypeNum(0)) + ");");
2728 NodeOps.push_back("Tmp" + utostr(ResNo));
2735 assert(0 && "Unknown leaf type!");
2739 Record *Op = N->getOperator();
2740 if (Op->isSubClassOf("Instruction")) {
2741 const CodeGenTarget &CGT = ISE.getTargetInfo();
2742 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2743 const DAGInstruction &Inst = ISE.getInstruction(Op);
2744 TreePattern *InstPat = Inst.getPattern();
2745 TreePatternNode *InstPatNode =
2746 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2747 : (InstPat ? InstPat->getOnlyTree() : NULL);
2748 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2749 InstPatNode = InstPatNode->getChild(1);
2751 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
2752 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2753 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2754 bool NodeHasOptInFlag = isRoot &&
2755 PatternHasProperty(Pattern, SDNPOptInFlag, ISE);
2756 bool NodeHasInFlag = isRoot &&
2757 PatternHasProperty(Pattern, SDNPInFlag, ISE);
2758 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2759 PatternHasProperty(Pattern, SDNPOutFlag, ISE));
2760 bool NodeHasChain = InstPatNode &&
2761 PatternHasProperty(InstPatNode, SDNPHasChain, ISE);
2762 bool InputHasChain = isRoot &&
2763 NodeHasProperty(Pattern, SDNPHasChain, ISE);
2764 unsigned NumResults = Inst.getNumResults();
2766 if (NodeHasOptInFlag) {
2767 emitCode("bool HasInFlag = "
2768 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
2771 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
2773 // How many results is this pattern expected to produce?
2774 unsigned PatResults = 0;
2775 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2776 MVT::ValueType VT = Pattern->getTypeNum(i);
2777 if (VT != MVT::isVoid && VT != MVT::Flag)
2781 if (OrigChains.size() > 0) {
2782 // The original input chain is being ignored. If it is not just
2783 // pointing to the op that's being folded, we should create a
2784 // TokenFactor with it and the chain of the folded op as the new chain.
2785 // We could potentially be doing multiple levels of folding, in that
2786 // case, the TokenFactor can have more operands.
2787 emitCode("SmallVector<SDOperand, 8> InChains;");
2788 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
2789 emitCode("if (" + OrigChains[i].first + ".Val != " +
2790 OrigChains[i].second + ".Val) {");
2791 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
2792 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
2795 emitCode("AddToISelQueue(" + ChainName + ");");
2796 emitCode("InChains.push_back(" + ChainName + ");");
2797 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
2798 "&InChains[0], InChains.size());");
2801 // Loop over all of the operands of the instruction pattern, emitting code
2802 // to fill them all in. The node 'N' usually has number children equal to
2803 // the number of input operands of the instruction. However, in cases
2804 // where there are predicate operands for an instruction, we need to fill
2805 // in the 'execute always' values. Match up the node operands to the
2806 // instruction operands to do this.
2807 std::vector<std::string> AllOps;
2808 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
2809 for (unsigned ChildNo = 0, InstOpNo = NumResults;
2810 InstOpNo != II.OperandList.size(); ++InstOpNo) {
2811 std::vector<std::string> Ops;
2813 // If this is a normal operand or a predicate operand without
2814 // 'execute always', emit it.
2815 Record *OperandNode = II.OperandList[InstOpNo].Rec;
2816 if (!OperandNode->isSubClassOf("PredicateOperand") ||
2817 ISE.getPredicateOperand(OperandNode).AlwaysOps.empty()) {
2818 Ops = EmitResultCode(N->getChild(ChildNo), RetSelected,
2819 InFlagDecled, ResNodeDecled);
2820 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2823 // Otherwise, this is a predicate operand, emit the 'execute always'
2825 const DAGPredicateOperand &Pred =
2826 ISE.getPredicateOperand(II.OperandList[InstOpNo].Rec);
2827 for (unsigned i = 0, e = Pred.AlwaysOps.size(); i != e; ++i) {
2828 Ops = EmitResultCode(Pred.AlwaysOps[i], RetSelected,
2829 InFlagDecled, ResNodeDecled);
2830 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2831 NumEAInputs += Ops.size();
2836 // Emit all the chain and CopyToReg stuff.
2837 bool ChainEmitted = NodeHasChain;
2839 emitCode("AddToISelQueue(" + ChainName + ");");
2840 if (NodeHasInFlag || HasImpInputs)
2841 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2842 InFlagDecled, ResNodeDecled, true);
2843 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
2844 if (!InFlagDecled) {
2845 emitCode("SDOperand InFlag(0, 0);");
2846 InFlagDecled = true;
2848 if (NodeHasOptInFlag) {
2849 emitCode("if (HasInFlag) {");
2850 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
2851 emitCode(" AddToISelQueue(InFlag);");
2856 unsigned ResNo = TmpNo++;
2857 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2861 std::string NodeName;
2863 NodeName = "Tmp" + utostr(ResNo);
2864 Code2 = "SDOperand " + NodeName + " = SDOperand(";
2866 NodeName = "ResNode";
2867 if (!ResNodeDecled) {
2868 Code2 = "SDNode *" + NodeName + " = ";
2869 ResNodeDecled = true;
2871 Code2 = NodeName + " = ";
2874 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2875 unsigned OpsNo = OpcNo;
2876 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2878 // Output order: results, chain, flags
2880 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2881 Code += ", VT" + utostr(VTNo);
2882 emitVT(getEnumName(N->getTypeNum(0)));
2885 Code += ", MVT::Other";
2887 Code += ", MVT::Flag";
2889 // Figure out how many fixed inputs the node has. This is important to
2890 // know which inputs are the variable ones if present.
2891 unsigned NumInputs = AllOps.size();
2892 NumInputs += NodeHasChain;
2896 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2897 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2902 // Figure out whether any operands at the end of the op list are not
2903 // part of the variable section.
2904 std::string EndAdjust;
2905 if (NodeHasInFlag || HasImpInputs)
2906 EndAdjust = "-1"; // Always has one flag.
2907 else if (NodeHasOptInFlag)
2908 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
2910 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
2911 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
2913 emitCode(" AddToISelQueue(N.getOperand(i));");
2914 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
2920 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
2922 AllOps.push_back(ChainName);
2926 if (NodeHasInFlag || HasImpInputs)
2927 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2928 else if (NodeHasOptInFlag) {
2929 emitCode("if (HasInFlag)");
2930 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2932 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2934 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2935 AllOps.push_back("InFlag");
2937 unsigned NumOps = AllOps.size();
2939 if (!NodeHasOptInFlag && NumOps < 4) {
2940 for (unsigned i = 0; i != NumOps; ++i)
2941 Code += ", " + AllOps[i];
2943 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
2944 for (unsigned i = 0; i != NumOps; ++i) {
2945 OpsCode += AllOps[i];
2949 emitCode(OpsCode + " };");
2950 Code += ", Ops" + utostr(OpsNo) + ", ";
2951 if (NodeHasOptInFlag) {
2952 Code += "HasInFlag ? ";
2953 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
2955 Code += utostr(NumOps);
2961 emitCode(Code2 + Code + ");");
2964 // Remember which op produces the chain.
2966 emitCode(ChainName + " = SDOperand(" + NodeName +
2967 ".Val, " + utostr(PatResults) + ");");
2969 emitCode(ChainName + " = SDOperand(" + NodeName +
2970 ", " + utostr(PatResults) + ");");
2973 NodeOps.push_back("Tmp" + utostr(ResNo));
2977 bool NeedReplace = false;
2978 if (NodeHasOutFlag) {
2979 if (!InFlagDecled) {
2980 emitCode("SDOperand InFlag = SDOperand(ResNode, " +
2981 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2982 InFlagDecled = true;
2984 emitCode("InFlag = SDOperand(ResNode, " +
2985 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2988 if (HasImpResults && EmitCopyFromRegs(N, ResNodeDecled, ChainEmitted)) {
2989 emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));");
2993 if (FoldedChains.size() > 0) {
2995 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2996 emitCode("ReplaceUses(SDOperand(" +
2997 FoldedChains[j].first + ".Val, " +
2998 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
2999 utostr(NumResults) + "));");
3003 if (NodeHasOutFlag) {
3004 emitCode("ReplaceUses(SDOperand(N.Val, " +
3005 utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);");
3010 for (unsigned i = 0; i < NumResults; i++)
3011 emitCode("ReplaceUses(SDOperand(N.Val, " +
3012 utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));");
3014 emitCode("ReplaceUses(SDOperand(N.Val, " +
3015 utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, "
3016 + ChainName + ".ResNo" + "));");
3020 // User does not expect the instruction would produce a chain!
3021 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
3023 } else if (InputHasChain && !NodeHasChain) {
3024 // One of the inner node produces a chain.
3026 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults+1) +
3027 "), SDOperand(ResNode, N.ResNo-1));");
3028 for (unsigned i = 0; i < PatResults; ++i)
3029 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(i) +
3030 "), SDOperand(ResNode, " + utostr(i) + "));");
3031 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults) +
3032 "), " + ChainName + ");");
3033 RetSelected = false;
3037 emitCode("return ResNode;");
3039 emitCode("return NULL;");
3041 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
3043 if (N->getTypeNum(0) != MVT::isVoid)
3044 Code += ", VT" + utostr(VTNo);
3046 Code += ", MVT::Flag";
3048 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
3049 AllOps.push_back("InFlag");
3051 unsigned NumOps = AllOps.size();
3053 if (!NodeHasOptInFlag && NumOps < 4) {
3054 for (unsigned i = 0; i != NumOps; ++i)
3055 Code += ", " + AllOps[i];
3057 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
3058 for (unsigned i = 0; i != NumOps; ++i) {
3059 OpsCode += AllOps[i];
3063 emitCode(OpsCode + " };");
3064 Code += ", Ops" + utostr(OpcNo) + ", ";
3065 Code += utostr(NumOps);
3068 emitCode(Code + ");");
3069 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
3070 if (N->getTypeNum(0) != MVT::isVoid)
3071 emitVT(getEnumName(N->getTypeNum(0)));
3075 } else if (Op->isSubClassOf("SDNodeXForm")) {
3076 assert(N->getNumChildren() == 1 && "node xform should have one child!");
3077 // PatLeaf node - the operand may or may not be a leaf node. But it should
3079 std::vector<std::string> Ops =
3080 EmitResultCode(N->getChild(0), RetSelected, InFlagDecled,
3081 ResNodeDecled, true);
3082 unsigned ResNo = TmpNo++;
3083 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
3084 + "(" + Ops.back() + ".Val);");
3085 NodeOps.push_back("Tmp" + utostr(ResNo));
3087 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
3092 throw std::string("Unknown node in result pattern!");
3096 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
3097 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
3098 /// 'Pat' may be missing types. If we find an unresolved type to add a check
3099 /// for, this returns true otherwise false if Pat has all types.
3100 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
3101 const std::string &Prefix, bool isRoot = false) {
3103 if (Pat->getExtTypes() != Other->getExtTypes()) {
3104 // Move a type over from 'other' to 'pat'.
3105 Pat->setTypes(Other->getExtTypes());
3106 // The top level node type is checked outside of the select function.
3108 emitCheck(Prefix + ".Val->getValueType(0) == " +
3109 getName(Pat->getTypeNum(0)));
3114 (unsigned) NodeHasProperty(Pat, SDNPHasChain, ISE);
3115 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
3116 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
3117 Prefix + utostr(OpNo)))
3123 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
3125 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
3126 bool &ChainEmitted, bool &InFlagDecled,
3127 bool &ResNodeDecled, bool isRoot = false) {
3128 const CodeGenTarget &T = ISE.getTargetInfo();
3130 (unsigned) NodeHasProperty(N, SDNPHasChain, ISE);
3131 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, ISE);
3132 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
3133 TreePatternNode *Child = N->getChild(i);
3134 if (!Child->isLeaf()) {
3135 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
3136 InFlagDecled, ResNodeDecled);
3138 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
3139 if (!Child->getName().empty()) {
3140 std::string Name = RootName + utostr(OpNo);
3141 if (Duplicates.find(Name) != Duplicates.end())
3142 // A duplicate! Do not emit a copy for this node.
3146 Record *RR = DI->getDef();
3147 if (RR->isSubClassOf("Register")) {
3148 MVT::ValueType RVT = getRegisterValueType(RR, T);
3149 if (RVT == MVT::Flag) {
3150 if (!InFlagDecled) {
3151 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
3152 InFlagDecled = true;
3154 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
3155 emitCode("AddToISelQueue(InFlag);");
3157 if (!ChainEmitted) {
3158 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
3159 ChainName = "Chain";
3160 ChainEmitted = true;
3162 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
3163 if (!InFlagDecled) {
3164 emitCode("SDOperand InFlag(0, 0);");
3165 InFlagDecled = true;
3167 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3168 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
3169 ", " + ISE.getQualifiedName(RR) +
3170 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
3171 ResNodeDecled = true;
3172 emitCode(ChainName + " = SDOperand(ResNode, 0);");
3173 emitCode("InFlag = SDOperand(ResNode, 1);");
3181 if (!InFlagDecled) {
3182 emitCode("SDOperand InFlag = " + RootName +
3183 ".getOperand(" + utostr(OpNo) + ");");
3184 InFlagDecled = true;
3186 emitCode("InFlag = " + RootName +
3187 ".getOperand(" + utostr(OpNo) + ");");
3188 emitCode("AddToISelQueue(InFlag);");
3192 /// EmitCopyFromRegs - Emit code to copy result to physical registers
3193 /// as specified by the instruction. It returns true if any copy is
3195 bool EmitCopyFromRegs(TreePatternNode *N, bool &ResNodeDecled,
3196 bool &ChainEmitted) {
3197 bool RetVal = false;
3198 Record *Op = N->getOperator();
3199 if (Op->isSubClassOf("Instruction")) {
3200 const DAGInstruction &Inst = ISE.getInstruction(Op);
3201 const CodeGenTarget &CGT = ISE.getTargetInfo();
3202 unsigned NumImpResults = Inst.getNumImpResults();
3203 for (unsigned i = 0; i < NumImpResults; i++) {
3204 Record *RR = Inst.getImpResult(i);
3205 if (RR->isSubClassOf("Register")) {
3206 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
3207 if (RVT != MVT::Flag) {
3208 if (!ChainEmitted) {
3209 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
3210 ChainEmitted = true;
3211 ChainName = "Chain";
3213 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3214 emitCode(Decl + "ResNode = CurDAG->getCopyFromReg(" + ChainName +
3215 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
3217 ResNodeDecled = true;
3218 emitCode(ChainName + " = SDOperand(ResNode, 1);");
3219 emitCode("InFlag = SDOperand(ResNode, 2);");
3229 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
3230 /// stream to match the pattern, and generate the code for the match if it
3231 /// succeeds. Returns true if the pattern is not guaranteed to match.
3232 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
3233 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
3234 std::set<std::string> &GeneratedDecl,
3235 std::vector<std::string> &TargetOpcodes,
3236 std::vector<std::string> &TargetVTs) {
3237 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3238 Pattern.getSrcPattern(), Pattern.getDstPattern(),
3239 GeneratedCode, GeneratedDecl,
3240 TargetOpcodes, TargetVTs);
3242 // Emit the matcher, capturing named arguments in VariableMap.
3243 bool FoundChain = false;
3244 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
3246 // TP - Get *SOME* tree pattern, we don't care which.
3247 TreePattern &TP = *PatternFragments.begin()->second;
3249 // At this point, we know that we structurally match the pattern, but the
3250 // types of the nodes may not match. Figure out the fewest number of type
3251 // comparisons we need to emit. For example, if there is only one integer
3252 // type supported by a target, there should be no type comparisons at all for
3253 // integer patterns!
3255 // To figure out the fewest number of type checks needed, clone the pattern,
3256 // remove the types, then perform type inference on the pattern as a whole.
3257 // If there are unresolved types, emit an explicit check for those types,
3258 // apply the type to the tree, then rerun type inference. Iterate until all
3259 // types are resolved.
3261 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
3262 RemoveAllTypes(Pat);
3265 // Resolve/propagate as many types as possible.
3267 bool MadeChange = true;
3269 MadeChange = Pat->ApplyTypeConstraints(TP,
3270 true/*Ignore reg constraints*/);
3272 assert(0 && "Error: could not find consistent types for something we"
3273 " already decided was ok!");
3277 // Insert a check for an unresolved type and add it to the tree. If we find
3278 // an unresolved type to add a check for, this returns true and we iterate,
3279 // otherwise we are done.
3280 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
3282 Emitter.EmitResultCode(Pattern.getDstPattern(),
3283 false, false, false, false, true);
3287 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
3288 /// a line causes any of them to be empty, remove them and return true when
3290 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
3291 std::vector<std::pair<unsigned, std::string> > > >
3293 bool ErasedPatterns = false;
3294 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3295 Patterns[i].second.pop_back();
3296 if (Patterns[i].second.empty()) {
3297 Patterns.erase(Patterns.begin()+i);
3299 ErasedPatterns = true;
3302 return ErasedPatterns;
3305 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3306 /// code together between the patterns.
3307 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3308 std::vector<std::pair<unsigned, std::string> > > >
3309 &Patterns, unsigned Indent,
3311 typedef std::pair<unsigned, std::string> CodeLine;
3312 typedef std::vector<CodeLine> CodeList;
3313 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3315 if (Patterns.empty()) return;
3317 // Figure out how many patterns share the next code line. Explicitly copy
3318 // FirstCodeLine so that we don't invalidate a reference when changing
3320 const CodeLine FirstCodeLine = Patterns.back().second.back();
3321 unsigned LastMatch = Patterns.size()-1;
3322 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3325 // If not all patterns share this line, split the list into two pieces. The
3326 // first chunk will use this line, the second chunk won't.
3327 if (LastMatch != 0) {
3328 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3329 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3331 // FIXME: Emit braces?
3332 if (Shared.size() == 1) {
3333 PatternToMatch &Pattern = *Shared.back().first;
3334 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3335 Pattern.getSrcPattern()->print(OS);
3336 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3337 Pattern.getDstPattern()->print(OS);
3339 unsigned AddedComplexity = Pattern.getAddedComplexity();
3340 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3341 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3343 << getResultPatternCost(Pattern.getDstPattern(), *this)
3345 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3347 if (FirstCodeLine.first != 1) {
3348 OS << std::string(Indent, ' ') << "{\n";
3351 EmitPatterns(Shared, Indent, OS);
3352 if (FirstCodeLine.first != 1) {
3354 OS << std::string(Indent, ' ') << "}\n";
3357 if (Other.size() == 1) {
3358 PatternToMatch &Pattern = *Other.back().first;
3359 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3360 Pattern.getSrcPattern()->print(OS);
3361 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3362 Pattern.getDstPattern()->print(OS);
3364 unsigned AddedComplexity = Pattern.getAddedComplexity();
3365 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3366 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3368 << getResultPatternCost(Pattern.getDstPattern(), *this)
3370 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3372 EmitPatterns(Other, Indent, OS);
3376 // Remove this code from all of the patterns that share it.
3377 bool ErasedPatterns = EraseCodeLine(Patterns);
3379 bool isPredicate = FirstCodeLine.first == 1;
3381 // Otherwise, every pattern in the list has this line. Emit it.
3384 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3386 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3388 // If the next code line is another predicate, and if all of the pattern
3389 // in this group share the same next line, emit it inline now. Do this
3390 // until we run out of common predicates.
3391 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
3392 // Check that all of fhe patterns in Patterns end with the same predicate.
3393 bool AllEndWithSamePredicate = true;
3394 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3395 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3396 AllEndWithSamePredicate = false;
3399 // If all of the predicates aren't the same, we can't share them.
3400 if (!AllEndWithSamePredicate) break;
3402 // Otherwise we can. Emit it shared now.
3403 OS << " &&\n" << std::string(Indent+4, ' ')
3404 << Patterns.back().second.back().second;
3405 ErasedPatterns = EraseCodeLine(Patterns);
3412 EmitPatterns(Patterns, Indent, OS);
3415 OS << std::string(Indent-2, ' ') << "}\n";
3418 static std::string getOpcodeName(Record *Op, DAGISelEmitter &ISE) {
3419 const SDNodeInfo &OpcodeInfo = ISE.getSDNodeInfo(Op);
3420 return OpcodeInfo.getEnumName();
3423 static std::string getLegalCName(std::string OpName) {
3424 std::string::size_type pos = OpName.find("::");
3425 if (pos != std::string::npos)
3426 OpName.replace(pos, 2, "_");
3430 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3431 // Get the namespace to insert instructions into. Make sure not to pick up
3432 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
3433 // instruction or something.
3435 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
3436 e = Target.inst_end(); i != e; ++i) {
3437 InstNS = i->second.Namespace;
3438 if (InstNS != "TargetInstrInfo")
3442 if (!InstNS.empty()) InstNS += "::";
3444 // Group the patterns by their top-level opcodes.
3445 std::map<std::string, std::vector<PatternToMatch*> > PatternsByOpcode;
3446 // All unique target node emission functions.
3447 std::map<std::string, unsigned> EmitFunctions;
3448 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3449 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3450 if (!Node->isLeaf()) {
3451 PatternsByOpcode[getOpcodeName(Node->getOperator(), *this)].
3452 push_back(&PatternsToMatch[i]);
3454 const ComplexPattern *CP;
3455 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
3456 PatternsByOpcode[getOpcodeName(getSDNodeNamed("imm"), *this)].
3457 push_back(&PatternsToMatch[i]);
3458 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3459 std::vector<Record*> OpNodes = CP->getRootNodes();
3460 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3461 PatternsByOpcode[getOpcodeName(OpNodes[j], *this)]
3462 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], *this)].begin(),
3463 &PatternsToMatch[i]);
3466 cerr << "Unrecognized opcode '";
3468 cerr << "' on tree pattern '";
3469 cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3476 // For each opcode, there might be multiple select functions, one per
3477 // ValueType of the node (or its first operand if it doesn't produce a
3478 // non-chain result.
3479 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3481 // Emit one Select_* method for each top-level opcode. We do this instead of
3482 // emitting one giant switch statement to support compilers where this will
3483 // result in the recursive functions taking less stack space.
3484 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3485 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3486 PBOI != E; ++PBOI) {
3487 const std::string &OpName = PBOI->first;
3488 std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3489 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3491 // We want to emit all of the matching code now. However, we want to emit
3492 // the matches in order of minimal cost. Sort the patterns so the least
3493 // cost one is at the start.
3494 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
3495 PatternSortingPredicate(*this));
3497 // Split them into groups by type.
3498 std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3499 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3500 PatternToMatch *Pat = PatternsOfOp[i];
3501 TreePatternNode *SrcPat = Pat->getSrcPattern();
3502 MVT::ValueType VT = SrcPat->getTypeNum(0);
3503 std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI =
3504 PatternsByType.find(VT);
3505 if (TI != PatternsByType.end())
3506 TI->second.push_back(Pat);
3508 std::vector<PatternToMatch*> PVec;
3509 PVec.push_back(Pat);
3510 PatternsByType.insert(std::make_pair(VT, PVec));
3514 for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3515 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3517 MVT::ValueType OpVT = II->first;
3518 std::vector<PatternToMatch*> &Patterns = II->second;
3519 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
3520 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
3522 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3523 std::vector<std::vector<std::string> > PatternOpcodes;
3524 std::vector<std::vector<std::string> > PatternVTs;
3525 std::vector<std::set<std::string> > PatternDecls;
3526 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3527 CodeList GeneratedCode;
3528 std::set<std::string> GeneratedDecl;
3529 std::vector<std::string> TargetOpcodes;
3530 std::vector<std::string> TargetVTs;
3531 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3532 TargetOpcodes, TargetVTs);
3533 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3534 PatternDecls.push_back(GeneratedDecl);
3535 PatternOpcodes.push_back(TargetOpcodes);
3536 PatternVTs.push_back(TargetVTs);
3539 // Scan the code to see if all of the patterns are reachable and if it is
3540 // possible that the last one might not match.
3541 bool mightNotMatch = true;
3542 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3543 CodeList &GeneratedCode = CodeForPatterns[i].second;
3544 mightNotMatch = false;
3546 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3547 if (GeneratedCode[j].first == 1) { // predicate.
3548 mightNotMatch = true;
3553 // If this pattern definitely matches, and if it isn't the last one, the
3554 // patterns after it CANNOT ever match. Error out.
3555 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3556 cerr << "Pattern '";
3557 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
3558 cerr << "' is impossible to select!\n";
3563 // Factor target node emission code (emitted by EmitResultCode) into
3564 // separate functions. Uniquing and share them among all instruction
3565 // selection routines.
3566 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3567 CodeList &GeneratedCode = CodeForPatterns[i].second;
3568 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3569 std::vector<std::string> &TargetVTs = PatternVTs[i];
3570 std::set<std::string> Decls = PatternDecls[i];
3571 std::vector<std::string> AddedInits;
3572 int CodeSize = (int)GeneratedCode.size();
3574 for (int j = CodeSize-1; j >= 0; --j) {
3575 if (LastPred == -1 && GeneratedCode[j].first == 1)
3577 else if (LastPred != -1 && GeneratedCode[j].first == 2)
3578 AddedInits.push_back(GeneratedCode[j].second);
3581 std::string CalleeCode = "(const SDOperand &N";
3582 std::string CallerCode = "(N";
3583 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3584 CalleeCode += ", unsigned Opc" + utostr(j);
3585 CallerCode += ", " + TargetOpcodes[j];
3587 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3588 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3589 CallerCode += ", " + TargetVTs[j];
3591 for (std::set<std::string>::iterator
3592 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
3593 std::string Name = *I;
3594 CalleeCode += ", SDOperand &" + Name;
3595 CallerCode += ", " + Name;
3599 // Prevent emission routines from being inlined to reduce selection
3600 // routines stack frame sizes.
3601 CalleeCode += "DISABLE_INLINE ";
3602 CalleeCode += "{\n";
3604 for (std::vector<std::string>::const_reverse_iterator
3605 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3606 CalleeCode += " " + *I + "\n";
3608 for (int j = LastPred+1; j < CodeSize; ++j)
3609 CalleeCode += " " + GeneratedCode[j].second + "\n";
3610 for (int j = LastPred+1; j < CodeSize; ++j)
3611 GeneratedCode.pop_back();
3612 CalleeCode += "}\n";
3614 // Uniquing the emission routines.
3615 unsigned EmitFuncNum;
3616 std::map<std::string, unsigned>::iterator EFI =
3617 EmitFunctions.find(CalleeCode);
3618 if (EFI != EmitFunctions.end()) {
3619 EmitFuncNum = EFI->second;
3621 EmitFuncNum = EmitFunctions.size();
3622 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
3623 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
3626 // Replace the emission code within selection routines with calls to the
3627 // emission functions.
3628 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
3629 GeneratedCode.push_back(std::make_pair(false, CallerCode));
3633 std::string OpVTStr;
3634 if (OpVT == MVT::iPTR) {
3636 } else if (OpVT == MVT::isVoid) {
3637 // Nodes with a void result actually have a first result type of either
3638 // Other (a chain) or Flag. Since there is no one-to-one mapping from
3639 // void to this case, we handle it specially here.
3641 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
3643 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3644 OpcodeVTMap.find(OpName);
3645 if (OpVTI == OpcodeVTMap.end()) {
3646 std::vector<std::string> VTSet;
3647 VTSet.push_back(OpVTStr);
3648 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3650 OpVTI->second.push_back(OpVTStr);
3652 OS << "SDNode *Select_" << getLegalCName(OpName)
3653 << OpVTStr << "(const SDOperand &N) {\n";
3655 // Loop through and reverse all of the CodeList vectors, as we will be
3656 // accessing them from their logical front, but accessing the end of a
3657 // vector is more efficient.
3658 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3659 CodeList &GeneratedCode = CodeForPatterns[i].second;
3660 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3663 // Next, reverse the list of patterns itself for the same reason.
3664 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3666 // Emit all of the patterns now, grouped together to share code.
3667 EmitPatterns(CodeForPatterns, 2, OS);
3669 // If the last pattern has predicates (which could fail) emit code to
3670 // catch the case where nothing handles a pattern.
3671 if (mightNotMatch) {
3672 OS << " cerr << \"Cannot yet select: \";\n";
3673 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
3674 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
3675 OpName != "ISD::INTRINSIC_VOID") {
3676 OS << " N.Val->dump(CurDAG);\n";
3678 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3679 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3680 << " cerr << \"intrinsic %\"<< "
3681 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3683 OS << " cerr << '\\n';\n"
3685 << " return NULL;\n";
3691 // Emit boilerplate.
3692 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
3693 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3694 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
3696 << " // Ensure that the asm operands are themselves selected.\n"
3697 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
3698 << " AddToISelQueue(Ops[j]);\n\n"
3700 << " std::vector<MVT::ValueType> VTs;\n"
3701 << " VTs.push_back(MVT::Other);\n"
3702 << " VTs.push_back(MVT::Flag);\n"
3703 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3705 << " return New.Val;\n"
3708 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
3709 << " SDOperand Chain = N.getOperand(0);\n"
3710 << " SDOperand N1 = N.getOperand(1);\n"
3711 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
3712 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
3713 << " AddToISelQueue(Chain);\n"
3714 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
3715 << " MVT::Other, Tmp, Chain);\n"
3718 OS << "// The main instruction selector code.\n"
3719 << "SDNode *SelectCode(SDOperand N) {\n"
3720 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3721 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3722 << "INSTRUCTION_LIST_END)) {\n"
3723 << " return NULL; // Already selected.\n"
3725 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
3726 << " switch (N.getOpcode()) {\n"
3727 << " default: break;\n"
3728 << " case ISD::EntryToken: // These leaves remain the same.\n"
3729 << " case ISD::BasicBlock:\n"
3730 << " case ISD::Register:\n"
3731 << " case ISD::HANDLENODE:\n"
3732 << " case ISD::TargetConstant:\n"
3733 << " case ISD::TargetConstantPool:\n"
3734 << " case ISD::TargetFrameIndex:\n"
3735 << " case ISD::TargetExternalSymbol:\n"
3736 << " case ISD::TargetJumpTable:\n"
3737 << " case ISD::TargetGlobalTLSAddress:\n"
3738 << " case ISD::TargetGlobalAddress: {\n"
3739 << " return NULL;\n"
3741 << " case ISD::AssertSext:\n"
3742 << " case ISD::AssertZext: {\n"
3743 << " AddToISelQueue(N.getOperand(0));\n"
3744 << " ReplaceUses(N, N.getOperand(0));\n"
3745 << " return NULL;\n"
3747 << " case ISD::TokenFactor:\n"
3748 << " case ISD::CopyFromReg:\n"
3749 << " case ISD::CopyToReg: {\n"
3750 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3751 << " AddToISelQueue(N.getOperand(i));\n"
3752 << " return NULL;\n"
3754 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
3755 << " case ISD::LABEL: return Select_LABEL(N);\n";
3758 // Loop over all of the case statements, emiting a call to each method we
3760 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3761 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3762 PBOI != E; ++PBOI) {
3763 const std::string &OpName = PBOI->first;
3764 // Potentially multiple versions of select for this opcode. One for each
3765 // ValueType of the node (or its first true operand if it doesn't produce a
3767 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3768 OpcodeVTMap.find(OpName);
3769 std::vector<std::string> &OpVTs = OpVTI->second;
3770 OS << " case " << OpName << ": {\n";
3771 if (OpVTs.size() == 1) {
3772 std::string &VTStr = OpVTs[0];
3773 OS << " return Select_" << getLegalCName(OpName)
3774 << VTStr << "(N);\n";
3776 // Keep track of whether we see a pattern that has an iPtr result.
3777 bool HasPtrPattern = false;
3778 bool HasDefaultPattern = false;
3780 OS << " switch (NVT) {\n";
3781 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3782 std::string &VTStr = OpVTs[i];
3783 if (VTStr.empty()) {
3784 HasDefaultPattern = true;
3788 // If this is a match on iPTR: don't emit it directly, we need special
3790 if (VTStr == "_iPTR") {
3791 HasPtrPattern = true;
3794 OS << " case MVT::" << VTStr.substr(1) << ":\n"
3795 << " return Select_" << getLegalCName(OpName)
3796 << VTStr << "(N);\n";
3798 OS << " default:\n";
3800 // If there is an iPTR result version of this pattern, emit it here.
3801 if (HasPtrPattern) {
3802 OS << " if (NVT == TLI.getPointerTy())\n";
3803 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
3805 if (HasDefaultPattern) {
3806 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
3815 OS << " } // end of big switch.\n\n"
3816 << " cerr << \"Cannot yet select: \";\n"
3817 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3818 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3819 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3820 << " N.Val->dump(CurDAG);\n"
3822 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3823 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3824 << " cerr << \"intrinsic %\"<< "
3825 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3827 << " cerr << '\\n';\n"
3829 << " return NULL;\n"
3833 void DAGISelEmitter::run(std::ostream &OS) {
3834 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3837 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3838 << "// *** instruction selector class. These functions are really "
3841 OS << "#include \"llvm/Support/Compiler.h\"\n";
3843 OS << "// Instruction selector priority queue:\n"
3844 << "std::vector<SDNode*> ISelQueue;\n";
3845 OS << "/// Keep track of nodes which have already been added to queue.\n"
3846 << "unsigned char *ISelQueued;\n";
3847 OS << "/// Keep track of nodes which have already been selected.\n"
3848 << "unsigned char *ISelSelected;\n";
3849 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3850 << "std::vector<SDNode*> ISelKilled;\n\n";
3852 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
3853 OS << "/// not reach Op.\n";
3854 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
3855 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
3856 OS << " return true;\n";
3857 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
3858 OS << " return false;\n";
3859 OS << " else if (Chain->getNumOperands() > 0) {\n";
3860 OS << " SDOperand C0 = Chain->getOperand(0);\n";
3861 OS << " if (C0.getValueType() == MVT::Other)\n";
3862 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
3864 OS << " return true;\n";
3867 OS << "/// Sorting functions for the selection queue.\n"
3868 << "struct isel_sort : public std::binary_function"
3869 << "<SDNode*, SDNode*, bool> {\n"
3870 << " bool operator()(const SDNode* left, const SDNode* right) "
3872 << " return (left->getNodeId() > right->getNodeId());\n"
3876 OS << "inline void setQueued(int Id) {\n";
3877 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
3879 OS << "inline bool isQueued(int Id) {\n";
3880 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
3882 OS << "inline void setSelected(int Id) {\n";
3883 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
3885 OS << "inline bool isSelected(int Id) {\n";
3886 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3889 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
3890 OS << " int Id = N.Val->getNodeId();\n";
3891 OS << " if (Id != -1 && !isQueued(Id)) {\n";
3892 OS << " ISelQueue.push_back(N.Val);\n";
3893 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3894 OS << " setQueued(Id);\n";
3898 OS << "inline void RemoveKilled() {\n";
3899 OS << " unsigned NumKilled = ISelKilled.size();\n";
3900 OS << " if (NumKilled) {\n";
3901 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
3902 OS << " SDNode *Temp = ISelKilled[i];\n";
3903 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
3904 << "Temp), ISelQueue.end());\n";
3906 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3907 OS << " ISelKilled.clear();\n";
3911 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
3912 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n";
3913 OS << " setSelected(F.Val->getNodeId());\n";
3914 OS << " RemoveKilled();\n";
3916 OS << "inline void ReplaceUses(SDNode *F, SDNode *T) {\n";
3917 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3918 OS << " setSelected(F->getNodeId());\n";
3919 OS << " RemoveKilled();\n";
3922 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3923 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3924 OS << " SelectRootInit();\n";
3925 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
3926 OS << " ISelQueued = new unsigned char[NumBytes];\n";
3927 OS << " ISelSelected = new unsigned char[NumBytes];\n";
3928 OS << " memset(ISelQueued, 0, NumBytes);\n";
3929 OS << " memset(ISelSelected, 0, NumBytes);\n";
3931 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
3932 << " // a reference to the root node, preventing it from being deleted,\n"
3933 << " // and tracking any changes of the root.\n"
3934 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
3935 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
3936 OS << " while (!ISelQueue.empty()) {\n";
3937 OS << " SDNode *Node = ISelQueue.front();\n";
3938 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3939 OS << " ISelQueue.pop_back();\n";
3940 OS << " if (!isSelected(Node->getNodeId())) {\n";
3941 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
3942 OS << " if (ResNode != Node) {\n";
3943 OS << " if (ResNode)\n";
3944 OS << " ReplaceUses(Node, ResNode);\n";
3945 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
3946 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
3947 OS << " RemoveKilled();\n";
3953 OS << " delete[] ISelQueued;\n";
3954 OS << " ISelQueued = NULL;\n";
3955 OS << " delete[] ISelSelected;\n";
3956 OS << " ISelSelected = NULL;\n";
3957 OS << " return Dummy.getValue();\n";
3960 Intrinsics = LoadIntrinsics(Records);
3962 ParseNodeTransforms(OS);
3963 ParseComplexPatterns();
3964 ParsePatternFragments(OS);
3965 ParsePredicateOperands();
3966 ParseInstructions();
3969 // Generate variants. For example, commutative patterns can match
3970 // multiple ways. Add them to PatternsToMatch as well.
3973 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
3974 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3975 DOUT << "PATTERN: "; DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
3976 DOUT << "\nRESULT: "; DEBUG(PatternsToMatch[i].getDstPattern()->dump());
3980 // At this point, we have full information about the 'Patterns' we need to
3981 // parse, both implicitly from instructions as well as from explicit pattern
3982 // definitions. Emit the resultant instruction selector.
3983 EmitInstructionSelector(OS);
3985 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3986 E = PatternFragments.end(); I != E; ++I)
3988 PatternFragments.clear();
3990 Instructions.clear();