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/MathExtras.h"
20 #include "llvm/Support/Streams.h"
21 //#include <algorithm>
25 //===----------------------------------------------------------------------===//
26 // Helpers for working with extended types.
28 /// FilterVTs - Filter a list of VT's according to a predicate.
31 static std::vector<MVT::ValueType>
32 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
33 std::vector<MVT::ValueType> Result;
34 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
36 Result.push_back(InVTs[i]);
41 static std::vector<unsigned char>
42 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
43 std::vector<unsigned char> Result;
44 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
45 if (Filter((MVT::ValueType)InVTs[i]))
46 Result.push_back(InVTs[i]);
50 static std::vector<unsigned char>
51 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
52 std::vector<unsigned char> Result;
53 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
54 Result.push_back(InVTs[i]);
58 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
59 const std::vector<unsigned char> &RHS) {
60 if (LHS.size() > RHS.size()) return false;
61 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
62 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
67 /// isExtIntegerVT - Return true if the specified extended value type vector
68 /// contains isInt or an integer value type.
71 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
72 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
73 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
76 /// isExtFloatingPointVT - Return true if the specified extended value type
77 /// vector contains isFP or a FP value type.
78 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
79 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
80 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
82 } // end namespace MVT.
83 } // end namespace llvm.
85 //===----------------------------------------------------------------------===//
86 // SDTypeConstraint implementation
89 SDTypeConstraint::SDTypeConstraint(Record *R) {
90 OperandNo = R->getValueAsInt("OperandNum");
92 if (R->isSubClassOf("SDTCisVT")) {
93 ConstraintType = SDTCisVT;
94 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
95 } else if (R->isSubClassOf("SDTCisPtrTy")) {
96 ConstraintType = SDTCisPtrTy;
97 } else if (R->isSubClassOf("SDTCisInt")) {
98 ConstraintType = SDTCisInt;
99 } else if (R->isSubClassOf("SDTCisFP")) {
100 ConstraintType = SDTCisFP;
101 } else if (R->isSubClassOf("SDTCisSameAs")) {
102 ConstraintType = SDTCisSameAs;
103 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
104 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
105 ConstraintType = SDTCisVTSmallerThanOp;
106 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
107 R->getValueAsInt("OtherOperandNum");
108 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
109 ConstraintType = SDTCisOpSmallerThanOp;
110 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
111 R->getValueAsInt("BigOperandNum");
112 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
113 ConstraintType = SDTCisIntVectorOfSameSize;
114 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
115 R->getValueAsInt("OtherOpNum");
117 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
122 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
123 /// N, which has NumResults results.
124 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
126 unsigned NumResults) const {
127 assert(NumResults <= 1 &&
128 "We only work with nodes with zero or one result so far!");
130 if (OpNo >= (NumResults + N->getNumChildren())) {
131 cerr << "Invalid operand number " << OpNo << " ";
137 if (OpNo < NumResults)
138 return N; // FIXME: need value #
140 return N->getChild(OpNo-NumResults);
143 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
144 /// constraint to the nodes operands. This returns true if it makes a
145 /// change, false otherwise. If a type contradiction is found, throw an
147 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
148 const SDNodeInfo &NodeInfo,
149 TreePattern &TP) const {
150 unsigned NumResults = NodeInfo.getNumResults();
151 assert(NumResults <= 1 &&
152 "We only work with nodes with zero or one result so far!");
154 // Check that the number of operands is sane. Negative operands -> varargs.
155 if (NodeInfo.getNumOperands() >= 0) {
156 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
157 TP.error(N->getOperator()->getName() + " node requires exactly " +
158 itostr(NodeInfo.getNumOperands()) + " operands!");
161 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
163 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
165 switch (ConstraintType) {
166 default: assert(0 && "Unknown constraint type!");
168 // Operand must be a particular type.
169 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
171 // Operand must be same as target pointer type.
172 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
175 // If there is only one integer type supported, this must be it.
176 std::vector<MVT::ValueType> IntVTs =
177 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
179 // If we found exactly one supported integer type, apply it.
180 if (IntVTs.size() == 1)
181 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
182 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
185 // If there is only one FP type supported, this must be it.
186 std::vector<MVT::ValueType> FPVTs =
187 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
189 // If we found exactly one supported FP type, apply it.
190 if (FPVTs.size() == 1)
191 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
192 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
195 TreePatternNode *OtherNode =
196 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
197 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
198 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
200 case SDTCisVTSmallerThanOp: {
201 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
202 // have an integer type that is smaller than the VT.
203 if (!NodeToApply->isLeaf() ||
204 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
205 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
206 ->isSubClassOf("ValueType"))
207 TP.error(N->getOperator()->getName() + " expects a VT operand!");
209 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
210 if (!MVT::isInteger(VT))
211 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
213 TreePatternNode *OtherNode =
214 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
216 // It must be integer.
217 bool MadeChange = false;
218 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
220 // This code only handles nodes that have one type set. Assert here so
221 // that we can change this if we ever need to deal with multiple value
222 // types at this point.
223 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
224 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
225 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
228 case SDTCisOpSmallerThanOp: {
229 TreePatternNode *BigOperand =
230 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
232 // Both operands must be integer or FP, but we don't care which.
233 bool MadeChange = false;
235 // This code does not currently handle nodes which have multiple types,
236 // where some types are integer, and some are fp. Assert that this is not
238 assert(!(MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
239 MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
240 !(MVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
241 MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
242 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
243 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
244 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
245 else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
246 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
247 if (MVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
248 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
249 else if (MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
250 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
252 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
254 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
255 VTs = FilterVTs(VTs, MVT::isInteger);
256 } else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
257 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
262 switch (VTs.size()) {
263 default: // Too many VT's to pick from.
264 case 0: break; // No info yet.
266 // Only one VT of this flavor. Cannot ever satisify the constraints.
267 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
269 // If we have exactly two possible types, the little operand must be the
270 // small one, the big operand should be the big one. Common with
271 // float/double for example.
272 assert(VTs[0] < VTs[1] && "Should be sorted!");
273 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
274 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
279 case SDTCisIntVectorOfSameSize: {
280 TreePatternNode *OtherOperand =
281 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
283 if (OtherOperand->hasTypeSet()) {
284 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
285 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
286 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
287 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
288 return NodeToApply->UpdateNodeType(IVT, TP);
296 //===----------------------------------------------------------------------===//
297 // SDNodeInfo implementation
299 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
300 EnumName = R->getValueAsString("Opcode");
301 SDClassName = R->getValueAsString("SDClass");
302 Record *TypeProfile = R->getValueAsDef("TypeProfile");
303 NumResults = TypeProfile->getValueAsInt("NumResults");
304 NumOperands = TypeProfile->getValueAsInt("NumOperands");
306 // Parse the properties.
308 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
309 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
310 if (PropList[i]->getName() == "SDNPCommutative") {
311 Properties |= 1 << SDNPCommutative;
312 } else if (PropList[i]->getName() == "SDNPAssociative") {
313 Properties |= 1 << SDNPAssociative;
314 } else if (PropList[i]->getName() == "SDNPHasChain") {
315 Properties |= 1 << SDNPHasChain;
316 } else if (PropList[i]->getName() == "SDNPOutFlag") {
317 Properties |= 1 << SDNPOutFlag;
318 } else if (PropList[i]->getName() == "SDNPInFlag") {
319 Properties |= 1 << SDNPInFlag;
320 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
321 Properties |= 1 << SDNPOptInFlag;
323 cerr << "Unknown SD Node property '" << PropList[i]->getName()
324 << "' on node '" << R->getName() << "'!\n";
330 // Parse the type constraints.
331 std::vector<Record*> ConstraintList =
332 TypeProfile->getValueAsListOfDefs("Constraints");
333 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
336 //===----------------------------------------------------------------------===//
337 // TreePatternNode implementation
340 TreePatternNode::~TreePatternNode() {
341 #if 0 // FIXME: implement refcounted tree nodes!
342 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
347 /// UpdateNodeType - Set the node type of N to VT if VT contains
348 /// information. If N already contains a conflicting type, then throw an
349 /// exception. This returns true if any information was updated.
351 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
353 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
355 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
357 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
362 if (getExtTypeNum(0) == MVT::iPTR) {
363 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
365 if (MVT::isExtIntegerInVTs(ExtVTs)) {
366 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
374 if (ExtVTs[0] == MVT::isInt && MVT::isExtIntegerInVTs(getExtTypes())) {
375 assert(hasTypeSet() && "should be handled above!");
376 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
377 if (getExtTypes() == FVTs)
382 if (ExtVTs[0] == MVT::iPTR && MVT::isExtIntegerInVTs(getExtTypes())) {
383 //assert(hasTypeSet() && "should be handled above!");
384 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
385 if (getExtTypes() == FVTs)
392 if (ExtVTs[0] == MVT::isFP && MVT::isExtFloatingPointInVTs(getExtTypes())) {
393 assert(hasTypeSet() && "should be handled above!");
394 std::vector<unsigned char> FVTs =
395 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
396 if (getExtTypes() == FVTs)
402 // If we know this is an int or fp type, and we are told it is a specific one,
405 // Similarly, we should probably set the type here to the intersection of
406 // {isInt|isFP} and ExtVTs
407 if ((getExtTypeNum(0) == MVT::isInt && MVT::isExtIntegerInVTs(ExtVTs)) ||
408 (getExtTypeNum(0) == MVT::isFP && MVT::isExtFloatingPointInVTs(ExtVTs))){
412 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
420 TP.error("Type inference contradiction found in node!");
422 TP.error("Type inference contradiction found in node " +
423 getOperator()->getName() + "!");
425 return true; // unreachable
429 void TreePatternNode::print(std::ostream &OS) const {
431 OS << *getLeafValue();
433 OS << "(" << getOperator()->getName();
436 // FIXME: At some point we should handle printing all the value types for
437 // nodes that are multiply typed.
438 switch (getExtTypeNum(0)) {
439 case MVT::Other: OS << ":Other"; break;
440 case MVT::isInt: OS << ":isInt"; break;
441 case MVT::isFP : OS << ":isFP"; break;
442 case MVT::isUnknown: ; /*OS << ":?";*/ break;
443 case MVT::iPTR: OS << ":iPTR"; break;
445 std::string VTName = llvm::getName(getTypeNum(0));
446 // Strip off MVT:: prefix if present.
447 if (VTName.substr(0,5) == "MVT::")
448 VTName = VTName.substr(5);
455 if (getNumChildren() != 0) {
457 getChild(0)->print(OS);
458 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
460 getChild(i)->print(OS);
466 if (!PredicateFn.empty())
467 OS << "<<P:" << PredicateFn << ">>";
469 OS << "<<X:" << TransformFn->getName() << ">>";
470 if (!getName().empty())
471 OS << ":$" << getName();
474 void TreePatternNode::dump() const {
475 print(*cerr.stream());
478 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
479 /// the specified node. For this comparison, all of the state of the node
480 /// is considered, except for the assigned name. Nodes with differing names
481 /// that are otherwise identical are considered isomorphic.
482 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
483 if (N == this) return true;
484 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
485 getPredicateFn() != N->getPredicateFn() ||
486 getTransformFn() != N->getTransformFn())
490 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
491 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
492 return DI->getDef() == NDI->getDef();
493 return getLeafValue() == N->getLeafValue();
496 if (N->getOperator() != getOperator() ||
497 N->getNumChildren() != getNumChildren()) return false;
498 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
499 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
504 /// clone - Make a copy of this tree and all of its children.
506 TreePatternNode *TreePatternNode::clone() const {
507 TreePatternNode *New;
509 New = new TreePatternNode(getLeafValue());
511 std::vector<TreePatternNode*> CChildren;
512 CChildren.reserve(Children.size());
513 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
514 CChildren.push_back(getChild(i)->clone());
515 New = new TreePatternNode(getOperator(), CChildren);
517 New->setName(getName());
518 New->setTypes(getExtTypes());
519 New->setPredicateFn(getPredicateFn());
520 New->setTransformFn(getTransformFn());
524 /// SubstituteFormalArguments - Replace the formal arguments in this tree
525 /// with actual values specified by ArgMap.
526 void TreePatternNode::
527 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
528 if (isLeaf()) return;
530 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
531 TreePatternNode *Child = getChild(i);
532 if (Child->isLeaf()) {
533 Init *Val = Child->getLeafValue();
534 if (dynamic_cast<DefInit*>(Val) &&
535 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
536 // We found a use of a formal argument, replace it with its value.
537 Child = ArgMap[Child->getName()];
538 assert(Child && "Couldn't find formal argument!");
542 getChild(i)->SubstituteFormalArguments(ArgMap);
548 /// InlinePatternFragments - If this pattern refers to any pattern
549 /// fragments, inline them into place, giving us a pattern without any
550 /// PatFrag references.
551 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
552 if (isLeaf()) return this; // nothing to do.
553 Record *Op = getOperator();
555 if (!Op->isSubClassOf("PatFrag")) {
556 // Just recursively inline children nodes.
557 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
558 setChild(i, getChild(i)->InlinePatternFragments(TP));
562 // Otherwise, we found a reference to a fragment. First, look up its
563 // TreePattern record.
564 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
566 // Verify that we are passing the right number of operands.
567 if (Frag->getNumArgs() != Children.size())
568 TP.error("'" + Op->getName() + "' fragment requires " +
569 utostr(Frag->getNumArgs()) + " operands!");
571 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
573 // Resolve formal arguments to their actual value.
574 if (Frag->getNumArgs()) {
575 // Compute the map of formal to actual arguments.
576 std::map<std::string, TreePatternNode*> ArgMap;
577 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
578 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
580 FragTree->SubstituteFormalArguments(ArgMap);
583 FragTree->setName(getName());
584 FragTree->UpdateNodeType(getExtTypes(), TP);
586 // Get a new copy of this fragment to stitch into here.
587 //delete this; // FIXME: implement refcounting!
591 /// getImplicitType - Check to see if the specified record has an implicit
592 /// type which should be applied to it. This infer the type of register
593 /// references from the register file information, for example.
595 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
597 // Some common return values
598 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
599 std::vector<unsigned char> Other(1, MVT::Other);
601 // Check to see if this is a register or a register class...
602 if (R->isSubClassOf("RegisterClass")) {
605 const CodeGenRegisterClass &RC =
606 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
607 return ConvertVTs(RC.getValueTypes());
608 } else if (R->isSubClassOf("PatFrag")) {
609 // Pattern fragment types will be resolved when they are inlined.
611 } else if (R->isSubClassOf("Register")) {
614 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
615 return T.getRegisterVTs(R);
616 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
617 // Using a VTSDNode or CondCodeSDNode.
619 } else if (R->isSubClassOf("ComplexPattern")) {
622 std::vector<unsigned char>
623 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
625 } else if (R->getName() == "ptr_rc") {
626 Other[0] = MVT::iPTR;
628 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
629 R->getName() == "zero_reg") {
634 TP.error("Unknown node flavor used in pattern: " + R->getName());
638 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
639 /// this node and its children in the tree. This returns true if it makes a
640 /// change, false otherwise. If a type contradiction is found, throw an
642 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
643 CodegenDAGPatterns &CDP = TP.getDAGPatterns();
645 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
646 // If it's a regclass or something else known, include the type.
647 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
648 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
649 // Int inits are always integers. :)
650 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
653 // At some point, it may make sense for this tree pattern to have
654 // multiple types. Assert here that it does not, so we revisit this
655 // code when appropriate.
656 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
657 MVT::ValueType VT = getTypeNum(0);
658 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
659 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
662 if (VT != MVT::iPTR) {
663 unsigned Size = MVT::getSizeInBits(VT);
664 // Make sure that the value is representable for this type.
666 int Val = (II->getValue() << (32-Size)) >> (32-Size);
667 if (Val != II->getValue())
668 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
669 "' is out of range for type '" +
670 getEnumName(getTypeNum(0)) + "'!");
680 // special handling for set, which isn't really an SDNode.
681 if (getOperator()->getName() == "set") {
682 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
683 unsigned NC = getNumChildren();
684 bool MadeChange = false;
685 for (unsigned i = 0; i < NC-1; ++i) {
686 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
687 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
689 // Types of operands must match.
690 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
692 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
694 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
697 } else if (getOperator()->getName() == "implicit" ||
698 getOperator()->getName() == "parallel") {
699 bool MadeChange = false;
700 for (unsigned i = 0; i < getNumChildren(); ++i)
701 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
702 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
704 } else if (getOperator() == CDP.get_intrinsic_void_sdnode() ||
705 getOperator() == CDP.get_intrinsic_w_chain_sdnode() ||
706 getOperator() == CDP.get_intrinsic_wo_chain_sdnode()) {
708 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
709 const CodeGenIntrinsic &Int = CDP.getIntrinsicInfo(IID);
710 bool MadeChange = false;
712 // Apply the result type to the node.
713 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
715 if (getNumChildren() != Int.ArgVTs.size())
716 TP.error("Intrinsic '" + Int.Name + "' expects " +
717 utostr(Int.ArgVTs.size()-1) + " operands, not " +
718 utostr(getNumChildren()-1) + " operands!");
720 // Apply type info to the intrinsic ID.
721 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
723 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
724 MVT::ValueType OpVT = Int.ArgVTs[i];
725 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
726 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
729 } else if (getOperator()->isSubClassOf("SDNode")) {
730 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
732 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
733 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
734 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
735 // Branch, etc. do not produce results and top-level forms in instr pattern
736 // must have void types.
737 if (NI.getNumResults() == 0)
738 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
740 // If this is a vector_shuffle operation, apply types to the build_vector
741 // operation. The types of the integers don't matter, but this ensures they
742 // won't get checked.
743 if (getOperator()->getName() == "vector_shuffle" &&
744 getChild(2)->getOperator()->getName() == "build_vector") {
745 TreePatternNode *BV = getChild(2);
746 const std::vector<MVT::ValueType> &LegalVTs
747 = CDP.getTargetInfo().getLegalValueTypes();
748 MVT::ValueType LegalIntVT = MVT::Other;
749 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
750 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
751 LegalIntVT = LegalVTs[i];
754 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
756 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
757 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
760 } else if (getOperator()->isSubClassOf("Instruction")) {
761 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
762 bool MadeChange = false;
763 unsigned NumResults = Inst.getNumResults();
765 assert(NumResults <= 1 &&
766 "Only supports zero or one result instrs!");
768 CodeGenInstruction &InstInfo =
769 CDP.getTargetInfo().getInstruction(getOperator()->getName());
770 // Apply the result type to the node
771 if (NumResults == 0 || InstInfo.NumDefs == 0) {
772 MadeChange = UpdateNodeType(MVT::isVoid, TP);
774 Record *ResultNode = Inst.getResult(0);
776 if (ResultNode->getName() == "ptr_rc") {
777 std::vector<unsigned char> VT;
778 VT.push_back(MVT::iPTR);
779 MadeChange = UpdateNodeType(VT, TP);
781 assert(ResultNode->isSubClassOf("RegisterClass") &&
782 "Operands should be register classes!");
784 const CodeGenRegisterClass &RC =
785 CDP.getTargetInfo().getRegisterClass(ResultNode);
786 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
790 unsigned ChildNo = 0;
791 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
792 Record *OperandNode = Inst.getOperand(i);
794 // If the instruction expects a predicate or optional def operand, we
795 // codegen this by setting the operand to it's default value if it has a
796 // non-empty DefaultOps field.
797 if ((OperandNode->isSubClassOf("PredicateOperand") ||
798 OperandNode->isSubClassOf("OptionalDefOperand")) &&
799 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
802 // Verify that we didn't run out of provided operands.
803 if (ChildNo >= getNumChildren())
804 TP.error("Instruction '" + getOperator()->getName() +
805 "' expects more operands than were provided.");
808 TreePatternNode *Child = getChild(ChildNo++);
809 if (OperandNode->isSubClassOf("RegisterClass")) {
810 const CodeGenRegisterClass &RC =
811 CDP.getTargetInfo().getRegisterClass(OperandNode);
812 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
813 } else if (OperandNode->isSubClassOf("Operand")) {
814 VT = getValueType(OperandNode->getValueAsDef("Type"));
815 MadeChange |= Child->UpdateNodeType(VT, TP);
816 } else if (OperandNode->getName() == "ptr_rc") {
817 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
819 assert(0 && "Unknown operand type!");
822 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
825 if (ChildNo != getNumChildren())
826 TP.error("Instruction '" + getOperator()->getName() +
827 "' was provided too many operands!");
831 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
833 // Node transforms always take one operand.
834 if (getNumChildren() != 1)
835 TP.error("Node transform '" + getOperator()->getName() +
836 "' requires one operand!");
838 // If either the output or input of the xform does not have exact
839 // type info. We assume they must be the same. Otherwise, it is perfectly
840 // legal to transform from one type to a completely different type.
841 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
842 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
843 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
850 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
851 /// RHS of a commutative operation, not the on LHS.
852 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
853 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
855 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
861 /// canPatternMatch - If it is impossible for this pattern to match on this
862 /// target, fill in Reason and return false. Otherwise, return true. This is
863 /// used as a santity check for .td files (to prevent people from writing stuff
864 /// that can never possibly work), and to prevent the pattern permuter from
865 /// generating stuff that is useless.
866 bool TreePatternNode::canPatternMatch(std::string &Reason,
867 CodegenDAGPatterns &CDP){
868 if (isLeaf()) return true;
870 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
871 if (!getChild(i)->canPatternMatch(Reason, CDP))
874 // If this is an intrinsic, handle cases that would make it not match. For
875 // example, if an operand is required to be an immediate.
876 if (getOperator()->isSubClassOf("Intrinsic")) {
881 // If this node is a commutative operator, check that the LHS isn't an
883 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
884 if (NodeInfo.hasProperty(SDNPCommutative)) {
885 // Scan all of the operands of the node and make sure that only the last one
886 // is a constant node, unless the RHS also is.
887 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
888 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
889 if (OnlyOnRHSOfCommutative(getChild(i))) {
890 Reason="Immediate value must be on the RHS of commutative operators!";
899 //===----------------------------------------------------------------------===//
900 // TreePattern implementation
903 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
904 CodegenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
905 isInputPattern = isInput;
906 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
907 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
910 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
911 CodegenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
912 isInputPattern = isInput;
913 Trees.push_back(ParseTreePattern(Pat));
916 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
917 CodegenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
918 isInputPattern = isInput;
919 Trees.push_back(Pat);
924 void TreePattern::error(const std::string &Msg) const {
926 throw "In " + TheRecord->getName() + ": " + Msg;
929 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
930 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
931 if (!OpDef) error("Pattern has unexpected operator type!");
932 Record *Operator = OpDef->getDef();
934 if (Operator->isSubClassOf("ValueType")) {
935 // If the operator is a ValueType, then this must be "type cast" of a leaf
937 if (Dag->getNumArgs() != 1)
938 error("Type cast only takes one operand!");
940 Init *Arg = Dag->getArg(0);
941 TreePatternNode *New;
942 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
943 Record *R = DI->getDef();
944 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
945 Dag->setArg(0, new DagInit(DI,
946 std::vector<std::pair<Init*, std::string> >()));
947 return ParseTreePattern(Dag);
949 New = new TreePatternNode(DI);
950 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
951 New = ParseTreePattern(DI);
952 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
953 New = new TreePatternNode(II);
954 if (!Dag->getArgName(0).empty())
955 error("Constant int argument should not have a name!");
956 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
957 // Turn this into an IntInit.
958 Init *II = BI->convertInitializerTo(new IntRecTy());
959 if (II == 0 || !dynamic_cast<IntInit*>(II))
960 error("Bits value must be constants!");
962 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
963 if (!Dag->getArgName(0).empty())
964 error("Constant int argument should not have a name!");
967 error("Unknown leaf value for tree pattern!");
971 // Apply the type cast.
972 New->UpdateNodeType(getValueType(Operator), *this);
973 New->setName(Dag->getArgName(0));
977 // Verify that this is something that makes sense for an operator.
978 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
979 !Operator->isSubClassOf("Instruction") &&
980 !Operator->isSubClassOf("SDNodeXForm") &&
981 !Operator->isSubClassOf("Intrinsic") &&
982 Operator->getName() != "set" &&
983 Operator->getName() != "implicit" &&
984 Operator->getName() != "parallel")
985 error("Unrecognized node '" + Operator->getName() + "'!");
987 // Check to see if this is something that is illegal in an input pattern.
988 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
989 Operator->isSubClassOf("SDNodeXForm")))
990 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
992 std::vector<TreePatternNode*> Children;
994 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
995 Init *Arg = Dag->getArg(i);
996 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
997 Children.push_back(ParseTreePattern(DI));
998 if (Children.back()->getName().empty())
999 Children.back()->setName(Dag->getArgName(i));
1000 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1001 Record *R = DefI->getDef();
1002 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1003 // TreePatternNode if its own.
1004 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1005 Dag->setArg(i, new DagInit(DefI,
1006 std::vector<std::pair<Init*, std::string> >()));
1007 --i; // Revisit this node...
1009 TreePatternNode *Node = new TreePatternNode(DefI);
1010 Node->setName(Dag->getArgName(i));
1011 Children.push_back(Node);
1014 if (R->getName() == "node") {
1015 if (Dag->getArgName(i).empty())
1016 error("'node' argument requires a name to match with operand list");
1017 Args.push_back(Dag->getArgName(i));
1020 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1021 TreePatternNode *Node = new TreePatternNode(II);
1022 if (!Dag->getArgName(i).empty())
1023 error("Constant int argument should not have a name!");
1024 Children.push_back(Node);
1025 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1026 // Turn this into an IntInit.
1027 Init *II = BI->convertInitializerTo(new IntRecTy());
1028 if (II == 0 || !dynamic_cast<IntInit*>(II))
1029 error("Bits value must be constants!");
1031 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1032 if (!Dag->getArgName(i).empty())
1033 error("Constant int argument should not have a name!");
1034 Children.push_back(Node);
1039 error("Unknown leaf value for tree pattern!");
1043 // If the operator is an intrinsic, then this is just syntactic sugar for for
1044 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1045 // convert the intrinsic name to a number.
1046 if (Operator->isSubClassOf("Intrinsic")) {
1047 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1048 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1050 // If this intrinsic returns void, it must have side-effects and thus a
1052 if (Int.ArgVTs[0] == MVT::isVoid) {
1053 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1054 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1055 // Has side-effects, requires chain.
1056 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1058 // Otherwise, no chain.
1059 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1062 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1063 Children.insert(Children.begin(), IIDNode);
1066 return new TreePatternNode(Operator, Children);
1069 /// InferAllTypes - Infer/propagate as many types throughout the expression
1070 /// patterns as possible. Return true if all types are infered, false
1071 /// otherwise. Throw an exception if a type contradiction is found.
1072 bool TreePattern::InferAllTypes() {
1073 bool MadeChange = true;
1074 while (MadeChange) {
1076 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1077 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1080 bool HasUnresolvedTypes = false;
1081 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1082 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1083 return !HasUnresolvedTypes;
1086 void TreePattern::print(std::ostream &OS) const {
1087 OS << getRecord()->getName();
1088 if (!Args.empty()) {
1089 OS << "(" << Args[0];
1090 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1091 OS << ", " << Args[i];
1096 if (Trees.size() > 1)
1098 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1100 Trees[i]->print(OS);
1104 if (Trees.size() > 1)
1108 void TreePattern::dump() const { print(*cerr.stream()); }
1110 //===----------------------------------------------------------------------===//
1111 // CodegenDAGPatterns implementation
1114 // FIXME: REMOVE OSTREAM ARGUMENT
1115 CodegenDAGPatterns::CodegenDAGPatterns(RecordKeeper &R, std::ostream &OS)
1118 Intrinsics = LoadIntrinsics(Records);
1120 ParseNodeTransforms(OS);
1121 ParseComplexPatterns();
1122 ParsePatternFragments(OS);
1123 ParseDefaultOperands();
1124 ParseInstructions();
1127 // Generate variants. For example, commutative patterns can match
1128 // multiple ways. Add them to PatternsToMatch as well.
1132 CodegenDAGPatterns::~CodegenDAGPatterns() {
1133 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1134 E = PatternFragments.end(); I != E; ++I)
1139 Record *CodegenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1140 Record *N = Records.getDef(Name);
1141 if (!N || !N->isSubClassOf("SDNode")) {
1142 cerr << "Error getting SDNode '" << Name << "'!\n";
1148 // Parse all of the SDNode definitions for the target, populating SDNodes.
1149 void CodegenDAGPatterns::ParseNodeInfo() {
1150 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1151 while (!Nodes.empty()) {
1152 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1156 // Get the buildin intrinsic nodes.
1157 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1158 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1159 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1162 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1163 /// map, and emit them to the file as functions.
1164 void CodegenDAGPatterns::ParseNodeTransforms(std::ostream &OS) {
1165 OS << "\n// Node transformations.\n";
1166 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1167 while (!Xforms.empty()) {
1168 Record *XFormNode = Xforms.back();
1169 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1170 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1171 SDNodeXForms.insert(std::make_pair(XFormNode,
1172 std::make_pair(SDNode, Code)));
1174 if (!Code.empty()) {
1175 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1176 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1178 OS << "inline SDOperand Transform_" << XFormNode->getName()
1179 << "(SDNode *" << C2 << ") {\n";
1180 if (ClassName != "SDNode")
1181 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1182 OS << Code << "\n}\n";
1189 void CodegenDAGPatterns::ParseComplexPatterns() {
1190 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1191 while (!AMs.empty()) {
1192 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1198 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1199 /// file, building up the PatternFragments map. After we've collected them all,
1200 /// inline fragments together as necessary, so that there are no references left
1201 /// inside a pattern fragment to a pattern fragment.
1203 /// This also emits all of the predicate functions to the output file.
1205 void CodegenDAGPatterns::ParsePatternFragments(std::ostream &OS) {
1206 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1208 // First step, parse all of the fragments and emit predicate functions.
1209 OS << "\n// Predicate functions.\n";
1210 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1211 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1212 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1213 PatternFragments[Fragments[i]] = P;
1215 // Validate the argument list, converting it to map, to discard duplicates.
1216 std::vector<std::string> &Args = P->getArgList();
1217 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1219 if (OperandsMap.count(""))
1220 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1222 // Parse the operands list.
1223 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1224 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1225 // Special cases: ops == outs == ins. Different names are used to
1226 // improve readibility.
1228 (OpsOp->getDef()->getName() != "ops" &&
1229 OpsOp->getDef()->getName() != "outs" &&
1230 OpsOp->getDef()->getName() != "ins"))
1231 P->error("Operands list should start with '(ops ... '!");
1233 // Copy over the arguments.
1235 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1236 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1237 static_cast<DefInit*>(OpsList->getArg(j))->
1238 getDef()->getName() != "node")
1239 P->error("Operands list should all be 'node' values.");
1240 if (OpsList->getArgName(j).empty())
1241 P->error("Operands list should have names for each operand!");
1242 if (!OperandsMap.count(OpsList->getArgName(j)))
1243 P->error("'" + OpsList->getArgName(j) +
1244 "' does not occur in pattern or was multiply specified!");
1245 OperandsMap.erase(OpsList->getArgName(j));
1246 Args.push_back(OpsList->getArgName(j));
1249 if (!OperandsMap.empty())
1250 P->error("Operands list does not contain an entry for operand '" +
1251 *OperandsMap.begin() + "'!");
1253 // If there is a code init for this fragment, emit the predicate code and
1254 // keep track of the fact that this fragment uses it.
1255 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1256 if (!Code.empty()) {
1257 if (P->getOnlyTree()->isLeaf())
1258 OS << "inline bool Predicate_" << Fragments[i]->getName()
1259 << "(SDNode *N) {\n";
1261 std::string ClassName =
1262 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1263 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1265 OS << "inline bool Predicate_" << Fragments[i]->getName()
1266 << "(SDNode *" << C2 << ") {\n";
1267 if (ClassName != "SDNode")
1268 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1270 OS << Code << "\n}\n";
1271 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1274 // If there is a node transformation corresponding to this, keep track of
1276 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1277 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1278 P->getOnlyTree()->setTransformFn(Transform);
1283 // Now that we've parsed all of the tree fragments, do a closure on them so
1284 // that there are not references to PatFrags left inside of them.
1285 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1286 E = PatternFragments.end(); I != E; ++I) {
1287 TreePattern *ThePat = I->second;
1288 ThePat->InlinePatternFragments();
1290 // Infer as many types as possible. Don't worry about it if we don't infer
1291 // all of them, some may depend on the inputs of the pattern.
1293 ThePat->InferAllTypes();
1295 // If this pattern fragment is not supported by this target (no types can
1296 // satisfy its constraints), just ignore it. If the bogus pattern is
1297 // actually used by instructions, the type consistency error will be
1301 // If debugging, print out the pattern fragment result.
1302 DEBUG(ThePat->dump());
1306 void CodegenDAGPatterns::ParseDefaultOperands() {
1307 std::vector<Record*> DefaultOps[2];
1308 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1309 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1311 // Find some SDNode.
1312 assert(!SDNodes.empty() && "No SDNodes parsed?");
1313 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1315 for (unsigned iter = 0; iter != 2; ++iter) {
1316 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1317 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1319 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1320 // SomeSDnode so that we can parse this.
1321 std::vector<std::pair<Init*, std::string> > Ops;
1322 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1323 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1324 DefaultInfo->getArgName(op)));
1325 DagInit *DI = new DagInit(SomeSDNode, Ops);
1327 // Create a TreePattern to parse this.
1328 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1329 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1331 // Copy the operands over into a DAGDefaultOperand.
1332 DAGDefaultOperand DefaultOpInfo;
1334 TreePatternNode *T = P.getTree(0);
1335 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1336 TreePatternNode *TPN = T->getChild(op);
1337 while (TPN->ApplyTypeConstraints(P, false))
1338 /* Resolve all types */;
1340 if (TPN->ContainsUnresolvedType())
1342 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1343 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1345 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1346 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1348 DefaultOpInfo.DefaultOps.push_back(TPN);
1351 // Insert it into the DefaultOperands map so we can find it later.
1352 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1357 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1358 /// instruction input. Return true if this is a real use.
1359 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1360 std::map<std::string, TreePatternNode*> &InstInputs,
1361 std::vector<Record*> &InstImpInputs) {
1362 // No name -> not interesting.
1363 if (Pat->getName().empty()) {
1364 if (Pat->isLeaf()) {
1365 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1366 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1367 I->error("Input " + DI->getDef()->getName() + " must be named!");
1368 else if (DI && DI->getDef()->isSubClassOf("Register"))
1369 InstImpInputs.push_back(DI->getDef());
1376 if (Pat->isLeaf()) {
1377 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1378 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1381 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1382 Rec = Pat->getOperator();
1385 // SRCVALUE nodes are ignored.
1386 if (Rec->getName() == "srcvalue")
1389 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1394 if (Slot->isLeaf()) {
1395 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1397 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1398 SlotRec = Slot->getOperator();
1401 // Ensure that the inputs agree if we've already seen this input.
1403 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1404 if (Slot->getExtTypes() != Pat->getExtTypes())
1405 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1410 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1411 /// part of "I", the instruction), computing the set of inputs and outputs of
1412 /// the pattern. Report errors if we see anything naughty.
1413 void CodegenDAGPatterns::
1414 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1415 std::map<std::string, TreePatternNode*> &InstInputs,
1416 std::map<std::string, TreePatternNode*>&InstResults,
1417 std::vector<Record*> &InstImpInputs,
1418 std::vector<Record*> &InstImpResults) {
1419 if (Pat->isLeaf()) {
1420 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1421 if (!isUse && Pat->getTransformFn())
1422 I->error("Cannot specify a transform function for a non-input value!");
1424 } else if (Pat->getOperator()->getName() == "implicit") {
1425 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1426 TreePatternNode *Dest = Pat->getChild(i);
1427 if (!Dest->isLeaf())
1428 I->error("implicitly defined value should be a register!");
1430 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1431 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1432 I->error("implicitly defined value should be a register!");
1433 InstImpResults.push_back(Val->getDef());
1436 } else if (Pat->getOperator()->getName() != "set") {
1437 // If this is not a set, verify that the children nodes are not void typed,
1439 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1440 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1441 I->error("Cannot have void nodes inside of patterns!");
1442 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1443 InstImpInputs, InstImpResults);
1446 // If this is a non-leaf node with no children, treat it basically as if
1447 // it were a leaf. This handles nodes like (imm).
1449 if (Pat->getNumChildren() == 0)
1450 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1452 if (!isUse && Pat->getTransformFn())
1453 I->error("Cannot specify a transform function for a non-input value!");
1457 // Otherwise, this is a set, validate and collect instruction results.
1458 if (Pat->getNumChildren() == 0)
1459 I->error("set requires operands!");
1461 if (Pat->getTransformFn())
1462 I->error("Cannot specify a transform function on a set node!");
1464 // Check the set destinations.
1465 unsigned NumDests = Pat->getNumChildren()-1;
1466 for (unsigned i = 0; i != NumDests; ++i) {
1467 TreePatternNode *Dest = Pat->getChild(i);
1468 if (!Dest->isLeaf())
1469 I->error("set destination should be a register!");
1471 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1473 I->error("set destination should be a register!");
1475 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1476 Val->getDef()->getName() == "ptr_rc") {
1477 if (Dest->getName().empty())
1478 I->error("set destination must have a name!");
1479 if (InstResults.count(Dest->getName()))
1480 I->error("cannot set '" + Dest->getName() +"' multiple times");
1481 InstResults[Dest->getName()] = Dest;
1482 } else if (Val->getDef()->isSubClassOf("Register")) {
1483 InstImpResults.push_back(Val->getDef());
1485 I->error("set destination should be a register!");
1489 // Verify and collect info from the computation.
1490 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1491 InstInputs, InstResults,
1492 InstImpInputs, InstImpResults);
1495 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1496 /// any fragments involved. This populates the Instructions list with fully
1497 /// resolved instructions.
1498 void CodegenDAGPatterns::ParseInstructions() {
1499 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1501 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1504 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1505 LI = Instrs[i]->getValueAsListInit("Pattern");
1507 // If there is no pattern, only collect minimal information about the
1508 // instruction for its operand list. We have to assume that there is one
1509 // result, as we have no detailed info.
1510 if (!LI || LI->getSize() == 0) {
1511 std::vector<Record*> Results;
1512 std::vector<Record*> Operands;
1514 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1516 if (InstInfo.OperandList.size() != 0) {
1517 if (InstInfo.NumDefs == 0) {
1518 // These produce no results
1519 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1520 Operands.push_back(InstInfo.OperandList[j].Rec);
1522 // Assume the first operand is the result.
1523 Results.push_back(InstInfo.OperandList[0].Rec);
1525 // The rest are inputs.
1526 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1527 Operands.push_back(InstInfo.OperandList[j].Rec);
1531 // Create and insert the instruction.
1532 std::vector<Record*> ImpResults;
1533 std::vector<Record*> ImpOperands;
1534 Instructions.insert(std::make_pair(Instrs[i],
1535 DAGInstruction(0, Results, Operands, ImpResults,
1537 continue; // no pattern.
1540 // Parse the instruction.
1541 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1542 // Inline pattern fragments into it.
1543 I->InlinePatternFragments();
1545 // Infer as many types as possible. If we cannot infer all of them, we can
1546 // never do anything with this instruction pattern: report it to the user.
1547 if (!I->InferAllTypes())
1548 I->error("Could not infer all types in pattern!");
1550 // InstInputs - Keep track of all of the inputs of the instruction, along
1551 // with the record they are declared as.
1552 std::map<std::string, TreePatternNode*> InstInputs;
1554 // InstResults - Keep track of all the virtual registers that are 'set'
1555 // in the instruction, including what reg class they are.
1556 std::map<std::string, TreePatternNode*> InstResults;
1558 std::vector<Record*> InstImpInputs;
1559 std::vector<Record*> InstImpResults;
1561 // Verify that the top-level forms in the instruction are of void type, and
1562 // fill in the InstResults map.
1563 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1564 TreePatternNode *Pat = I->getTree(j);
1565 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1566 I->error("Top-level forms in instruction pattern should have"
1569 // Find inputs and outputs, and verify the structure of the uses/defs.
1570 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1571 InstImpInputs, InstImpResults);
1574 // Now that we have inputs and outputs of the pattern, inspect the operands
1575 // list for the instruction. This determines the order that operands are
1576 // added to the machine instruction the node corresponds to.
1577 unsigned NumResults = InstResults.size();
1579 // Parse the operands list from the (ops) list, validating it.
1580 assert(I->getArgList().empty() && "Args list should still be empty here!");
1581 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1583 // Check that all of the results occur first in the list.
1584 std::vector<Record*> Results;
1585 TreePatternNode *Res0Node = NULL;
1586 for (unsigned i = 0; i != NumResults; ++i) {
1587 if (i == CGI.OperandList.size())
1588 I->error("'" + InstResults.begin()->first +
1589 "' set but does not appear in operand list!");
1590 const std::string &OpName = CGI.OperandList[i].Name;
1592 // Check that it exists in InstResults.
1593 TreePatternNode *RNode = InstResults[OpName];
1595 I->error("Operand $" + OpName + " does not exist in operand list!");
1599 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1601 I->error("Operand $" + OpName + " should be a set destination: all "
1602 "outputs must occur before inputs in operand list!");
1604 if (CGI.OperandList[i].Rec != R)
1605 I->error("Operand $" + OpName + " class mismatch!");
1607 // Remember the return type.
1608 Results.push_back(CGI.OperandList[i].Rec);
1610 // Okay, this one checks out.
1611 InstResults.erase(OpName);
1614 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1615 // the copy while we're checking the inputs.
1616 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1618 std::vector<TreePatternNode*> ResultNodeOperands;
1619 std::vector<Record*> Operands;
1620 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1621 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1622 const std::string &OpName = Op.Name;
1624 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1626 if (!InstInputsCheck.count(OpName)) {
1627 // If this is an predicate operand or optional def operand with an
1628 // DefaultOps set filled in, we can ignore this. When we codegen it,
1629 // we will do so as always executed.
1630 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1631 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1632 // Does it have a non-empty DefaultOps field? If so, ignore this
1634 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1637 I->error("Operand $" + OpName +
1638 " does not appear in the instruction pattern");
1640 TreePatternNode *InVal = InstInputsCheck[OpName];
1641 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1643 if (InVal->isLeaf() &&
1644 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1645 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1646 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1647 I->error("Operand $" + OpName + "'s register class disagrees"
1648 " between the operand and pattern");
1650 Operands.push_back(Op.Rec);
1652 // Construct the result for the dest-pattern operand list.
1653 TreePatternNode *OpNode = InVal->clone();
1655 // No predicate is useful on the result.
1656 OpNode->setPredicateFn("");
1658 // Promote the xform function to be an explicit node if set.
1659 if (Record *Xform = OpNode->getTransformFn()) {
1660 OpNode->setTransformFn(0);
1661 std::vector<TreePatternNode*> Children;
1662 Children.push_back(OpNode);
1663 OpNode = new TreePatternNode(Xform, Children);
1666 ResultNodeOperands.push_back(OpNode);
1669 if (!InstInputsCheck.empty())
1670 I->error("Input operand $" + InstInputsCheck.begin()->first +
1671 " occurs in pattern but not in operands list!");
1673 TreePatternNode *ResultPattern =
1674 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1675 // Copy fully inferred output node type to instruction result pattern.
1677 ResultPattern->setTypes(Res0Node->getExtTypes());
1679 // Create and insert the instruction.
1680 // FIXME: InstImpResults and InstImpInputs should not be part of
1682 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1683 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1685 // Use a temporary tree pattern to infer all types and make sure that the
1686 // constructed result is correct. This depends on the instruction already
1687 // being inserted into the Instructions map.
1688 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1689 Temp.InferAllTypes();
1691 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1692 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1697 // If we can, convert the instructions to be patterns that are matched!
1698 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1699 E = Instructions.end(); II != E; ++II) {
1700 DAGInstruction &TheInst = II->second;
1701 TreePattern *I = TheInst.getPattern();
1702 if (I == 0) continue; // No pattern.
1704 // FIXME: Assume only the first tree is the pattern. The others are clobber
1706 TreePatternNode *Pattern = I->getTree(0);
1707 TreePatternNode *SrcPattern;
1708 if (Pattern->getOperator()->getName() == "set") {
1709 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1711 // Not a set (store or something?)
1712 SrcPattern = Pattern;
1716 if (!SrcPattern->canPatternMatch(Reason, *this))
1717 I->error("Instruction can never match: " + Reason);
1719 Record *Instr = II->first;
1720 TreePatternNode *DstPattern = TheInst.getResultPattern();
1722 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1723 SrcPattern, DstPattern, TheInst.getImpResults(),
1724 Instr->getValueAsInt("AddedComplexity")));
1728 void CodegenDAGPatterns::ParsePatterns() {
1729 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1731 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1732 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1733 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1734 Record *Operator = OpDef->getDef();
1735 TreePattern *Pattern;
1736 if (Operator->getName() != "parallel")
1737 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1739 std::vector<Init*> Values;
1740 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1741 Values.push_back(Tree->getArg(j));
1742 ListInit *LI = new ListInit(Values);
1743 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1746 // Inline pattern fragments into it.
1747 Pattern->InlinePatternFragments();
1749 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1750 if (LI->getSize() == 0) continue; // no pattern.
1752 // Parse the instruction.
1753 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1755 // Inline pattern fragments into it.
1756 Result->InlinePatternFragments();
1758 if (Result->getNumTrees() != 1)
1759 Result->error("Cannot handle instructions producing instructions "
1760 "with temporaries yet!");
1762 bool IterateInference;
1763 bool InferredAllPatternTypes, InferredAllResultTypes;
1765 // Infer as many types as possible. If we cannot infer all of them, we
1766 // can never do anything with this pattern: report it to the user.
1767 InferredAllPatternTypes = Pattern->InferAllTypes();
1769 // Infer as many types as possible. If we cannot infer all of them, we
1770 // can never do anything with this pattern: report it to the user.
1771 InferredAllResultTypes = Result->InferAllTypes();
1773 // Apply the type of the result to the source pattern. This helps us
1774 // resolve cases where the input type is known to be a pointer type (which
1775 // is considered resolved), but the result knows it needs to be 32- or
1776 // 64-bits. Infer the other way for good measure.
1777 IterateInference = Pattern->getTree(0)->
1778 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
1779 IterateInference |= Result->getTree(0)->
1780 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
1781 } while (IterateInference);
1783 // Verify that we inferred enough types that we can do something with the
1784 // pattern and result. If these fire the user has to add type casts.
1785 if (!InferredAllPatternTypes)
1786 Pattern->error("Could not infer all types in pattern!");
1787 if (!InferredAllResultTypes)
1788 Result->error("Could not infer all types in pattern result!");
1790 // Validate that the input pattern is correct.
1791 std::map<std::string, TreePatternNode*> InstInputs;
1792 std::map<std::string, TreePatternNode*> InstResults;
1793 std::vector<Record*> InstImpInputs;
1794 std::vector<Record*> InstImpResults;
1795 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
1796 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
1797 InstInputs, InstResults,
1798 InstImpInputs, InstImpResults);
1800 // Promote the xform function to be an explicit node if set.
1801 TreePatternNode *DstPattern = Result->getOnlyTree();
1802 std::vector<TreePatternNode*> ResultNodeOperands;
1803 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1804 TreePatternNode *OpNode = DstPattern->getChild(ii);
1805 if (Record *Xform = OpNode->getTransformFn()) {
1806 OpNode->setTransformFn(0);
1807 std::vector<TreePatternNode*> Children;
1808 Children.push_back(OpNode);
1809 OpNode = new TreePatternNode(Xform, Children);
1811 ResultNodeOperands.push_back(OpNode);
1813 DstPattern = Result->getOnlyTree();
1814 if (!DstPattern->isLeaf())
1815 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1816 ResultNodeOperands);
1817 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1818 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1819 Temp.InferAllTypes();
1822 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
1823 Pattern->error("Pattern can never match: " + Reason);
1826 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1827 Pattern->getTree(0),
1828 Temp.getOnlyTree(), InstImpResults,
1829 Patterns[i]->getValueAsInt("AddedComplexity")));
1833 /// CombineChildVariants - Given a bunch of permutations of each child of the
1834 /// 'operator' node, put them together in all possible ways.
1835 static void CombineChildVariants(TreePatternNode *Orig,
1836 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1837 std::vector<TreePatternNode*> &OutVariants,
1838 CodegenDAGPatterns &CDP) {
1839 // Make sure that each operand has at least one variant to choose from.
1840 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1841 if (ChildVariants[i].empty())
1844 // The end result is an all-pairs construction of the resultant pattern.
1845 std::vector<unsigned> Idxs;
1846 Idxs.resize(ChildVariants.size());
1847 bool NotDone = true;
1849 // Create the variant and add it to the output list.
1850 std::vector<TreePatternNode*> NewChildren;
1851 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1852 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1853 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1855 // Copy over properties.
1856 R->setName(Orig->getName());
1857 R->setPredicateFn(Orig->getPredicateFn());
1858 R->setTransformFn(Orig->getTransformFn());
1859 R->setTypes(Orig->getExtTypes());
1861 // If this pattern cannot every match, do not include it as a variant.
1862 std::string ErrString;
1863 if (!R->canPatternMatch(ErrString, CDP)) {
1866 bool AlreadyExists = false;
1868 // Scan to see if this pattern has already been emitted. We can get
1869 // duplication due to things like commuting:
1870 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1871 // which are the same pattern. Ignore the dups.
1872 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1873 if (R->isIsomorphicTo(OutVariants[i])) {
1874 AlreadyExists = true;
1881 OutVariants.push_back(R);
1884 // Increment indices to the next permutation.
1886 // Look for something we can increment without causing a wrap-around.
1887 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1888 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1889 NotDone = true; // Found something to increment.
1897 /// CombineChildVariants - A helper function for binary operators.
1899 static void CombineChildVariants(TreePatternNode *Orig,
1900 const std::vector<TreePatternNode*> &LHS,
1901 const std::vector<TreePatternNode*> &RHS,
1902 std::vector<TreePatternNode*> &OutVariants,
1903 CodegenDAGPatterns &CDP) {
1904 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1905 ChildVariants.push_back(LHS);
1906 ChildVariants.push_back(RHS);
1907 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP);
1911 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1912 std::vector<TreePatternNode *> &Children) {
1913 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1914 Record *Operator = N->getOperator();
1916 // Only permit raw nodes.
1917 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1918 N->getTransformFn()) {
1919 Children.push_back(N);
1923 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1924 Children.push_back(N->getChild(0));
1926 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1928 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1929 Children.push_back(N->getChild(1));
1931 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1934 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1935 /// the (potentially recursive) pattern by using algebraic laws.
1937 static void GenerateVariantsOf(TreePatternNode *N,
1938 std::vector<TreePatternNode*> &OutVariants,
1939 CodegenDAGPatterns &CDP) {
1940 // We cannot permute leaves.
1942 OutVariants.push_back(N);
1946 // Look up interesting info about the node.
1947 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
1949 // If this node is associative, reassociate.
1950 if (NodeInfo.hasProperty(SDNPAssociative)) {
1951 // Reassociate by pulling together all of the linked operators
1952 std::vector<TreePatternNode*> MaximalChildren;
1953 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1955 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1957 if (MaximalChildren.size() == 3) {
1958 // Find the variants of all of our maximal children.
1959 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1960 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP);
1961 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP);
1962 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP);
1964 // There are only two ways we can permute the tree:
1965 // (A op B) op C and A op (B op C)
1966 // Within these forms, we can also permute A/B/C.
1968 // Generate legal pair permutations of A/B/C.
1969 std::vector<TreePatternNode*> ABVariants;
1970 std::vector<TreePatternNode*> BAVariants;
1971 std::vector<TreePatternNode*> ACVariants;
1972 std::vector<TreePatternNode*> CAVariants;
1973 std::vector<TreePatternNode*> BCVariants;
1974 std::vector<TreePatternNode*> CBVariants;
1975 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP);
1976 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP);
1977 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP);
1978 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP);
1979 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP);
1980 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP);
1982 // Combine those into the result: (x op x) op x
1983 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP);
1984 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP);
1985 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP);
1986 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP);
1987 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP);
1988 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP);
1990 // Combine those into the result: x op (x op x)
1991 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP);
1992 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP);
1993 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP);
1994 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP);
1995 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP);
1996 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP);
2001 // Compute permutations of all children.
2002 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2003 ChildVariants.resize(N->getNumChildren());
2004 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2005 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP);
2007 // Build all permutations based on how the children were formed.
2008 CombineChildVariants(N, ChildVariants, OutVariants, CDP);
2010 // If this node is commutative, consider the commuted order.
2011 if (NodeInfo.hasProperty(SDNPCommutative)) {
2012 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
2013 // Don't count children which are actually register references.
2015 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2016 TreePatternNode *Child = N->getChild(i);
2017 if (Child->isLeaf())
2018 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2019 Record *RR = DI->getDef();
2020 if (RR->isSubClassOf("Register"))
2025 // Consider the commuted order.
2027 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2033 // GenerateVariants - Generate variants. For example, commutative patterns can
2034 // match multiple ways. Add them to PatternsToMatch as well.
2035 void CodegenDAGPatterns::GenerateVariants() {
2036 DOUT << "Generating instruction variants.\n";
2038 // Loop over all of the patterns we've collected, checking to see if we can
2039 // generate variants of the instruction, through the exploitation of
2040 // identities. This permits the target to provide agressive matching without
2041 // the .td file having to contain tons of variants of instructions.
2043 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2044 // intentionally do not reconsider these. Any variants of added patterns have
2045 // already been added.
2047 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2048 std::vector<TreePatternNode*> Variants;
2049 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
2051 assert(!Variants.empty() && "Must create at least original variant!");
2052 Variants.erase(Variants.begin()); // Remove the original pattern.
2054 if (Variants.empty()) // No variants for this pattern.
2057 DOUT << "FOUND VARIANTS OF: ";
2058 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2061 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2062 TreePatternNode *Variant = Variants[v];
2064 DOUT << " VAR#" << v << ": ";
2065 DEBUG(Variant->dump());
2068 // Scan to see if an instruction or explicit pattern already matches this.
2069 bool AlreadyExists = false;
2070 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2071 // Check to see if this variant already exists.
2072 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
2073 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2074 AlreadyExists = true;
2078 // If we already have it, ignore the variant.
2079 if (AlreadyExists) continue;
2081 // Otherwise, add it to the list of patterns we have.
2083 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2084 Variant, PatternsToMatch[i].getDstPattern(),
2085 PatternsToMatch[i].getDstRegs(),
2086 PatternsToMatch[i].getAddedComplexity()));