1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Streams.h"
23 //===----------------------------------------------------------------------===//
24 // Helpers for working with extended types.
26 /// FilterVTs - Filter a list of VT's according to a predicate.
29 static std::vector<MVT::ValueType>
30 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
31 std::vector<MVT::ValueType> Result;
32 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 Result.push_back(InVTs[i]);
39 static std::vector<unsigned char>
40 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
41 std::vector<unsigned char> Result;
42 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
43 if (Filter((MVT::ValueType)InVTs[i]))
44 Result.push_back(InVTs[i]);
48 static std::vector<unsigned char>
49 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
50 std::vector<unsigned char> Result;
51 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
52 Result.push_back(InVTs[i]);
56 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
57 const std::vector<unsigned char> &RHS) {
58 if (LHS.size() > RHS.size()) return false;
59 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
60 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
65 /// isExtIntegerVT - Return true if the specified extended value type vector
66 /// contains isInt or an integer value type.
69 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
70 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
71 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
74 /// isExtFloatingPointVT - Return true if the specified extended value type
75 /// vector contains isFP or a FP value type.
76 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
77 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
78 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
80 } // end namespace MVT.
81 } // end namespace llvm.
83 //===----------------------------------------------------------------------===//
84 // SDTypeConstraint implementation
87 SDTypeConstraint::SDTypeConstraint(Record *R) {
88 OperandNo = R->getValueAsInt("OperandNum");
90 if (R->isSubClassOf("SDTCisVT")) {
91 ConstraintType = SDTCisVT;
92 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
93 } else if (R->isSubClassOf("SDTCisPtrTy")) {
94 ConstraintType = SDTCisPtrTy;
95 } else if (R->isSubClassOf("SDTCisInt")) {
96 ConstraintType = SDTCisInt;
97 } else if (R->isSubClassOf("SDTCisFP")) {
98 ConstraintType = SDTCisFP;
99 } else if (R->isSubClassOf("SDTCisSameAs")) {
100 ConstraintType = SDTCisSameAs;
101 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
102 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
103 ConstraintType = SDTCisVTSmallerThanOp;
104 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
105 R->getValueAsInt("OtherOperandNum");
106 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
107 ConstraintType = SDTCisOpSmallerThanOp;
108 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
109 R->getValueAsInt("BigOperandNum");
110 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
111 ConstraintType = SDTCisIntVectorOfSameSize;
112 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
113 R->getValueAsInt("OtherOpNum");
115 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
120 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
121 /// N, which has NumResults results.
122 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
124 unsigned NumResults) const {
125 assert(NumResults <= 1 &&
126 "We only work with nodes with zero or one result so far!");
128 if (OpNo >= (NumResults + N->getNumChildren())) {
129 cerr << "Invalid operand number " << OpNo << " ";
135 if (OpNo < NumResults)
136 return N; // FIXME: need value #
138 return N->getChild(OpNo-NumResults);
141 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
142 /// constraint to the nodes operands. This returns true if it makes a
143 /// change, false otherwise. If a type contradiction is found, throw an
145 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
146 const SDNodeInfo &NodeInfo,
147 TreePattern &TP) const {
148 unsigned NumResults = NodeInfo.getNumResults();
149 assert(NumResults <= 1 &&
150 "We only work with nodes with zero or one result so far!");
152 // Check that the number of operands is sane. Negative operands -> varargs.
153 if (NodeInfo.getNumOperands() >= 0) {
154 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
155 TP.error(N->getOperator()->getName() + " node requires exactly " +
156 itostr(NodeInfo.getNumOperands()) + " operands!");
159 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
161 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
163 switch (ConstraintType) {
164 default: assert(0 && "Unknown constraint type!");
166 // Operand must be a particular type.
167 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
169 // Operand must be same as target pointer type.
170 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
173 // If there is only one integer type supported, this must be it.
174 std::vector<MVT::ValueType> IntVTs =
175 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
177 // If we found exactly one supported integer type, apply it.
178 if (IntVTs.size() == 1)
179 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
180 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
183 // If there is only one FP type supported, this must be it.
184 std::vector<MVT::ValueType> FPVTs =
185 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
187 // If we found exactly one supported FP type, apply it.
188 if (FPVTs.size() == 1)
189 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
190 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
193 TreePatternNode *OtherNode =
194 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
195 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
196 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
198 case SDTCisVTSmallerThanOp: {
199 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
200 // have an integer type that is smaller than the VT.
201 if (!NodeToApply->isLeaf() ||
202 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
203 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
204 ->isSubClassOf("ValueType"))
205 TP.error(N->getOperator()->getName() + " expects a VT operand!");
207 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
208 if (!MVT::isInteger(VT))
209 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
211 TreePatternNode *OtherNode =
212 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
214 // It must be integer.
215 bool MadeChange = false;
216 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
218 // This code only handles nodes that have one type set. Assert here so
219 // that we can change this if we ever need to deal with multiple value
220 // types at this point.
221 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
222 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
223 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
226 case SDTCisOpSmallerThanOp: {
227 TreePatternNode *BigOperand =
228 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
230 // Both operands must be integer or FP, but we don't care which.
231 bool MadeChange = false;
233 // This code does not currently handle nodes which have multiple types,
234 // where some types are integer, and some are fp. Assert that this is not
236 assert(!(MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
237 MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
238 !(MVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
239 MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
240 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
241 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
242 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
243 else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
244 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
245 if (MVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
246 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
247 else if (MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
248 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
250 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
252 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
253 VTs = FilterVTs(VTs, MVT::isInteger);
254 } else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
255 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
260 switch (VTs.size()) {
261 default: // Too many VT's to pick from.
262 case 0: break; // No info yet.
264 // Only one VT of this flavor. Cannot ever satisify the constraints.
265 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
267 // If we have exactly two possible types, the little operand must be the
268 // small one, the big operand should be the big one. Common with
269 // float/double for example.
270 assert(VTs[0] < VTs[1] && "Should be sorted!");
271 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
272 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
277 case SDTCisIntVectorOfSameSize: {
278 TreePatternNode *OtherOperand =
279 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
281 if (OtherOperand->hasTypeSet()) {
282 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
283 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
284 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
285 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
286 return NodeToApply->UpdateNodeType(IVT, TP);
294 //===----------------------------------------------------------------------===//
295 // SDNodeInfo implementation
297 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
298 EnumName = R->getValueAsString("Opcode");
299 SDClassName = R->getValueAsString("SDClass");
300 Record *TypeProfile = R->getValueAsDef("TypeProfile");
301 NumResults = TypeProfile->getValueAsInt("NumResults");
302 NumOperands = TypeProfile->getValueAsInt("NumOperands");
304 // Parse the properties.
306 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
307 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
308 if (PropList[i]->getName() == "SDNPCommutative") {
309 Properties |= 1 << SDNPCommutative;
310 } else if (PropList[i]->getName() == "SDNPAssociative") {
311 Properties |= 1 << SDNPAssociative;
312 } else if (PropList[i]->getName() == "SDNPHasChain") {
313 Properties |= 1 << SDNPHasChain;
314 } else if (PropList[i]->getName() == "SDNPOutFlag") {
315 Properties |= 1 << SDNPOutFlag;
316 } else if (PropList[i]->getName() == "SDNPInFlag") {
317 Properties |= 1 << SDNPInFlag;
318 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
319 Properties |= 1 << SDNPOptInFlag;
320 } else if (PropList[i]->getName() == "SDNPMayStore") {
321 Properties |= 1 << SDNPMayStore;
322 } else if (PropList[i]->getName() == "SDNPMayLoad") {
323 Properties |= 1 << SDNPMayLoad;
325 cerr << "Unknown SD Node property '" << PropList[i]->getName()
326 << "' on node '" << R->getName() << "'!\n";
332 // Parse the type constraints.
333 std::vector<Record*> ConstraintList =
334 TypeProfile->getValueAsListOfDefs("Constraints");
335 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
338 //===----------------------------------------------------------------------===//
339 // TreePatternNode implementation
342 TreePatternNode::~TreePatternNode() {
343 #if 0 // FIXME: implement refcounted tree nodes!
344 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
349 /// UpdateNodeType - Set the node type of N to VT if VT contains
350 /// information. If N already contains a conflicting type, then throw an
351 /// exception. This returns true if any information was updated.
353 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
355 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
357 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
359 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
364 if (getExtTypeNum(0) == MVT::iPTR) {
365 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
367 if (MVT::isExtIntegerInVTs(ExtVTs)) {
368 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
376 if (ExtVTs[0] == MVT::isInt && MVT::isExtIntegerInVTs(getExtTypes())) {
377 assert(hasTypeSet() && "should be handled above!");
378 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
379 if (getExtTypes() == FVTs)
384 if (ExtVTs[0] == MVT::iPTR && MVT::isExtIntegerInVTs(getExtTypes())) {
385 //assert(hasTypeSet() && "should be handled above!");
386 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
387 if (getExtTypes() == FVTs)
394 if (ExtVTs[0] == MVT::isFP && MVT::isExtFloatingPointInVTs(getExtTypes())) {
395 assert(hasTypeSet() && "should be handled above!");
396 std::vector<unsigned char> FVTs =
397 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
398 if (getExtTypes() == FVTs)
404 // If we know this is an int or fp type, and we are told it is a specific one,
407 // Similarly, we should probably set the type here to the intersection of
408 // {isInt|isFP} and ExtVTs
409 if ((getExtTypeNum(0) == MVT::isInt && MVT::isExtIntegerInVTs(ExtVTs)) ||
410 (getExtTypeNum(0) == MVT::isFP && MVT::isExtFloatingPointInVTs(ExtVTs))){
414 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
422 TP.error("Type inference contradiction found in node!");
424 TP.error("Type inference contradiction found in node " +
425 getOperator()->getName() + "!");
427 return true; // unreachable
431 void TreePatternNode::print(std::ostream &OS) const {
433 OS << *getLeafValue();
435 OS << "(" << getOperator()->getName();
438 // FIXME: At some point we should handle printing all the value types for
439 // nodes that are multiply typed.
440 switch (getExtTypeNum(0)) {
441 case MVT::Other: OS << ":Other"; break;
442 case MVT::isInt: OS << ":isInt"; break;
443 case MVT::isFP : OS << ":isFP"; break;
444 case MVT::isUnknown: ; /*OS << ":?";*/ break;
445 case MVT::iPTR: OS << ":iPTR"; break;
447 std::string VTName = llvm::getName(getTypeNum(0));
448 // Strip off MVT:: prefix if present.
449 if (VTName.substr(0,5) == "MVT::")
450 VTName = VTName.substr(5);
457 if (getNumChildren() != 0) {
459 getChild(0)->print(OS);
460 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
462 getChild(i)->print(OS);
468 if (!PredicateFn.empty())
469 OS << "<<P:" << PredicateFn << ">>";
471 OS << "<<X:" << TransformFn->getName() << ">>";
472 if (!getName().empty())
473 OS << ":$" << getName();
476 void TreePatternNode::dump() const {
477 print(*cerr.stream());
480 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
481 /// the specified node. For this comparison, all of the state of the node
482 /// is considered, except for the assigned name. Nodes with differing names
483 /// that are otherwise identical are considered isomorphic.
484 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
485 if (N == this) return true;
486 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
487 getPredicateFn() != N->getPredicateFn() ||
488 getTransformFn() != N->getTransformFn())
492 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
493 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
494 return DI->getDef() == NDI->getDef();
495 return getLeafValue() == N->getLeafValue();
498 if (N->getOperator() != getOperator() ||
499 N->getNumChildren() != getNumChildren()) return false;
500 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
501 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
506 /// clone - Make a copy of this tree and all of its children.
508 TreePatternNode *TreePatternNode::clone() const {
509 TreePatternNode *New;
511 New = new TreePatternNode(getLeafValue());
513 std::vector<TreePatternNode*> CChildren;
514 CChildren.reserve(Children.size());
515 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
516 CChildren.push_back(getChild(i)->clone());
517 New = new TreePatternNode(getOperator(), CChildren);
519 New->setName(getName());
520 New->setTypes(getExtTypes());
521 New->setPredicateFn(getPredicateFn());
522 New->setTransformFn(getTransformFn());
526 /// SubstituteFormalArguments - Replace the formal arguments in this tree
527 /// with actual values specified by ArgMap.
528 void TreePatternNode::
529 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
530 if (isLeaf()) return;
532 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
533 TreePatternNode *Child = getChild(i);
534 if (Child->isLeaf()) {
535 Init *Val = Child->getLeafValue();
536 if (dynamic_cast<DefInit*>(Val) &&
537 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
538 // We found a use of a formal argument, replace it with its value.
539 Child = ArgMap[Child->getName()];
540 assert(Child && "Couldn't find formal argument!");
544 getChild(i)->SubstituteFormalArguments(ArgMap);
550 /// InlinePatternFragments - If this pattern refers to any pattern
551 /// fragments, inline them into place, giving us a pattern without any
552 /// PatFrag references.
553 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
554 if (isLeaf()) return this; // nothing to do.
555 Record *Op = getOperator();
557 if (!Op->isSubClassOf("PatFrag")) {
558 // Just recursively inline children nodes.
559 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
560 setChild(i, getChild(i)->InlinePatternFragments(TP));
564 // Otherwise, we found a reference to a fragment. First, look up its
565 // TreePattern record.
566 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
568 // Verify that we are passing the right number of operands.
569 if (Frag->getNumArgs() != Children.size())
570 TP.error("'" + Op->getName() + "' fragment requires " +
571 utostr(Frag->getNumArgs()) + " operands!");
573 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
575 // Resolve formal arguments to their actual value.
576 if (Frag->getNumArgs()) {
577 // Compute the map of formal to actual arguments.
578 std::map<std::string, TreePatternNode*> ArgMap;
579 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
580 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
582 FragTree->SubstituteFormalArguments(ArgMap);
585 FragTree->setName(getName());
586 FragTree->UpdateNodeType(getExtTypes(), TP);
588 // Get a new copy of this fragment to stitch into here.
589 //delete this; // FIXME: implement refcounting!
593 /// getImplicitType - Check to see if the specified record has an implicit
594 /// type which should be applied to it. This infer the type of register
595 /// references from the register file information, for example.
597 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
599 // Some common return values
600 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
601 std::vector<unsigned char> Other(1, MVT::Other);
603 // Check to see if this is a register or a register class...
604 if (R->isSubClassOf("RegisterClass")) {
607 const CodeGenRegisterClass &RC =
608 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
609 return ConvertVTs(RC.getValueTypes());
610 } else if (R->isSubClassOf("PatFrag")) {
611 // Pattern fragment types will be resolved when they are inlined.
613 } else if (R->isSubClassOf("Register")) {
616 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
617 return T.getRegisterVTs(R);
618 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
619 // Using a VTSDNode or CondCodeSDNode.
621 } else if (R->isSubClassOf("ComplexPattern")) {
624 std::vector<unsigned char>
625 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
627 } else if (R->getName() == "ptr_rc") {
628 Other[0] = MVT::iPTR;
630 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
631 R->getName() == "zero_reg") {
636 TP.error("Unknown node flavor used in pattern: " + R->getName());
641 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
642 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
643 const CodeGenIntrinsic *TreePatternNode::
644 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
645 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
646 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
647 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
651 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
652 return &CDP.getIntrinsicInfo(IID);
656 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
657 /// this node and its children in the tree. This returns true if it makes a
658 /// change, false otherwise. If a type contradiction is found, throw an
660 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
661 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
663 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
664 // If it's a regclass or something else known, include the type.
665 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
666 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
667 // Int inits are always integers. :)
668 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
671 // At some point, it may make sense for this tree pattern to have
672 // multiple types. Assert here that it does not, so we revisit this
673 // code when appropriate.
674 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
675 MVT::ValueType VT = getTypeNum(0);
676 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
677 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
680 if (VT != MVT::iPTR) {
681 unsigned Size = MVT::getSizeInBits(VT);
682 // Make sure that the value is representable for this type.
684 int Val = (II->getValue() << (32-Size)) >> (32-Size);
685 if (Val != II->getValue())
686 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
687 "' is out of range for type '" +
688 getEnumName(getTypeNum(0)) + "'!");
698 // special handling for set, which isn't really an SDNode.
699 if (getOperator()->getName() == "set") {
700 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
701 unsigned NC = getNumChildren();
702 bool MadeChange = false;
703 for (unsigned i = 0; i < NC-1; ++i) {
704 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
705 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
707 // Types of operands must match.
708 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
710 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
712 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
715 } else if (getOperator()->getName() == "implicit" ||
716 getOperator()->getName() == "parallel") {
717 bool MadeChange = false;
718 for (unsigned i = 0; i < getNumChildren(); ++i)
719 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
720 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
722 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
723 bool MadeChange = false;
725 // Apply the result type to the node.
726 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
728 if (getNumChildren() != Int->ArgVTs.size())
729 TP.error("Intrinsic '" + Int->Name + "' expects " +
730 utostr(Int->ArgVTs.size()-1) + " operands, not " +
731 utostr(getNumChildren()-1) + " operands!");
733 // Apply type info to the intrinsic ID.
734 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
736 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
737 MVT::ValueType OpVT = Int->ArgVTs[i];
738 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
739 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
742 } else if (getOperator()->isSubClassOf("SDNode")) {
743 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
745 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
746 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
747 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
748 // Branch, etc. do not produce results and top-level forms in instr pattern
749 // must have void types.
750 if (NI.getNumResults() == 0)
751 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
753 // If this is a vector_shuffle operation, apply types to the build_vector
754 // operation. The types of the integers don't matter, but this ensures they
755 // won't get checked.
756 if (getOperator()->getName() == "vector_shuffle" &&
757 getChild(2)->getOperator()->getName() == "build_vector") {
758 TreePatternNode *BV = getChild(2);
759 const std::vector<MVT::ValueType> &LegalVTs
760 = CDP.getTargetInfo().getLegalValueTypes();
761 MVT::ValueType LegalIntVT = MVT::Other;
762 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
763 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
764 LegalIntVT = LegalVTs[i];
767 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
769 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
770 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
773 } else if (getOperator()->isSubClassOf("Instruction")) {
774 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
775 bool MadeChange = false;
776 unsigned NumResults = Inst.getNumResults();
778 assert(NumResults <= 1 &&
779 "Only supports zero or one result instrs!");
781 CodeGenInstruction &InstInfo =
782 CDP.getTargetInfo().getInstruction(getOperator()->getName());
783 // Apply the result type to the node
784 if (NumResults == 0 || InstInfo.NumDefs == 0) {
785 MadeChange = UpdateNodeType(MVT::isVoid, TP);
787 Record *ResultNode = Inst.getResult(0);
789 if (ResultNode->getName() == "ptr_rc") {
790 std::vector<unsigned char> VT;
791 VT.push_back(MVT::iPTR);
792 MadeChange = UpdateNodeType(VT, TP);
794 assert(ResultNode->isSubClassOf("RegisterClass") &&
795 "Operands should be register classes!");
797 const CodeGenRegisterClass &RC =
798 CDP.getTargetInfo().getRegisterClass(ResultNode);
799 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
803 unsigned ChildNo = 0;
804 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
805 Record *OperandNode = Inst.getOperand(i);
807 // If the instruction expects a predicate or optional def operand, we
808 // codegen this by setting the operand to it's default value if it has a
809 // non-empty DefaultOps field.
810 if ((OperandNode->isSubClassOf("PredicateOperand") ||
811 OperandNode->isSubClassOf("OptionalDefOperand")) &&
812 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
815 // Verify that we didn't run out of provided operands.
816 if (ChildNo >= getNumChildren())
817 TP.error("Instruction '" + getOperator()->getName() +
818 "' expects more operands than were provided.");
821 TreePatternNode *Child = getChild(ChildNo++);
822 if (OperandNode->isSubClassOf("RegisterClass")) {
823 const CodeGenRegisterClass &RC =
824 CDP.getTargetInfo().getRegisterClass(OperandNode);
825 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
826 } else if (OperandNode->isSubClassOf("Operand")) {
827 VT = getValueType(OperandNode->getValueAsDef("Type"));
828 MadeChange |= Child->UpdateNodeType(VT, TP);
829 } else if (OperandNode->getName() == "ptr_rc") {
830 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
832 assert(0 && "Unknown operand type!");
835 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
838 if (ChildNo != getNumChildren())
839 TP.error("Instruction '" + getOperator()->getName() +
840 "' was provided too many operands!");
844 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
846 // Node transforms always take one operand.
847 if (getNumChildren() != 1)
848 TP.error("Node transform '" + getOperator()->getName() +
849 "' requires one operand!");
851 // If either the output or input of the xform does not have exact
852 // type info. We assume they must be the same. Otherwise, it is perfectly
853 // legal to transform from one type to a completely different type.
854 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
855 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
856 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
863 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
864 /// RHS of a commutative operation, not the on LHS.
865 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
866 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
868 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
874 /// canPatternMatch - If it is impossible for this pattern to match on this
875 /// target, fill in Reason and return false. Otherwise, return true. This is
876 /// used as a santity check for .td files (to prevent people from writing stuff
877 /// that can never possibly work), and to prevent the pattern permuter from
878 /// generating stuff that is useless.
879 bool TreePatternNode::canPatternMatch(std::string &Reason,
880 CodeGenDAGPatterns &CDP){
881 if (isLeaf()) return true;
883 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
884 if (!getChild(i)->canPatternMatch(Reason, CDP))
887 // If this is an intrinsic, handle cases that would make it not match. For
888 // example, if an operand is required to be an immediate.
889 if (getOperator()->isSubClassOf("Intrinsic")) {
894 // If this node is a commutative operator, check that the LHS isn't an
896 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
897 if (NodeInfo.hasProperty(SDNPCommutative)) {
898 // Scan all of the operands of the node and make sure that only the last one
899 // is a constant node, unless the RHS also is.
900 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
901 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
902 if (OnlyOnRHSOfCommutative(getChild(i))) {
903 Reason="Immediate value must be on the RHS of commutative operators!";
912 //===----------------------------------------------------------------------===//
913 // TreePattern implementation
916 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
917 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
918 isInputPattern = isInput;
919 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
920 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
923 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
924 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
925 isInputPattern = isInput;
926 Trees.push_back(ParseTreePattern(Pat));
929 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
930 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
931 isInputPattern = isInput;
932 Trees.push_back(Pat);
937 void TreePattern::error(const std::string &Msg) const {
939 throw "In " + TheRecord->getName() + ": " + Msg;
942 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
943 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
944 if (!OpDef) error("Pattern has unexpected operator type!");
945 Record *Operator = OpDef->getDef();
947 if (Operator->isSubClassOf("ValueType")) {
948 // If the operator is a ValueType, then this must be "type cast" of a leaf
950 if (Dag->getNumArgs() != 1)
951 error("Type cast only takes one operand!");
953 Init *Arg = Dag->getArg(0);
954 TreePatternNode *New;
955 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
956 Record *R = DI->getDef();
957 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
958 Dag->setArg(0, new DagInit(DI,
959 std::vector<std::pair<Init*, std::string> >()));
960 return ParseTreePattern(Dag);
962 New = new TreePatternNode(DI);
963 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
964 New = ParseTreePattern(DI);
965 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
966 New = new TreePatternNode(II);
967 if (!Dag->getArgName(0).empty())
968 error("Constant int argument should not have a name!");
969 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
970 // Turn this into an IntInit.
971 Init *II = BI->convertInitializerTo(new IntRecTy());
972 if (II == 0 || !dynamic_cast<IntInit*>(II))
973 error("Bits value must be constants!");
975 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
976 if (!Dag->getArgName(0).empty())
977 error("Constant int argument should not have a name!");
980 error("Unknown leaf value for tree pattern!");
984 // Apply the type cast.
985 New->UpdateNodeType(getValueType(Operator), *this);
986 New->setName(Dag->getArgName(0));
990 // Verify that this is something that makes sense for an operator.
991 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
992 !Operator->isSubClassOf("Instruction") &&
993 !Operator->isSubClassOf("SDNodeXForm") &&
994 !Operator->isSubClassOf("Intrinsic") &&
995 Operator->getName() != "set" &&
996 Operator->getName() != "implicit" &&
997 Operator->getName() != "parallel")
998 error("Unrecognized node '" + Operator->getName() + "'!");
1000 // Check to see if this is something that is illegal in an input pattern.
1001 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1002 Operator->isSubClassOf("SDNodeXForm")))
1003 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1005 std::vector<TreePatternNode*> Children;
1007 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1008 Init *Arg = Dag->getArg(i);
1009 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1010 Children.push_back(ParseTreePattern(DI));
1011 if (Children.back()->getName().empty())
1012 Children.back()->setName(Dag->getArgName(i));
1013 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1014 Record *R = DefI->getDef();
1015 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1016 // TreePatternNode if its own.
1017 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1018 Dag->setArg(i, new DagInit(DefI,
1019 std::vector<std::pair<Init*, std::string> >()));
1020 --i; // Revisit this node...
1022 TreePatternNode *Node = new TreePatternNode(DefI);
1023 Node->setName(Dag->getArgName(i));
1024 Children.push_back(Node);
1027 if (R->getName() == "node") {
1028 if (Dag->getArgName(i).empty())
1029 error("'node' argument requires a name to match with operand list");
1030 Args.push_back(Dag->getArgName(i));
1033 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1034 TreePatternNode *Node = new TreePatternNode(II);
1035 if (!Dag->getArgName(i).empty())
1036 error("Constant int argument should not have a name!");
1037 Children.push_back(Node);
1038 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1039 // Turn this into an IntInit.
1040 Init *II = BI->convertInitializerTo(new IntRecTy());
1041 if (II == 0 || !dynamic_cast<IntInit*>(II))
1042 error("Bits value must be constants!");
1044 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1045 if (!Dag->getArgName(i).empty())
1046 error("Constant int argument should not have a name!");
1047 Children.push_back(Node);
1052 error("Unknown leaf value for tree pattern!");
1056 // If the operator is an intrinsic, then this is just syntactic sugar for for
1057 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1058 // convert the intrinsic name to a number.
1059 if (Operator->isSubClassOf("Intrinsic")) {
1060 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1061 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1063 // If this intrinsic returns void, it must have side-effects and thus a
1065 if (Int.ArgVTs[0] == MVT::isVoid) {
1066 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1067 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1068 // Has side-effects, requires chain.
1069 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1071 // Otherwise, no chain.
1072 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1075 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1076 Children.insert(Children.begin(), IIDNode);
1079 return new TreePatternNode(Operator, Children);
1082 /// InferAllTypes - Infer/propagate as many types throughout the expression
1083 /// patterns as possible. Return true if all types are infered, false
1084 /// otherwise. Throw an exception if a type contradiction is found.
1085 bool TreePattern::InferAllTypes() {
1086 bool MadeChange = true;
1087 while (MadeChange) {
1089 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1090 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1093 bool HasUnresolvedTypes = false;
1094 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1095 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1096 return !HasUnresolvedTypes;
1099 void TreePattern::print(std::ostream &OS) const {
1100 OS << getRecord()->getName();
1101 if (!Args.empty()) {
1102 OS << "(" << Args[0];
1103 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1104 OS << ", " << Args[i];
1109 if (Trees.size() > 1)
1111 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1113 Trees[i]->print(OS);
1117 if (Trees.size() > 1)
1121 void TreePattern::dump() const { print(*cerr.stream()); }
1123 //===----------------------------------------------------------------------===//
1124 // CodeGenDAGPatterns implementation
1127 // FIXME: REMOVE OSTREAM ARGUMENT
1128 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1129 Intrinsics = LoadIntrinsics(Records);
1131 ParseNodeTransforms();
1132 ParseComplexPatterns();
1133 ParsePatternFragments();
1134 ParseDefaultOperands();
1135 ParseInstructions();
1138 // Generate variants. For example, commutative patterns can match
1139 // multiple ways. Add them to PatternsToMatch as well.
1143 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1144 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1145 E = PatternFragments.end(); I != E; ++I)
1150 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1151 Record *N = Records.getDef(Name);
1152 if (!N || !N->isSubClassOf("SDNode")) {
1153 cerr << "Error getting SDNode '" << Name << "'!\n";
1159 // Parse all of the SDNode definitions for the target, populating SDNodes.
1160 void CodeGenDAGPatterns::ParseNodeInfo() {
1161 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1162 while (!Nodes.empty()) {
1163 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1167 // Get the buildin intrinsic nodes.
1168 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1169 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1170 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1173 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1174 /// map, and emit them to the file as functions.
1175 void CodeGenDAGPatterns::ParseNodeTransforms() {
1176 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1177 while (!Xforms.empty()) {
1178 Record *XFormNode = Xforms.back();
1179 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1180 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1181 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1187 void CodeGenDAGPatterns::ParseComplexPatterns() {
1188 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1189 while (!AMs.empty()) {
1190 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1196 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1197 /// file, building up the PatternFragments map. After we've collected them all,
1198 /// inline fragments together as necessary, so that there are no references left
1199 /// inside a pattern fragment to a pattern fragment.
1201 void CodeGenDAGPatterns::ParsePatternFragments() {
1202 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1204 // First step, parse all of the fragments.
1205 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1206 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1207 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1208 PatternFragments[Fragments[i]] = P;
1210 // Validate the argument list, converting it to set, to discard duplicates.
1211 std::vector<std::string> &Args = P->getArgList();
1212 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1214 if (OperandsSet.count(""))
1215 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1217 // Parse the operands list.
1218 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1219 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1220 // Special cases: ops == outs == ins. Different names are used to
1221 // improve readibility.
1223 (OpsOp->getDef()->getName() != "ops" &&
1224 OpsOp->getDef()->getName() != "outs" &&
1225 OpsOp->getDef()->getName() != "ins"))
1226 P->error("Operands list should start with '(ops ... '!");
1228 // Copy over the arguments.
1230 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1231 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1232 static_cast<DefInit*>(OpsList->getArg(j))->
1233 getDef()->getName() != "node")
1234 P->error("Operands list should all be 'node' values.");
1235 if (OpsList->getArgName(j).empty())
1236 P->error("Operands list should have names for each operand!");
1237 if (!OperandsSet.count(OpsList->getArgName(j)))
1238 P->error("'" + OpsList->getArgName(j) +
1239 "' does not occur in pattern or was multiply specified!");
1240 OperandsSet.erase(OpsList->getArgName(j));
1241 Args.push_back(OpsList->getArgName(j));
1244 if (!OperandsSet.empty())
1245 P->error("Operands list does not contain an entry for operand '" +
1246 *OperandsSet.begin() + "'!");
1248 // If there is a code init for this fragment, keep track of the fact that
1249 // this fragment uses it.
1250 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1252 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1254 // If there is a node transformation corresponding to this, keep track of
1256 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1257 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1258 P->getOnlyTree()->setTransformFn(Transform);
1261 // Now that we've parsed all of the tree fragments, do a closure on them so
1262 // that there are not references to PatFrags left inside of them.
1263 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1264 E = PatternFragments.end(); I != E; ++I) {
1265 TreePattern *ThePat = I->second;
1266 ThePat->InlinePatternFragments();
1268 // Infer as many types as possible. Don't worry about it if we don't infer
1269 // all of them, some may depend on the inputs of the pattern.
1271 ThePat->InferAllTypes();
1273 // If this pattern fragment is not supported by this target (no types can
1274 // satisfy its constraints), just ignore it. If the bogus pattern is
1275 // actually used by instructions, the type consistency error will be
1279 // If debugging, print out the pattern fragment result.
1280 DEBUG(ThePat->dump());
1284 void CodeGenDAGPatterns::ParseDefaultOperands() {
1285 std::vector<Record*> DefaultOps[2];
1286 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1287 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1289 // Find some SDNode.
1290 assert(!SDNodes.empty() && "No SDNodes parsed?");
1291 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1293 for (unsigned iter = 0; iter != 2; ++iter) {
1294 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1295 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1297 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1298 // SomeSDnode so that we can parse this.
1299 std::vector<std::pair<Init*, std::string> > Ops;
1300 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1301 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1302 DefaultInfo->getArgName(op)));
1303 DagInit *DI = new DagInit(SomeSDNode, Ops);
1305 // Create a TreePattern to parse this.
1306 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1307 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1309 // Copy the operands over into a DAGDefaultOperand.
1310 DAGDefaultOperand DefaultOpInfo;
1312 TreePatternNode *T = P.getTree(0);
1313 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1314 TreePatternNode *TPN = T->getChild(op);
1315 while (TPN->ApplyTypeConstraints(P, false))
1316 /* Resolve all types */;
1318 if (TPN->ContainsUnresolvedType())
1320 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1321 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1323 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1324 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1326 DefaultOpInfo.DefaultOps.push_back(TPN);
1329 // Insert it into the DefaultOperands map so we can find it later.
1330 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1335 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1336 /// instruction input. Return true if this is a real use.
1337 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1338 std::map<std::string, TreePatternNode*> &InstInputs,
1339 std::vector<Record*> &InstImpInputs) {
1340 // No name -> not interesting.
1341 if (Pat->getName().empty()) {
1342 if (Pat->isLeaf()) {
1343 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1344 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1345 I->error("Input " + DI->getDef()->getName() + " must be named!");
1346 else if (DI && DI->getDef()->isSubClassOf("Register"))
1347 InstImpInputs.push_back(DI->getDef());
1354 if (Pat->isLeaf()) {
1355 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1356 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1359 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1360 Rec = Pat->getOperator();
1363 // SRCVALUE nodes are ignored.
1364 if (Rec->getName() == "srcvalue")
1367 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1372 if (Slot->isLeaf()) {
1373 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1375 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1376 SlotRec = Slot->getOperator();
1379 // Ensure that the inputs agree if we've already seen this input.
1381 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1382 if (Slot->getExtTypes() != Pat->getExtTypes())
1383 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1388 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1389 /// part of "I", the instruction), computing the set of inputs and outputs of
1390 /// the pattern. Report errors if we see anything naughty.
1391 void CodeGenDAGPatterns::
1392 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1393 std::map<std::string, TreePatternNode*> &InstInputs,
1394 std::map<std::string, TreePatternNode*>&InstResults,
1395 std::vector<Record*> &InstImpInputs,
1396 std::vector<Record*> &InstImpResults) {
1397 if (Pat->isLeaf()) {
1398 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1399 if (!isUse && Pat->getTransformFn())
1400 I->error("Cannot specify a transform function for a non-input value!");
1402 } else if (Pat->getOperator()->getName() == "implicit") {
1403 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1404 TreePatternNode *Dest = Pat->getChild(i);
1405 if (!Dest->isLeaf())
1406 I->error("implicitly defined value should be a register!");
1408 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1409 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1410 I->error("implicitly defined value should be a register!");
1411 InstImpResults.push_back(Val->getDef());
1414 } else if (Pat->getOperator()->getName() != "set") {
1415 // If this is not a set, verify that the children nodes are not void typed,
1417 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1418 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1419 I->error("Cannot have void nodes inside of patterns!");
1420 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1421 InstImpInputs, InstImpResults);
1424 // If this is a non-leaf node with no children, treat it basically as if
1425 // it were a leaf. This handles nodes like (imm).
1427 if (Pat->getNumChildren() == 0)
1428 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1430 if (!isUse && Pat->getTransformFn())
1431 I->error("Cannot specify a transform function for a non-input value!");
1435 // Otherwise, this is a set, validate and collect instruction results.
1436 if (Pat->getNumChildren() == 0)
1437 I->error("set requires operands!");
1439 if (Pat->getTransformFn())
1440 I->error("Cannot specify a transform function on a set node!");
1442 // Check the set destinations.
1443 unsigned NumDests = Pat->getNumChildren()-1;
1444 for (unsigned i = 0; i != NumDests; ++i) {
1445 TreePatternNode *Dest = Pat->getChild(i);
1446 if (!Dest->isLeaf())
1447 I->error("set destination should be a register!");
1449 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1451 I->error("set destination should be a register!");
1453 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1454 Val->getDef()->getName() == "ptr_rc") {
1455 if (Dest->getName().empty())
1456 I->error("set destination must have a name!");
1457 if (InstResults.count(Dest->getName()))
1458 I->error("cannot set '" + Dest->getName() +"' multiple times");
1459 InstResults[Dest->getName()] = Dest;
1460 } else if (Val->getDef()->isSubClassOf("Register")) {
1461 InstImpResults.push_back(Val->getDef());
1463 I->error("set destination should be a register!");
1467 // Verify and collect info from the computation.
1468 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1469 InstInputs, InstResults,
1470 InstImpInputs, InstImpResults);
1473 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1474 /// any fragments involved. This populates the Instructions list with fully
1475 /// resolved instructions.
1476 void CodeGenDAGPatterns::ParseInstructions() {
1477 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1479 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1482 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1483 LI = Instrs[i]->getValueAsListInit("Pattern");
1485 // If there is no pattern, only collect minimal information about the
1486 // instruction for its operand list. We have to assume that there is one
1487 // result, as we have no detailed info.
1488 if (!LI || LI->getSize() == 0) {
1489 std::vector<Record*> Results;
1490 std::vector<Record*> Operands;
1492 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1494 if (InstInfo.OperandList.size() != 0) {
1495 if (InstInfo.NumDefs == 0) {
1496 // These produce no results
1497 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1498 Operands.push_back(InstInfo.OperandList[j].Rec);
1500 // Assume the first operand is the result.
1501 Results.push_back(InstInfo.OperandList[0].Rec);
1503 // The rest are inputs.
1504 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1505 Operands.push_back(InstInfo.OperandList[j].Rec);
1509 // Create and insert the instruction.
1510 std::vector<Record*> ImpResults;
1511 std::vector<Record*> ImpOperands;
1512 Instructions.insert(std::make_pair(Instrs[i],
1513 DAGInstruction(0, Results, Operands, ImpResults,
1515 continue; // no pattern.
1518 // Parse the instruction.
1519 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1520 // Inline pattern fragments into it.
1521 I->InlinePatternFragments();
1523 // Infer as many types as possible. If we cannot infer all of them, we can
1524 // never do anything with this instruction pattern: report it to the user.
1525 if (!I->InferAllTypes())
1526 I->error("Could not infer all types in pattern!");
1528 // InstInputs - Keep track of all of the inputs of the instruction, along
1529 // with the record they are declared as.
1530 std::map<std::string, TreePatternNode*> InstInputs;
1532 // InstResults - Keep track of all the virtual registers that are 'set'
1533 // in the instruction, including what reg class they are.
1534 std::map<std::string, TreePatternNode*> InstResults;
1536 std::vector<Record*> InstImpInputs;
1537 std::vector<Record*> InstImpResults;
1539 // Verify that the top-level forms in the instruction are of void type, and
1540 // fill in the InstResults map.
1541 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1542 TreePatternNode *Pat = I->getTree(j);
1543 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1544 I->error("Top-level forms in instruction pattern should have"
1547 // Find inputs and outputs, and verify the structure of the uses/defs.
1548 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1549 InstImpInputs, InstImpResults);
1552 // Now that we have inputs and outputs of the pattern, inspect the operands
1553 // list for the instruction. This determines the order that operands are
1554 // added to the machine instruction the node corresponds to.
1555 unsigned NumResults = InstResults.size();
1557 // Parse the operands list from the (ops) list, validating it.
1558 assert(I->getArgList().empty() && "Args list should still be empty here!");
1559 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1561 // Check that all of the results occur first in the list.
1562 std::vector<Record*> Results;
1563 TreePatternNode *Res0Node = NULL;
1564 for (unsigned i = 0; i != NumResults; ++i) {
1565 if (i == CGI.OperandList.size())
1566 I->error("'" + InstResults.begin()->first +
1567 "' set but does not appear in operand list!");
1568 const std::string &OpName = CGI.OperandList[i].Name;
1570 // Check that it exists in InstResults.
1571 TreePatternNode *RNode = InstResults[OpName];
1573 I->error("Operand $" + OpName + " does not exist in operand list!");
1577 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1579 I->error("Operand $" + OpName + " should be a set destination: all "
1580 "outputs must occur before inputs in operand list!");
1582 if (CGI.OperandList[i].Rec != R)
1583 I->error("Operand $" + OpName + " class mismatch!");
1585 // Remember the return type.
1586 Results.push_back(CGI.OperandList[i].Rec);
1588 // Okay, this one checks out.
1589 InstResults.erase(OpName);
1592 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1593 // the copy while we're checking the inputs.
1594 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1596 std::vector<TreePatternNode*> ResultNodeOperands;
1597 std::vector<Record*> Operands;
1598 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1599 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1600 const std::string &OpName = Op.Name;
1602 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1604 if (!InstInputsCheck.count(OpName)) {
1605 // If this is an predicate operand or optional def operand with an
1606 // DefaultOps set filled in, we can ignore this. When we codegen it,
1607 // we will do so as always executed.
1608 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1609 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1610 // Does it have a non-empty DefaultOps field? If so, ignore this
1612 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1615 I->error("Operand $" + OpName +
1616 " does not appear in the instruction pattern");
1618 TreePatternNode *InVal = InstInputsCheck[OpName];
1619 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1621 if (InVal->isLeaf() &&
1622 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1623 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1624 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1625 I->error("Operand $" + OpName + "'s register class disagrees"
1626 " between the operand and pattern");
1628 Operands.push_back(Op.Rec);
1630 // Construct the result for the dest-pattern operand list.
1631 TreePatternNode *OpNode = InVal->clone();
1633 // No predicate is useful on the result.
1634 OpNode->setPredicateFn("");
1636 // Promote the xform function to be an explicit node if set.
1637 if (Record *Xform = OpNode->getTransformFn()) {
1638 OpNode->setTransformFn(0);
1639 std::vector<TreePatternNode*> Children;
1640 Children.push_back(OpNode);
1641 OpNode = new TreePatternNode(Xform, Children);
1644 ResultNodeOperands.push_back(OpNode);
1647 if (!InstInputsCheck.empty())
1648 I->error("Input operand $" + InstInputsCheck.begin()->first +
1649 " occurs in pattern but not in operands list!");
1651 TreePatternNode *ResultPattern =
1652 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1653 // Copy fully inferred output node type to instruction result pattern.
1655 ResultPattern->setTypes(Res0Node->getExtTypes());
1657 // Create and insert the instruction.
1658 // FIXME: InstImpResults and InstImpInputs should not be part of
1660 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1661 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1663 // Use a temporary tree pattern to infer all types and make sure that the
1664 // constructed result is correct. This depends on the instruction already
1665 // being inserted into the Instructions map.
1666 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1667 Temp.InferAllTypes();
1669 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1670 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1675 // If we can, convert the instructions to be patterns that are matched!
1676 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1677 E = Instructions.end(); II != E; ++II) {
1678 DAGInstruction &TheInst = II->second;
1679 const TreePattern *I = TheInst.getPattern();
1680 if (I == 0) continue; // No pattern.
1682 // FIXME: Assume only the first tree is the pattern. The others are clobber
1684 TreePatternNode *Pattern = I->getTree(0);
1685 TreePatternNode *SrcPattern;
1686 if (Pattern->getOperator()->getName() == "set") {
1687 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1689 // Not a set (store or something?)
1690 SrcPattern = Pattern;
1694 if (!SrcPattern->canPatternMatch(Reason, *this))
1695 I->error("Instruction can never match: " + Reason);
1697 Record *Instr = II->first;
1698 TreePatternNode *DstPattern = TheInst.getResultPattern();
1700 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1701 SrcPattern, DstPattern, TheInst.getImpResults(),
1702 Instr->getValueAsInt("AddedComplexity")));
1706 void CodeGenDAGPatterns::ParsePatterns() {
1707 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1709 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1710 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1711 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1712 Record *Operator = OpDef->getDef();
1713 TreePattern *Pattern;
1714 if (Operator->getName() != "parallel")
1715 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1717 std::vector<Init*> Values;
1718 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1719 Values.push_back(Tree->getArg(j));
1720 ListInit *LI = new ListInit(Values);
1721 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1724 // Inline pattern fragments into it.
1725 Pattern->InlinePatternFragments();
1727 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1728 if (LI->getSize() == 0) continue; // no pattern.
1730 // Parse the instruction.
1731 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1733 // Inline pattern fragments into it.
1734 Result->InlinePatternFragments();
1736 if (Result->getNumTrees() != 1)
1737 Result->error("Cannot handle instructions producing instructions "
1738 "with temporaries yet!");
1740 bool IterateInference;
1741 bool InferredAllPatternTypes, InferredAllResultTypes;
1743 // Infer as many types as possible. If we cannot infer all of them, we
1744 // can never do anything with this pattern: report it to the user.
1745 InferredAllPatternTypes = Pattern->InferAllTypes();
1747 // Infer as many types as possible. If we cannot infer all of them, we
1748 // can never do anything with this pattern: report it to the user.
1749 InferredAllResultTypes = Result->InferAllTypes();
1751 // Apply the type of the result to the source pattern. This helps us
1752 // resolve cases where the input type is known to be a pointer type (which
1753 // is considered resolved), but the result knows it needs to be 32- or
1754 // 64-bits. Infer the other way for good measure.
1755 IterateInference = Pattern->getTree(0)->
1756 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
1757 IterateInference |= Result->getTree(0)->
1758 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
1759 } while (IterateInference);
1761 // Verify that we inferred enough types that we can do something with the
1762 // pattern and result. If these fire the user has to add type casts.
1763 if (!InferredAllPatternTypes)
1764 Pattern->error("Could not infer all types in pattern!");
1765 if (!InferredAllResultTypes)
1766 Result->error("Could not infer all types in pattern result!");
1768 // Validate that the input pattern is correct.
1769 std::map<std::string, TreePatternNode*> InstInputs;
1770 std::map<std::string, TreePatternNode*> InstResults;
1771 std::vector<Record*> InstImpInputs;
1772 std::vector<Record*> InstImpResults;
1773 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
1774 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
1775 InstInputs, InstResults,
1776 InstImpInputs, InstImpResults);
1778 // Promote the xform function to be an explicit node if set.
1779 TreePatternNode *DstPattern = Result->getOnlyTree();
1780 std::vector<TreePatternNode*> ResultNodeOperands;
1781 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1782 TreePatternNode *OpNode = DstPattern->getChild(ii);
1783 if (Record *Xform = OpNode->getTransformFn()) {
1784 OpNode->setTransformFn(0);
1785 std::vector<TreePatternNode*> Children;
1786 Children.push_back(OpNode);
1787 OpNode = new TreePatternNode(Xform, Children);
1789 ResultNodeOperands.push_back(OpNode);
1791 DstPattern = Result->getOnlyTree();
1792 if (!DstPattern->isLeaf())
1793 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1794 ResultNodeOperands);
1795 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1796 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1797 Temp.InferAllTypes();
1800 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
1801 Pattern->error("Pattern can never match: " + Reason);
1804 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1805 Pattern->getTree(0),
1806 Temp.getOnlyTree(), InstImpResults,
1807 Patterns[i]->getValueAsInt("AddedComplexity")));
1811 /// CombineChildVariants - Given a bunch of permutations of each child of the
1812 /// 'operator' node, put them together in all possible ways.
1813 static void CombineChildVariants(TreePatternNode *Orig,
1814 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1815 std::vector<TreePatternNode*> &OutVariants,
1816 CodeGenDAGPatterns &CDP) {
1817 // Make sure that each operand has at least one variant to choose from.
1818 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1819 if (ChildVariants[i].empty())
1822 // The end result is an all-pairs construction of the resultant pattern.
1823 std::vector<unsigned> Idxs;
1824 Idxs.resize(ChildVariants.size());
1825 bool NotDone = true;
1827 // Create the variant and add it to the output list.
1828 std::vector<TreePatternNode*> NewChildren;
1829 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1830 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1831 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1833 // Copy over properties.
1834 R->setName(Orig->getName());
1835 R->setPredicateFn(Orig->getPredicateFn());
1836 R->setTransformFn(Orig->getTransformFn());
1837 R->setTypes(Orig->getExtTypes());
1839 // If this pattern cannot every match, do not include it as a variant.
1840 std::string ErrString;
1841 if (!R->canPatternMatch(ErrString, CDP)) {
1844 bool AlreadyExists = false;
1846 // Scan to see if this pattern has already been emitted. We can get
1847 // duplication due to things like commuting:
1848 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1849 // which are the same pattern. Ignore the dups.
1850 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1851 if (R->isIsomorphicTo(OutVariants[i])) {
1852 AlreadyExists = true;
1859 OutVariants.push_back(R);
1862 // Increment indices to the next permutation.
1864 // Look for something we can increment without causing a wrap-around.
1865 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1866 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1867 NotDone = true; // Found something to increment.
1875 /// CombineChildVariants - A helper function for binary operators.
1877 static void CombineChildVariants(TreePatternNode *Orig,
1878 const std::vector<TreePatternNode*> &LHS,
1879 const std::vector<TreePatternNode*> &RHS,
1880 std::vector<TreePatternNode*> &OutVariants,
1881 CodeGenDAGPatterns &CDP) {
1882 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1883 ChildVariants.push_back(LHS);
1884 ChildVariants.push_back(RHS);
1885 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP);
1889 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1890 std::vector<TreePatternNode *> &Children) {
1891 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1892 Record *Operator = N->getOperator();
1894 // Only permit raw nodes.
1895 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1896 N->getTransformFn()) {
1897 Children.push_back(N);
1901 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1902 Children.push_back(N->getChild(0));
1904 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1906 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1907 Children.push_back(N->getChild(1));
1909 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1912 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1913 /// the (potentially recursive) pattern by using algebraic laws.
1915 static void GenerateVariantsOf(TreePatternNode *N,
1916 std::vector<TreePatternNode*> &OutVariants,
1917 CodeGenDAGPatterns &CDP) {
1918 // We cannot permute leaves.
1920 OutVariants.push_back(N);
1924 // Look up interesting info about the node.
1925 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
1927 // If this node is associative, reassociate.
1928 if (NodeInfo.hasProperty(SDNPAssociative)) {
1929 // Reassociate by pulling together all of the linked operators
1930 std::vector<TreePatternNode*> MaximalChildren;
1931 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1933 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1935 if (MaximalChildren.size() == 3) {
1936 // Find the variants of all of our maximal children.
1937 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1938 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP);
1939 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP);
1940 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP);
1942 // There are only two ways we can permute the tree:
1943 // (A op B) op C and A op (B op C)
1944 // Within these forms, we can also permute A/B/C.
1946 // Generate legal pair permutations of A/B/C.
1947 std::vector<TreePatternNode*> ABVariants;
1948 std::vector<TreePatternNode*> BAVariants;
1949 std::vector<TreePatternNode*> ACVariants;
1950 std::vector<TreePatternNode*> CAVariants;
1951 std::vector<TreePatternNode*> BCVariants;
1952 std::vector<TreePatternNode*> CBVariants;
1953 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP);
1954 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP);
1955 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP);
1956 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP);
1957 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP);
1958 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP);
1960 // Combine those into the result: (x op x) op x
1961 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP);
1962 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP);
1963 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP);
1964 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP);
1965 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP);
1966 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP);
1968 // Combine those into the result: x op (x op x)
1969 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP);
1970 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP);
1971 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP);
1972 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP);
1973 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP);
1974 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP);
1979 // Compute permutations of all children.
1980 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1981 ChildVariants.resize(N->getNumChildren());
1982 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1983 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP);
1985 // Build all permutations based on how the children were formed.
1986 CombineChildVariants(N, ChildVariants, OutVariants, CDP);
1988 // If this node is commutative, consider the commuted order.
1989 if (NodeInfo.hasProperty(SDNPCommutative)) {
1990 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1991 // Don't count children which are actually register references.
1993 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1994 TreePatternNode *Child = N->getChild(i);
1995 if (Child->isLeaf())
1996 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1997 Record *RR = DI->getDef();
1998 if (RR->isSubClassOf("Register"))
2003 // Consider the commuted order.
2005 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2011 // GenerateVariants - Generate variants. For example, commutative patterns can
2012 // match multiple ways. Add them to PatternsToMatch as well.
2013 void CodeGenDAGPatterns::GenerateVariants() {
2014 DOUT << "Generating instruction variants.\n";
2016 // Loop over all of the patterns we've collected, checking to see if we can
2017 // generate variants of the instruction, through the exploitation of
2018 // identities. This permits the target to provide agressive matching without
2019 // the .td file having to contain tons of variants of instructions.
2021 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2022 // intentionally do not reconsider these. Any variants of added patterns have
2023 // already been added.
2025 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2026 std::vector<TreePatternNode*> Variants;
2027 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
2029 assert(!Variants.empty() && "Must create at least original variant!");
2030 Variants.erase(Variants.begin()); // Remove the original pattern.
2032 if (Variants.empty()) // No variants for this pattern.
2035 DOUT << "FOUND VARIANTS OF: ";
2036 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2039 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2040 TreePatternNode *Variant = Variants[v];
2042 DOUT << " VAR#" << v << ": ";
2043 DEBUG(Variant->dump());
2046 // Scan to see if an instruction or explicit pattern already matches this.
2047 bool AlreadyExists = false;
2048 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2049 // Check to see if this variant already exists.
2050 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
2051 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2052 AlreadyExists = true;
2056 // If we already have it, ignore the variant.
2057 if (AlreadyExists) continue;
2059 // Otherwise, add it to the list of patterns we have.
2061 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2062 Variant, PatternsToMatch[i].getDstPattern(),
2063 PatternsToMatch[i].getDstRegs(),
2064 PatternsToMatch[i].getAddedComplexity()));