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) {
447 if (ExtVTs[0] == MVT::iPTR || 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 && EMVT::isExtIntegerInVTs(getExtTypes())) {
467 //assert(hasTypeSet() && "should be handled above!");
468 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
469 if (getExtTypes() == FVTs)
476 if (ExtVTs[0] == EMVT::isFP && EMVT::isExtFloatingPointInVTs(getExtTypes())) {
477 assert(hasTypeSet() && "should be handled above!");
478 std::vector<unsigned char> FVTs =
479 FilterEVTs(getExtTypes(), isFloatingPoint);
480 if (getExtTypes() == FVTs)
486 // If we know this is an int or fp type, and we are told it is a specific one,
489 // Similarly, we should probably set the type here to the intersection of
490 // {isInt|isFP} and ExtVTs
491 if ((getExtTypeNum(0) == EMVT::isInt &&
492 EMVT::isExtIntegerInVTs(ExtVTs)) ||
493 (getExtTypeNum(0) == EMVT::isFP &&
494 EMVT::isExtFloatingPointInVTs(ExtVTs))) {
498 if (getExtTypeNum(0) == EMVT::isInt && ExtVTs[0] == MVT::iPTR) {
506 TP.error("Type inference contradiction found in node!");
508 TP.error("Type inference contradiction found in node " +
509 getOperator()->getName() + "!");
511 return true; // unreachable
515 void TreePatternNode::print(std::ostream &OS) const {
517 OS << *getLeafValue();
519 OS << "(" << getOperator()->getName();
522 // FIXME: At some point we should handle printing all the value types for
523 // nodes that are multiply typed.
524 switch (getExtTypeNum(0)) {
525 case MVT::Other: OS << ":Other"; break;
526 case EMVT::isInt: OS << ":isInt"; break;
527 case EMVT::isFP : OS << ":isFP"; break;
528 case EMVT::isUnknown: ; /*OS << ":?";*/ break;
529 case MVT::iPTR: OS << ":iPTR"; break;
531 std::string VTName = llvm::getName(getTypeNum(0));
532 // Strip off MVT:: prefix if present.
533 if (VTName.substr(0,5) == "MVT::")
534 VTName = VTName.substr(5);
541 if (getNumChildren() != 0) {
543 getChild(0)->print(OS);
544 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
546 getChild(i)->print(OS);
552 if (!PredicateFn.empty())
553 OS << "<<P:" << PredicateFn << ">>";
555 OS << "<<X:" << TransformFn->getName() << ">>";
556 if (!getName().empty())
557 OS << ":$" << getName();
560 void TreePatternNode::dump() const {
561 print(*cerr.stream());
564 /// isIsomorphicTo - Return true if this node is recursively
565 /// isomorphic to the specified node. For this comparison, the node's
566 /// entire state is considered. The assigned name is ignored, since
567 /// nodes with differing names are considered isomorphic. However, if
568 /// the assigned name is present in the dependent variable set, then
569 /// the assigned name is considered significant and the node is
570 /// isomorphic if the names match.
571 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
572 const MultipleUseVarSet &DepVars) const {
573 if (N == this) return true;
574 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
575 getPredicateFn() != N->getPredicateFn() ||
576 getTransformFn() != N->getTransformFn())
580 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
581 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
582 return ((DI->getDef() == NDI->getDef())
583 && (DepVars.find(getName()) == DepVars.end()
584 || getName() == N->getName()));
587 return getLeafValue() == N->getLeafValue();
590 if (N->getOperator() != getOperator() ||
591 N->getNumChildren() != getNumChildren()) return false;
592 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
593 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
598 /// clone - Make a copy of this tree and all of its children.
600 TreePatternNode *TreePatternNode::clone() const {
601 TreePatternNode *New;
603 New = new TreePatternNode(getLeafValue());
605 std::vector<TreePatternNode*> CChildren;
606 CChildren.reserve(Children.size());
607 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
608 CChildren.push_back(getChild(i)->clone());
609 New = new TreePatternNode(getOperator(), CChildren);
611 New->setName(getName());
612 New->setTypes(getExtTypes());
613 New->setPredicateFn(getPredicateFn());
614 New->setTransformFn(getTransformFn());
618 /// SubstituteFormalArguments - Replace the formal arguments in this tree
619 /// with actual values specified by ArgMap.
620 void TreePatternNode::
621 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
622 if (isLeaf()) return;
624 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
625 TreePatternNode *Child = getChild(i);
626 if (Child->isLeaf()) {
627 Init *Val = Child->getLeafValue();
628 if (dynamic_cast<DefInit*>(Val) &&
629 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
630 // We found a use of a formal argument, replace it with its value.
631 Child = ArgMap[Child->getName()];
632 assert(Child && "Couldn't find formal argument!");
636 getChild(i)->SubstituteFormalArguments(ArgMap);
642 /// InlinePatternFragments - If this pattern refers to any pattern
643 /// fragments, inline them into place, giving us a pattern without any
644 /// PatFrag references.
645 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
646 if (isLeaf()) return this; // nothing to do.
647 Record *Op = getOperator();
649 if (!Op->isSubClassOf("PatFrag")) {
650 // Just recursively inline children nodes.
651 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
652 setChild(i, getChild(i)->InlinePatternFragments(TP));
656 // Otherwise, we found a reference to a fragment. First, look up its
657 // TreePattern record.
658 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
660 // Verify that we are passing the right number of operands.
661 if (Frag->getNumArgs() != Children.size())
662 TP.error("'" + Op->getName() + "' fragment requires " +
663 utostr(Frag->getNumArgs()) + " operands!");
665 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
667 // Resolve formal arguments to their actual value.
668 if (Frag->getNumArgs()) {
669 // Compute the map of formal to actual arguments.
670 std::map<std::string, TreePatternNode*> ArgMap;
671 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
672 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
674 FragTree->SubstituteFormalArguments(ArgMap);
677 FragTree->setName(getName());
678 FragTree->UpdateNodeType(getExtTypes(), TP);
680 // Get a new copy of this fragment to stitch into here.
681 //delete this; // FIXME: implement refcounting!
683 // The fragment we inlined could have recursive inlining that is needed. See
684 // if there are any pattern fragments in it and inline them as needed.
685 return FragTree->InlinePatternFragments(TP);
688 /// getImplicitType - Check to see if the specified record has an implicit
689 /// type which should be applied to it. This infer the type of register
690 /// references from the register file information, for example.
692 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
694 // Some common return values
695 std::vector<unsigned char> Unknown(1, EMVT::isUnknown);
696 std::vector<unsigned char> Other(1, MVT::Other);
698 // Check to see if this is a register or a register class...
699 if (R->isSubClassOf("RegisterClass")) {
702 const CodeGenRegisterClass &RC =
703 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
704 return ConvertVTs(RC.getValueTypes());
705 } else if (R->isSubClassOf("PatFrag")) {
706 // Pattern fragment types will be resolved when they are inlined.
708 } else if (R->isSubClassOf("Register")) {
711 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
712 return T.getRegisterVTs(R);
713 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
714 // Using a VTSDNode or CondCodeSDNode.
716 } else if (R->isSubClassOf("ComplexPattern")) {
719 std::vector<unsigned char>
720 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
722 } else if (R->getName() == "ptr_rc") {
723 Other[0] = MVT::iPTR;
725 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
726 R->getName() == "zero_reg") {
731 TP.error("Unknown node flavor used in pattern: " + R->getName());
736 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
737 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
738 const CodeGenIntrinsic *TreePatternNode::
739 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
740 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
741 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
742 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
746 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
747 return &CDP.getIntrinsicInfo(IID);
750 /// isCommutativeIntrinsic - Return true if the node corresponds to a
751 /// commutative intrinsic.
753 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
754 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
755 return Int->isCommutative;
760 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
761 /// this node and its children in the tree. This returns true if it makes a
762 /// change, false otherwise. If a type contradiction is found, throw an
764 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
765 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
767 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
768 // If it's a regclass or something else known, include the type.
769 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
770 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
771 // Int inits are always integers. :)
772 bool MadeChange = UpdateNodeType(EMVT::isInt, TP);
775 // At some point, it may make sense for this tree pattern to have
776 // multiple types. Assert here that it does not, so we revisit this
777 // code when appropriate.
778 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
779 MVT::SimpleValueType VT = getTypeNum(0);
780 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
781 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
784 if (VT != MVT::iPTR) {
785 unsigned Size = MVT(VT).getSizeInBits();
786 // Make sure that the value is representable for this type.
788 int Val = (II->getValue() << (32-Size)) >> (32-Size);
789 if (Val != II->getValue()) {
790 // If sign-extended doesn't fit, does it fit as unsigned?
792 unsigned UnsignedVal;
793 ValueMask = unsigned(MVT(VT).getIntegerVTBitMask());
794 UnsignedVal = unsigned(II->getValue());
796 if ((ValueMask & UnsignedVal) != UnsignedVal) {
797 TP.error("Integer value '" + itostr(II->getValue())+
798 "' is out of range for type '" +
799 getEnumName(getTypeNum(0)) + "'!");
811 // special handling for set, which isn't really an SDNode.
812 if (getOperator()->getName() == "set") {
813 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
814 unsigned NC = getNumChildren();
815 bool MadeChange = false;
816 for (unsigned i = 0; i < NC-1; ++i) {
817 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
818 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
820 // Types of operands must match.
821 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
823 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
825 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
828 } else if (getOperator()->getName() == "implicit" ||
829 getOperator()->getName() == "parallel") {
830 bool MadeChange = false;
831 for (unsigned i = 0; i < getNumChildren(); ++i)
832 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
833 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
835 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
836 bool MadeChange = false;
838 // Apply the result type to the node.
839 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
841 if (getNumChildren() != Int->ArgVTs.size())
842 TP.error("Intrinsic '" + Int->Name + "' expects " +
843 utostr(Int->ArgVTs.size()-1) + " operands, not " +
844 utostr(getNumChildren()-1) + " operands!");
846 // Apply type info to the intrinsic ID.
847 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
849 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
850 MVT::SimpleValueType OpVT = Int->ArgVTs[i];
851 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
852 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
855 } else if (getOperator()->isSubClassOf("SDNode")) {
856 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
858 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
859 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
860 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
861 // Branch, etc. do not produce results and top-level forms in instr pattern
862 // must have void types.
863 if (NI.getNumResults() == 0)
864 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
866 // If this is a vector_shuffle operation, apply types to the build_vector
867 // operation. The types of the integers don't matter, but this ensures they
868 // won't get checked.
869 if (getOperator()->getName() == "vector_shuffle" &&
870 getChild(2)->getOperator()->getName() == "build_vector") {
871 TreePatternNode *BV = getChild(2);
872 const std::vector<MVT::SimpleValueType> &LegalVTs
873 = CDP.getTargetInfo().getLegalValueTypes();
874 MVT::SimpleValueType LegalIntVT = MVT::Other;
875 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
876 if (isInteger(LegalVTs[i]) && !isVector(LegalVTs[i])) {
877 LegalIntVT = LegalVTs[i];
880 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
882 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
883 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
886 } else if (getOperator()->isSubClassOf("Instruction")) {
887 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
888 bool MadeChange = false;
889 unsigned NumResults = Inst.getNumResults();
891 assert(NumResults <= 1 &&
892 "Only supports zero or one result instrs!");
894 CodeGenInstruction &InstInfo =
895 CDP.getTargetInfo().getInstruction(getOperator()->getName());
896 // Apply the result type to the node
897 if (NumResults == 0 || InstInfo.NumDefs == 0) {
898 MadeChange = UpdateNodeType(MVT::isVoid, TP);
900 Record *ResultNode = Inst.getResult(0);
902 if (ResultNode->getName() == "ptr_rc") {
903 std::vector<unsigned char> VT;
904 VT.push_back(MVT::iPTR);
905 MadeChange = UpdateNodeType(VT, TP);
906 } else if (ResultNode->getName() == "unknown") {
907 std::vector<unsigned char> VT;
908 VT.push_back(EMVT::isUnknown);
909 MadeChange = UpdateNodeType(VT, TP);
911 assert(ResultNode->isSubClassOf("RegisterClass") &&
912 "Operands should be register classes!");
914 const CodeGenRegisterClass &RC =
915 CDP.getTargetInfo().getRegisterClass(ResultNode);
916 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
920 unsigned ChildNo = 0;
921 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
922 Record *OperandNode = Inst.getOperand(i);
924 // If the instruction expects a predicate or optional def operand, we
925 // codegen this by setting the operand to it's default value if it has a
926 // non-empty DefaultOps field.
927 if ((OperandNode->isSubClassOf("PredicateOperand") ||
928 OperandNode->isSubClassOf("OptionalDefOperand")) &&
929 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
932 // Verify that we didn't run out of provided operands.
933 if (ChildNo >= getNumChildren())
934 TP.error("Instruction '" + getOperator()->getName() +
935 "' expects more operands than were provided.");
937 MVT::SimpleValueType VT;
938 TreePatternNode *Child = getChild(ChildNo++);
939 if (OperandNode->isSubClassOf("RegisterClass")) {
940 const CodeGenRegisterClass &RC =
941 CDP.getTargetInfo().getRegisterClass(OperandNode);
942 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
943 } else if (OperandNode->isSubClassOf("Operand")) {
944 VT = getValueType(OperandNode->getValueAsDef("Type"));
945 MadeChange |= Child->UpdateNodeType(VT, TP);
946 } else if (OperandNode->getName() == "ptr_rc") {
947 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
948 } else if (OperandNode->getName() == "unknown") {
949 MadeChange |= Child->UpdateNodeType(EMVT::isUnknown, TP);
951 assert(0 && "Unknown operand type!");
954 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
957 if (ChildNo != getNumChildren())
958 TP.error("Instruction '" + getOperator()->getName() +
959 "' was provided too many operands!");
963 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
965 // Node transforms always take one operand.
966 if (getNumChildren() != 1)
967 TP.error("Node transform '" + getOperator()->getName() +
968 "' requires one operand!");
970 // If either the output or input of the xform does not have exact
971 // type info. We assume they must be the same. Otherwise, it is perfectly
972 // legal to transform from one type to a completely different type.
973 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
974 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
975 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
982 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
983 /// RHS of a commutative operation, not the on LHS.
984 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
985 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
987 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
993 /// canPatternMatch - If it is impossible for this pattern to match on this
994 /// target, fill in Reason and return false. Otherwise, return true. This is
995 /// used as a santity check for .td files (to prevent people from writing stuff
996 /// that can never possibly work), and to prevent the pattern permuter from
997 /// generating stuff that is useless.
998 bool TreePatternNode::canPatternMatch(std::string &Reason,
999 const CodeGenDAGPatterns &CDP) {
1000 if (isLeaf()) return true;
1002 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1003 if (!getChild(i)->canPatternMatch(Reason, CDP))
1006 // If this is an intrinsic, handle cases that would make it not match. For
1007 // example, if an operand is required to be an immediate.
1008 if (getOperator()->isSubClassOf("Intrinsic")) {
1013 // If this node is a commutative operator, check that the LHS isn't an
1015 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1016 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1017 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1018 // Scan all of the operands of the node and make sure that only the last one
1019 // is a constant node, unless the RHS also is.
1020 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1021 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1022 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1023 if (OnlyOnRHSOfCommutative(getChild(i))) {
1024 Reason="Immediate value must be on the RHS of commutative operators!";
1033 //===----------------------------------------------------------------------===//
1034 // TreePattern implementation
1037 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1038 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1039 isInputPattern = isInput;
1040 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1041 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1044 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1045 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1046 isInputPattern = isInput;
1047 Trees.push_back(ParseTreePattern(Pat));
1050 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1051 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1052 isInputPattern = isInput;
1053 Trees.push_back(Pat);
1058 void TreePattern::error(const std::string &Msg) const {
1060 throw "In " + TheRecord->getName() + ": " + Msg;
1063 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1064 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1065 if (!OpDef) error("Pattern has unexpected operator type!");
1066 Record *Operator = OpDef->getDef();
1068 if (Operator->isSubClassOf("ValueType")) {
1069 // If the operator is a ValueType, then this must be "type cast" of a leaf
1071 if (Dag->getNumArgs() != 1)
1072 error("Type cast only takes one operand!");
1074 Init *Arg = Dag->getArg(0);
1075 TreePatternNode *New;
1076 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1077 Record *R = DI->getDef();
1078 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1079 Dag->setArg(0, new DagInit(DI,
1080 std::vector<std::pair<Init*, std::string> >()));
1081 return ParseTreePattern(Dag);
1083 New = new TreePatternNode(DI);
1084 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1085 New = ParseTreePattern(DI);
1086 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1087 New = new TreePatternNode(II);
1088 if (!Dag->getArgName(0).empty())
1089 error("Constant int argument should not have a name!");
1090 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1091 // Turn this into an IntInit.
1092 Init *II = BI->convertInitializerTo(new IntRecTy());
1093 if (II == 0 || !dynamic_cast<IntInit*>(II))
1094 error("Bits value must be constants!");
1096 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1097 if (!Dag->getArgName(0).empty())
1098 error("Constant int argument should not have a name!");
1101 error("Unknown leaf value for tree pattern!");
1105 // Apply the type cast.
1106 New->UpdateNodeType(getValueType(Operator), *this);
1107 New->setName(Dag->getArgName(0));
1111 // Verify that this is something that makes sense for an operator.
1112 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1113 !Operator->isSubClassOf("Instruction") &&
1114 !Operator->isSubClassOf("SDNodeXForm") &&
1115 !Operator->isSubClassOf("Intrinsic") &&
1116 Operator->getName() != "set" &&
1117 Operator->getName() != "implicit" &&
1118 Operator->getName() != "parallel")
1119 error("Unrecognized node '" + Operator->getName() + "'!");
1121 // Check to see if this is something that is illegal in an input pattern.
1122 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1123 Operator->isSubClassOf("SDNodeXForm")))
1124 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1126 std::vector<TreePatternNode*> Children;
1128 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1129 Init *Arg = Dag->getArg(i);
1130 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1131 Children.push_back(ParseTreePattern(DI));
1132 if (Children.back()->getName().empty())
1133 Children.back()->setName(Dag->getArgName(i));
1134 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1135 Record *R = DefI->getDef();
1136 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1137 // TreePatternNode if its own.
1138 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1139 Dag->setArg(i, new DagInit(DefI,
1140 std::vector<std::pair<Init*, std::string> >()));
1141 --i; // Revisit this node...
1143 TreePatternNode *Node = new TreePatternNode(DefI);
1144 Node->setName(Dag->getArgName(i));
1145 Children.push_back(Node);
1148 if (R->getName() == "node") {
1149 if (Dag->getArgName(i).empty())
1150 error("'node' argument requires a name to match with operand list");
1151 Args.push_back(Dag->getArgName(i));
1154 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1155 TreePatternNode *Node = new TreePatternNode(II);
1156 if (!Dag->getArgName(i).empty())
1157 error("Constant int argument should not have a name!");
1158 Children.push_back(Node);
1159 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1160 // Turn this into an IntInit.
1161 Init *II = BI->convertInitializerTo(new IntRecTy());
1162 if (II == 0 || !dynamic_cast<IntInit*>(II))
1163 error("Bits value must be constants!");
1165 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1166 if (!Dag->getArgName(i).empty())
1167 error("Constant int argument should not have a name!");
1168 Children.push_back(Node);
1173 error("Unknown leaf value for tree pattern!");
1177 // If the operator is an intrinsic, then this is just syntactic sugar for for
1178 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1179 // convert the intrinsic name to a number.
1180 if (Operator->isSubClassOf("Intrinsic")) {
1181 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1182 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1184 // If this intrinsic returns void, it must have side-effects and thus a
1186 if (Int.ArgVTs[0] == MVT::isVoid) {
1187 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1188 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1189 // Has side-effects, requires chain.
1190 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1192 // Otherwise, no chain.
1193 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1196 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1197 Children.insert(Children.begin(), IIDNode);
1200 return new TreePatternNode(Operator, Children);
1203 /// InferAllTypes - Infer/propagate as many types throughout the expression
1204 /// patterns as possible. Return true if all types are infered, false
1205 /// otherwise. Throw an exception if a type contradiction is found.
1206 bool TreePattern::InferAllTypes() {
1207 bool MadeChange = true;
1208 while (MadeChange) {
1210 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1211 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1214 bool HasUnresolvedTypes = false;
1215 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1216 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1217 return !HasUnresolvedTypes;
1220 void TreePattern::print(std::ostream &OS) const {
1221 OS << getRecord()->getName();
1222 if (!Args.empty()) {
1223 OS << "(" << Args[0];
1224 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1225 OS << ", " << Args[i];
1230 if (Trees.size() > 1)
1232 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1234 Trees[i]->print(OS);
1238 if (Trees.size() > 1)
1242 void TreePattern::dump() const { print(*cerr.stream()); }
1244 //===----------------------------------------------------------------------===//
1245 // CodeGenDAGPatterns implementation
1248 // FIXME: REMOVE OSTREAM ARGUMENT
1249 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1250 Intrinsics = LoadIntrinsics(Records);
1252 ParseNodeTransforms();
1253 ParseComplexPatterns();
1254 ParsePatternFragments();
1255 ParseDefaultOperands();
1256 ParseInstructions();
1259 // Generate variants. For example, commutative patterns can match
1260 // multiple ways. Add them to PatternsToMatch as well.
1263 // Infer instruction flags. For example, we can detect loads,
1264 // stores, and side effects in many cases by examining an
1265 // instruction's pattern.
1266 InferInstructionFlags();
1269 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1270 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1271 E = PatternFragments.end(); I != E; ++I)
1276 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1277 Record *N = Records.getDef(Name);
1278 if (!N || !N->isSubClassOf("SDNode")) {
1279 cerr << "Error getting SDNode '" << Name << "'!\n";
1285 // Parse all of the SDNode definitions for the target, populating SDNodes.
1286 void CodeGenDAGPatterns::ParseNodeInfo() {
1287 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1288 while (!Nodes.empty()) {
1289 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1293 // Get the buildin intrinsic nodes.
1294 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1295 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1296 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1299 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1300 /// map, and emit them to the file as functions.
1301 void CodeGenDAGPatterns::ParseNodeTransforms() {
1302 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1303 while (!Xforms.empty()) {
1304 Record *XFormNode = Xforms.back();
1305 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1306 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1307 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1313 void CodeGenDAGPatterns::ParseComplexPatterns() {
1314 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1315 while (!AMs.empty()) {
1316 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1322 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1323 /// file, building up the PatternFragments map. After we've collected them all,
1324 /// inline fragments together as necessary, so that there are no references left
1325 /// inside a pattern fragment to a pattern fragment.
1327 void CodeGenDAGPatterns::ParsePatternFragments() {
1328 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1330 // First step, parse all of the fragments.
1331 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1332 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1333 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1334 PatternFragments[Fragments[i]] = P;
1336 // Validate the argument list, converting it to set, to discard duplicates.
1337 std::vector<std::string> &Args = P->getArgList();
1338 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1340 if (OperandsSet.count(""))
1341 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1343 // Parse the operands list.
1344 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1345 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1346 // Special cases: ops == outs == ins. Different names are used to
1347 // improve readibility.
1349 (OpsOp->getDef()->getName() != "ops" &&
1350 OpsOp->getDef()->getName() != "outs" &&
1351 OpsOp->getDef()->getName() != "ins"))
1352 P->error("Operands list should start with '(ops ... '!");
1354 // Copy over the arguments.
1356 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1357 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1358 static_cast<DefInit*>(OpsList->getArg(j))->
1359 getDef()->getName() != "node")
1360 P->error("Operands list should all be 'node' values.");
1361 if (OpsList->getArgName(j).empty())
1362 P->error("Operands list should have names for each operand!");
1363 if (!OperandsSet.count(OpsList->getArgName(j)))
1364 P->error("'" + OpsList->getArgName(j) +
1365 "' does not occur in pattern or was multiply specified!");
1366 OperandsSet.erase(OpsList->getArgName(j));
1367 Args.push_back(OpsList->getArgName(j));
1370 if (!OperandsSet.empty())
1371 P->error("Operands list does not contain an entry for operand '" +
1372 *OperandsSet.begin() + "'!");
1374 // If there is a code init for this fragment, keep track of the fact that
1375 // this fragment uses it.
1376 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1378 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1380 // If there is a node transformation corresponding to this, keep track of
1382 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1383 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1384 P->getOnlyTree()->setTransformFn(Transform);
1387 // Now that we've parsed all of the tree fragments, do a closure on them so
1388 // that there are not references to PatFrags left inside of them.
1389 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1390 TreePattern *ThePat = PatternFragments[Fragments[i]];
1391 ThePat->InlinePatternFragments();
1393 // Infer as many types as possible. Don't worry about it if we don't infer
1394 // all of them, some may depend on the inputs of the pattern.
1396 ThePat->InferAllTypes();
1398 // If this pattern fragment is not supported by this target (no types can
1399 // satisfy its constraints), just ignore it. If the bogus pattern is
1400 // actually used by instructions, the type consistency error will be
1404 // If debugging, print out the pattern fragment result.
1405 DEBUG(ThePat->dump());
1409 void CodeGenDAGPatterns::ParseDefaultOperands() {
1410 std::vector<Record*> DefaultOps[2];
1411 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1412 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1414 // Find some SDNode.
1415 assert(!SDNodes.empty() && "No SDNodes parsed?");
1416 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1418 for (unsigned iter = 0; iter != 2; ++iter) {
1419 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1420 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1422 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1423 // SomeSDnode so that we can parse this.
1424 std::vector<std::pair<Init*, std::string> > Ops;
1425 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1426 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1427 DefaultInfo->getArgName(op)));
1428 DagInit *DI = new DagInit(SomeSDNode, Ops);
1430 // Create a TreePattern to parse this.
1431 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1432 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1434 // Copy the operands over into a DAGDefaultOperand.
1435 DAGDefaultOperand DefaultOpInfo;
1437 TreePatternNode *T = P.getTree(0);
1438 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1439 TreePatternNode *TPN = T->getChild(op);
1440 while (TPN->ApplyTypeConstraints(P, false))
1441 /* Resolve all types */;
1443 if (TPN->ContainsUnresolvedType()) {
1445 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1446 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1448 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1449 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1451 DefaultOpInfo.DefaultOps.push_back(TPN);
1454 // Insert it into the DefaultOperands map so we can find it later.
1455 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1460 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1461 /// instruction input. Return true if this is a real use.
1462 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1463 std::map<std::string, TreePatternNode*> &InstInputs,
1464 std::vector<Record*> &InstImpInputs) {
1465 // No name -> not interesting.
1466 if (Pat->getName().empty()) {
1467 if (Pat->isLeaf()) {
1468 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1469 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1470 I->error("Input " + DI->getDef()->getName() + " must be named!");
1471 else if (DI && DI->getDef()->isSubClassOf("Register"))
1472 InstImpInputs.push_back(DI->getDef());
1479 if (Pat->isLeaf()) {
1480 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1481 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1484 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1485 Rec = Pat->getOperator();
1488 // SRCVALUE nodes are ignored.
1489 if (Rec->getName() == "srcvalue")
1492 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1497 if (Slot->isLeaf()) {
1498 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1500 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1501 SlotRec = Slot->getOperator();
1504 // Ensure that the inputs agree if we've already seen this input.
1506 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1507 if (Slot->getExtTypes() != Pat->getExtTypes())
1508 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1513 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1514 /// part of "I", the instruction), computing the set of inputs and outputs of
1515 /// the pattern. Report errors if we see anything naughty.
1516 void CodeGenDAGPatterns::
1517 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1518 std::map<std::string, TreePatternNode*> &InstInputs,
1519 std::map<std::string, TreePatternNode*>&InstResults,
1520 std::vector<Record*> &InstImpInputs,
1521 std::vector<Record*> &InstImpResults) {
1522 if (Pat->isLeaf()) {
1523 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1524 if (!isUse && Pat->getTransformFn())
1525 I->error("Cannot specify a transform function for a non-input value!");
1527 } else if (Pat->getOperator()->getName() == "implicit") {
1528 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1529 TreePatternNode *Dest = Pat->getChild(i);
1530 if (!Dest->isLeaf())
1531 I->error("implicitly defined value should be a register!");
1533 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1534 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1535 I->error("implicitly defined value should be a register!");
1536 InstImpResults.push_back(Val->getDef());
1539 } else if (Pat->getOperator()->getName() != "set") {
1540 // If this is not a set, verify that the children nodes are not void typed,
1542 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1543 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1544 I->error("Cannot have void nodes inside of patterns!");
1545 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1546 InstImpInputs, InstImpResults);
1549 // If this is a non-leaf node with no children, treat it basically as if
1550 // it were a leaf. This handles nodes like (imm).
1552 if (Pat->getNumChildren() == 0)
1553 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1555 if (!isUse && Pat->getTransformFn())
1556 I->error("Cannot specify a transform function for a non-input value!");
1560 // Otherwise, this is a set, validate and collect instruction results.
1561 if (Pat->getNumChildren() == 0)
1562 I->error("set requires operands!");
1564 if (Pat->getTransformFn())
1565 I->error("Cannot specify a transform function on a set node!");
1567 // Check the set destinations.
1568 unsigned NumDests = Pat->getNumChildren()-1;
1569 for (unsigned i = 0; i != NumDests; ++i) {
1570 TreePatternNode *Dest = Pat->getChild(i);
1571 if (!Dest->isLeaf())
1572 I->error("set destination should be a register!");
1574 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1576 I->error("set destination should be a register!");
1578 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1579 Val->getDef()->getName() == "ptr_rc") {
1580 if (Dest->getName().empty())
1581 I->error("set destination must have a name!");
1582 if (InstResults.count(Dest->getName()))
1583 I->error("cannot set '" + Dest->getName() +"' multiple times");
1584 InstResults[Dest->getName()] = Dest;
1585 } else if (Val->getDef()->isSubClassOf("Register")) {
1586 InstImpResults.push_back(Val->getDef());
1588 I->error("set destination should be a register!");
1592 // Verify and collect info from the computation.
1593 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1594 InstInputs, InstResults,
1595 InstImpInputs, InstImpResults);
1598 //===----------------------------------------------------------------------===//
1599 // Instruction Analysis
1600 //===----------------------------------------------------------------------===//
1602 class InstAnalyzer {
1603 const CodeGenDAGPatterns &CDP;
1606 bool &HasSideEffects;
1608 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1609 bool &maystore, bool &mayload, bool &hse)
1610 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1613 /// Analyze - Analyze the specified instruction, returning true if the
1614 /// instruction had a pattern.
1615 bool Analyze(Record *InstRecord) {
1616 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1619 return false; // No pattern.
1622 // FIXME: Assume only the first tree is the pattern. The others are clobber
1624 AnalyzeNode(Pattern->getTree(0));
1629 void AnalyzeNode(const TreePatternNode *N) {
1631 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1632 Record *LeafRec = DI->getDef();
1633 // Handle ComplexPattern leaves.
1634 if (LeafRec->isSubClassOf("ComplexPattern")) {
1635 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1636 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1637 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1638 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1644 // Analyze children.
1645 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1646 AnalyzeNode(N->getChild(i));
1648 // Ignore set nodes, which are not SDNodes.
1649 if (N->getOperator()->getName() == "set")
1652 // Get information about the SDNode for the operator.
1653 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1655 // Notice properties of the node.
1656 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1657 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1658 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1660 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1661 // If this is an intrinsic, analyze it.
1662 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1663 mayLoad = true;// These may load memory.
1665 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1666 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1668 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1669 // WriteMem intrinsics can have other strange effects.
1670 HasSideEffects = true;
1676 static void InferFromPattern(const CodeGenInstruction &Inst,
1677 bool &MayStore, bool &MayLoad,
1678 bool &HasSideEffects,
1679 const CodeGenDAGPatterns &CDP) {
1680 MayStore = MayLoad = HasSideEffects = false;
1683 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1685 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1686 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1687 // If we decided that this is a store from the pattern, then the .td file
1688 // entry is redundant.
1691 "Warning: mayStore flag explicitly set on instruction '%s'"
1692 " but flag already inferred from pattern.\n",
1693 Inst.TheDef->getName().c_str());
1697 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1698 // If we decided that this is a load from the pattern, then the .td file
1699 // entry is redundant.
1702 "Warning: mayLoad flag explicitly set on instruction '%s'"
1703 " but flag already inferred from pattern.\n",
1704 Inst.TheDef->getName().c_str());
1708 if (Inst.neverHasSideEffects) {
1710 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1711 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1712 HasSideEffects = false;
1715 if (Inst.hasSideEffects) {
1717 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1718 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1719 HasSideEffects = true;
1723 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1724 /// any fragments involved. This populates the Instructions list with fully
1725 /// resolved instructions.
1726 void CodeGenDAGPatterns::ParseInstructions() {
1727 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1729 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1732 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1733 LI = Instrs[i]->getValueAsListInit("Pattern");
1735 // If there is no pattern, only collect minimal information about the
1736 // instruction for its operand list. We have to assume that there is one
1737 // result, as we have no detailed info.
1738 if (!LI || LI->getSize() == 0) {
1739 std::vector<Record*> Results;
1740 std::vector<Record*> Operands;
1742 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1744 if (InstInfo.OperandList.size() != 0) {
1745 if (InstInfo.NumDefs == 0) {
1746 // These produce no results
1747 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1748 Operands.push_back(InstInfo.OperandList[j].Rec);
1750 // Assume the first operand is the result.
1751 Results.push_back(InstInfo.OperandList[0].Rec);
1753 // The rest are inputs.
1754 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1755 Operands.push_back(InstInfo.OperandList[j].Rec);
1759 // Create and insert the instruction.
1760 std::vector<Record*> ImpResults;
1761 std::vector<Record*> ImpOperands;
1762 Instructions.insert(std::make_pair(Instrs[i],
1763 DAGInstruction(0, Results, Operands, ImpResults,
1765 continue; // no pattern.
1768 // Parse the instruction.
1769 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1770 // Inline pattern fragments into it.
1771 I->InlinePatternFragments();
1773 // Infer as many types as possible. If we cannot infer all of them, we can
1774 // never do anything with this instruction pattern: report it to the user.
1775 if (!I->InferAllTypes())
1776 I->error("Could not infer all types in pattern!");
1778 // InstInputs - Keep track of all of the inputs of the instruction, along
1779 // with the record they are declared as.
1780 std::map<std::string, TreePatternNode*> InstInputs;
1782 // InstResults - Keep track of all the virtual registers that are 'set'
1783 // in the instruction, including what reg class they are.
1784 std::map<std::string, TreePatternNode*> InstResults;
1786 std::vector<Record*> InstImpInputs;
1787 std::vector<Record*> InstImpResults;
1789 // Verify that the top-level forms in the instruction are of void type, and
1790 // fill in the InstResults map.
1791 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1792 TreePatternNode *Pat = I->getTree(j);
1793 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1794 I->error("Top-level forms in instruction pattern should have"
1797 // Find inputs and outputs, and verify the structure of the uses/defs.
1798 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1799 InstImpInputs, InstImpResults);
1802 // Now that we have inputs and outputs of the pattern, inspect the operands
1803 // list for the instruction. This determines the order that operands are
1804 // added to the machine instruction the node corresponds to.
1805 unsigned NumResults = InstResults.size();
1807 // Parse the operands list from the (ops) list, validating it.
1808 assert(I->getArgList().empty() && "Args list should still be empty here!");
1809 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1811 // Check that all of the results occur first in the list.
1812 std::vector<Record*> Results;
1813 TreePatternNode *Res0Node = NULL;
1814 for (unsigned i = 0; i != NumResults; ++i) {
1815 if (i == CGI.OperandList.size())
1816 I->error("'" + InstResults.begin()->first +
1817 "' set but does not appear in operand list!");
1818 const std::string &OpName = CGI.OperandList[i].Name;
1820 // Check that it exists in InstResults.
1821 TreePatternNode *RNode = InstResults[OpName];
1823 I->error("Operand $" + OpName + " does not exist in operand list!");
1827 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1829 I->error("Operand $" + OpName + " should be a set destination: all "
1830 "outputs must occur before inputs in operand list!");
1832 if (CGI.OperandList[i].Rec != R)
1833 I->error("Operand $" + OpName + " class mismatch!");
1835 // Remember the return type.
1836 Results.push_back(CGI.OperandList[i].Rec);
1838 // Okay, this one checks out.
1839 InstResults.erase(OpName);
1842 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1843 // the copy while we're checking the inputs.
1844 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1846 std::vector<TreePatternNode*> ResultNodeOperands;
1847 std::vector<Record*> Operands;
1848 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1849 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1850 const std::string &OpName = Op.Name;
1852 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1854 if (!InstInputsCheck.count(OpName)) {
1855 // If this is an predicate operand or optional def operand with an
1856 // DefaultOps set filled in, we can ignore this. When we codegen it,
1857 // we will do so as always executed.
1858 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1859 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1860 // Does it have a non-empty DefaultOps field? If so, ignore this
1862 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1865 I->error("Operand $" + OpName +
1866 " does not appear in the instruction pattern");
1868 TreePatternNode *InVal = InstInputsCheck[OpName];
1869 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1871 if (InVal->isLeaf() &&
1872 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1873 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1874 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1875 I->error("Operand $" + OpName + "'s register class disagrees"
1876 " between the operand and pattern");
1878 Operands.push_back(Op.Rec);
1880 // Construct the result for the dest-pattern operand list.
1881 TreePatternNode *OpNode = InVal->clone();
1883 // No predicate is useful on the result.
1884 OpNode->setPredicateFn("");
1886 // Promote the xform function to be an explicit node if set.
1887 if (Record *Xform = OpNode->getTransformFn()) {
1888 OpNode->setTransformFn(0);
1889 std::vector<TreePatternNode*> Children;
1890 Children.push_back(OpNode);
1891 OpNode = new TreePatternNode(Xform, Children);
1894 ResultNodeOperands.push_back(OpNode);
1897 if (!InstInputsCheck.empty())
1898 I->error("Input operand $" + InstInputsCheck.begin()->first +
1899 " occurs in pattern but not in operands list!");
1901 TreePatternNode *ResultPattern =
1902 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1903 // Copy fully inferred output node type to instruction result pattern.
1905 ResultPattern->setTypes(Res0Node->getExtTypes());
1907 // Create and insert the instruction.
1908 // FIXME: InstImpResults and InstImpInputs should not be part of
1910 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1911 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1913 // Use a temporary tree pattern to infer all types and make sure that the
1914 // constructed result is correct. This depends on the instruction already
1915 // being inserted into the Instructions map.
1916 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1917 Temp.InferAllTypes();
1919 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1920 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1925 // If we can, convert the instructions to be patterns that are matched!
1926 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1927 E = Instructions.end(); II != E; ++II) {
1928 DAGInstruction &TheInst = II->second;
1929 const TreePattern *I = TheInst.getPattern();
1930 if (I == 0) continue; // No pattern.
1932 // FIXME: Assume only the first tree is the pattern. The others are clobber
1934 TreePatternNode *Pattern = I->getTree(0);
1935 TreePatternNode *SrcPattern;
1936 if (Pattern->getOperator()->getName() == "set") {
1937 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1939 // Not a set (store or something?)
1940 SrcPattern = Pattern;
1944 if (!SrcPattern->canPatternMatch(Reason, *this))
1945 I->error("Instruction can never match: " + Reason);
1947 Record *Instr = II->first;
1948 TreePatternNode *DstPattern = TheInst.getResultPattern();
1950 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1951 SrcPattern, DstPattern, TheInst.getImpResults(),
1952 Instr->getValueAsInt("AddedComplexity")));
1957 void CodeGenDAGPatterns::InferInstructionFlags() {
1958 std::map<std::string, CodeGenInstruction> &InstrDescs =
1959 Target.getInstructions();
1960 for (std::map<std::string, CodeGenInstruction>::iterator
1961 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
1962 CodeGenInstruction &InstInfo = II->second;
1963 // Determine properties of the instruction from its pattern.
1964 bool MayStore, MayLoad, HasSideEffects;
1965 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
1966 InstInfo.mayStore = MayStore;
1967 InstInfo.mayLoad = MayLoad;
1968 InstInfo.hasSideEffects = HasSideEffects;
1972 void CodeGenDAGPatterns::ParsePatterns() {
1973 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1975 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1976 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1977 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1978 Record *Operator = OpDef->getDef();
1979 TreePattern *Pattern;
1980 if (Operator->getName() != "parallel")
1981 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1983 std::vector<Init*> Values;
1984 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1985 Values.push_back(Tree->getArg(j));
1986 ListInit *LI = new ListInit(Values);
1987 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1990 // Inline pattern fragments into it.
1991 Pattern->InlinePatternFragments();
1993 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1994 if (LI->getSize() == 0) continue; // no pattern.
1996 // Parse the instruction.
1997 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1999 // Inline pattern fragments into it.
2000 Result->InlinePatternFragments();
2002 if (Result->getNumTrees() != 1)
2003 Result->error("Cannot handle instructions producing instructions "
2004 "with temporaries yet!");
2006 bool IterateInference;
2007 bool InferredAllPatternTypes, InferredAllResultTypes;
2009 // Infer as many types as possible. If we cannot infer all of them, we
2010 // can never do anything with this pattern: report it to the user.
2011 InferredAllPatternTypes = Pattern->InferAllTypes();
2013 // Infer as many types as possible. If we cannot infer all of them, we
2014 // can never do anything with this pattern: report it to the user.
2015 InferredAllResultTypes = Result->InferAllTypes();
2017 // Apply the type of the result to the source pattern. This helps us
2018 // resolve cases where the input type is known to be a pointer type (which
2019 // is considered resolved), but the result knows it needs to be 32- or
2020 // 64-bits. Infer the other way for good measure.
2021 IterateInference = Pattern->getTree(0)->
2022 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2023 IterateInference |= Result->getTree(0)->
2024 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2025 } while (IterateInference);
2027 // Verify that we inferred enough types that we can do something with the
2028 // pattern and result. If these fire the user has to add type casts.
2029 if (!InferredAllPatternTypes)
2030 Pattern->error("Could not infer all types in pattern!");
2031 if (!InferredAllResultTypes)
2032 Result->error("Could not infer all types in pattern result!");
2034 // Validate that the input pattern is correct.
2035 std::map<std::string, TreePatternNode*> InstInputs;
2036 std::map<std::string, TreePatternNode*> InstResults;
2037 std::vector<Record*> InstImpInputs;
2038 std::vector<Record*> InstImpResults;
2039 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2040 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2041 InstInputs, InstResults,
2042 InstImpInputs, InstImpResults);
2044 // Promote the xform function to be an explicit node if set.
2045 TreePatternNode *DstPattern = Result->getOnlyTree();
2046 std::vector<TreePatternNode*> ResultNodeOperands;
2047 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2048 TreePatternNode *OpNode = DstPattern->getChild(ii);
2049 if (Record *Xform = OpNode->getTransformFn()) {
2050 OpNode->setTransformFn(0);
2051 std::vector<TreePatternNode*> Children;
2052 Children.push_back(OpNode);
2053 OpNode = new TreePatternNode(Xform, Children);
2055 ResultNodeOperands.push_back(OpNode);
2057 DstPattern = Result->getOnlyTree();
2058 if (!DstPattern->isLeaf())
2059 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2060 ResultNodeOperands);
2061 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2062 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2063 Temp.InferAllTypes();
2066 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2067 Pattern->error("Pattern can never match: " + Reason);
2070 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2071 Pattern->getTree(0),
2072 Temp.getOnlyTree(), InstImpResults,
2073 Patterns[i]->getValueAsInt("AddedComplexity")));
2077 /// CombineChildVariants - Given a bunch of permutations of each child of the
2078 /// 'operator' node, put them together in all possible ways.
2079 static void CombineChildVariants(TreePatternNode *Orig,
2080 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2081 std::vector<TreePatternNode*> &OutVariants,
2082 CodeGenDAGPatterns &CDP,
2083 const MultipleUseVarSet &DepVars) {
2084 // Make sure that each operand has at least one variant to choose from.
2085 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2086 if (ChildVariants[i].empty())
2089 // The end result is an all-pairs construction of the resultant pattern.
2090 std::vector<unsigned> Idxs;
2091 Idxs.resize(ChildVariants.size());
2095 if (DebugFlag && !Idxs.empty()) {
2096 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
2097 for (unsigned i = 0; i < Idxs.size(); ++i) {
2098 cerr << Idxs[i] << " ";
2103 // Create the variant and add it to the output list.
2104 std::vector<TreePatternNode*> NewChildren;
2105 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2106 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2107 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2109 // Copy over properties.
2110 R->setName(Orig->getName());
2111 R->setPredicateFn(Orig->getPredicateFn());
2112 R->setTransformFn(Orig->getTransformFn());
2113 R->setTypes(Orig->getExtTypes());
2115 // If this pattern cannot match, do not include it as a variant.
2116 std::string ErrString;
2117 if (!R->canPatternMatch(ErrString, CDP)) {
2120 bool AlreadyExists = false;
2122 // Scan to see if this pattern has already been emitted. We can get
2123 // duplication due to things like commuting:
2124 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2125 // which are the same pattern. Ignore the dups.
2126 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2127 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2128 AlreadyExists = true;
2135 OutVariants.push_back(R);
2138 // Increment indices to the next permutation by incrementing the
2139 // indicies from last index backward, e.g., generate the sequence
2140 // [0, 0], [0, 1], [1, 0], [1, 1].
2142 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2143 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2148 NotDone = (IdxsIdx >= 0);
2152 /// CombineChildVariants - A helper function for binary operators.
2154 static void CombineChildVariants(TreePatternNode *Orig,
2155 const std::vector<TreePatternNode*> &LHS,
2156 const std::vector<TreePatternNode*> &RHS,
2157 std::vector<TreePatternNode*> &OutVariants,
2158 CodeGenDAGPatterns &CDP,
2159 const MultipleUseVarSet &DepVars) {
2160 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2161 ChildVariants.push_back(LHS);
2162 ChildVariants.push_back(RHS);
2163 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2167 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2168 std::vector<TreePatternNode *> &Children) {
2169 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2170 Record *Operator = N->getOperator();
2172 // Only permit raw nodes.
2173 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
2174 N->getTransformFn()) {
2175 Children.push_back(N);
2179 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2180 Children.push_back(N->getChild(0));
2182 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2184 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2185 Children.push_back(N->getChild(1));
2187 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2190 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2191 /// the (potentially recursive) pattern by using algebraic laws.
2193 static void GenerateVariantsOf(TreePatternNode *N,
2194 std::vector<TreePatternNode*> &OutVariants,
2195 CodeGenDAGPatterns &CDP,
2196 const MultipleUseVarSet &DepVars) {
2197 // We cannot permute leaves.
2199 OutVariants.push_back(N);
2203 // Look up interesting info about the node.
2204 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2206 // If this node is associative, reassociate.
2207 if (NodeInfo.hasProperty(SDNPAssociative)) {
2208 // Reassociate by pulling together all of the linked operators
2209 std::vector<TreePatternNode*> MaximalChildren;
2210 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2212 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2214 if (MaximalChildren.size() == 3) {
2215 // Find the variants of all of our maximal children.
2216 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2217 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2218 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2219 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2221 // There are only two ways we can permute the tree:
2222 // (A op B) op C and A op (B op C)
2223 // Within these forms, we can also permute A/B/C.
2225 // Generate legal pair permutations of A/B/C.
2226 std::vector<TreePatternNode*> ABVariants;
2227 std::vector<TreePatternNode*> BAVariants;
2228 std::vector<TreePatternNode*> ACVariants;
2229 std::vector<TreePatternNode*> CAVariants;
2230 std::vector<TreePatternNode*> BCVariants;
2231 std::vector<TreePatternNode*> CBVariants;
2232 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2233 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2234 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2235 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2236 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2237 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2239 // Combine those into the result: (x op x) op x
2240 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2241 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2242 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2243 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2244 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2245 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2247 // Combine those into the result: x op (x op x)
2248 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2249 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2250 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2251 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2252 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2253 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2258 // Compute permutations of all children.
2259 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2260 ChildVariants.resize(N->getNumChildren());
2261 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2262 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2264 // Build all permutations based on how the children were formed.
2265 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2267 // If this node is commutative, consider the commuted order.
2268 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2269 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2270 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2271 "Commutative but doesn't have 2 children!");
2272 // Don't count children which are actually register references.
2274 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2275 TreePatternNode *Child = N->getChild(i);
2276 if (Child->isLeaf())
2277 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2278 Record *RR = DI->getDef();
2279 if (RR->isSubClassOf("Register"))
2284 // Consider the commuted order.
2285 if (isCommIntrinsic) {
2286 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2287 // operands are the commutative operands, and there might be more operands
2290 "Commutative intrinsic should have at least 3 childrean!");
2291 std::vector<std::vector<TreePatternNode*> > Variants;
2292 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2293 Variants.push_back(ChildVariants[2]);
2294 Variants.push_back(ChildVariants[1]);
2295 for (unsigned i = 3; i != NC; ++i)
2296 Variants.push_back(ChildVariants[i]);
2297 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2299 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2300 OutVariants, CDP, DepVars);
2305 // GenerateVariants - Generate variants. For example, commutative patterns can
2306 // match multiple ways. Add them to PatternsToMatch as well.
2307 void CodeGenDAGPatterns::GenerateVariants() {
2308 DOUT << "Generating instruction variants.\n";
2310 // Loop over all of the patterns we've collected, checking to see if we can
2311 // generate variants of the instruction, through the exploitation of
2312 // identities. This permits the target to provide agressive matching without
2313 // the .td file having to contain tons of variants of instructions.
2315 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2316 // intentionally do not reconsider these. Any variants of added patterns have
2317 // already been added.
2319 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2320 MultipleUseVarSet DepVars;
2321 std::vector<TreePatternNode*> Variants;
2322 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2323 DOUT << "Dependent/multiply used variables: ";
2324 DEBUG(DumpDepVars(DepVars));
2326 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2328 assert(!Variants.empty() && "Must create at least original variant!");
2329 Variants.erase(Variants.begin()); // Remove the original pattern.
2331 if (Variants.empty()) // No variants for this pattern.
2334 DOUT << "FOUND VARIANTS OF: ";
2335 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2338 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2339 TreePatternNode *Variant = Variants[v];
2341 DOUT << " VAR#" << v << ": ";
2342 DEBUG(Variant->dump());
2345 // Scan to see if an instruction or explicit pattern already matches this.
2346 bool AlreadyExists = false;
2347 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2348 // Check to see if this variant already exists.
2349 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2350 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2351 AlreadyExists = true;
2355 // If we already have it, ignore the variant.
2356 if (AlreadyExists) continue;
2358 // Otherwise, add it to the list of patterns we have.
2360 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2361 Variant, PatternsToMatch[i].getDstPattern(),
2362 PatternsToMatch[i].getDstRegs(),
2363 PatternsToMatch[i].getAddedComplexity()));