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"
24 //===----------------------------------------------------------------------===//
25 // Helpers for working with extended types.
27 /// FilterVTs - Filter a list of VT's according to a predicate.
30 static std::vector<MVT::SimpleValueType>
31 FilterVTs(const std::vector<MVT::SimpleValueType> &InVTs, T Filter) {
32 std::vector<MVT::SimpleValueType> Result;
33 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
35 Result.push_back(InVTs[i]);
40 static std::vector<unsigned char>
41 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44 if (Filter((MVT::SimpleValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
49 static std::vector<unsigned char>
50 ConvertVTs(const std::vector<MVT::SimpleValueType> &InVTs) {
51 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
57 static inline bool isInteger(MVT::SimpleValueType VT) {
58 return EVT(VT).isInteger();
61 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62 return EVT(VT).isFloatingPoint();
65 static inline bool isVector(MVT::SimpleValueType VT) {
66 return EVT(VT).isVector();
69 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
70 const std::vector<unsigned char> &RHS) {
71 if (LHS.size() > RHS.size()) return false;
72 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
73 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
80 /// isExtIntegerInVTs - Return true if the specified extended value type vector
81 /// contains isInt or an integer value type.
82 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
83 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
84 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
87 /// isExtFloatingPointInVTs - Return true if the specified extended value type
88 /// vector contains isFP or a FP value type.
89 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
90 assert(!EVTs.empty() && "Cannot check for FP in empty ExtVT list!");
91 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
94 /// isExtVectorInVTs - Return true if the specified extended value type
95 /// vector contains a vector value type.
96 bool isExtVectorInVTs(const std::vector<unsigned char> &EVTs) {
97 assert(!EVTs.empty() && "Cannot check for vector in empty ExtVT list!");
98 return EVTs[0] == isVec || !(FilterEVTs(EVTs, isVector).empty());
100 } // end namespace EEVT.
101 } // end namespace llvm.
104 /// Dependent variable map for CodeGenDAGPattern variant generation
105 typedef std::map<std::string, int> DepVarMap;
107 /// Const iterator shorthand for DepVarMap
108 typedef DepVarMap::const_iterator DepVarMap_citer;
111 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
113 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
114 DepMap[N->getName()]++;
117 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
118 FindDepVarsOf(N->getChild(i), DepMap);
122 //! Find dependent variables within child patterns
125 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
127 FindDepVarsOf(N, depcounts);
128 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
129 if (i->second > 1) { // std::pair<std::string, int>
130 DepVars.insert(i->first);
135 //! Dump the dependent variable set:
136 void DumpDepVars(MultipleUseVarSet &DepVars) {
137 if (DepVars.empty()) {
138 DOUT << "<empty set>";
141 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
150 //===----------------------------------------------------------------------===//
151 // PatternToMatch implementation
154 /// getPredicateCheck - Return a single string containing all of this
155 /// pattern's predicates concatenated with "&&" operators.
157 std::string PatternToMatch::getPredicateCheck() const {
158 std::string PredicateCheck;
159 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
160 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
161 Record *Def = Pred->getDef();
162 if (!Def->isSubClassOf("Predicate")) {
166 assert(0 && "Unknown predicate type!");
168 if (!PredicateCheck.empty())
169 PredicateCheck += " && ";
170 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
174 return PredicateCheck;
177 //===----------------------------------------------------------------------===//
178 // SDTypeConstraint implementation
181 SDTypeConstraint::SDTypeConstraint(Record *R) {
182 OperandNo = R->getValueAsInt("OperandNum");
184 if (R->isSubClassOf("SDTCisVT")) {
185 ConstraintType = SDTCisVT;
186 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
187 } else if (R->isSubClassOf("SDTCisPtrTy")) {
188 ConstraintType = SDTCisPtrTy;
189 } else if (R->isSubClassOf("SDTCisInt")) {
190 ConstraintType = SDTCisInt;
191 } else if (R->isSubClassOf("SDTCisFP")) {
192 ConstraintType = SDTCisFP;
193 } else if (R->isSubClassOf("SDTCisVec")) {
194 ConstraintType = SDTCisVec;
195 } else if (R->isSubClassOf("SDTCisSameAs")) {
196 ConstraintType = SDTCisSameAs;
197 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
198 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
199 ConstraintType = SDTCisVTSmallerThanOp;
200 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
201 R->getValueAsInt("OtherOperandNum");
202 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
203 ConstraintType = SDTCisOpSmallerThanOp;
204 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
205 R->getValueAsInt("BigOperandNum");
206 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
207 ConstraintType = SDTCisEltOfVec;
208 x.SDTCisEltOfVec_Info.OtherOperandNum =
209 R->getValueAsInt("OtherOpNum");
211 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
216 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
217 /// N, which has NumResults results.
218 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
220 unsigned NumResults) const {
221 assert(NumResults <= 1 &&
222 "We only work with nodes with zero or one result so far!");
224 if (OpNo >= (NumResults + N->getNumChildren())) {
225 errs() << "Invalid operand number " << OpNo << " ";
231 if (OpNo < NumResults)
232 return N; // FIXME: need value #
234 return N->getChild(OpNo-NumResults);
237 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
238 /// constraint to the nodes operands. This returns true if it makes a
239 /// change, false otherwise. If a type contradiction is found, throw an
241 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
242 const SDNodeInfo &NodeInfo,
243 TreePattern &TP) const {
244 unsigned NumResults = NodeInfo.getNumResults();
245 assert(NumResults <= 1 &&
246 "We only work with nodes with zero or one result so far!");
248 // Check that the number of operands is sane. Negative operands -> varargs.
249 if (NodeInfo.getNumOperands() >= 0) {
250 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
251 TP.error(N->getOperator()->getName() + " node requires exactly " +
252 itostr(NodeInfo.getNumOperands()) + " operands!");
255 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
257 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
259 switch (ConstraintType) {
260 default: assert(0 && "Unknown constraint type!");
262 // Operand must be a particular type.
263 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
265 // Operand must be same as target pointer type.
266 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
269 // If there is only one integer type supported, this must be it.
270 std::vector<MVT::SimpleValueType> IntVTs =
271 FilterVTs(CGT.getLegalValueTypes(), isInteger);
273 // If we found exactly one supported integer type, apply it.
274 if (IntVTs.size() == 1)
275 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
276 return NodeToApply->UpdateNodeType(EEVT::isInt, TP);
279 // If there is only one FP type supported, this must be it.
280 std::vector<MVT::SimpleValueType> FPVTs =
281 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
283 // If we found exactly one supported FP type, apply it.
284 if (FPVTs.size() == 1)
285 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
286 return NodeToApply->UpdateNodeType(EEVT::isFP, TP);
289 // If there is only one vector type supported, this must be it.
290 std::vector<MVT::SimpleValueType> VecVTs =
291 FilterVTs(CGT.getLegalValueTypes(), isVector);
293 // If we found exactly one supported vector type, apply it.
294 if (VecVTs.size() == 1)
295 return NodeToApply->UpdateNodeType(VecVTs[0], TP);
296 return NodeToApply->UpdateNodeType(EEVT::isVec, TP);
299 TreePatternNode *OtherNode =
300 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
301 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
302 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
304 case SDTCisVTSmallerThanOp: {
305 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
306 // have an integer type that is smaller than the VT.
307 if (!NodeToApply->isLeaf() ||
308 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
309 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
310 ->isSubClassOf("ValueType"))
311 TP.error(N->getOperator()->getName() + " expects a VT operand!");
312 MVT::SimpleValueType VT =
313 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
315 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
317 TreePatternNode *OtherNode =
318 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
320 // It must be integer.
321 bool MadeChange = false;
322 MadeChange |= OtherNode->UpdateNodeType(EEVT::isInt, TP);
324 // This code only handles nodes that have one type set. Assert here so
325 // that we can change this if we ever need to deal with multiple value
326 // types at this point.
327 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
328 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
329 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
332 case SDTCisOpSmallerThanOp: {
333 TreePatternNode *BigOperand =
334 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
336 // Both operands must be integer or FP, but we don't care which.
337 bool MadeChange = false;
339 // This code does not currently handle nodes which have multiple types,
340 // where some types are integer, and some are fp. Assert that this is not
342 assert(!(EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
343 EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
344 !(EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
345 EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
346 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
347 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
348 MadeChange |= BigOperand->UpdateNodeType(EEVT::isInt, TP);
349 else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
350 MadeChange |= BigOperand->UpdateNodeType(EEVT::isFP, TP);
351 if (EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
352 MadeChange |= NodeToApply->UpdateNodeType(EEVT::isInt, TP);
353 else if (EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
354 MadeChange |= NodeToApply->UpdateNodeType(EEVT::isFP, TP);
356 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
358 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
359 VTs = FilterVTs(VTs, isInteger);
360 } else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
361 VTs = FilterVTs(VTs, isFloatingPoint);
366 switch (VTs.size()) {
367 default: // Too many VT's to pick from.
368 case 0: break; // No info yet.
370 // Only one VT of this flavor. Cannot ever satisfy the constraints.
371 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
373 // If we have exactly two possible types, the little operand must be the
374 // small one, the big operand should be the big one. Common with
375 // float/double for example.
376 assert(VTs[0] < VTs[1] && "Should be sorted!");
377 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
378 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
383 case SDTCisEltOfVec: {
384 TreePatternNode *OtherOperand =
385 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum,
387 if (OtherOperand->hasTypeSet()) {
388 if (!isVector(OtherOperand->getTypeNum(0)))
389 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
390 EVT IVT = OtherOperand->getTypeNum(0);
391 IVT = IVT.getVectorElementType();
392 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
400 //===----------------------------------------------------------------------===//
401 // SDNodeInfo implementation
403 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
404 EnumName = R->getValueAsString("Opcode");
405 SDClassName = R->getValueAsString("SDClass");
406 Record *TypeProfile = R->getValueAsDef("TypeProfile");
407 NumResults = TypeProfile->getValueAsInt("NumResults");
408 NumOperands = TypeProfile->getValueAsInt("NumOperands");
410 // Parse the properties.
412 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
413 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
414 if (PropList[i]->getName() == "SDNPCommutative") {
415 Properties |= 1 << SDNPCommutative;
416 } else if (PropList[i]->getName() == "SDNPAssociative") {
417 Properties |= 1 << SDNPAssociative;
418 } else if (PropList[i]->getName() == "SDNPHasChain") {
419 Properties |= 1 << SDNPHasChain;
420 } else if (PropList[i]->getName() == "SDNPOutFlag") {
421 Properties |= 1 << SDNPOutFlag;
422 } else if (PropList[i]->getName() == "SDNPInFlag") {
423 Properties |= 1 << SDNPInFlag;
424 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
425 Properties |= 1 << SDNPOptInFlag;
426 } else if (PropList[i]->getName() == "SDNPMayStore") {
427 Properties |= 1 << SDNPMayStore;
428 } else if (PropList[i]->getName() == "SDNPMayLoad") {
429 Properties |= 1 << SDNPMayLoad;
430 } else if (PropList[i]->getName() == "SDNPSideEffect") {
431 Properties |= 1 << SDNPSideEffect;
432 } else if (PropList[i]->getName() == "SDNPMemOperand") {
433 Properties |= 1 << SDNPMemOperand;
435 errs() << "Unknown SD Node property '" << PropList[i]->getName()
436 << "' on node '" << R->getName() << "'!\n";
442 // Parse the type constraints.
443 std::vector<Record*> ConstraintList =
444 TypeProfile->getValueAsListOfDefs("Constraints");
445 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
448 //===----------------------------------------------------------------------===//
449 // TreePatternNode implementation
452 TreePatternNode::~TreePatternNode() {
453 #if 0 // FIXME: implement refcounted tree nodes!
454 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
459 /// UpdateNodeType - Set the node type of N to VT if VT contains
460 /// information. If N already contains a conflicting type, then throw an
461 /// exception. This returns true if any information was updated.
463 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
465 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
467 if (ExtVTs[0] == EEVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
469 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
474 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
475 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
476 ExtVTs[0] == EEVT::isInt)
478 if (EEVT::isExtIntegerInVTs(ExtVTs)) {
479 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
487 if ((ExtVTs[0] == EEVT::isInt || ExtVTs[0] == MVT::iAny) &&
488 EEVT::isExtIntegerInVTs(getExtTypes())) {
489 assert(hasTypeSet() && "should be handled above!");
490 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
491 if (getExtTypes() == FVTs)
496 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
497 EEVT::isExtIntegerInVTs(getExtTypes())) {
498 //assert(hasTypeSet() && "should be handled above!");
499 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
500 if (getExtTypes() == FVTs)
507 if ((ExtVTs[0] == EEVT::isFP || ExtVTs[0] == MVT::fAny) &&
508 EEVT::isExtFloatingPointInVTs(getExtTypes())) {
509 assert(hasTypeSet() && "should be handled above!");
510 std::vector<unsigned char> FVTs =
511 FilterEVTs(getExtTypes(), isFloatingPoint);
512 if (getExtTypes() == FVTs)
517 if ((ExtVTs[0] == EEVT::isVec || ExtVTs[0] == MVT::vAny) &&
518 EEVT::isExtVectorInVTs(getExtTypes())) {
519 assert(hasTypeSet() && "should be handled above!");
520 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isVector);
521 if (getExtTypes() == FVTs)
527 // If we know this is an int, FP, or vector type, and we are told it is a
528 // specific one, take the advice.
530 // Similarly, we should probably set the type here to the intersection of
531 // {isInt|isFP|isVec} and ExtVTs
532 if (((getExtTypeNum(0) == EEVT::isInt || getExtTypeNum(0) == MVT::iAny) &&
533 EEVT::isExtIntegerInVTs(ExtVTs)) ||
534 ((getExtTypeNum(0) == EEVT::isFP || getExtTypeNum(0) == MVT::fAny) &&
535 EEVT::isExtFloatingPointInVTs(ExtVTs)) ||
536 ((getExtTypeNum(0) == EEVT::isVec || getExtTypeNum(0) == MVT::vAny) &&
537 EEVT::isExtVectorInVTs(ExtVTs))) {
541 if (getExtTypeNum(0) == EEVT::isInt &&
542 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
550 TP.error("Type inference contradiction found in node!");
552 TP.error("Type inference contradiction found in node " +
553 getOperator()->getName() + "!");
555 return true; // unreachable
559 void TreePatternNode::print(raw_ostream &OS) const {
561 OS << *getLeafValue();
563 OS << "(" << getOperator()->getName();
566 // FIXME: At some point we should handle printing all the value types for
567 // nodes that are multiply typed.
568 switch (getExtTypeNum(0)) {
569 case MVT::Other: OS << ":Other"; break;
570 case EEVT::isInt: OS << ":isInt"; break;
571 case EEVT::isFP : OS << ":isFP"; break;
572 case EEVT::isVec: OS << ":isVec"; break;
573 case EEVT::isUnknown: ; /*OS << ":?";*/ break;
574 case MVT::iPTR: OS << ":iPTR"; break;
575 case MVT::iPTRAny: OS << ":iPTRAny"; break;
577 std::string VTName = llvm::getName(getTypeNum(0));
578 // Strip off EVT:: prefix if present.
579 if (VTName.substr(0,5) == "MVT::")
580 VTName = VTName.substr(5);
587 if (getNumChildren() != 0) {
589 getChild(0)->print(OS);
590 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
592 getChild(i)->print(OS);
598 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
599 OS << "<<P:" << PredicateFns[i] << ">>";
601 OS << "<<X:" << TransformFn->getName() << ">>";
602 if (!getName().empty())
603 OS << ":$" << getName();
606 void TreePatternNode::dump() const {
610 /// isIsomorphicTo - Return true if this node is recursively
611 /// isomorphic to the specified node. For this comparison, the node's
612 /// entire state is considered. The assigned name is ignored, since
613 /// nodes with differing names are considered isomorphic. However, if
614 /// the assigned name is present in the dependent variable set, then
615 /// the assigned name is considered significant and the node is
616 /// isomorphic if the names match.
617 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
618 const MultipleUseVarSet &DepVars) const {
619 if (N == this) return true;
620 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
621 getPredicateFns() != N->getPredicateFns() ||
622 getTransformFn() != N->getTransformFn())
626 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
627 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
628 return ((DI->getDef() == NDI->getDef())
629 && (DepVars.find(getName()) == DepVars.end()
630 || getName() == N->getName()));
633 return getLeafValue() == N->getLeafValue();
636 if (N->getOperator() != getOperator() ||
637 N->getNumChildren() != getNumChildren()) return false;
638 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
639 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
644 /// clone - Make a copy of this tree and all of its children.
646 TreePatternNode *TreePatternNode::clone() const {
647 TreePatternNode *New;
649 New = new TreePatternNode(getLeafValue());
651 std::vector<TreePatternNode*> CChildren;
652 CChildren.reserve(Children.size());
653 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
654 CChildren.push_back(getChild(i)->clone());
655 New = new TreePatternNode(getOperator(), CChildren);
657 New->setName(getName());
658 New->setTypes(getExtTypes());
659 New->setPredicateFns(getPredicateFns());
660 New->setTransformFn(getTransformFn());
664 /// SubstituteFormalArguments - Replace the formal arguments in this tree
665 /// with actual values specified by ArgMap.
666 void TreePatternNode::
667 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
668 if (isLeaf()) return;
670 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
671 TreePatternNode *Child = getChild(i);
672 if (Child->isLeaf()) {
673 Init *Val = Child->getLeafValue();
674 if (dynamic_cast<DefInit*>(Val) &&
675 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
676 // We found a use of a formal argument, replace it with its value.
677 TreePatternNode *NewChild = ArgMap[Child->getName()];
678 assert(NewChild && "Couldn't find formal argument!");
679 assert((Child->getPredicateFns().empty() ||
680 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
681 "Non-empty child predicate clobbered!");
682 setChild(i, NewChild);
685 getChild(i)->SubstituteFormalArguments(ArgMap);
691 /// InlinePatternFragments - If this pattern refers to any pattern
692 /// fragments, inline them into place, giving us a pattern without any
693 /// PatFrag references.
694 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
695 if (isLeaf()) return this; // nothing to do.
696 Record *Op = getOperator();
698 if (!Op->isSubClassOf("PatFrag")) {
699 // Just recursively inline children nodes.
700 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
701 TreePatternNode *Child = getChild(i);
702 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
704 assert((Child->getPredicateFns().empty() ||
705 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
706 "Non-empty child predicate clobbered!");
708 setChild(i, NewChild);
713 // Otherwise, we found a reference to a fragment. First, look up its
714 // TreePattern record.
715 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
717 // Verify that we are passing the right number of operands.
718 if (Frag->getNumArgs() != Children.size())
719 TP.error("'" + Op->getName() + "' fragment requires " +
720 utostr(Frag->getNumArgs()) + " operands!");
722 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
724 std::string Code = Op->getValueAsCode("Predicate");
726 FragTree->addPredicateFn("Predicate_"+Op->getName());
728 // Resolve formal arguments to their actual value.
729 if (Frag->getNumArgs()) {
730 // Compute the map of formal to actual arguments.
731 std::map<std::string, TreePatternNode*> ArgMap;
732 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
733 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
735 FragTree->SubstituteFormalArguments(ArgMap);
738 FragTree->setName(getName());
739 FragTree->UpdateNodeType(getExtTypes(), TP);
741 // Transfer in the old predicates.
742 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
743 FragTree->addPredicateFn(getPredicateFns()[i]);
745 // Get a new copy of this fragment to stitch into here.
746 //delete this; // FIXME: implement refcounting!
748 // The fragment we inlined could have recursive inlining that is needed. See
749 // if there are any pattern fragments in it and inline them as needed.
750 return FragTree->InlinePatternFragments(TP);
753 /// getImplicitType - Check to see if the specified record has an implicit
754 /// type which should be applied to it. This will infer the type of register
755 /// references from the register file information, for example.
757 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
759 // Some common return values
760 std::vector<unsigned char> Unknown(1, EEVT::isUnknown);
761 std::vector<unsigned char> Other(1, MVT::Other);
763 // Check to see if this is a register or a register class...
764 if (R->isSubClassOf("RegisterClass")) {
767 const CodeGenRegisterClass &RC =
768 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
769 return ConvertVTs(RC.getValueTypes());
770 } else if (R->isSubClassOf("PatFrag")) {
771 // Pattern fragment types will be resolved when they are inlined.
773 } else if (R->isSubClassOf("Register")) {
776 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
777 return T.getRegisterVTs(R);
778 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
779 // Using a VTSDNode or CondCodeSDNode.
781 } else if (R->isSubClassOf("ComplexPattern")) {
784 std::vector<unsigned char>
785 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
787 } else if (R->isSubClassOf("PointerLikeRegClass")) {
788 Other[0] = MVT::iPTR;
790 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
791 R->getName() == "zero_reg") {
796 TP.error("Unknown node flavor used in pattern: " + R->getName());
801 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
802 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
803 const CodeGenIntrinsic *TreePatternNode::
804 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
805 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
806 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
807 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
811 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
812 return &CDP.getIntrinsicInfo(IID);
815 /// isCommutativeIntrinsic - Return true if the node corresponds to a
816 /// commutative intrinsic.
818 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
819 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
820 return Int->isCommutative;
825 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
826 /// this node and its children in the tree. This returns true if it makes a
827 /// change, false otherwise. If a type contradiction is found, throw an
829 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
830 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
832 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
833 // If it's a regclass or something else known, include the type.
834 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
835 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
836 // Int inits are always integers. :)
837 bool MadeChange = UpdateNodeType(EEVT::isInt, TP);
840 // At some point, it may make sense for this tree pattern to have
841 // multiple types. Assert here that it does not, so we revisit this
842 // code when appropriate.
843 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
844 MVT::SimpleValueType VT = getTypeNum(0);
845 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
846 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
849 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
850 unsigned Size = EVT(VT).getSizeInBits();
851 // Make sure that the value is representable for this type.
853 int Val = (II->getValue() << (32-Size)) >> (32-Size);
854 if (Val != II->getValue()) {
855 // If sign-extended doesn't fit, does it fit as unsigned?
857 unsigned UnsignedVal;
858 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
859 UnsignedVal = unsigned(II->getValue());
861 if ((ValueMask & UnsignedVal) != UnsignedVal) {
862 TP.error("Integer value '" + itostr(II->getValue())+
863 "' is out of range for type '" +
864 getEnumName(getTypeNum(0)) + "'!");
876 // special handling for set, which isn't really an SDNode.
877 if (getOperator()->getName() == "set") {
878 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
879 unsigned NC = getNumChildren();
880 bool MadeChange = false;
881 for (unsigned i = 0; i < NC-1; ++i) {
882 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
883 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
885 // Types of operands must match.
886 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
888 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
890 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
893 } else if (getOperator()->getName() == "implicit" ||
894 getOperator()->getName() == "parallel") {
895 bool MadeChange = false;
896 for (unsigned i = 0; i < getNumChildren(); ++i)
897 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
898 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
900 } else if (getOperator()->getName() == "COPY_TO_REGCLASS") {
901 bool MadeChange = false;
902 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
903 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
904 MadeChange |= UpdateNodeType(getChild(1)->getTypeNum(0), TP);
906 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
907 bool MadeChange = false;
909 // Apply the result type to the node.
910 unsigned NumRetVTs = Int->IS.RetVTs.size();
911 unsigned NumParamVTs = Int->IS.ParamVTs.size();
913 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
914 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
916 if (getNumChildren() != NumParamVTs + NumRetVTs)
917 TP.error("Intrinsic '" + Int->Name + "' expects " +
918 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
919 utostr(getNumChildren() - 1) + " operands!");
921 // Apply type info to the intrinsic ID.
922 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
924 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
925 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
926 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
927 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
930 } else if (getOperator()->isSubClassOf("SDNode")) {
931 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
933 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
934 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
935 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
936 // Branch, etc. do not produce results and top-level forms in instr pattern
937 // must have void types.
938 if (NI.getNumResults() == 0)
939 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
942 } else if (getOperator()->isSubClassOf("Instruction")) {
943 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
944 bool MadeChange = false;
945 unsigned NumResults = Inst.getNumResults();
947 assert(NumResults <= 1 &&
948 "Only supports zero or one result instrs!");
950 CodeGenInstruction &InstInfo =
951 CDP.getTargetInfo().getInstruction(getOperator()->getName());
952 // Apply the result type to the node
953 if (NumResults == 0 || InstInfo.NumDefs == 0) {
954 MadeChange = UpdateNodeType(MVT::isVoid, TP);
956 Record *ResultNode = Inst.getResult(0);
958 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
959 std::vector<unsigned char> VT;
960 VT.push_back(MVT::iPTR);
961 MadeChange = UpdateNodeType(VT, TP);
962 } else if (ResultNode->getName() == "unknown") {
963 std::vector<unsigned char> VT;
964 VT.push_back(EEVT::isUnknown);
965 MadeChange = UpdateNodeType(VT, TP);
967 assert(ResultNode->isSubClassOf("RegisterClass") &&
968 "Operands should be register classes!");
970 const CodeGenRegisterClass &RC =
971 CDP.getTargetInfo().getRegisterClass(ResultNode);
972 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
976 unsigned ChildNo = 0;
977 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
978 Record *OperandNode = Inst.getOperand(i);
980 // If the instruction expects a predicate or optional def operand, we
981 // codegen this by setting the operand to it's default value if it has a
982 // non-empty DefaultOps field.
983 if ((OperandNode->isSubClassOf("PredicateOperand") ||
984 OperandNode->isSubClassOf("OptionalDefOperand")) &&
985 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
988 // Verify that we didn't run out of provided operands.
989 if (ChildNo >= getNumChildren())
990 TP.error("Instruction '" + getOperator()->getName() +
991 "' expects more operands than were provided.");
993 MVT::SimpleValueType VT;
994 TreePatternNode *Child = getChild(ChildNo++);
995 if (OperandNode->isSubClassOf("RegisterClass")) {
996 const CodeGenRegisterClass &RC =
997 CDP.getTargetInfo().getRegisterClass(OperandNode);
998 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
999 } else if (OperandNode->isSubClassOf("Operand")) {
1000 VT = getValueType(OperandNode->getValueAsDef("Type"));
1001 MadeChange |= Child->UpdateNodeType(VT, TP);
1002 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1003 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1004 } else if (OperandNode->getName() == "unknown") {
1005 MadeChange |= Child->UpdateNodeType(EEVT::isUnknown, TP);
1007 assert(0 && "Unknown operand type!");
1010 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1013 if (ChildNo != getNumChildren())
1014 TP.error("Instruction '" + getOperator()->getName() +
1015 "' was provided too many operands!");
1019 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1021 // Node transforms always take one operand.
1022 if (getNumChildren() != 1)
1023 TP.error("Node transform '" + getOperator()->getName() +
1024 "' requires one operand!");
1026 // If either the output or input of the xform does not have exact
1027 // type info. We assume they must be the same. Otherwise, it is perfectly
1028 // legal to transform from one type to a completely different type.
1029 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1030 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1031 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1038 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1039 /// RHS of a commutative operation, not the on LHS.
1040 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1041 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1043 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1049 /// canPatternMatch - If it is impossible for this pattern to match on this
1050 /// target, fill in Reason and return false. Otherwise, return true. This is
1051 /// used as a sanity check for .td files (to prevent people from writing stuff
1052 /// that can never possibly work), and to prevent the pattern permuter from
1053 /// generating stuff that is useless.
1054 bool TreePatternNode::canPatternMatch(std::string &Reason,
1055 const CodeGenDAGPatterns &CDP) {
1056 if (isLeaf()) return true;
1058 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1059 if (!getChild(i)->canPatternMatch(Reason, CDP))
1062 // If this is an intrinsic, handle cases that would make it not match. For
1063 // example, if an operand is required to be an immediate.
1064 if (getOperator()->isSubClassOf("Intrinsic")) {
1069 // If this node is a commutative operator, check that the LHS isn't an
1071 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1072 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1073 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1074 // Scan all of the operands of the node and make sure that only the last one
1075 // is a constant node, unless the RHS also is.
1076 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1077 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1078 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1079 if (OnlyOnRHSOfCommutative(getChild(i))) {
1080 Reason="Immediate value must be on the RHS of commutative operators!";
1089 //===----------------------------------------------------------------------===//
1090 // TreePattern implementation
1093 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1094 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1095 isInputPattern = isInput;
1096 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1097 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1100 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1101 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1102 isInputPattern = isInput;
1103 Trees.push_back(ParseTreePattern(Pat));
1106 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1107 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1108 isInputPattern = isInput;
1109 Trees.push_back(Pat);
1114 void TreePattern::error(const std::string &Msg) const {
1116 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1119 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1120 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1121 if (!OpDef) error("Pattern has unexpected operator type!");
1122 Record *Operator = OpDef->getDef();
1124 if (Operator->isSubClassOf("ValueType")) {
1125 // If the operator is a ValueType, then this must be "type cast" of a leaf
1127 if (Dag->getNumArgs() != 1)
1128 error("Type cast only takes one operand!");
1130 Init *Arg = Dag->getArg(0);
1131 TreePatternNode *New;
1132 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1133 Record *R = DI->getDef();
1134 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1135 Dag->setArg(0, new DagInit(DI, "",
1136 std::vector<std::pair<Init*, std::string> >()));
1137 return ParseTreePattern(Dag);
1139 New = new TreePatternNode(DI);
1140 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1141 New = ParseTreePattern(DI);
1142 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1143 New = new TreePatternNode(II);
1144 if (!Dag->getArgName(0).empty())
1145 error("Constant int argument should not have a name!");
1146 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1147 // Turn this into an IntInit.
1148 Init *II = BI->convertInitializerTo(new IntRecTy());
1149 if (II == 0 || !dynamic_cast<IntInit*>(II))
1150 error("Bits value must be constants!");
1152 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1153 if (!Dag->getArgName(0).empty())
1154 error("Constant int argument should not have a name!");
1157 error("Unknown leaf value for tree pattern!");
1161 // Apply the type cast.
1162 New->UpdateNodeType(getValueType(Operator), *this);
1163 if (New->getNumChildren() == 0)
1164 New->setName(Dag->getArgName(0));
1168 // Verify that this is something that makes sense for an operator.
1169 if (!Operator->isSubClassOf("PatFrag") &&
1170 !Operator->isSubClassOf("SDNode") &&
1171 !Operator->isSubClassOf("Instruction") &&
1172 !Operator->isSubClassOf("SDNodeXForm") &&
1173 !Operator->isSubClassOf("Intrinsic") &&
1174 Operator->getName() != "set" &&
1175 Operator->getName() != "implicit" &&
1176 Operator->getName() != "parallel")
1177 error("Unrecognized node '" + Operator->getName() + "'!");
1179 // Check to see if this is something that is illegal in an input pattern.
1180 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1181 Operator->isSubClassOf("SDNodeXForm")))
1182 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1184 std::vector<TreePatternNode*> Children;
1186 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1187 Init *Arg = Dag->getArg(i);
1188 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1189 Children.push_back(ParseTreePattern(DI));
1190 if (Children.back()->getName().empty())
1191 Children.back()->setName(Dag->getArgName(i));
1192 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1193 Record *R = DefI->getDef();
1194 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1195 // TreePatternNode if its own.
1196 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1197 Dag->setArg(i, new DagInit(DefI, "",
1198 std::vector<std::pair<Init*, std::string> >()));
1199 --i; // Revisit this node...
1201 TreePatternNode *Node = new TreePatternNode(DefI);
1202 Node->setName(Dag->getArgName(i));
1203 Children.push_back(Node);
1206 if (R->getName() == "node") {
1207 if (Dag->getArgName(i).empty())
1208 error("'node' argument requires a name to match with operand list");
1209 Args.push_back(Dag->getArgName(i));
1212 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1213 TreePatternNode *Node = new TreePatternNode(II);
1214 if (!Dag->getArgName(i).empty())
1215 error("Constant int argument should not have a name!");
1216 Children.push_back(Node);
1217 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1218 // Turn this into an IntInit.
1219 Init *II = BI->convertInitializerTo(new IntRecTy());
1220 if (II == 0 || !dynamic_cast<IntInit*>(II))
1221 error("Bits value must be constants!");
1223 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1224 if (!Dag->getArgName(i).empty())
1225 error("Constant int argument should not have a name!");
1226 Children.push_back(Node);
1231 error("Unknown leaf value for tree pattern!");
1235 // If the operator is an intrinsic, then this is just syntactic sugar for for
1236 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1237 // convert the intrinsic name to a number.
1238 if (Operator->isSubClassOf("Intrinsic")) {
1239 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1240 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1242 // If this intrinsic returns void, it must have side-effects and thus a
1244 if (Int.IS.RetVTs[0] == MVT::isVoid) {
1245 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1246 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1247 // Has side-effects, requires chain.
1248 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1250 // Otherwise, no chain.
1251 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1254 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1255 Children.insert(Children.begin(), IIDNode);
1258 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1259 Result->setName(Dag->getName());
1263 /// InferAllTypes - Infer/propagate as many types throughout the expression
1264 /// patterns as possible. Return true if all types are inferred, false
1265 /// otherwise. Throw an exception if a type contradiction is found.
1266 bool TreePattern::InferAllTypes() {
1267 bool MadeChange = true;
1268 while (MadeChange) {
1270 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1271 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1274 bool HasUnresolvedTypes = false;
1275 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1276 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1277 return !HasUnresolvedTypes;
1280 void TreePattern::print(raw_ostream &OS) const {
1281 OS << getRecord()->getName();
1282 if (!Args.empty()) {
1283 OS << "(" << Args[0];
1284 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1285 OS << ", " << Args[i];
1290 if (Trees.size() > 1)
1292 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1294 Trees[i]->print(OS);
1298 if (Trees.size() > 1)
1302 void TreePattern::dump() const { print(errs()); }
1304 //===----------------------------------------------------------------------===//
1305 // CodeGenDAGPatterns implementation
1308 // FIXME: REMOVE OSTREAM ARGUMENT
1309 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1310 Intrinsics = LoadIntrinsics(Records, false);
1311 TgtIntrinsics = LoadIntrinsics(Records, true);
1313 ParseNodeTransforms();
1314 ParseComplexPatterns();
1315 ParsePatternFragments();
1316 ParseDefaultOperands();
1317 ParseInstructions();
1320 // Generate variants. For example, commutative patterns can match
1321 // multiple ways. Add them to PatternsToMatch as well.
1324 // Infer instruction flags. For example, we can detect loads,
1325 // stores, and side effects in many cases by examining an
1326 // instruction's pattern.
1327 InferInstructionFlags();
1330 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1331 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1332 E = PatternFragments.end(); I != E; ++I)
1337 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1338 Record *N = Records.getDef(Name);
1339 if (!N || !N->isSubClassOf("SDNode")) {
1340 errs() << "Error getting SDNode '" << Name << "'!\n";
1346 // Parse all of the SDNode definitions for the target, populating SDNodes.
1347 void CodeGenDAGPatterns::ParseNodeInfo() {
1348 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1349 while (!Nodes.empty()) {
1350 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1354 // Get the builtin intrinsic nodes.
1355 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1356 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1357 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1360 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1361 /// map, and emit them to the file as functions.
1362 void CodeGenDAGPatterns::ParseNodeTransforms() {
1363 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1364 while (!Xforms.empty()) {
1365 Record *XFormNode = Xforms.back();
1366 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1367 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1368 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1374 void CodeGenDAGPatterns::ParseComplexPatterns() {
1375 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1376 while (!AMs.empty()) {
1377 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1383 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1384 /// file, building up the PatternFragments map. After we've collected them all,
1385 /// inline fragments together as necessary, so that there are no references left
1386 /// inside a pattern fragment to a pattern fragment.
1388 void CodeGenDAGPatterns::ParsePatternFragments() {
1389 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1391 // First step, parse all of the fragments.
1392 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1393 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1394 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1395 PatternFragments[Fragments[i]] = P;
1397 // Validate the argument list, converting it to set, to discard duplicates.
1398 std::vector<std::string> &Args = P->getArgList();
1399 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1401 if (OperandsSet.count(""))
1402 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1404 // Parse the operands list.
1405 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1406 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1407 // Special cases: ops == outs == ins. Different names are used to
1408 // improve readability.
1410 (OpsOp->getDef()->getName() != "ops" &&
1411 OpsOp->getDef()->getName() != "outs" &&
1412 OpsOp->getDef()->getName() != "ins"))
1413 P->error("Operands list should start with '(ops ... '!");
1415 // Copy over the arguments.
1417 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1418 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1419 static_cast<DefInit*>(OpsList->getArg(j))->
1420 getDef()->getName() != "node")
1421 P->error("Operands list should all be 'node' values.");
1422 if (OpsList->getArgName(j).empty())
1423 P->error("Operands list should have names for each operand!");
1424 if (!OperandsSet.count(OpsList->getArgName(j)))
1425 P->error("'" + OpsList->getArgName(j) +
1426 "' does not occur in pattern or was multiply specified!");
1427 OperandsSet.erase(OpsList->getArgName(j));
1428 Args.push_back(OpsList->getArgName(j));
1431 if (!OperandsSet.empty())
1432 P->error("Operands list does not contain an entry for operand '" +
1433 *OperandsSet.begin() + "'!");
1435 // If there is a code init for this fragment, keep track of the fact that
1436 // this fragment uses it.
1437 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1439 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1441 // If there is a node transformation corresponding to this, keep track of
1443 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1444 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1445 P->getOnlyTree()->setTransformFn(Transform);
1448 // Now that we've parsed all of the tree fragments, do a closure on them so
1449 // that there are not references to PatFrags left inside of them.
1450 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1451 TreePattern *ThePat = PatternFragments[Fragments[i]];
1452 ThePat->InlinePatternFragments();
1454 // Infer as many types as possible. Don't worry about it if we don't infer
1455 // all of them, some may depend on the inputs of the pattern.
1457 ThePat->InferAllTypes();
1459 // If this pattern fragment is not supported by this target (no types can
1460 // satisfy its constraints), just ignore it. If the bogus pattern is
1461 // actually used by instructions, the type consistency error will be
1465 // If debugging, print out the pattern fragment result.
1466 DEBUG(ThePat->dump());
1470 void CodeGenDAGPatterns::ParseDefaultOperands() {
1471 std::vector<Record*> DefaultOps[2];
1472 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1473 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1475 // Find some SDNode.
1476 assert(!SDNodes.empty() && "No SDNodes parsed?");
1477 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1479 for (unsigned iter = 0; iter != 2; ++iter) {
1480 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1481 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1483 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1484 // SomeSDnode so that we can parse this.
1485 std::vector<std::pair<Init*, std::string> > Ops;
1486 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1487 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1488 DefaultInfo->getArgName(op)));
1489 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1491 // Create a TreePattern to parse this.
1492 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1493 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1495 // Copy the operands over into a DAGDefaultOperand.
1496 DAGDefaultOperand DefaultOpInfo;
1498 TreePatternNode *T = P.getTree(0);
1499 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1500 TreePatternNode *TPN = T->getChild(op);
1501 while (TPN->ApplyTypeConstraints(P, false))
1502 /* Resolve all types */;
1504 if (TPN->ContainsUnresolvedType()) {
1506 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1507 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1509 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1510 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1512 DefaultOpInfo.DefaultOps.push_back(TPN);
1515 // Insert it into the DefaultOperands map so we can find it later.
1516 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1521 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1522 /// instruction input. Return true if this is a real use.
1523 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1524 std::map<std::string, TreePatternNode*> &InstInputs,
1525 std::vector<Record*> &InstImpInputs) {
1526 // No name -> not interesting.
1527 if (Pat->getName().empty()) {
1528 if (Pat->isLeaf()) {
1529 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1530 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1531 I->error("Input " + DI->getDef()->getName() + " must be named!");
1532 else if (DI && DI->getDef()->isSubClassOf("Register"))
1533 InstImpInputs.push_back(DI->getDef());
1539 if (Pat->isLeaf()) {
1540 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1541 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1544 Rec = Pat->getOperator();
1547 // SRCVALUE nodes are ignored.
1548 if (Rec->getName() == "srcvalue")
1551 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1556 if (Slot->isLeaf()) {
1557 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1559 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1560 SlotRec = Slot->getOperator();
1563 // Ensure that the inputs agree if we've already seen this input.
1565 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1566 if (Slot->getExtTypes() != Pat->getExtTypes())
1567 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1572 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1573 /// part of "I", the instruction), computing the set of inputs and outputs of
1574 /// the pattern. Report errors if we see anything naughty.
1575 void CodeGenDAGPatterns::
1576 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1577 std::map<std::string, TreePatternNode*> &InstInputs,
1578 std::map<std::string, TreePatternNode*>&InstResults,
1579 std::vector<Record*> &InstImpInputs,
1580 std::vector<Record*> &InstImpResults) {
1581 if (Pat->isLeaf()) {
1582 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1583 if (!isUse && Pat->getTransformFn())
1584 I->error("Cannot specify a transform function for a non-input value!");
1586 } else if (Pat->getOperator()->getName() == "implicit") {
1587 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1588 TreePatternNode *Dest = Pat->getChild(i);
1589 if (!Dest->isLeaf())
1590 I->error("implicitly defined value should be a register!");
1592 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1593 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1594 I->error("implicitly defined value should be a register!");
1595 InstImpResults.push_back(Val->getDef());
1598 } else if (Pat->getOperator()->getName() != "set") {
1599 // If this is not a set, verify that the children nodes are not void typed,
1601 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1602 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1603 I->error("Cannot have void nodes inside of patterns!");
1604 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1605 InstImpInputs, InstImpResults);
1608 // If this is a non-leaf node with no children, treat it basically as if
1609 // it were a leaf. This handles nodes like (imm).
1610 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1612 if (!isUse && Pat->getTransformFn())
1613 I->error("Cannot specify a transform function for a non-input value!");
1617 // Otherwise, this is a set, validate and collect instruction results.
1618 if (Pat->getNumChildren() == 0)
1619 I->error("set requires operands!");
1621 if (Pat->getTransformFn())
1622 I->error("Cannot specify a transform function on a set node!");
1624 // Check the set destinations.
1625 unsigned NumDests = Pat->getNumChildren()-1;
1626 for (unsigned i = 0; i != NumDests; ++i) {
1627 TreePatternNode *Dest = Pat->getChild(i);
1628 if (!Dest->isLeaf())
1629 I->error("set destination should be a register!");
1631 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1633 I->error("set destination should be a register!");
1635 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1636 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1637 if (Dest->getName().empty())
1638 I->error("set destination must have a name!");
1639 if (InstResults.count(Dest->getName()))
1640 I->error("cannot set '" + Dest->getName() +"' multiple times");
1641 InstResults[Dest->getName()] = Dest;
1642 } else if (Val->getDef()->isSubClassOf("Register")) {
1643 InstImpResults.push_back(Val->getDef());
1645 I->error("set destination should be a register!");
1649 // Verify and collect info from the computation.
1650 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1651 InstInputs, InstResults,
1652 InstImpInputs, InstImpResults);
1655 //===----------------------------------------------------------------------===//
1656 // Instruction Analysis
1657 //===----------------------------------------------------------------------===//
1659 class InstAnalyzer {
1660 const CodeGenDAGPatterns &CDP;
1663 bool &HasSideEffects;
1665 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1666 bool &maystore, bool &mayload, bool &hse)
1667 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1670 /// Analyze - Analyze the specified instruction, returning true if the
1671 /// instruction had a pattern.
1672 bool Analyze(Record *InstRecord) {
1673 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1676 return false; // No pattern.
1679 // FIXME: Assume only the first tree is the pattern. The others are clobber
1681 AnalyzeNode(Pattern->getTree(0));
1686 void AnalyzeNode(const TreePatternNode *N) {
1688 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1689 Record *LeafRec = DI->getDef();
1690 // Handle ComplexPattern leaves.
1691 if (LeafRec->isSubClassOf("ComplexPattern")) {
1692 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1693 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1694 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1695 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1701 // Analyze children.
1702 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1703 AnalyzeNode(N->getChild(i));
1705 // Ignore set nodes, which are not SDNodes.
1706 if (N->getOperator()->getName() == "set")
1709 // Get information about the SDNode for the operator.
1710 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1712 // Notice properties of the node.
1713 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1714 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1715 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1717 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1718 // If this is an intrinsic, analyze it.
1719 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1720 mayLoad = true;// These may load memory.
1722 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1723 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1725 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1726 // WriteMem intrinsics can have other strange effects.
1727 HasSideEffects = true;
1733 static void InferFromPattern(const CodeGenInstruction &Inst,
1734 bool &MayStore, bool &MayLoad,
1735 bool &HasSideEffects,
1736 const CodeGenDAGPatterns &CDP) {
1737 MayStore = MayLoad = HasSideEffects = false;
1740 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1742 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1743 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1744 // If we decided that this is a store from the pattern, then the .td file
1745 // entry is redundant.
1748 "Warning: mayStore flag explicitly set on instruction '%s'"
1749 " but flag already inferred from pattern.\n",
1750 Inst.TheDef->getName().c_str());
1754 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1755 // If we decided that this is a load from the pattern, then the .td file
1756 // entry is redundant.
1759 "Warning: mayLoad flag explicitly set on instruction '%s'"
1760 " but flag already inferred from pattern.\n",
1761 Inst.TheDef->getName().c_str());
1765 if (Inst.neverHasSideEffects) {
1767 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1768 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1769 HasSideEffects = false;
1772 if (Inst.hasSideEffects) {
1774 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1775 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1776 HasSideEffects = true;
1780 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1781 /// any fragments involved. This populates the Instructions list with fully
1782 /// resolved instructions.
1783 void CodeGenDAGPatterns::ParseInstructions() {
1784 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1786 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1789 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1790 LI = Instrs[i]->getValueAsListInit("Pattern");
1792 // If there is no pattern, only collect minimal information about the
1793 // instruction for its operand list. We have to assume that there is one
1794 // result, as we have no detailed info.
1795 if (!LI || LI->getSize() == 0) {
1796 std::vector<Record*> Results;
1797 std::vector<Record*> Operands;
1799 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1801 if (InstInfo.OperandList.size() != 0) {
1802 if (InstInfo.NumDefs == 0) {
1803 // These produce no results
1804 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1805 Operands.push_back(InstInfo.OperandList[j].Rec);
1807 // Assume the first operand is the result.
1808 Results.push_back(InstInfo.OperandList[0].Rec);
1810 // The rest are inputs.
1811 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1812 Operands.push_back(InstInfo.OperandList[j].Rec);
1816 // Create and insert the instruction.
1817 std::vector<Record*> ImpResults;
1818 std::vector<Record*> ImpOperands;
1819 Instructions.insert(std::make_pair(Instrs[i],
1820 DAGInstruction(0, Results, Operands, ImpResults,
1822 continue; // no pattern.
1825 // Parse the instruction.
1826 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1827 // Inline pattern fragments into it.
1828 I->InlinePatternFragments();
1830 // Infer as many types as possible. If we cannot infer all of them, we can
1831 // never do anything with this instruction pattern: report it to the user.
1832 if (!I->InferAllTypes())
1833 I->error("Could not infer all types in pattern!");
1835 // InstInputs - Keep track of all of the inputs of the instruction, along
1836 // with the record they are declared as.
1837 std::map<std::string, TreePatternNode*> InstInputs;
1839 // InstResults - Keep track of all the virtual registers that are 'set'
1840 // in the instruction, including what reg class they are.
1841 std::map<std::string, TreePatternNode*> InstResults;
1843 std::vector<Record*> InstImpInputs;
1844 std::vector<Record*> InstImpResults;
1846 // Verify that the top-level forms in the instruction are of void type, and
1847 // fill in the InstResults map.
1848 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1849 TreePatternNode *Pat = I->getTree(j);
1850 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1851 I->error("Top-level forms in instruction pattern should have"
1854 // Find inputs and outputs, and verify the structure of the uses/defs.
1855 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1856 InstImpInputs, InstImpResults);
1859 // Now that we have inputs and outputs of the pattern, inspect the operands
1860 // list for the instruction. This determines the order that operands are
1861 // added to the machine instruction the node corresponds to.
1862 unsigned NumResults = InstResults.size();
1864 // Parse the operands list from the (ops) list, validating it.
1865 assert(I->getArgList().empty() && "Args list should still be empty here!");
1866 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1868 // Check that all of the results occur first in the list.
1869 std::vector<Record*> Results;
1870 TreePatternNode *Res0Node = NULL;
1871 for (unsigned i = 0; i != NumResults; ++i) {
1872 if (i == CGI.OperandList.size())
1873 I->error("'" + InstResults.begin()->first +
1874 "' set but does not appear in operand list!");
1875 const std::string &OpName = CGI.OperandList[i].Name;
1877 // Check that it exists in InstResults.
1878 TreePatternNode *RNode = InstResults[OpName];
1880 I->error("Operand $" + OpName + " does not exist in operand list!");
1884 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1886 I->error("Operand $" + OpName + " should be a set destination: all "
1887 "outputs must occur before inputs in operand list!");
1889 if (CGI.OperandList[i].Rec != R)
1890 I->error("Operand $" + OpName + " class mismatch!");
1892 // Remember the return type.
1893 Results.push_back(CGI.OperandList[i].Rec);
1895 // Okay, this one checks out.
1896 InstResults.erase(OpName);
1899 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1900 // the copy while we're checking the inputs.
1901 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1903 std::vector<TreePatternNode*> ResultNodeOperands;
1904 std::vector<Record*> Operands;
1905 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1906 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1907 const std::string &OpName = Op.Name;
1909 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1911 if (!InstInputsCheck.count(OpName)) {
1912 // If this is an predicate operand or optional def operand with an
1913 // DefaultOps set filled in, we can ignore this. When we codegen it,
1914 // we will do so as always executed.
1915 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1916 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1917 // Does it have a non-empty DefaultOps field? If so, ignore this
1919 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1922 I->error("Operand $" + OpName +
1923 " does not appear in the instruction pattern");
1925 TreePatternNode *InVal = InstInputsCheck[OpName];
1926 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1928 if (InVal->isLeaf() &&
1929 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1930 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1931 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1932 I->error("Operand $" + OpName + "'s register class disagrees"
1933 " between the operand and pattern");
1935 Operands.push_back(Op.Rec);
1937 // Construct the result for the dest-pattern operand list.
1938 TreePatternNode *OpNode = InVal->clone();
1940 // No predicate is useful on the result.
1941 OpNode->clearPredicateFns();
1943 // Promote the xform function to be an explicit node if set.
1944 if (Record *Xform = OpNode->getTransformFn()) {
1945 OpNode->setTransformFn(0);
1946 std::vector<TreePatternNode*> Children;
1947 Children.push_back(OpNode);
1948 OpNode = new TreePatternNode(Xform, Children);
1951 ResultNodeOperands.push_back(OpNode);
1954 if (!InstInputsCheck.empty())
1955 I->error("Input operand $" + InstInputsCheck.begin()->first +
1956 " occurs in pattern but not in operands list!");
1958 TreePatternNode *ResultPattern =
1959 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1960 // Copy fully inferred output node type to instruction result pattern.
1962 ResultPattern->setTypes(Res0Node->getExtTypes());
1964 // Create and insert the instruction.
1965 // FIXME: InstImpResults and InstImpInputs should not be part of
1967 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1968 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1970 // Use a temporary tree pattern to infer all types and make sure that the
1971 // constructed result is correct. This depends on the instruction already
1972 // being inserted into the Instructions map.
1973 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1974 Temp.InferAllTypes();
1976 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1977 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1982 // If we can, convert the instructions to be patterns that are matched!
1983 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1984 E = Instructions.end(); II != E; ++II) {
1985 DAGInstruction &TheInst = II->second;
1986 const TreePattern *I = TheInst.getPattern();
1987 if (I == 0) continue; // No pattern.
1989 // FIXME: Assume only the first tree is the pattern. The others are clobber
1991 TreePatternNode *Pattern = I->getTree(0);
1992 TreePatternNode *SrcPattern;
1993 if (Pattern->getOperator()->getName() == "set") {
1994 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1996 // Not a set (store or something?)
1997 SrcPattern = Pattern;
2001 if (!SrcPattern->canPatternMatch(Reason, *this))
2002 I->error("Instruction can never match: " + Reason);
2004 Record *Instr = II->first;
2005 TreePatternNode *DstPattern = TheInst.getResultPattern();
2007 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
2008 SrcPattern, DstPattern, TheInst.getImpResults(),
2009 Instr->getValueAsInt("AddedComplexity")));
2014 void CodeGenDAGPatterns::InferInstructionFlags() {
2015 std::map<std::string, CodeGenInstruction> &InstrDescs =
2016 Target.getInstructions();
2017 for (std::map<std::string, CodeGenInstruction>::iterator
2018 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2019 CodeGenInstruction &InstInfo = II->second;
2020 // Determine properties of the instruction from its pattern.
2021 bool MayStore, MayLoad, HasSideEffects;
2022 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2023 InstInfo.mayStore = MayStore;
2024 InstInfo.mayLoad = MayLoad;
2025 InstInfo.hasSideEffects = HasSideEffects;
2029 void CodeGenDAGPatterns::ParsePatterns() {
2030 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2032 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2033 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2034 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2035 Record *Operator = OpDef->getDef();
2036 TreePattern *Pattern;
2037 if (Operator->getName() != "parallel")
2038 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2040 std::vector<Init*> Values;
2042 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2043 Values.push_back(Tree->getArg(j));
2044 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2046 errs() << "In dag: " << Tree->getAsString();
2047 errs() << " -- Untyped argument in pattern\n";
2048 assert(0 && "Untyped argument in pattern");
2051 ListTy = resolveTypes(ListTy, TArg->getType());
2053 errs() << "In dag: " << Tree->getAsString();
2054 errs() << " -- Incompatible types in pattern arguments\n";
2055 assert(0 && "Incompatible types in pattern arguments");
2059 ListTy = TArg->getType();
2062 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2063 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2066 // Inline pattern fragments into it.
2067 Pattern->InlinePatternFragments();
2069 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2070 if (LI->getSize() == 0) continue; // no pattern.
2072 // Parse the instruction.
2073 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2075 // Inline pattern fragments into it.
2076 Result->InlinePatternFragments();
2078 if (Result->getNumTrees() != 1)
2079 Result->error("Cannot handle instructions producing instructions "
2080 "with temporaries yet!");
2082 bool IterateInference;
2083 bool InferredAllPatternTypes, InferredAllResultTypes;
2085 // Infer as many types as possible. If we cannot infer all of them, we
2086 // can never do anything with this pattern: report it to the user.
2087 InferredAllPatternTypes = Pattern->InferAllTypes();
2089 // Infer as many types as possible. If we cannot infer all of them, we
2090 // can never do anything with this pattern: report it to the user.
2091 InferredAllResultTypes = Result->InferAllTypes();
2093 // Apply the type of the result to the source pattern. This helps us
2094 // resolve cases where the input type is known to be a pointer type (which
2095 // is considered resolved), but the result knows it needs to be 32- or
2096 // 64-bits. Infer the other way for good measure.
2097 IterateInference = Pattern->getTree(0)->
2098 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2099 IterateInference |= Result->getTree(0)->
2100 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2101 } while (IterateInference);
2103 // Verify that we inferred enough types that we can do something with the
2104 // pattern and result. If these fire the user has to add type casts.
2105 if (!InferredAllPatternTypes)
2106 Pattern->error("Could not infer all types in pattern!");
2107 if (!InferredAllResultTypes)
2108 Result->error("Could not infer all types in pattern result!");
2110 // Validate that the input pattern is correct.
2111 std::map<std::string, TreePatternNode*> InstInputs;
2112 std::map<std::string, TreePatternNode*> InstResults;
2113 std::vector<Record*> InstImpInputs;
2114 std::vector<Record*> InstImpResults;
2115 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2116 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2117 InstInputs, InstResults,
2118 InstImpInputs, InstImpResults);
2120 // Promote the xform function to be an explicit node if set.
2121 TreePatternNode *DstPattern = Result->getOnlyTree();
2122 std::vector<TreePatternNode*> ResultNodeOperands;
2123 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2124 TreePatternNode *OpNode = DstPattern->getChild(ii);
2125 if (Record *Xform = OpNode->getTransformFn()) {
2126 OpNode->setTransformFn(0);
2127 std::vector<TreePatternNode*> Children;
2128 Children.push_back(OpNode);
2129 OpNode = new TreePatternNode(Xform, Children);
2131 ResultNodeOperands.push_back(OpNode);
2133 DstPattern = Result->getOnlyTree();
2134 if (!DstPattern->isLeaf())
2135 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2136 ResultNodeOperands);
2137 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2138 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2139 Temp.InferAllTypes();
2142 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2143 Pattern->error("Pattern can never match: " + Reason);
2146 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2147 Pattern->getTree(0),
2148 Temp.getOnlyTree(), InstImpResults,
2149 Patterns[i]->getValueAsInt("AddedComplexity")));
2153 /// CombineChildVariants - Given a bunch of permutations of each child of the
2154 /// 'operator' node, put them together in all possible ways.
2155 static void CombineChildVariants(TreePatternNode *Orig,
2156 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2157 std::vector<TreePatternNode*> &OutVariants,
2158 CodeGenDAGPatterns &CDP,
2159 const MultipleUseVarSet &DepVars) {
2160 // Make sure that each operand has at least one variant to choose from.
2161 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2162 if (ChildVariants[i].empty())
2165 // The end result is an all-pairs construction of the resultant pattern.
2166 std::vector<unsigned> Idxs;
2167 Idxs.resize(ChildVariants.size());
2171 if (DebugFlag && !Idxs.empty()) {
2172 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2173 for (unsigned i = 0; i < Idxs.size(); ++i) {
2174 errs() << Idxs[i] << " ";
2179 // Create the variant and add it to the output list.
2180 std::vector<TreePatternNode*> NewChildren;
2181 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2182 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2183 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2185 // Copy over properties.
2186 R->setName(Orig->getName());
2187 R->setPredicateFns(Orig->getPredicateFns());
2188 R->setTransformFn(Orig->getTransformFn());
2189 R->setTypes(Orig->getExtTypes());
2191 // If this pattern cannot match, do not include it as a variant.
2192 std::string ErrString;
2193 if (!R->canPatternMatch(ErrString, CDP)) {
2196 bool AlreadyExists = false;
2198 // Scan to see if this pattern has already been emitted. We can get
2199 // duplication due to things like commuting:
2200 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2201 // which are the same pattern. Ignore the dups.
2202 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2203 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2204 AlreadyExists = true;
2211 OutVariants.push_back(R);
2214 // Increment indices to the next permutation by incrementing the
2215 // indicies from last index backward, e.g., generate the sequence
2216 // [0, 0], [0, 1], [1, 0], [1, 1].
2218 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2219 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2224 NotDone = (IdxsIdx >= 0);
2228 /// CombineChildVariants - A helper function for binary operators.
2230 static void CombineChildVariants(TreePatternNode *Orig,
2231 const std::vector<TreePatternNode*> &LHS,
2232 const std::vector<TreePatternNode*> &RHS,
2233 std::vector<TreePatternNode*> &OutVariants,
2234 CodeGenDAGPatterns &CDP,
2235 const MultipleUseVarSet &DepVars) {
2236 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2237 ChildVariants.push_back(LHS);
2238 ChildVariants.push_back(RHS);
2239 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2243 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2244 std::vector<TreePatternNode *> &Children) {
2245 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2246 Record *Operator = N->getOperator();
2248 // Only permit raw nodes.
2249 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2250 N->getTransformFn()) {
2251 Children.push_back(N);
2255 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2256 Children.push_back(N->getChild(0));
2258 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2260 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2261 Children.push_back(N->getChild(1));
2263 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2266 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2267 /// the (potentially recursive) pattern by using algebraic laws.
2269 static void GenerateVariantsOf(TreePatternNode *N,
2270 std::vector<TreePatternNode*> &OutVariants,
2271 CodeGenDAGPatterns &CDP,
2272 const MultipleUseVarSet &DepVars) {
2273 // We cannot permute leaves.
2275 OutVariants.push_back(N);
2279 // Look up interesting info about the node.
2280 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2282 // If this node is associative, re-associate.
2283 if (NodeInfo.hasProperty(SDNPAssociative)) {
2284 // Re-associate by pulling together all of the linked operators
2285 std::vector<TreePatternNode*> MaximalChildren;
2286 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2288 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2290 if (MaximalChildren.size() == 3) {
2291 // Find the variants of all of our maximal children.
2292 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2293 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2294 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2295 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2297 // There are only two ways we can permute the tree:
2298 // (A op B) op C and A op (B op C)
2299 // Within these forms, we can also permute A/B/C.
2301 // Generate legal pair permutations of A/B/C.
2302 std::vector<TreePatternNode*> ABVariants;
2303 std::vector<TreePatternNode*> BAVariants;
2304 std::vector<TreePatternNode*> ACVariants;
2305 std::vector<TreePatternNode*> CAVariants;
2306 std::vector<TreePatternNode*> BCVariants;
2307 std::vector<TreePatternNode*> CBVariants;
2308 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2309 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2310 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2311 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2312 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2313 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2315 // Combine those into the result: (x op x) op x
2316 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2317 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2318 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2319 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2320 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2321 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2323 // Combine those into the result: x op (x op x)
2324 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2325 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2326 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2327 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2328 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2329 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2334 // Compute permutations of all children.
2335 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2336 ChildVariants.resize(N->getNumChildren());
2337 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2338 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2340 // Build all permutations based on how the children were formed.
2341 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2343 // If this node is commutative, consider the commuted order.
2344 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2345 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2346 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2347 "Commutative but doesn't have 2 children!");
2348 // Don't count children which are actually register references.
2350 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2351 TreePatternNode *Child = N->getChild(i);
2352 if (Child->isLeaf())
2353 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2354 Record *RR = DI->getDef();
2355 if (RR->isSubClassOf("Register"))
2360 // Consider the commuted order.
2361 if (isCommIntrinsic) {
2362 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2363 // operands are the commutative operands, and there might be more operands
2366 "Commutative intrinsic should have at least 3 childrean!");
2367 std::vector<std::vector<TreePatternNode*> > Variants;
2368 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2369 Variants.push_back(ChildVariants[2]);
2370 Variants.push_back(ChildVariants[1]);
2371 for (unsigned i = 3; i != NC; ++i)
2372 Variants.push_back(ChildVariants[i]);
2373 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2375 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2376 OutVariants, CDP, DepVars);
2381 // GenerateVariants - Generate variants. For example, commutative patterns can
2382 // match multiple ways. Add them to PatternsToMatch as well.
2383 void CodeGenDAGPatterns::GenerateVariants() {
2384 DOUT << "Generating instruction variants.\n";
2386 // Loop over all of the patterns we've collected, checking to see if we can
2387 // generate variants of the instruction, through the exploitation of
2388 // identities. This permits the target to provide aggressive matching without
2389 // the .td file having to contain tons of variants of instructions.
2391 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2392 // intentionally do not reconsider these. Any variants of added patterns have
2393 // already been added.
2395 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2396 MultipleUseVarSet DepVars;
2397 std::vector<TreePatternNode*> Variants;
2398 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2399 DOUT << "Dependent/multiply used variables: ";
2400 DEBUG(DumpDepVars(DepVars));
2402 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2404 assert(!Variants.empty() && "Must create at least original variant!");
2405 Variants.erase(Variants.begin()); // Remove the original pattern.
2407 if (Variants.empty()) // No variants for this pattern.
2410 DOUT << "FOUND VARIANTS OF: ";
2411 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2414 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2415 TreePatternNode *Variant = Variants[v];
2417 DOUT << " VAR#" << v << ": ";
2418 DEBUG(Variant->dump());
2421 // Scan to see if an instruction or explicit pattern already matches this.
2422 bool AlreadyExists = false;
2423 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2424 // Skip if the top level predicates do not match.
2425 if (PatternsToMatch[i].getPredicates() !=
2426 PatternsToMatch[p].getPredicates())
2428 // Check to see if this variant already exists.
2429 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2430 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2431 AlreadyExists = true;
2435 // If we already have it, ignore the variant.
2436 if (AlreadyExists) continue;
2438 // Otherwise, add it to the list of patterns we have.
2440 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2441 Variant, PatternsToMatch[i].getDstPattern(),
2442 PatternsToMatch[i].getDstRegs(),
2443 PatternsToMatch[i].getAddedComplexity()));