1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Streams.h"
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 MVT(VT).isInteger();
61 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62 return MVT(VT).isFloatingPoint();
65 static inline bool isVector(MVT::SimpleValueType VT) {
66 return MVT(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())
78 /// isExtIntegerVT - Return true if the specified extended value type vector
79 /// 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 /// isExtFloatingPointVT - 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 integer in empty ExtVT list!");
91 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
93 } // end namespace EMVT.
94 } // end namespace llvm.
97 /// Dependent variable map for CodeGenDAGPattern variant generation
98 typedef std::map<std::string, int> DepVarMap;
100 /// Const iterator shorthand for DepVarMap
101 typedef DepVarMap::const_iterator DepVarMap_citer;
104 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
106 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
107 DepMap[N->getName()]++;
110 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
111 FindDepVarsOf(N->getChild(i), DepMap);
115 //! Find dependent variables within child patterns
118 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
120 FindDepVarsOf(N, depcounts);
121 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
122 if (i->second > 1) { // std::pair<std::string, int>
123 DepVars.insert(i->first);
128 //! Dump the dependent variable set:
129 void DumpDepVars(MultipleUseVarSet &DepVars) {
130 if (DepVars.empty()) {
131 DOUT << "<empty set>";
134 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
143 //===----------------------------------------------------------------------===//
144 // SDTypeConstraint implementation
147 SDTypeConstraint::SDTypeConstraint(Record *R) {
148 OperandNo = R->getValueAsInt("OperandNum");
150 if (R->isSubClassOf("SDTCisVT")) {
151 ConstraintType = SDTCisVT;
152 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
153 } else if (R->isSubClassOf("SDTCisPtrTy")) {
154 ConstraintType = SDTCisPtrTy;
155 } else if (R->isSubClassOf("SDTCisInt")) {
156 ConstraintType = SDTCisInt;
157 } else if (R->isSubClassOf("SDTCisFP")) {
158 ConstraintType = SDTCisFP;
159 } else if (R->isSubClassOf("SDTCisSameAs")) {
160 ConstraintType = SDTCisSameAs;
161 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
162 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
163 ConstraintType = SDTCisVTSmallerThanOp;
164 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
165 R->getValueAsInt("OtherOperandNum");
166 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
167 ConstraintType = SDTCisOpSmallerThanOp;
168 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
169 R->getValueAsInt("BigOperandNum");
170 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
171 ConstraintType = SDTCisIntVectorOfSameSize;
172 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
173 R->getValueAsInt("OtherOpNum");
174 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
175 ConstraintType = SDTCisEltOfVec;
176 x.SDTCisEltOfVec_Info.OtherOperandNum =
177 R->getValueAsInt("OtherOpNum");
179 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
184 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
185 /// N, which has NumResults results.
186 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
188 unsigned NumResults) const {
189 assert(NumResults <= 1 &&
190 "We only work with nodes with zero or one result so far!");
192 if (OpNo >= (NumResults + N->getNumChildren())) {
193 cerr << "Invalid operand number " << OpNo << " ";
199 if (OpNo < NumResults)
200 return N; // FIXME: need value #
202 return N->getChild(OpNo-NumResults);
205 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
206 /// constraint to the nodes operands. This returns true if it makes a
207 /// change, false otherwise. If a type contradiction is found, throw an
209 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
210 const SDNodeInfo &NodeInfo,
211 TreePattern &TP) const {
212 unsigned NumResults = NodeInfo.getNumResults();
213 assert(NumResults <= 1 &&
214 "We only work with nodes with zero or one result so far!");
216 // Check that the number of operands is sane. Negative operands -> varargs.
217 if (NodeInfo.getNumOperands() >= 0) {
218 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
219 TP.error(N->getOperator()->getName() + " node requires exactly " +
220 itostr(NodeInfo.getNumOperands()) + " operands!");
223 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
225 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
227 switch (ConstraintType) {
228 default: assert(0 && "Unknown constraint type!");
230 // Operand must be a particular type.
231 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
233 // Operand must be same as target pointer type.
234 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
237 // If there is only one integer type supported, this must be it.
238 std::vector<MVT::SimpleValueType> IntVTs =
239 FilterVTs(CGT.getLegalValueTypes(), isInteger);
241 // If we found exactly one supported integer type, apply it.
242 if (IntVTs.size() == 1)
243 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
244 return NodeToApply->UpdateNodeType(EMVT::isInt, TP);
247 // If there is only one FP type supported, this must be it.
248 std::vector<MVT::SimpleValueType> FPVTs =
249 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
251 // If we found exactly one supported FP type, apply it.
252 if (FPVTs.size() == 1)
253 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
254 return NodeToApply->UpdateNodeType(EMVT::isFP, TP);
257 TreePatternNode *OtherNode =
258 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
259 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
260 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
262 case SDTCisVTSmallerThanOp: {
263 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
264 // have an integer type that is smaller than the VT.
265 if (!NodeToApply->isLeaf() ||
266 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
267 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
268 ->isSubClassOf("ValueType"))
269 TP.error(N->getOperator()->getName() + " expects a VT operand!");
270 MVT::SimpleValueType VT =
271 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
273 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
275 TreePatternNode *OtherNode =
276 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
278 // It must be integer.
279 bool MadeChange = false;
280 MadeChange |= OtherNode->UpdateNodeType(EMVT::isInt, TP);
282 // This code only handles nodes that have one type set. Assert here so
283 // that we can change this if we ever need to deal with multiple value
284 // types at this point.
285 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
286 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
287 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
290 case SDTCisOpSmallerThanOp: {
291 TreePatternNode *BigOperand =
292 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
294 // Both operands must be integer or FP, but we don't care which.
295 bool MadeChange = false;
297 // This code does not currently handle nodes which have multiple types,
298 // where some types are integer, and some are fp. Assert that this is not
300 assert(!(EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
301 EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
302 !(EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
303 EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
304 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
305 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
306 MadeChange |= BigOperand->UpdateNodeType(EMVT::isInt, TP);
307 else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
308 MadeChange |= BigOperand->UpdateNodeType(EMVT::isFP, TP);
309 if (EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
310 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isInt, TP);
311 else if (EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
312 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isFP, TP);
314 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
316 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
317 VTs = FilterVTs(VTs, isInteger);
318 } else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
319 VTs = FilterVTs(VTs, isFloatingPoint);
324 switch (VTs.size()) {
325 default: // Too many VT's to pick from.
326 case 0: break; // No info yet.
328 // Only one VT of this flavor. Cannot ever satisify the constraints.
329 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
331 // If we have exactly two possible types, the little operand must be the
332 // small one, the big operand should be the big one. Common with
333 // float/double for example.
334 assert(VTs[0] < VTs[1] && "Should be sorted!");
335 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
336 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
341 case SDTCisIntVectorOfSameSize: {
342 TreePatternNode *OtherOperand =
343 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
345 if (OtherOperand->hasTypeSet()) {
346 if (!isVector(OtherOperand->getTypeNum(0)))
347 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
348 MVT IVT = OtherOperand->getTypeNum(0);
349 unsigned NumElements = IVT.getVectorNumElements();
350 IVT = MVT::getIntVectorWithNumElements(NumElements);
351 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
355 case SDTCisEltOfVec: {
356 TreePatternNode *OtherOperand =
357 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
359 if (OtherOperand->hasTypeSet()) {
360 if (!isVector(OtherOperand->getTypeNum(0)))
361 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
362 MVT IVT = OtherOperand->getTypeNum(0);
363 IVT = IVT.getVectorElementType();
364 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
372 //===----------------------------------------------------------------------===//
373 // SDNodeInfo implementation
375 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
376 EnumName = R->getValueAsString("Opcode");
377 SDClassName = R->getValueAsString("SDClass");
378 Record *TypeProfile = R->getValueAsDef("TypeProfile");
379 NumResults = TypeProfile->getValueAsInt("NumResults");
380 NumOperands = TypeProfile->getValueAsInt("NumOperands");
382 // Parse the properties.
384 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
385 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
386 if (PropList[i]->getName() == "SDNPCommutative") {
387 Properties |= 1 << SDNPCommutative;
388 } else if (PropList[i]->getName() == "SDNPAssociative") {
389 Properties |= 1 << SDNPAssociative;
390 } else if (PropList[i]->getName() == "SDNPHasChain") {
391 Properties |= 1 << SDNPHasChain;
392 } else if (PropList[i]->getName() == "SDNPOutFlag") {
393 Properties |= 1 << SDNPOutFlag;
394 } else if (PropList[i]->getName() == "SDNPInFlag") {
395 Properties |= 1 << SDNPInFlag;
396 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
397 Properties |= 1 << SDNPOptInFlag;
398 } else if (PropList[i]->getName() == "SDNPMayStore") {
399 Properties |= 1 << SDNPMayStore;
400 } else if (PropList[i]->getName() == "SDNPMayLoad") {
401 Properties |= 1 << SDNPMayLoad;
402 } else if (PropList[i]->getName() == "SDNPSideEffect") {
403 Properties |= 1 << SDNPSideEffect;
404 } else if (PropList[i]->getName() == "SDNPMemOperand") {
405 Properties |= 1 << SDNPMemOperand;
407 cerr << "Unknown SD Node property '" << PropList[i]->getName()
408 << "' on node '" << R->getName() << "'!\n";
414 // Parse the type constraints.
415 std::vector<Record*> ConstraintList =
416 TypeProfile->getValueAsListOfDefs("Constraints");
417 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
420 //===----------------------------------------------------------------------===//
421 // TreePatternNode implementation
424 TreePatternNode::~TreePatternNode() {
425 #if 0 // FIXME: implement refcounted tree nodes!
426 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
431 /// UpdateNodeType - Set the node type of N to VT if VT contains
432 /// information. If N already contains a conflicting type, then throw an
433 /// exception. This returns true if any information was updated.
435 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
437 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
439 if (ExtVTs[0] == EMVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
441 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
446 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
447 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny || ExtVTs[0] == EMVT::isInt)
449 if (EMVT::isExtIntegerInVTs(ExtVTs)) {
450 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
458 if (ExtVTs[0] == EMVT::isInt && EMVT::isExtIntegerInVTs(getExtTypes())) {
459 assert(hasTypeSet() && "should be handled above!");
460 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
461 if (getExtTypes() == FVTs)
466 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
467 EMVT::isExtIntegerInVTs(getExtTypes())) {
468 //assert(hasTypeSet() && "should be handled above!");
469 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
470 if (getExtTypes() == FVTs)
477 if (ExtVTs[0] == EMVT::isFP && EMVT::isExtFloatingPointInVTs(getExtTypes())) {
478 assert(hasTypeSet() && "should be handled above!");
479 std::vector<unsigned char> FVTs =
480 FilterEVTs(getExtTypes(), isFloatingPoint);
481 if (getExtTypes() == FVTs)
487 // If we know this is an int or fp type, and we are told it is a specific one,
490 // Similarly, we should probably set the type here to the intersection of
491 // {isInt|isFP} and ExtVTs
492 if ((getExtTypeNum(0) == EMVT::isInt &&
493 EMVT::isExtIntegerInVTs(ExtVTs)) ||
494 (getExtTypeNum(0) == EMVT::isFP &&
495 EMVT::isExtFloatingPointInVTs(ExtVTs))) {
499 if (getExtTypeNum(0) == EMVT::isInt &&
500 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
508 TP.error("Type inference contradiction found in node!");
510 TP.error("Type inference contradiction found in node " +
511 getOperator()->getName() + "!");
513 return true; // unreachable
517 void TreePatternNode::print(std::ostream &OS) const {
519 OS << *getLeafValue();
521 OS << "(" << getOperator()->getName();
524 // FIXME: At some point we should handle printing all the value types for
525 // nodes that are multiply typed.
526 switch (getExtTypeNum(0)) {
527 case MVT::Other: OS << ":Other"; break;
528 case EMVT::isInt: OS << ":isInt"; break;
529 case EMVT::isFP : OS << ":isFP"; break;
530 case EMVT::isUnknown: ; /*OS << ":?";*/ break;
531 case MVT::iPTR: OS << ":iPTR"; break;
532 case MVT::iPTRAny: OS << ":iPTRAny"; break;
534 std::string VTName = llvm::getName(getTypeNum(0));
535 // Strip off MVT:: prefix if present.
536 if (VTName.substr(0,5) == "MVT::")
537 VTName = VTName.substr(5);
544 if (getNumChildren() != 0) {
546 getChild(0)->print(OS);
547 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
549 getChild(i)->print(OS);
555 if (!PredicateFn.empty())
556 OS << "<<P:" << PredicateFn << ">>";
558 OS << "<<X:" << TransformFn->getName() << ">>";
559 if (!getName().empty())
560 OS << ":$" << getName();
563 void TreePatternNode::dump() const {
564 print(*cerr.stream());
567 /// isIsomorphicTo - Return true if this node is recursively
568 /// isomorphic to the specified node. For this comparison, the node's
569 /// entire state is considered. The assigned name is ignored, since
570 /// nodes with differing names are considered isomorphic. However, if
571 /// the assigned name is present in the dependent variable set, then
572 /// the assigned name is considered significant and the node is
573 /// isomorphic if the names match.
574 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
575 const MultipleUseVarSet &DepVars) const {
576 if (N == this) return true;
577 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
578 getPredicateFn() != N->getPredicateFn() ||
579 getTransformFn() != N->getTransformFn())
583 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
584 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
585 return ((DI->getDef() == NDI->getDef())
586 && (DepVars.find(getName()) == DepVars.end()
587 || getName() == N->getName()));
590 return getLeafValue() == N->getLeafValue();
593 if (N->getOperator() != getOperator() ||
594 N->getNumChildren() != getNumChildren()) return false;
595 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
596 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
601 /// clone - Make a copy of this tree and all of its children.
603 TreePatternNode *TreePatternNode::clone() const {
604 TreePatternNode *New;
606 New = new TreePatternNode(getLeafValue());
608 std::vector<TreePatternNode*> CChildren;
609 CChildren.reserve(Children.size());
610 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
611 CChildren.push_back(getChild(i)->clone());
612 New = new TreePatternNode(getOperator(), CChildren);
614 New->setName(getName());
615 New->setTypes(getExtTypes());
616 New->setPredicateFn(getPredicateFn());
617 New->setTransformFn(getTransformFn());
621 /// SubstituteFormalArguments - Replace the formal arguments in this tree
622 /// with actual values specified by ArgMap.
623 void TreePatternNode::
624 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
625 if (isLeaf()) return;
627 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
628 TreePatternNode *Child = getChild(i);
629 if (Child->isLeaf()) {
630 Init *Val = Child->getLeafValue();
631 if (dynamic_cast<DefInit*>(Val) &&
632 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
633 // We found a use of a formal argument, replace it with its value.
634 Child = ArgMap[Child->getName()];
635 assert(Child && "Couldn't find formal argument!");
639 getChild(i)->SubstituteFormalArguments(ArgMap);
645 /// InlinePatternFragments - If this pattern refers to any pattern
646 /// fragments, inline them into place, giving us a pattern without any
647 /// PatFrag references.
648 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
649 if (isLeaf()) return this; // nothing to do.
650 Record *Op = getOperator();
652 if (!Op->isSubClassOf("PatFrag")) {
653 // Just recursively inline children nodes.
654 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
655 setChild(i, getChild(i)->InlinePatternFragments(TP));
659 // Otherwise, we found a reference to a fragment. First, look up its
660 // TreePattern record.
661 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
663 // Verify that we are passing the right number of operands.
664 if (Frag->getNumArgs() != Children.size())
665 TP.error("'" + Op->getName() + "' fragment requires " +
666 utostr(Frag->getNumArgs()) + " operands!");
668 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
670 // Resolve formal arguments to their actual value.
671 if (Frag->getNumArgs()) {
672 // Compute the map of formal to actual arguments.
673 std::map<std::string, TreePatternNode*> ArgMap;
674 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
675 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
677 FragTree->SubstituteFormalArguments(ArgMap);
680 FragTree->setName(getName());
681 FragTree->UpdateNodeType(getExtTypes(), TP);
683 // Get a new copy of this fragment to stitch into here.
684 //delete this; // FIXME: implement refcounting!
686 // The fragment we inlined could have recursive inlining that is needed. See
687 // if there are any pattern fragments in it and inline them as needed.
688 return FragTree->InlinePatternFragments(TP);
691 /// getImplicitType - Check to see if the specified record has an implicit
692 /// type which should be applied to it. This infer the type of register
693 /// references from the register file information, for example.
695 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
697 // Some common return values
698 std::vector<unsigned char> Unknown(1, EMVT::isUnknown);
699 std::vector<unsigned char> Other(1, MVT::Other);
701 // Check to see if this is a register or a register class...
702 if (R->isSubClassOf("RegisterClass")) {
705 const CodeGenRegisterClass &RC =
706 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
707 return ConvertVTs(RC.getValueTypes());
708 } else if (R->isSubClassOf("PatFrag")) {
709 // Pattern fragment types will be resolved when they are inlined.
711 } else if (R->isSubClassOf("Register")) {
714 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
715 return T.getRegisterVTs(R);
716 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
717 // Using a VTSDNode or CondCodeSDNode.
719 } else if (R->isSubClassOf("ComplexPattern")) {
722 std::vector<unsigned char>
723 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
725 } else if (R->getName() == "ptr_rc") {
726 Other[0] = MVT::iPTR;
728 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
729 R->getName() == "zero_reg") {
734 TP.error("Unknown node flavor used in pattern: " + R->getName());
739 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
740 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
741 const CodeGenIntrinsic *TreePatternNode::
742 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
743 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
744 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
745 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
749 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
750 return &CDP.getIntrinsicInfo(IID);
753 /// isCommutativeIntrinsic - Return true if the node corresponds to a
754 /// commutative intrinsic.
756 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
757 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
758 return Int->isCommutative;
763 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
764 /// this node and its children in the tree. This returns true if it makes a
765 /// change, false otherwise. If a type contradiction is found, throw an
767 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
768 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
770 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
771 // If it's a regclass or something else known, include the type.
772 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
773 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
774 // Int inits are always integers. :)
775 bool MadeChange = UpdateNodeType(EMVT::isInt, TP);
778 // At some point, it may make sense for this tree pattern to have
779 // multiple types. Assert here that it does not, so we revisit this
780 // code when appropriate.
781 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
782 MVT::SimpleValueType VT = getTypeNum(0);
783 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
784 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
787 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
788 unsigned Size = MVT(VT).getSizeInBits();
789 // Make sure that the value is representable for this type.
791 int Val = (II->getValue() << (32-Size)) >> (32-Size);
792 if (Val != II->getValue()) {
793 // If sign-extended doesn't fit, does it fit as unsigned?
795 unsigned UnsignedVal;
796 ValueMask = unsigned(MVT(VT).getIntegerVTBitMask());
797 UnsignedVal = unsigned(II->getValue());
799 if ((ValueMask & UnsignedVal) != UnsignedVal) {
800 TP.error("Integer value '" + itostr(II->getValue())+
801 "' is out of range for type '" +
802 getEnumName(getTypeNum(0)) + "'!");
814 // special handling for set, which isn't really an SDNode.
815 if (getOperator()->getName() == "set") {
816 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
817 unsigned NC = getNumChildren();
818 bool MadeChange = false;
819 for (unsigned i = 0; i < NC-1; ++i) {
820 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
821 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
823 // Types of operands must match.
824 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
826 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
828 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
831 } else if (getOperator()->getName() == "implicit" ||
832 getOperator()->getName() == "parallel") {
833 bool MadeChange = false;
834 for (unsigned i = 0; i < getNumChildren(); ++i)
835 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
836 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
838 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
839 bool MadeChange = false;
841 // Apply the result type to the node.
842 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
844 if (getNumChildren() != Int->ArgVTs.size())
845 TP.error("Intrinsic '" + Int->Name + "' expects " +
846 utostr(Int->ArgVTs.size()-1) + " operands, not " +
847 utostr(getNumChildren()-1) + " operands!");
849 // Apply type info to the intrinsic ID.
850 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
852 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
853 MVT::SimpleValueType OpVT = Int->ArgVTs[i];
854 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
855 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
858 } else if (getOperator()->isSubClassOf("SDNode")) {
859 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
861 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
862 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
863 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
864 // Branch, etc. do not produce results and top-level forms in instr pattern
865 // must have void types.
866 if (NI.getNumResults() == 0)
867 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
869 // If this is a vector_shuffle operation, apply types to the build_vector
870 // operation. The types of the integers don't matter, but this ensures they
871 // won't get checked.
872 if (getOperator()->getName() == "vector_shuffle" &&
873 getChild(2)->getOperator()->getName() == "build_vector") {
874 TreePatternNode *BV = getChild(2);
875 const std::vector<MVT::SimpleValueType> &LegalVTs
876 = CDP.getTargetInfo().getLegalValueTypes();
877 MVT::SimpleValueType LegalIntVT = MVT::Other;
878 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
879 if (isInteger(LegalVTs[i]) && !isVector(LegalVTs[i])) {
880 LegalIntVT = LegalVTs[i];
883 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
885 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
886 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
889 } else if (getOperator()->isSubClassOf("Instruction")) {
890 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
891 bool MadeChange = false;
892 unsigned NumResults = Inst.getNumResults();
894 assert(NumResults <= 1 &&
895 "Only supports zero or one result instrs!");
897 CodeGenInstruction &InstInfo =
898 CDP.getTargetInfo().getInstruction(getOperator()->getName());
899 // Apply the result type to the node
900 if (NumResults == 0 || InstInfo.NumDefs == 0) {
901 MadeChange = UpdateNodeType(MVT::isVoid, TP);
903 Record *ResultNode = Inst.getResult(0);
905 if (ResultNode->getName() == "ptr_rc") {
906 std::vector<unsigned char> VT;
907 VT.push_back(MVT::iPTR);
908 MadeChange = UpdateNodeType(VT, TP);
909 } else if (ResultNode->getName() == "unknown") {
910 std::vector<unsigned char> VT;
911 VT.push_back(EMVT::isUnknown);
912 MadeChange = UpdateNodeType(VT, TP);
914 assert(ResultNode->isSubClassOf("RegisterClass") &&
915 "Operands should be register classes!");
917 const CodeGenRegisterClass &RC =
918 CDP.getTargetInfo().getRegisterClass(ResultNode);
919 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
923 unsigned ChildNo = 0;
924 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
925 Record *OperandNode = Inst.getOperand(i);
927 // If the instruction expects a predicate or optional def operand, we
928 // codegen this by setting the operand to it's default value if it has a
929 // non-empty DefaultOps field.
930 if ((OperandNode->isSubClassOf("PredicateOperand") ||
931 OperandNode->isSubClassOf("OptionalDefOperand")) &&
932 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
935 // Verify that we didn't run out of provided operands.
936 if (ChildNo >= getNumChildren())
937 TP.error("Instruction '" + getOperator()->getName() +
938 "' expects more operands than were provided.");
940 MVT::SimpleValueType VT;
941 TreePatternNode *Child = getChild(ChildNo++);
942 if (OperandNode->isSubClassOf("RegisterClass")) {
943 const CodeGenRegisterClass &RC =
944 CDP.getTargetInfo().getRegisterClass(OperandNode);
945 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
946 } else if (OperandNode->isSubClassOf("Operand")) {
947 VT = getValueType(OperandNode->getValueAsDef("Type"));
948 MadeChange |= Child->UpdateNodeType(VT, TP);
949 } else if (OperandNode->getName() == "ptr_rc") {
950 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
951 } else if (OperandNode->getName() == "unknown") {
952 MadeChange |= Child->UpdateNodeType(EMVT::isUnknown, TP);
954 assert(0 && "Unknown operand type!");
957 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
960 if (ChildNo != getNumChildren())
961 TP.error("Instruction '" + getOperator()->getName() +
962 "' was provided too many operands!");
966 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
968 // Node transforms always take one operand.
969 if (getNumChildren() != 1)
970 TP.error("Node transform '" + getOperator()->getName() +
971 "' requires one operand!");
973 // If either the output or input of the xform does not have exact
974 // type info. We assume they must be the same. Otherwise, it is perfectly
975 // legal to transform from one type to a completely different type.
976 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
977 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
978 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
985 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
986 /// RHS of a commutative operation, not the on LHS.
987 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
988 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
990 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
996 /// canPatternMatch - If it is impossible for this pattern to match on this
997 /// target, fill in Reason and return false. Otherwise, return true. This is
998 /// used as a santity check for .td files (to prevent people from writing stuff
999 /// that can never possibly work), and to prevent the pattern permuter from
1000 /// generating stuff that is useless.
1001 bool TreePatternNode::canPatternMatch(std::string &Reason,
1002 const CodeGenDAGPatterns &CDP) {
1003 if (isLeaf()) return true;
1005 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1006 if (!getChild(i)->canPatternMatch(Reason, CDP))
1009 // If this is an intrinsic, handle cases that would make it not match. For
1010 // example, if an operand is required to be an immediate.
1011 if (getOperator()->isSubClassOf("Intrinsic")) {
1016 // If this node is a commutative operator, check that the LHS isn't an
1018 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1019 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1020 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1021 // Scan all of the operands of the node and make sure that only the last one
1022 // is a constant node, unless the RHS also is.
1023 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1024 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1025 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1026 if (OnlyOnRHSOfCommutative(getChild(i))) {
1027 Reason="Immediate value must be on the RHS of commutative operators!";
1036 //===----------------------------------------------------------------------===//
1037 // TreePattern implementation
1040 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1041 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1042 isInputPattern = isInput;
1043 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1044 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1047 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1048 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1049 isInputPattern = isInput;
1050 Trees.push_back(ParseTreePattern(Pat));
1053 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1054 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1055 isInputPattern = isInput;
1056 Trees.push_back(Pat);
1061 void TreePattern::error(const std::string &Msg) const {
1063 throw "In " + TheRecord->getName() + ": " + Msg;
1066 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1067 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1068 if (!OpDef) error("Pattern has unexpected operator type!");
1069 Record *Operator = OpDef->getDef();
1071 if (Operator->isSubClassOf("ValueType")) {
1072 // If the operator is a ValueType, then this must be "type cast" of a leaf
1074 if (Dag->getNumArgs() != 1)
1075 error("Type cast only takes one operand!");
1077 Init *Arg = Dag->getArg(0);
1078 TreePatternNode *New;
1079 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1080 Record *R = DI->getDef();
1081 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1082 Dag->setArg(0, new DagInit(DI,
1083 std::vector<std::pair<Init*, std::string> >()));
1084 return ParseTreePattern(Dag);
1086 New = new TreePatternNode(DI);
1087 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1088 New = ParseTreePattern(DI);
1089 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1090 New = new TreePatternNode(II);
1091 if (!Dag->getArgName(0).empty())
1092 error("Constant int argument should not have a name!");
1093 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1094 // Turn this into an IntInit.
1095 Init *II = BI->convertInitializerTo(new IntRecTy());
1096 if (II == 0 || !dynamic_cast<IntInit*>(II))
1097 error("Bits value must be constants!");
1099 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1100 if (!Dag->getArgName(0).empty())
1101 error("Constant int argument should not have a name!");
1104 error("Unknown leaf value for tree pattern!");
1108 // Apply the type cast.
1109 New->UpdateNodeType(getValueType(Operator), *this);
1110 New->setName(Dag->getArgName(0));
1114 // Verify that this is something that makes sense for an operator.
1115 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1116 !Operator->isSubClassOf("Instruction") &&
1117 !Operator->isSubClassOf("SDNodeXForm") &&
1118 !Operator->isSubClassOf("Intrinsic") &&
1119 Operator->getName() != "set" &&
1120 Operator->getName() != "implicit" &&
1121 Operator->getName() != "parallel")
1122 error("Unrecognized node '" + Operator->getName() + "'!");
1124 // Check to see if this is something that is illegal in an input pattern.
1125 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1126 Operator->isSubClassOf("SDNodeXForm")))
1127 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1129 std::vector<TreePatternNode*> Children;
1131 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1132 Init *Arg = Dag->getArg(i);
1133 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1134 Children.push_back(ParseTreePattern(DI));
1135 if (Children.back()->getName().empty())
1136 Children.back()->setName(Dag->getArgName(i));
1137 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1138 Record *R = DefI->getDef();
1139 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1140 // TreePatternNode if its own.
1141 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1142 Dag->setArg(i, new DagInit(DefI,
1143 std::vector<std::pair<Init*, std::string> >()));
1144 --i; // Revisit this node...
1146 TreePatternNode *Node = new TreePatternNode(DefI);
1147 Node->setName(Dag->getArgName(i));
1148 Children.push_back(Node);
1151 if (R->getName() == "node") {
1152 if (Dag->getArgName(i).empty())
1153 error("'node' argument requires a name to match with operand list");
1154 Args.push_back(Dag->getArgName(i));
1157 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1158 TreePatternNode *Node = new TreePatternNode(II);
1159 if (!Dag->getArgName(i).empty())
1160 error("Constant int argument should not have a name!");
1161 Children.push_back(Node);
1162 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1163 // Turn this into an IntInit.
1164 Init *II = BI->convertInitializerTo(new IntRecTy());
1165 if (II == 0 || !dynamic_cast<IntInit*>(II))
1166 error("Bits value must be constants!");
1168 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1169 if (!Dag->getArgName(i).empty())
1170 error("Constant int argument should not have a name!");
1171 Children.push_back(Node);
1176 error("Unknown leaf value for tree pattern!");
1180 // If the operator is an intrinsic, then this is just syntactic sugar for for
1181 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1182 // convert the intrinsic name to a number.
1183 if (Operator->isSubClassOf("Intrinsic")) {
1184 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1185 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1187 // If this intrinsic returns void, it must have side-effects and thus a
1189 if (Int.ArgVTs[0] == MVT::isVoid) {
1190 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1191 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1192 // Has side-effects, requires chain.
1193 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1195 // Otherwise, no chain.
1196 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1199 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1200 Children.insert(Children.begin(), IIDNode);
1203 return new TreePatternNode(Operator, Children);
1206 /// InferAllTypes - Infer/propagate as many types throughout the expression
1207 /// patterns as possible. Return true if all types are infered, false
1208 /// otherwise. Throw an exception if a type contradiction is found.
1209 bool TreePattern::InferAllTypes() {
1210 bool MadeChange = true;
1211 while (MadeChange) {
1213 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1214 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1217 bool HasUnresolvedTypes = false;
1218 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1219 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1220 return !HasUnresolvedTypes;
1223 void TreePattern::print(std::ostream &OS) const {
1224 OS << getRecord()->getName();
1225 if (!Args.empty()) {
1226 OS << "(" << Args[0];
1227 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1228 OS << ", " << Args[i];
1233 if (Trees.size() > 1)
1235 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1237 Trees[i]->print(OS);
1241 if (Trees.size() > 1)
1245 void TreePattern::dump() const { print(*cerr.stream()); }
1247 //===----------------------------------------------------------------------===//
1248 // CodeGenDAGPatterns implementation
1251 // FIXME: REMOVE OSTREAM ARGUMENT
1252 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1253 Intrinsics = LoadIntrinsics(Records);
1255 ParseNodeTransforms();
1256 ParseComplexPatterns();
1257 ParsePatternFragments();
1258 ParseDefaultOperands();
1259 ParseInstructions();
1262 // Generate variants. For example, commutative patterns can match
1263 // multiple ways. Add them to PatternsToMatch as well.
1266 // Infer instruction flags. For example, we can detect loads,
1267 // stores, and side effects in many cases by examining an
1268 // instruction's pattern.
1269 InferInstructionFlags();
1272 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1273 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1274 E = PatternFragments.end(); I != E; ++I)
1279 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1280 Record *N = Records.getDef(Name);
1281 if (!N || !N->isSubClassOf("SDNode")) {
1282 cerr << "Error getting SDNode '" << Name << "'!\n";
1288 // Parse all of the SDNode definitions for the target, populating SDNodes.
1289 void CodeGenDAGPatterns::ParseNodeInfo() {
1290 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1291 while (!Nodes.empty()) {
1292 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1296 // Get the buildin intrinsic nodes.
1297 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1298 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1299 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1302 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1303 /// map, and emit them to the file as functions.
1304 void CodeGenDAGPatterns::ParseNodeTransforms() {
1305 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1306 while (!Xforms.empty()) {
1307 Record *XFormNode = Xforms.back();
1308 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1309 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1310 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1316 void CodeGenDAGPatterns::ParseComplexPatterns() {
1317 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1318 while (!AMs.empty()) {
1319 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1325 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1326 /// file, building up the PatternFragments map. After we've collected them all,
1327 /// inline fragments together as necessary, so that there are no references left
1328 /// inside a pattern fragment to a pattern fragment.
1330 void CodeGenDAGPatterns::ParsePatternFragments() {
1331 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1333 // First step, parse all of the fragments.
1334 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1335 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1336 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1337 PatternFragments[Fragments[i]] = P;
1339 // Validate the argument list, converting it to set, to discard duplicates.
1340 std::vector<std::string> &Args = P->getArgList();
1341 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1343 if (OperandsSet.count(""))
1344 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1346 // Parse the operands list.
1347 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1348 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1349 // Special cases: ops == outs == ins. Different names are used to
1350 // improve readibility.
1352 (OpsOp->getDef()->getName() != "ops" &&
1353 OpsOp->getDef()->getName() != "outs" &&
1354 OpsOp->getDef()->getName() != "ins"))
1355 P->error("Operands list should start with '(ops ... '!");
1357 // Copy over the arguments.
1359 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1360 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1361 static_cast<DefInit*>(OpsList->getArg(j))->
1362 getDef()->getName() != "node")
1363 P->error("Operands list should all be 'node' values.");
1364 if (OpsList->getArgName(j).empty())
1365 P->error("Operands list should have names for each operand!");
1366 if (!OperandsSet.count(OpsList->getArgName(j)))
1367 P->error("'" + OpsList->getArgName(j) +
1368 "' does not occur in pattern or was multiply specified!");
1369 OperandsSet.erase(OpsList->getArgName(j));
1370 Args.push_back(OpsList->getArgName(j));
1373 if (!OperandsSet.empty())
1374 P->error("Operands list does not contain an entry for operand '" +
1375 *OperandsSet.begin() + "'!");
1377 // If there is a code init for this fragment, keep track of the fact that
1378 // this fragment uses it.
1379 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1381 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1383 // If there is a node transformation corresponding to this, keep track of
1385 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1386 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1387 P->getOnlyTree()->setTransformFn(Transform);
1390 // Now that we've parsed all of the tree fragments, do a closure on them so
1391 // that there are not references to PatFrags left inside of them.
1392 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1393 TreePattern *ThePat = PatternFragments[Fragments[i]];
1394 ThePat->InlinePatternFragments();
1396 // Infer as many types as possible. Don't worry about it if we don't infer
1397 // all of them, some may depend on the inputs of the pattern.
1399 ThePat->InferAllTypes();
1401 // If this pattern fragment is not supported by this target (no types can
1402 // satisfy its constraints), just ignore it. If the bogus pattern is
1403 // actually used by instructions, the type consistency error will be
1407 // If debugging, print out the pattern fragment result.
1408 DEBUG(ThePat->dump());
1412 void CodeGenDAGPatterns::ParseDefaultOperands() {
1413 std::vector<Record*> DefaultOps[2];
1414 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1415 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1417 // Find some SDNode.
1418 assert(!SDNodes.empty() && "No SDNodes parsed?");
1419 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1421 for (unsigned iter = 0; iter != 2; ++iter) {
1422 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1423 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1425 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1426 // SomeSDnode so that we can parse this.
1427 std::vector<std::pair<Init*, std::string> > Ops;
1428 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1429 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1430 DefaultInfo->getArgName(op)));
1431 DagInit *DI = new DagInit(SomeSDNode, Ops);
1433 // Create a TreePattern to parse this.
1434 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1435 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1437 // Copy the operands over into a DAGDefaultOperand.
1438 DAGDefaultOperand DefaultOpInfo;
1440 TreePatternNode *T = P.getTree(0);
1441 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1442 TreePatternNode *TPN = T->getChild(op);
1443 while (TPN->ApplyTypeConstraints(P, false))
1444 /* Resolve all types */;
1446 if (TPN->ContainsUnresolvedType()) {
1448 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1449 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1451 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1452 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1454 DefaultOpInfo.DefaultOps.push_back(TPN);
1457 // Insert it into the DefaultOperands map so we can find it later.
1458 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1463 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1464 /// instruction input. Return true if this is a real use.
1465 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1466 std::map<std::string, TreePatternNode*> &InstInputs,
1467 std::vector<Record*> &InstImpInputs) {
1468 // No name -> not interesting.
1469 if (Pat->getName().empty()) {
1470 if (Pat->isLeaf()) {
1471 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1472 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1473 I->error("Input " + DI->getDef()->getName() + " must be named!");
1474 else if (DI && DI->getDef()->isSubClassOf("Register"))
1475 InstImpInputs.push_back(DI->getDef());
1482 if (Pat->isLeaf()) {
1483 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1484 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1487 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1488 Rec = Pat->getOperator();
1491 // SRCVALUE nodes are ignored.
1492 if (Rec->getName() == "srcvalue")
1495 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1500 if (Slot->isLeaf()) {
1501 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1503 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1504 SlotRec = Slot->getOperator();
1507 // Ensure that the inputs agree if we've already seen this input.
1509 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1510 if (Slot->getExtTypes() != Pat->getExtTypes())
1511 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1516 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1517 /// part of "I", the instruction), computing the set of inputs and outputs of
1518 /// the pattern. Report errors if we see anything naughty.
1519 void CodeGenDAGPatterns::
1520 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1521 std::map<std::string, TreePatternNode*> &InstInputs,
1522 std::map<std::string, TreePatternNode*>&InstResults,
1523 std::vector<Record*> &InstImpInputs,
1524 std::vector<Record*> &InstImpResults) {
1525 if (Pat->isLeaf()) {
1526 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1527 if (!isUse && Pat->getTransformFn())
1528 I->error("Cannot specify a transform function for a non-input value!");
1530 } else if (Pat->getOperator()->getName() == "implicit") {
1531 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1532 TreePatternNode *Dest = Pat->getChild(i);
1533 if (!Dest->isLeaf())
1534 I->error("implicitly defined value should be a register!");
1536 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1537 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1538 I->error("implicitly defined value should be a register!");
1539 InstImpResults.push_back(Val->getDef());
1542 } else if (Pat->getOperator()->getName() != "set") {
1543 // If this is not a set, verify that the children nodes are not void typed,
1545 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1546 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1547 I->error("Cannot have void nodes inside of patterns!");
1548 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1549 InstImpInputs, InstImpResults);
1552 // If this is a non-leaf node with no children, treat it basically as if
1553 // it were a leaf. This handles nodes like (imm).
1555 if (Pat->getNumChildren() == 0)
1556 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1558 if (!isUse && Pat->getTransformFn())
1559 I->error("Cannot specify a transform function for a non-input value!");
1563 // Otherwise, this is a set, validate and collect instruction results.
1564 if (Pat->getNumChildren() == 0)
1565 I->error("set requires operands!");
1567 if (Pat->getTransformFn())
1568 I->error("Cannot specify a transform function on a set node!");
1570 // Check the set destinations.
1571 unsigned NumDests = Pat->getNumChildren()-1;
1572 for (unsigned i = 0; i != NumDests; ++i) {
1573 TreePatternNode *Dest = Pat->getChild(i);
1574 if (!Dest->isLeaf())
1575 I->error("set destination should be a register!");
1577 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1579 I->error("set destination should be a register!");
1581 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1582 Val->getDef()->getName() == "ptr_rc") {
1583 if (Dest->getName().empty())
1584 I->error("set destination must have a name!");
1585 if (InstResults.count(Dest->getName()))
1586 I->error("cannot set '" + Dest->getName() +"' multiple times");
1587 InstResults[Dest->getName()] = Dest;
1588 } else if (Val->getDef()->isSubClassOf("Register")) {
1589 InstImpResults.push_back(Val->getDef());
1591 I->error("set destination should be a register!");
1595 // Verify and collect info from the computation.
1596 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1597 InstInputs, InstResults,
1598 InstImpInputs, InstImpResults);
1601 //===----------------------------------------------------------------------===//
1602 // Instruction Analysis
1603 //===----------------------------------------------------------------------===//
1605 class InstAnalyzer {
1606 const CodeGenDAGPatterns &CDP;
1609 bool &HasSideEffects;
1611 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1612 bool &maystore, bool &mayload, bool &hse)
1613 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1616 /// Analyze - Analyze the specified instruction, returning true if the
1617 /// instruction had a pattern.
1618 bool Analyze(Record *InstRecord) {
1619 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1622 return false; // No pattern.
1625 // FIXME: Assume only the first tree is the pattern. The others are clobber
1627 AnalyzeNode(Pattern->getTree(0));
1632 void AnalyzeNode(const TreePatternNode *N) {
1634 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1635 Record *LeafRec = DI->getDef();
1636 // Handle ComplexPattern leaves.
1637 if (LeafRec->isSubClassOf("ComplexPattern")) {
1638 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1639 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1640 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1641 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1647 // Analyze children.
1648 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1649 AnalyzeNode(N->getChild(i));
1651 // Ignore set nodes, which are not SDNodes.
1652 if (N->getOperator()->getName() == "set")
1655 // Get information about the SDNode for the operator.
1656 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1658 // Notice properties of the node.
1659 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1660 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1661 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1663 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1664 // If this is an intrinsic, analyze it.
1665 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1666 mayLoad = true;// These may load memory.
1668 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1669 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1671 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1672 // WriteMem intrinsics can have other strange effects.
1673 HasSideEffects = true;
1679 static void InferFromPattern(const CodeGenInstruction &Inst,
1680 bool &MayStore, bool &MayLoad,
1681 bool &HasSideEffects,
1682 const CodeGenDAGPatterns &CDP) {
1683 MayStore = MayLoad = HasSideEffects = false;
1686 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1688 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1689 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1690 // If we decided that this is a store from the pattern, then the .td file
1691 // entry is redundant.
1694 "Warning: mayStore flag explicitly set on instruction '%s'"
1695 " but flag already inferred from pattern.\n",
1696 Inst.TheDef->getName().c_str());
1700 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1701 // If we decided that this is a load from the pattern, then the .td file
1702 // entry is redundant.
1705 "Warning: mayLoad flag explicitly set on instruction '%s'"
1706 " but flag already inferred from pattern.\n",
1707 Inst.TheDef->getName().c_str());
1711 if (Inst.neverHasSideEffects) {
1713 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1714 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1715 HasSideEffects = false;
1718 if (Inst.hasSideEffects) {
1720 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1721 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1722 HasSideEffects = true;
1726 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1727 /// any fragments involved. This populates the Instructions list with fully
1728 /// resolved instructions.
1729 void CodeGenDAGPatterns::ParseInstructions() {
1730 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1732 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1735 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1736 LI = Instrs[i]->getValueAsListInit("Pattern");
1738 // If there is no pattern, only collect minimal information about the
1739 // instruction for its operand list. We have to assume that there is one
1740 // result, as we have no detailed info.
1741 if (!LI || LI->getSize() == 0) {
1742 std::vector<Record*> Results;
1743 std::vector<Record*> Operands;
1745 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1747 if (InstInfo.OperandList.size() != 0) {
1748 if (InstInfo.NumDefs == 0) {
1749 // These produce no results
1750 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1751 Operands.push_back(InstInfo.OperandList[j].Rec);
1753 // Assume the first operand is the result.
1754 Results.push_back(InstInfo.OperandList[0].Rec);
1756 // The rest are inputs.
1757 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1758 Operands.push_back(InstInfo.OperandList[j].Rec);
1762 // Create and insert the instruction.
1763 std::vector<Record*> ImpResults;
1764 std::vector<Record*> ImpOperands;
1765 Instructions.insert(std::make_pair(Instrs[i],
1766 DAGInstruction(0, Results, Operands, ImpResults,
1768 continue; // no pattern.
1771 // Parse the instruction.
1772 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1773 // Inline pattern fragments into it.
1774 I->InlinePatternFragments();
1776 // Infer as many types as possible. If we cannot infer all of them, we can
1777 // never do anything with this instruction pattern: report it to the user.
1778 if (!I->InferAllTypes())
1779 I->error("Could not infer all types in pattern!");
1781 // InstInputs - Keep track of all of the inputs of the instruction, along
1782 // with the record they are declared as.
1783 std::map<std::string, TreePatternNode*> InstInputs;
1785 // InstResults - Keep track of all the virtual registers that are 'set'
1786 // in the instruction, including what reg class they are.
1787 std::map<std::string, TreePatternNode*> InstResults;
1789 std::vector<Record*> InstImpInputs;
1790 std::vector<Record*> InstImpResults;
1792 // Verify that the top-level forms in the instruction are of void type, and
1793 // fill in the InstResults map.
1794 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1795 TreePatternNode *Pat = I->getTree(j);
1796 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1797 I->error("Top-level forms in instruction pattern should have"
1800 // Find inputs and outputs, and verify the structure of the uses/defs.
1801 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1802 InstImpInputs, InstImpResults);
1805 // Now that we have inputs and outputs of the pattern, inspect the operands
1806 // list for the instruction. This determines the order that operands are
1807 // added to the machine instruction the node corresponds to.
1808 unsigned NumResults = InstResults.size();
1810 // Parse the operands list from the (ops) list, validating it.
1811 assert(I->getArgList().empty() && "Args list should still be empty here!");
1812 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1814 // Check that all of the results occur first in the list.
1815 std::vector<Record*> Results;
1816 TreePatternNode *Res0Node = NULL;
1817 for (unsigned i = 0; i != NumResults; ++i) {
1818 if (i == CGI.OperandList.size())
1819 I->error("'" + InstResults.begin()->first +
1820 "' set but does not appear in operand list!");
1821 const std::string &OpName = CGI.OperandList[i].Name;
1823 // Check that it exists in InstResults.
1824 TreePatternNode *RNode = InstResults[OpName];
1826 I->error("Operand $" + OpName + " does not exist in operand list!");
1830 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1832 I->error("Operand $" + OpName + " should be a set destination: all "
1833 "outputs must occur before inputs in operand list!");
1835 if (CGI.OperandList[i].Rec != R)
1836 I->error("Operand $" + OpName + " class mismatch!");
1838 // Remember the return type.
1839 Results.push_back(CGI.OperandList[i].Rec);
1841 // Okay, this one checks out.
1842 InstResults.erase(OpName);
1845 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1846 // the copy while we're checking the inputs.
1847 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1849 std::vector<TreePatternNode*> ResultNodeOperands;
1850 std::vector<Record*> Operands;
1851 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1852 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1853 const std::string &OpName = Op.Name;
1855 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1857 if (!InstInputsCheck.count(OpName)) {
1858 // If this is an predicate operand or optional def operand with an
1859 // DefaultOps set filled in, we can ignore this. When we codegen it,
1860 // we will do so as always executed.
1861 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1862 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1863 // Does it have a non-empty DefaultOps field? If so, ignore this
1865 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1868 I->error("Operand $" + OpName +
1869 " does not appear in the instruction pattern");
1871 TreePatternNode *InVal = InstInputsCheck[OpName];
1872 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1874 if (InVal->isLeaf() &&
1875 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1876 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1877 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1878 I->error("Operand $" + OpName + "'s register class disagrees"
1879 " between the operand and pattern");
1881 Operands.push_back(Op.Rec);
1883 // Construct the result for the dest-pattern operand list.
1884 TreePatternNode *OpNode = InVal->clone();
1886 // No predicate is useful on the result.
1887 OpNode->setPredicateFn("");
1889 // Promote the xform function to be an explicit node if set.
1890 if (Record *Xform = OpNode->getTransformFn()) {
1891 OpNode->setTransformFn(0);
1892 std::vector<TreePatternNode*> Children;
1893 Children.push_back(OpNode);
1894 OpNode = new TreePatternNode(Xform, Children);
1897 ResultNodeOperands.push_back(OpNode);
1900 if (!InstInputsCheck.empty())
1901 I->error("Input operand $" + InstInputsCheck.begin()->first +
1902 " occurs in pattern but not in operands list!");
1904 TreePatternNode *ResultPattern =
1905 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1906 // Copy fully inferred output node type to instruction result pattern.
1908 ResultPattern->setTypes(Res0Node->getExtTypes());
1910 // Create and insert the instruction.
1911 // FIXME: InstImpResults and InstImpInputs should not be part of
1913 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1914 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1916 // Use a temporary tree pattern to infer all types and make sure that the
1917 // constructed result is correct. This depends on the instruction already
1918 // being inserted into the Instructions map.
1919 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1920 Temp.InferAllTypes();
1922 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1923 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1928 // If we can, convert the instructions to be patterns that are matched!
1929 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1930 E = Instructions.end(); II != E; ++II) {
1931 DAGInstruction &TheInst = II->second;
1932 const TreePattern *I = TheInst.getPattern();
1933 if (I == 0) continue; // No pattern.
1935 // FIXME: Assume only the first tree is the pattern. The others are clobber
1937 TreePatternNode *Pattern = I->getTree(0);
1938 TreePatternNode *SrcPattern;
1939 if (Pattern->getOperator()->getName() == "set") {
1940 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1942 // Not a set (store or something?)
1943 SrcPattern = Pattern;
1947 if (!SrcPattern->canPatternMatch(Reason, *this))
1948 I->error("Instruction can never match: " + Reason);
1950 Record *Instr = II->first;
1951 TreePatternNode *DstPattern = TheInst.getResultPattern();
1953 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1954 SrcPattern, DstPattern, TheInst.getImpResults(),
1955 Instr->getValueAsInt("AddedComplexity")));
1960 void CodeGenDAGPatterns::InferInstructionFlags() {
1961 std::map<std::string, CodeGenInstruction> &InstrDescs =
1962 Target.getInstructions();
1963 for (std::map<std::string, CodeGenInstruction>::iterator
1964 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
1965 CodeGenInstruction &InstInfo = II->second;
1966 // Determine properties of the instruction from its pattern.
1967 bool MayStore, MayLoad, HasSideEffects;
1968 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
1969 InstInfo.mayStore = MayStore;
1970 InstInfo.mayLoad = MayLoad;
1971 InstInfo.hasSideEffects = HasSideEffects;
1975 void CodeGenDAGPatterns::ParsePatterns() {
1976 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1978 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1979 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1980 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1981 Record *Operator = OpDef->getDef();
1982 TreePattern *Pattern;
1983 if (Operator->getName() != "parallel")
1984 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1986 std::vector<Init*> Values;
1987 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1988 Values.push_back(Tree->getArg(j));
1989 ListInit *LI = new ListInit(Values);
1990 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1993 // Inline pattern fragments into it.
1994 Pattern->InlinePatternFragments();
1996 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1997 if (LI->getSize() == 0) continue; // no pattern.
1999 // Parse the instruction.
2000 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2002 // Inline pattern fragments into it.
2003 Result->InlinePatternFragments();
2005 if (Result->getNumTrees() != 1)
2006 Result->error("Cannot handle instructions producing instructions "
2007 "with temporaries yet!");
2009 bool IterateInference;
2010 bool InferredAllPatternTypes, InferredAllResultTypes;
2012 // Infer as many types as possible. If we cannot infer all of them, we
2013 // can never do anything with this pattern: report it to the user.
2014 InferredAllPatternTypes = Pattern->InferAllTypes();
2016 // Infer as many types as possible. If we cannot infer all of them, we
2017 // can never do anything with this pattern: report it to the user.
2018 InferredAllResultTypes = Result->InferAllTypes();
2020 // Apply the type of the result to the source pattern. This helps us
2021 // resolve cases where the input type is known to be a pointer type (which
2022 // is considered resolved), but the result knows it needs to be 32- or
2023 // 64-bits. Infer the other way for good measure.
2024 IterateInference = Pattern->getTree(0)->
2025 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2026 IterateInference |= Result->getTree(0)->
2027 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2028 } while (IterateInference);
2030 // Verify that we inferred enough types that we can do something with the
2031 // pattern and result. If these fire the user has to add type casts.
2032 if (!InferredAllPatternTypes)
2033 Pattern->error("Could not infer all types in pattern!");
2034 if (!InferredAllResultTypes)
2035 Result->error("Could not infer all types in pattern result!");
2037 // Validate that the input pattern is correct.
2038 std::map<std::string, TreePatternNode*> InstInputs;
2039 std::map<std::string, TreePatternNode*> InstResults;
2040 std::vector<Record*> InstImpInputs;
2041 std::vector<Record*> InstImpResults;
2042 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2043 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2044 InstInputs, InstResults,
2045 InstImpInputs, InstImpResults);
2047 // Promote the xform function to be an explicit node if set.
2048 TreePatternNode *DstPattern = Result->getOnlyTree();
2049 std::vector<TreePatternNode*> ResultNodeOperands;
2050 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2051 TreePatternNode *OpNode = DstPattern->getChild(ii);
2052 if (Record *Xform = OpNode->getTransformFn()) {
2053 OpNode->setTransformFn(0);
2054 std::vector<TreePatternNode*> Children;
2055 Children.push_back(OpNode);
2056 OpNode = new TreePatternNode(Xform, Children);
2058 ResultNodeOperands.push_back(OpNode);
2060 DstPattern = Result->getOnlyTree();
2061 if (!DstPattern->isLeaf())
2062 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2063 ResultNodeOperands);
2064 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2065 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2066 Temp.InferAllTypes();
2069 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2070 Pattern->error("Pattern can never match: " + Reason);
2073 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2074 Pattern->getTree(0),
2075 Temp.getOnlyTree(), InstImpResults,
2076 Patterns[i]->getValueAsInt("AddedComplexity")));
2080 /// CombineChildVariants - Given a bunch of permutations of each child of the
2081 /// 'operator' node, put them together in all possible ways.
2082 static void CombineChildVariants(TreePatternNode *Orig,
2083 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2084 std::vector<TreePatternNode*> &OutVariants,
2085 CodeGenDAGPatterns &CDP,
2086 const MultipleUseVarSet &DepVars) {
2087 // Make sure that each operand has at least one variant to choose from.
2088 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2089 if (ChildVariants[i].empty())
2092 // The end result is an all-pairs construction of the resultant pattern.
2093 std::vector<unsigned> Idxs;
2094 Idxs.resize(ChildVariants.size());
2098 if (DebugFlag && !Idxs.empty()) {
2099 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
2100 for (unsigned i = 0; i < Idxs.size(); ++i) {
2101 cerr << Idxs[i] << " ";
2106 // Create the variant and add it to the output list.
2107 std::vector<TreePatternNode*> NewChildren;
2108 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2109 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2110 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2112 // Copy over properties.
2113 R->setName(Orig->getName());
2114 R->setPredicateFn(Orig->getPredicateFn());
2115 R->setTransformFn(Orig->getTransformFn());
2116 R->setTypes(Orig->getExtTypes());
2118 // If this pattern cannot match, do not include it as a variant.
2119 std::string ErrString;
2120 if (!R->canPatternMatch(ErrString, CDP)) {
2123 bool AlreadyExists = false;
2125 // Scan to see if this pattern has already been emitted. We can get
2126 // duplication due to things like commuting:
2127 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2128 // which are the same pattern. Ignore the dups.
2129 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2130 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2131 AlreadyExists = true;
2138 OutVariants.push_back(R);
2141 // Increment indices to the next permutation by incrementing the
2142 // indicies from last index backward, e.g., generate the sequence
2143 // [0, 0], [0, 1], [1, 0], [1, 1].
2145 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2146 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2151 NotDone = (IdxsIdx >= 0);
2155 /// CombineChildVariants - A helper function for binary operators.
2157 static void CombineChildVariants(TreePatternNode *Orig,
2158 const std::vector<TreePatternNode*> &LHS,
2159 const std::vector<TreePatternNode*> &RHS,
2160 std::vector<TreePatternNode*> &OutVariants,
2161 CodeGenDAGPatterns &CDP,
2162 const MultipleUseVarSet &DepVars) {
2163 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2164 ChildVariants.push_back(LHS);
2165 ChildVariants.push_back(RHS);
2166 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2170 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2171 std::vector<TreePatternNode *> &Children) {
2172 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2173 Record *Operator = N->getOperator();
2175 // Only permit raw nodes.
2176 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
2177 N->getTransformFn()) {
2178 Children.push_back(N);
2182 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2183 Children.push_back(N->getChild(0));
2185 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2187 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2188 Children.push_back(N->getChild(1));
2190 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2193 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2194 /// the (potentially recursive) pattern by using algebraic laws.
2196 static void GenerateVariantsOf(TreePatternNode *N,
2197 std::vector<TreePatternNode*> &OutVariants,
2198 CodeGenDAGPatterns &CDP,
2199 const MultipleUseVarSet &DepVars) {
2200 // We cannot permute leaves.
2202 OutVariants.push_back(N);
2206 // Look up interesting info about the node.
2207 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2209 // If this node is associative, reassociate.
2210 if (NodeInfo.hasProperty(SDNPAssociative)) {
2211 // Reassociate by pulling together all of the linked operators
2212 std::vector<TreePatternNode*> MaximalChildren;
2213 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2215 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2217 if (MaximalChildren.size() == 3) {
2218 // Find the variants of all of our maximal children.
2219 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2220 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2221 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2222 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2224 // There are only two ways we can permute the tree:
2225 // (A op B) op C and A op (B op C)
2226 // Within these forms, we can also permute A/B/C.
2228 // Generate legal pair permutations of A/B/C.
2229 std::vector<TreePatternNode*> ABVariants;
2230 std::vector<TreePatternNode*> BAVariants;
2231 std::vector<TreePatternNode*> ACVariants;
2232 std::vector<TreePatternNode*> CAVariants;
2233 std::vector<TreePatternNode*> BCVariants;
2234 std::vector<TreePatternNode*> CBVariants;
2235 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2236 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2237 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2238 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2239 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2240 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2242 // Combine those into the result: (x op x) op x
2243 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2244 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2245 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2246 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2247 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2248 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2250 // Combine those into the result: x op (x op x)
2251 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2252 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2253 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2254 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2255 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2256 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2261 // Compute permutations of all children.
2262 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2263 ChildVariants.resize(N->getNumChildren());
2264 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2265 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2267 // Build all permutations based on how the children were formed.
2268 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2270 // If this node is commutative, consider the commuted order.
2271 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2272 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2273 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2274 "Commutative but doesn't have 2 children!");
2275 // Don't count children which are actually register references.
2277 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2278 TreePatternNode *Child = N->getChild(i);
2279 if (Child->isLeaf())
2280 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2281 Record *RR = DI->getDef();
2282 if (RR->isSubClassOf("Register"))
2287 // Consider the commuted order.
2288 if (isCommIntrinsic) {
2289 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2290 // operands are the commutative operands, and there might be more operands
2293 "Commutative intrinsic should have at least 3 childrean!");
2294 std::vector<std::vector<TreePatternNode*> > Variants;
2295 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2296 Variants.push_back(ChildVariants[2]);
2297 Variants.push_back(ChildVariants[1]);
2298 for (unsigned i = 3; i != NC; ++i)
2299 Variants.push_back(ChildVariants[i]);
2300 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2302 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2303 OutVariants, CDP, DepVars);
2308 // GenerateVariants - Generate variants. For example, commutative patterns can
2309 // match multiple ways. Add them to PatternsToMatch as well.
2310 void CodeGenDAGPatterns::GenerateVariants() {
2311 DOUT << "Generating instruction variants.\n";
2313 // Loop over all of the patterns we've collected, checking to see if we can
2314 // generate variants of the instruction, through the exploitation of
2315 // identities. This permits the target to provide agressive matching without
2316 // the .td file having to contain tons of variants of instructions.
2318 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2319 // intentionally do not reconsider these. Any variants of added patterns have
2320 // already been added.
2322 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2323 MultipleUseVarSet DepVars;
2324 std::vector<TreePatternNode*> Variants;
2325 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2326 DOUT << "Dependent/multiply used variables: ";
2327 DEBUG(DumpDepVars(DepVars));
2329 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2331 assert(!Variants.empty() && "Must create at least original variant!");
2332 Variants.erase(Variants.begin()); // Remove the original pattern.
2334 if (Variants.empty()) // No variants for this pattern.
2337 DOUT << "FOUND VARIANTS OF: ";
2338 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2341 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2342 TreePatternNode *Variant = Variants[v];
2344 DOUT << " VAR#" << v << ": ";
2345 DEBUG(Variant->dump());
2348 // Scan to see if an instruction or explicit pattern already matches this.
2349 bool AlreadyExists = false;
2350 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2351 // Check to see if this variant already exists.
2352 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2353 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2354 AlreadyExists = true;
2358 // If we already have it, ignore the variant.
2359 if (AlreadyExists) continue;
2361 // Otherwise, add it to the list of patterns we have.
2363 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2364 Variant, PatternsToMatch[i].getDstPattern(),
2365 PatternsToMatch[i].getDstRegs(),
2366 PatternsToMatch[i].getAddedComplexity()));